Compare commits

..
7 Commits
Author SHA1 Message Date
yiling dc9adcf9ac Release v0.7.1 2026-11-23 20:48:49 +08:00
Yiling-J 5f6f3799fb feat(storage): align local presigned URL expiry with env vars and float hours (#543) 2026-11-23 19:35:40 +08:00
Yiling-J 6c71de4160 fix(search): match latest version only for version stacks and return stack assets (#542)
* fix(search): match latest version only for version stacks and return stack assets

* fix(search): preserve cross-project moved files in semantic search and align stack timestamps
2026-11-23 16:40:12 +08:00
Yiling-J db628e65fa fix(storage): use wall-clock TTL and half-lifetime margin for presigned URL cache (#541)
* fix(storage): use wall-clock TTL and half-lifetime margin for presigned URL cache

* test(e2e): eliminate offline race in uploader resilience harness test
2026-11-23 13:39:31 +08:00
Yiling-J eeb41fee03 fix(search): preview matched video chunks on hover (#540)
* fix(search): preview matched video chunks on hover

* fix(search): show chunk covers before hover

* fix(search): reuse sprites for whole-video matches
2026-11-23 11:42:00 +08:00
Yiling-J aabf59cbe7 refactor(transcode): offload video embedding chunk slicing to transcode queue (#539)
* refactor(transcode): offload video embedding chunk slicing to transcode queue

* fix(transcode): address video chunk offloading review findings
2026-11-22 11:52:58 +08:00
Yiling-J 3943407093 feat(search): add image similarity search (#537)
* feat(search): add image similarity search

* feat(search): support pasting image attachments
2026-11-21 10:32:46 +08:00
97 changed files with 5500 additions and 1164 deletions
+16
View File
@@ -12,6 +12,22 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Changed
## [0.7.1] - 2026-11-23
### Added
- **search**: Find similar images and video segments from a project image, or choose, drop, or paste an image in semantic search.
### Fixed
- **storage**: Fix an issue where cached media preview and file URLs could expire and break after the host machine slept or near the end of an S3 link's lifetime.
- **search**: Video segment matches in Semantic Search and Find Similar show the segment’s first frame and let you scrub through it on hover. Matches that span the entire video reuse its full preview when available.
- **search**: Fix an issue where version stacks appeared as separate individual versions in Search and Find Similar results instead of matching only the latest version and showing a single stacked asset with its version badge.
### Changed
- **transcode**: Offload video chunk slicing for search embeddings to the transcode worker queue.
## [0.7.0] - 2026-11-18
### Added
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/cli",
"version": "0.7.0",
"version": "0.7.1",
"private": true,
"type": "module",
"bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/premiere-uxp",
"version": "0.7.0",
"version": "0.7.1",
"private": true,
"type": "commonjs",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/transcode-app",
"version": "0.7.0",
"version": "0.7.1",
"private": true,
"type": "module",
"bin": {
+3
View File
@@ -95,6 +95,9 @@ apps/web/e2e/
| Owner searches the file list by an English name keyword | `tests/project/search-file-list.spec.ts` |
| Owner searches the file list by Chinese, Japanese, and Korean name keywords | `tests/project/search-file-list.spec.ts` |
| Owner searches the file list with a keyword and a filter condition | `tests/project/search-file-list.spec.ts` |
| Owner finds similar media and filters the results by type | `tests/project/search-file-list.spec.ts` |
| Owner previews matched video ranges in both search dialogs | `tests/project/search-file-list.spec.ts` |
| Owner submits a resized image with filters and can remove the attachment | `tests/project/search-file-list.spec.ts` |
| Owner saves a search result as a collection | `tests/project/save-search-collection.spec.ts` |
| Image share with watermark + download disabled: no download buttons on public list/detail pages, watermarked proxy served, download-url rejected | `tests/project/share-watermark-no-download.spec.ts` |
| Video share with watermark + download disabled: no download buttons on public list/detail pages, watermarked proxy served, download-url rejected | `tests/project/share-watermark-no-download.spec.ts` |
@@ -28,7 +28,7 @@ test('owner saves a search result as a collection', async ({ project, prisma })
await expect(dialog).toBeVisible()
await dialog.getByPlaceholder('Search records by name...').fill('report')
await dialog.getByRole('button', { name: 'Search' }).click()
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
await expect(dialog.getByText(matching, { exact: true })).toBeVisible()
await expect(dialog.getByText(other, { exact: true })).not.toBeVisible()
@@ -1,4 +1,5 @@
import type { APIRequestContext } from '@playwright/test'
import type { APIRequestContext, Locator } from '@playwright/test'
import type { AssetInfo, ImageSearchRequest, SearchRequest } from '@shumai/dtos'
import { expect, test } from '../../fixtures'
import { apiUploadFile, fileCard } from '../../helpers/files'
@@ -38,7 +39,7 @@ test('owner searches the file list by an English name keyword', async ({ project
// Keyword-only search (no filter conditions)
await dialog.getByPlaceholder('Search records by name...').fill('report')
await dialog.getByRole('button', { name: 'Search' }).click()
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
await expect(dialog.getByText(report2024, { exact: true })).toBeVisible()
await expect(dialog.getByText(report2025, { exact: true })).toBeVisible()
@@ -75,7 +76,7 @@ test('owner searches the file list by Chinese, Japanese, and Korean name keyword
const dialog = page.getByRole('dialog')
await expect(dialog).toBeVisible()
await dialog.getByPlaceholder('Search records by name...').fill(keyword)
await dialog.getByRole('button', { name: 'Search' }).click()
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
for (const name of visible) {
await expect(dialog.getByText(name, { exact: true })).toBeVisible()
}
@@ -149,7 +150,7 @@ test('owner searches the file list with a keyword and a filter condition', async
// confirms the filter became active before we run the search.
await expect(dialog.getByText('1 active')).toBeVisible()
await dialog.getByRole('button', { name: 'Search' }).click()
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
await expect(dialog.getByText(bigReport, { exact: true })).toBeVisible()
await expect(dialog.getByText(smallReport, { exact: true })).not.toBeVisible()
@@ -160,3 +161,290 @@ test('owner searches the file list with a keyword and a filter condition', async
await expect(fileCard(page, bigReport)).toBeVisible()
await expect(fileCard(page, smallReport)).not.toBeVisible()
})
test.describe('image search', () => {
test.use({ fileOptions: { mediaType: 'image' } })
test('owner previews matched video ranges in both search dialogs', async ({ file }) => {
const { page, teamId, projectId, rootFolderId, fileName } = file
const layout = { columns: 5, rows: 2, frameCount: 7 }
const video: AssetInfo = {
id: 'video-result',
name: 'result.mp4',
type: 'file',
sizeByte: 100,
fileCount: 1,
status: 'processed',
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
proxyType: 'video',
preview: {
thumbnailUrl: '/test-sprites/poster.svg',
spriteUrl: '/test-sprites/full.svg',
originalWidth: 100,
originalHeight: 40,
},
startTime: 0,
endTime: 30,
matchedSprite: { ...layout, url: '/test-sprites/chunk.svg' },
}
const brokenMatch: AssetInfo = {
...video,
startTime: 55,
endTime: 85,
matchedSprite: { ...layout, url: '/test-sprites/broken.svg' },
}
const secondMatch: AssetInfo = {
...video,
startTime: 25,
endTime: 55,
matchedSprite: { ...layout, url: '/test-sprites/second.svg' },
}
await page.route(`**/api/teams/${teamId}/settings`, async (route) => {
const response = await route.fetch()
await route.fulfill({
response,
json: { ...(await response.json()), semanticSearchEnabled: true },
})
})
const results = { json: { data: [video, secondMatch, brokenMatch], pageInfo: { total: 3 } } }
await page.route(`**/api/folders/${rootFolderId}/image-search`, (route) =>
route.fulfill(results),
)
await page.route(`**/api/folders/${rootFolderId}/search`, (route) => {
const request = route.request().postDataJSON() as SearchRequest | null
return request?.isSemantic ? route.fulfill(results) : route.continue()
})
await page.route('**/test-sprites/*.svg', (route) =>
route.request().url().endsWith('/broken.svg')
? route.fulfill({ status: 404 })
: route.fulfill({
contentType: 'image/svg+xml',
body: '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="40"/>',
}),
)
async function verifyPreviews(dialog: Locator) {
const heading = dialog.getByRole('heading').first()
await heading.hover()
const cards = dialog.getByTestId('sprite-scrubber')
const firstFrame = cards.nth(0).locator('.opacity-100 > [style*="/test-sprites/chunk.svg"]')
const secondFrame = cards.nth(1).locator('.opacity-100 > [style*="/test-sprites/second.svg"]')
await expect(firstFrame).toHaveCSS('background-position', '0px 0px')
await expect(secondFrame).toHaveCSS('background-position', '0px 0px')
await expect(cards.nth(2).getByAltText('Thumbnail')).toHaveClass(/opacity-100/)
await expect(dialog.locator('[style*="/test-sprites/full.svg"]')).toHaveCount(0)
await cards.nth(0).hover()
await expect(cards.nth(0)).not.toHaveAttribute('data-frame', '0')
await heading.hover()
await expect(firstFrame).toHaveCSS('background-position', '0px 0px')
await cards.nth(2).hover()
await expect(
cards.nth(2).locator('.opacity-100 > [style*="/test-sprites/full.svg"]'),
).toBeVisible()
await heading.hover()
await expect(cards.nth(2).getByAltText('Thumbnail')).toHaveClass(/opacity-100/)
}
await page.goto(`/projects/${projectId}`)
await fileCard(page, fileName).click({ button: 'right' })
await page.getByRole('menuitem', { name: 'Find similar' }).click()
await verifyPreviews(page.getByRole('dialog', { name: 'Find similar' }))
await page.keyboard.press('Escape')
await page.getByRole('button', { name: 'Search' }).click()
const semanticSearch = page.getByRole('dialog', { name: 'Search', exact: true })
await semanticSearch.getByRole('switch', { name: 'Semantic Search' }).click()
const searchInput = semanticSearch.getByPlaceholder('Search records by content...')
await searchInput.fill('video scene')
await searchInput.press('Enter')
await verifyPreviews(semanticSearch)
})
test('owner finds similar media and filters the results by type', async ({ file }) => {
const { page, teamId, projectId, rootFolderId, fileId, fileName } = file
const source = fileCard(page, fileName)
await page.goto(`/projects/${projectId}`)
await source.click({ button: 'right' })
await expect(page.getByRole('menu')).toBeVisible()
await expect(page.getByRole('menuitem', { name: 'Find similar' })).toHaveCount(0)
await page.route(`**/api/teams/${teamId}/settings`, async (route) => {
const response = await route.fetch()
await route.fulfill({
response,
json: { ...(await response.json()), semanticSearchEnabled: true },
})
})
const image: AssetInfo = {
id: 'image-result',
name: 'result.jpg',
type: 'file',
sizeByte: 100,
fileCount: 1,
status: 'processed',
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
proxyType: 'image',
}
const video: AssetInfo = {
...image,
id: 'video-result',
name: 'result.mp4',
proxyType: 'video',
startTime: 65,
endTime: 120,
}
const requests: ImageSearchRequest[] = []
await page.route(`**/api/folders/${rootFolderId}/image-search`, async (route) => {
const request = route.request().postDataJSON() as ImageSearchRequest
requests.push(request)
const data =
request.mediaType === 'image'
? [image]
: request.mediaType === 'video'
? [video]
: [image, video]
await route.fulfill({ json: { data, pageInfo: { total: data.length } } })
})
const settingsLoaded = page.waitForResponse(`**/api/teams/${teamId}/settings`)
await page.reload()
await settingsLoaded
await source.click({ button: 'right' })
await page.getByRole('menuitem', { name: 'Find similar' }).click()
const dialog = page.getByRole('dialog', { name: 'Find similar' })
await expect(dialog.getByText(image.name)).toBeVisible()
await expect(dialog.getByText(video.name)).toBeVisible()
await expect(dialog.getByTestId('file-preview-matched-duration')).toHaveText('01:05 - 02:00')
expect(requests.at(-1)).toMatchObject({ sourceAssetId: fileId, first: 20 })
await dialog.getByText('Videos', { exact: true }).click()
await expect(dialog.getByText(video.name)).toBeVisible()
await expect(dialog.getByText(image.name)).toHaveCount(0)
expect(requests.at(-1)).toMatchObject({ sourceAssetId: fileId, mediaType: 'video' })
await dialog.getByText('Images', { exact: true }).click()
await expect(dialog.getByText(image.name)).toBeVisible()
await expect(dialog.getByText(video.name)).toHaveCount(0)
expect(requests.at(-1)).toMatchObject({ sourceAssetId: fileId, mediaType: 'image' })
})
test('owner submits a resized image with filters and can remove the attachment', async ({
project,
browserName,
}) => {
const { page, teamId, projectId, rootFolderId } = project
await page.route(`**/api/teams/${teamId}/settings`, async (route) => {
const response = await route.fetch()
await route.fulfill({
response,
json: { ...(await response.json()), semanticSearchEnabled: true },
})
})
const requests: ImageSearchRequest[] = []
await page.route(`**/api/folders/${rootFolderId}/image-search`, async (route) => {
requests.push(route.request().postDataJSON() as ImageSearchRequest)
await route.fulfill({ json: { data: [], pageInfo: { total: 0 } } })
})
await page.goto(`/projects/${projectId}`)
await page.getByRole('button', { name: 'Search' }).click()
const dialog = page.getByRole('dialog', { name: 'Search', exact: true })
const semantic = dialog.getByRole('switch', { name: 'Semantic Search' })
await expect(semantic).toBeEnabled()
await semantic.click()
await dialog.getByPlaceholder('Search records by content...').fill('text draft')
await dialog.getByRole('button', { name: '+ Add condition' }).click()
const comboboxes = dialog.getByRole('combobox')
await comboboxes.first().click()
await page.getByRole('option', { name: 'Size', exact: true }).click()
await comboboxes.nth(1).click()
await page.getByRole('option', { name: '>', exact: true }).click()
await dialog.locator('input[type="number"]').fill('100')
await expect(dialog.getByText('1 active')).toBeVisible()
await dialog.getByRole('button', { name: 'Attach an image' }).click()
const picker = page.getByRole('dialog', { name: 'Attach an image' })
await expect(picker).toBeVisible()
const png = await page.evaluate(() => {
const canvas = document.createElement('canvas')
canvas.width = 2560
canvas.height = 1440
return canvas.toDataURL('image/png').split(',')[1]
})
const chooser = page.waitForEvent('filechooser')
await picker.getByRole('button', { name: 'Choose image' }).click()
await (
await chooser
).setFiles({ name: 'reference.png', mimeType: 'image/png', buffer: Buffer.from(png, 'base64') })
await expect(dialog.getByText('reference.png')).toBeVisible()
await expect(dialog.getByPlaceholder('Search records by content...')).toHaveCount(0)
const thumbnail = dialog.locator('img').first()
await expect
.poll(() =>
thumbnail.evaluate((image: HTMLImageElement) => ({
width: image.naturalWidth,
height: image.naturalHeight,
})),
)
.toEqual({ width: 1280, height: 720 })
expect(requests).toHaveLength(0)
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
await expect.poll(() => requests.length).toBe(1)
expect(requests[0]).toMatchObject({
image: expect.stringMatching(/^\/9j\//),
conditions: [{ field: 'sizeByte', operator: 'gt', value: 100 }],
})
expect(requests[0]).not.toHaveProperty('query')
await dialog.getByRole('button', { name: 'Attach an image' }).click()
const transfer = await page.evaluateHandle(() => {
const canvas = document.createElement('canvas')
canvas.width = 720
canvas.height = 1280
const png = atob(canvas.toDataURL('image/png').split(',')[1])
const bytes = Uint8Array.from(png, (byte) => byte.charCodeAt(0))
const transfer = new DataTransfer()
transfer.items.add(new File([bytes], 'dropped.png', { type: 'image/png' }))
return transfer
})
await picker
.getByRole('button', { name: 'Choose image' })
.dispatchEvent('drop', { dataTransfer: transfer })
await transfer.dispose()
await expect(dialog.getByText('dropped.png')).toBeVisible()
if (browserName === 'chromium') {
await page.context().grantPermissions(['clipboard-read', 'clipboard-write'])
await page.evaluate(async (base64) => {
const bytes = Uint8Array.from(atob(base64), (byte) => byte.charCodeAt(0))
const image = new Blob([bytes], { type: 'image/png' })
await navigator.clipboard.write([new ClipboardItem({ 'image/png': image })])
}, png)
await dialog.getByRole('button', { name: 'Attach an image' }).click()
await expect(picker).toBeVisible()
await page.keyboard.press('ControlOrMeta+V')
await expect(picker).toBeHidden()
await expect(dialog.getByText('dropped.png')).toHaveCount(0)
await expect(thumbnail).toHaveJSProperty('naturalWidth', 1280)
await expect(thumbnail).toHaveJSProperty('naturalHeight', 720)
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
await expect.poll(() => requests.length).toBe(2)
expect(requests[1]).toMatchObject({
image: expect.stringMatching(/^\/9j\//),
conditions: [{ field: 'sizeByte', operator: 'gt', value: 100 }],
})
}
await dialog.getByRole('button', { name: 'Remove image' }).click()
await expect(dialog.getByPlaceholder('Search records by content...')).toBeVisible()
await expect(dialog.getByText('1 active')).toBeVisible()
await dialog.getByRole('button', { name: 'Close', exact: true }).last().click()
await expect(page.getByText('This folder is empty')).toBeVisible()
})
})
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/web-app",
"version": "0.7.0",
"version": "0.7.1",
"private": true,
"type": "module",
"dependencies": {
+15 -15
View File
@@ -32,7 +32,7 @@
},
"apps/cli": {
"name": "@shumai/cli",
"version": "0.7.0",
"version": "0.7.1",
"bin": {
"shumai-cli": "./src/index.ts",
},
@@ -59,7 +59,7 @@
},
"apps/premiere-uxp": {
"name": "@shumai/premiere-uxp",
"version": "0.7.0",
"version": "0.7.1",
"dependencies": {
"@shumai/api": "workspace:*",
"@shumai/dtos": "workspace:*",
@@ -113,7 +113,7 @@
},
"apps/transcode": {
"name": "@shumai/transcode-app",
"version": "0.7.0",
"version": "0.7.1",
"bin": {
"shumai-transcode": "./src/index.ts",
},
@@ -125,7 +125,7 @@
},
"apps/web": {
"name": "@shumai/web-app",
"version": "0.7.0",
"version": "0.7.1",
"dependencies": {
"@shumai/agent": "workspace:*",
"@shumai/api": "workspace:*",
@@ -145,7 +145,7 @@
},
"packages/agent": {
"name": "@shumai/agent",
"version": "0.7.0",
"version": "0.7.1",
"dependencies": {
"@earendil-works/chord": "1.5.0",
"@earendil-works/pi-ai": "1.5.0",
@@ -169,7 +169,7 @@
},
"packages/api": {
"name": "@shumai/api",
"version": "0.7.0",
"version": "0.7.1",
"dependencies": {
"@better-auth/mcp": "1.7.12",
"@earendil-works/pi-durable": "1.5.0",
@@ -190,7 +190,7 @@
},
"packages/core": {
"name": "@shumai/core",
"version": "0.7.0",
"version": "0.7.1",
"dependencies": {
"@ai-sdk/alibaba": "2.0.38",
"@ai-sdk/amazon-bedrock": "5.0.67",
@@ -254,7 +254,7 @@
},
"packages/db": {
"name": "@shumai/db",
"version": "0.7.0",
"version": "0.7.1",
"dependencies": {
"@prisma/adapter-pg": "7.10.0",
"@prisma/client": "7.10.0",
@@ -269,7 +269,7 @@
},
"packages/dtos": {
"name": "@shumai/dtos",
"version": "0.7.0",
"version": "0.7.1",
"dependencies": {
"@earendil-works/pi-ai": "1.5.0",
"@earendil-works/pi-durable": "1.5.0",
@@ -278,7 +278,7 @@
},
"packages/e2e": {
"name": "@shumai/e2e",
"version": "0.7.0",
"version": "0.7.1",
"dependencies": {
"@earendil-works/pi-ai": "1.5.0",
"@earendil-works/pi-durable": "1.5.0",
@@ -294,18 +294,18 @@
},
"packages/operations": {
"name": "@shumai/operations",
"version": "0.7.0",
"version": "0.7.1",
"dependencies": {
"zod": "4.5.4",
},
},
"packages/tableprinter": {
"name": "@shumai/tableprinter",
"version": "0.7.0",
"version": "0.7.1",
},
"packages/transcode": {
"name": "@shumai/transcode",
"version": "0.7.0",
"version": "0.7.1",
"dependencies": {
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
@@ -316,7 +316,7 @@
},
"packages/webui": {
"name": "@shumai/webui",
"version": "0.7.0",
"version": "0.7.1",
"dependencies": {
"@base-ui/react": "1.7.0",
"@better-auth/oauth-provider": "1.7.12",
@@ -421,7 +421,7 @@
},
"packages/workflow-core": {
"name": "@shumai/workflow-core",
"version": "0.7.0",
"version": "0.7.1",
"dependencies": {
"@dbos-inc/dbos-sdk": "5.2.11",
"@shumai/core": "workspace:*",
+18
View File
@@ -3,6 +3,24 @@ title: "Changelog"
description: "Recent updates, new features, and improvements in Shumai"
---
<Update label="v0.7.1" description="November 23, 2026">
### Added
- **search**: Find similar images and video segments from a project image, or choose, drop, or paste an image in semantic search.
### Fixed
- **storage**: Fix an issue where cached media preview and file URLs could expire and break after the host machine slept or near the end of an S3 link's lifetime.
- **search**: Video segment matches in Semantic Search and Find Similar show the segment’s first frame and let you scrub through it on hover. Matches that span the entire video reuse its full preview when available.
- **search**: Fix an issue where version stacks appeared as separate individual versions in Search and Find Similar results instead of matching only the latest version and showing a single stacked asset with its version badge.
### Changed
- **transcode**: Offload video chunk slicing for search embeddings to the transcode worker queue.
</Update>
<Update label="v0.7.0" description="November 18, 2026">
### Added
+10 -10
View File
@@ -38,16 +38,16 @@ Shumai is configured via environment variables. You can define these variables i
Shumai supports storing files locally or on S3-compatible endpoints.
| Variable | Description | Example / Default |
| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------ |
| `STORAGE_BACKEND` | Storage type. Use `local` for local file system storage, or `s3` for S3-compatible cloud storage. | `local` (default) or `s3` |
| `AWS_ENDPOINT_URL_S3` | Endpoint for S3 storage or local storage. Used by the browser to build file upload URLs. Must include port if deploying remotely or using custom ports. | `http://localhost:3000` (respects `SHUMAI_SERVER_PORT` fallback if unset) |
| `S3_BUCKET` | S3 bucket name. | `shumai` (default) |
| `S3_ACCESS_KEY_ID` | Access key credentials for S3. | `minioadmin` (default) |
| `S3_SECRET_ACCESS_KEY` | Secret key credentials for S3. | `minioadmin` (default) |
| `S3_REGION` | S3 storage region. | `auto` (default) |
| `PRESIGNED_URL_EXPIRES_IN` | Number of hours for which generated presigned download links are valid. | `5` (default) |
| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | Number of hours for which generated presigned upload links are valid. Falls back to `PRESIGNED_URL_EXPIRES_IN` if unset. | `12` (default) |
| Variable | Description | Example / Default |
| :-------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------ |
| `STORAGE_BACKEND` | Storage type. Use `local` for local file system storage, or `s3` for S3-compatible cloud storage. | `local` (default) or `s3` |
| `AWS_ENDPOINT_URL_S3` | Endpoint for S3 storage or local storage. Used by the browser to build file upload URLs. Must include port if deploying remotely or using custom ports. | `http://localhost:3000` (respects `SHUMAI_SERVER_PORT` fallback if unset) |
| `S3_BUCKET` | S3 bucket name. | `shumai` (default) |
| `S3_ACCESS_KEY_ID` | Access key credentials for S3. | `minioadmin` (default) |
| `S3_SECRET_ACCESS_KEY` | Secret key credentials for S3. | `minioadmin` (default) |
| `S3_REGION` | S3 storage region. | `auto` (default) |
| `PRESIGNED_URL_EXPIRES_IN` | Number of hours (decimals supported, e.g. `0.5`) for which generated presigned download links are valid. Applies to both local and S3 storage. | `12` (default) |
| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | Number of hours (decimals supported, e.g. `0.5`) for which generated presigned upload links are valid. Falls back to `PRESIGNED_URL_EXPIRES_IN` if unset. Applies to both local and S3. | `12` (default) |
### Local Storage Port Configuration
+10 -10
View File
@@ -13,16 +13,16 @@ Using external S3 storage is highly recommended for production teams. It allows
To enable S3-compatible storage, update the following environment variables in your `.env` file or Docker Compose configuration:
| Variable | Description | Required | Default / Example |
| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------ | :------- | :----------------------------------- |
| `STORAGE_BACKEND` | Set to `s3` to enable S3 compatible storage. | Yes | `s3` |
| `S3_BUCKET` | The name of the S3 bucket where files will be stored. | Yes | `shumai-bucket` |
| `S3_REGION` | The region of your S3 bucket. | No | `auto` |
| `S3_ACCESS_KEY_ID` | The access key ID for your storage service. | Yes | `your-access-key-id` |
| `S3_SECRET_ACCESS_KEY` | The secret access key for your storage service. | Yes | `your-secret-access-key` |
| `AWS_ENDPOINT_URL_S3` | The endpoint URL of your S3 compatible storage provider. | Yes | `https://s3.us-east-1.amazonaws.com` |
| `PRESIGNED_URL_EXPIRES_IN` | Duration in hours before generated presigned download URLs expire. | No | `5` |
| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | Duration in hours before generated presigned upload URLs expire. Falls back to `PRESIGNED_URL_EXPIRES_IN` if unset. | No | `12` |
| Variable | Description | Required | Default / Example |
| :-------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------- | :------- | :----------------------------------- |
| `STORAGE_BACKEND` | Set to `s3` to enable S3 compatible storage. | Yes | `s3` |
| `S3_BUCKET` | The name of the S3 bucket where files will be stored. | Yes | `shumai-bucket` |
| `S3_REGION` | The region of your S3 bucket. | No | `auto` |
| `S3_ACCESS_KEY_ID` | The access key ID for your storage service. | Yes | `your-access-key-id` |
| `S3_SECRET_ACCESS_KEY` | The secret access key for your storage service. | Yes | `your-secret-access-key` |
| `AWS_ENDPOINT_URL_S3` | The endpoint URL of your S3 compatible storage provider. | Yes | `https://s3.us-east-1.amazonaws.com` |
| `PRESIGNED_URL_EXPIRES_IN` | Duration in hours (decimals supported, e.g. `0.5`) before generated presigned download URLs expire. | No | `12` |
| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | Duration in hours (decimals supported, e.g. `0.5`) before generated presigned upload URLs expire. Falls back to `PRESIGNED_URL_EXPIRES_IN` if unset. | No | `12` |
---
+10 -10
View File
@@ -38,16 +38,16 @@ Shumai 通过环境变量配置。可以在应用工作区根目录的 `.env`
Shumai 支持将文件存储在本地文件系统或兼容 S3 的对象存储中。
| 变量 | 说明 | 示例 / 默认值 |
| :-------------------------------- | :------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------- |
| `STORAGE_BACKEND` | 存储类型。使用 `local` 表示本地文件系统存储,使用 `s3` 表示兼容 S3 的云对象存储。 | `local`(默认)或 `s3` |
| `AWS_ENDPOINT_URL_S3` | S3 存储或本地存储的服务端点。浏览器据此生成文件上传链接。在远程部署或使用自定义端口时,必须包含端口号。 | `http://localhost:3000`(未设置时回退至 `SHUMAI_SERVER_PORT`) |
| `S3_BUCKET` | S3 存储桶名称。 | `shumai`(默认) |
| `S3_ACCESS_KEY_ID` | S3 访问凭据 Access Key ID。 | `minioadmin`(默认) |
| `S3_SECRET_ACCESS_KEY` | S3 访问凭据 Secret Access Key。 | `minioadmin`(默认) |
| `S3_REGION` | S3 存储区域。 | `auto`(默认) |
| `PRESIGNED_URL_EXPIRES_IN` | 生成的预签名下载链接的有效时长(单位:小时)。 | `5`(默认) |
| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | 生成的预签名上传链接的有效时长(单位:小时)。未设置时回退至 `PRESIGNED_URL_EXPIRES_IN`。 | `12`(默认) |
| 变量 | 说明 | 示例 / 默认值 |
| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------- |
| `STORAGE_BACKEND` | 存储类型。使用 `local` 表示本地文件系统存储,使用 `s3` 表示兼容 S3 的云对象存储。 | `local`(默认)或 `s3` |
| `AWS_ENDPOINT_URL_S3` | S3 存储或本地存储的服务端点。浏览器据此生成文件上传链接。在远程部署或使用自定义端口时,必须包含端口号。 | `http://localhost:3000`(未设置时回退至 `SHUMAI_SERVER_PORT`) |
| `S3_BUCKET` | S3 存储桶名称。 | `shumai`(默认) |
| `S3_ACCESS_KEY_ID` | S3 访问凭据 Access Key ID。 | `minioadmin`(默认) |
| `S3_SECRET_ACCESS_KEY` | S3 访问凭据 Secret Access Key。 | `minioadmin`(默认) |
| `S3_REGION` | S3 存储区域。 | `auto`(默认) |
| `PRESIGNED_URL_EXPIRES_IN` | 生成的预签名下载链接的有效时长(单位:小时,支持小数如 `0.5`),同时适用于本地与 S3 存储。 | `12`(默认) |
| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | 生成的预签名上传链接的有效时长(单位:小时,支持小数如 `0.5`)。未设置时回退至 `PRESIGNED_URL_EXPIRES_IN`,同时适用于本地与 S3 存储。 | `12`(默认) |
### 本地存储端口配置
+10 -10
View File
@@ -13,16 +13,16 @@ Shumai 采用 Bun 原生高性能 S3 客户端存储与分发创意资产。借
若要启用兼容 S3 的存储,请在 `.env` 文件或 Docker Compose 配置中更新以下环境变量:
| 变量名 | 说明 | 必填 | 默认值 / 示例 |
| :-------------------------------- | :------------------------------------------------------------------------------------------ | :--- | :----------------------------------- |
| `STORAGE_BACKEND` | 设为 `s3` 以启用兼容 S3 的存储后端。 | 是 | `s3` |
| `S3_BUCKET` | 存放文件的 S3 存储桶名称。 | 是 | `shumai-bucket` |
| `S3_REGION` | S3 存储桶所在地域(Region)。 | 否 | `auto` |
| `S3_ACCESS_KEY_ID` | 存储服务的访问密钥 ID(Access Key ID)。 | 是 | `your-access-key-id` |
| `S3_SECRET_ACCESS_KEY` | 存储服务的私有访问密钥(Secret Access Key)。 | 是 | `your-secret-access-key` |
| `AWS_ENDPOINT_URL_S3` | 兼容 S3 的存储服务端点 URL。 | 是 | `https://s3.us-east-1.amazonaws.com` |
| `PRESIGNED_URL_EXPIRES_IN` | 生成的预签名下载链接有效期(单位:小时)。 | 否 | `5` |
| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | 生成的预签名上传链接有效期(单位:小时)。若未指定,则回退继承 `PRESIGNED_URL_EXPIRES_IN`。 | 否 | `12` |
| 变量名 | 说明 | 必填 | 默认值 / 示例 |
| :-------------------------------- | :------------------------------------------------------------------------------------------------------------ | :--- | :----------------------------------- |
| `STORAGE_BACKEND` | 设为 `s3` 以启用兼容 S3 的存储后端。 | 是 | `s3` |
| `S3_BUCKET` | 存放文件的 S3 存储桶名称。 | 是 | `shumai-bucket` |
| `S3_REGION` | S3 存储桶所在地域(Region)。 | 否 | `auto` |
| `S3_ACCESS_KEY_ID` | 存储服务的访问密钥 ID(Access Key ID)。 | 是 | `your-access-key-id` |
| `S3_SECRET_ACCESS_KEY` | 存储服务的私有访问密钥(Secret Access Key)。 | 是 | `your-secret-access-key` |
| `AWS_ENDPOINT_URL_S3` | 兼容 S3 的存储服务端点 URL。 | 是 | `https://s3.us-east-1.amazonaws.com` |
| `PRESIGNED_URL_EXPIRES_IN` | 生成的预签名下载链接有效期(单位:小时,支持小数如 `0.5`)。 | 否 | `12` |
| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | 生成的预签名上传链接有效期(单位:小时,支持小数如 `0.5`)。若未指定,则回退继承 `PRESIGNED_URL_EXPIRES_IN`。 | 否 | `12` |
---
+1 -1
View File
@@ -22,7 +22,7 @@ const baseNamingConvention = [
filter: {
// Allow CSS variables, common HTTP headers, library-specific names, paths, and hyphenated/numeric keys
regex:
'^(Authorization|Content-Type|Accept|--.*|string_contains|disableCSRFCheck|X-Frameio-.*|/.*|field-.*|class-name|icon-.*|[0-9]+|@typescript-eslint/.*|Variables|Read|Edit|Admin|Bucket|Key|Body|ContentLength|ContentType|Prefix|ContinuationToken|Signature|CopySource|Delete|Objects|Quiet|ResponseContentDisposition|UploadId|PartNumber)$',
'^(Authorization|Content-Type|Accept|--.*|string_contains|disableCSRFCheck|X-Frameio-.*|/.*|field-.*|class-name|icon-.*|[0-9]+|@typescript-eslint/.*|Variables|Read|Edit|Admin|Bucket|Key|Body|ContentLength|ContentType|Prefix|ContinuationToken|Signature|Expires|CopySource|Delete|Objects|Quiet|ResponseContentDisposition|UploadId|PartNumber)$',
match: false,
},
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "shumai",
"version": "0.7.0",
"version": "0.7.1",
"private": true,
"type": "module",
"repository": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/agent",
"version": "0.7.0",
"version": "0.7.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+334 -121
View File
@@ -1,37 +1,25 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import {
generateTextEmbeddingActivity,
extractAiMetadataActivity,
getEmbeddingContextActivity,
saveAssetEmbeddingsActivity,
deleteAssetEmbeddingsActivity,
generateImageEmbeddingActivity,
generateVideoChunkEmbeddingActivity,
getGemmaEmbeddingTargetFrameCount,
transcodeVideoChunksActivity,
} from './ai'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/core'
import { prisma, AssetType, AssetStatus } from '@shumai/db'
import { prisma, AssetType, AssetStatus, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import {
DBOSError,
registerLocalTaskAbortController,
unregisterLocalTaskAbortController,
workflowService,
} from '@shumai/workflow-core'
import sharp from 'sharp'
vi.mock('fs', async (importOriginal) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- importOriginal returns the raw fs module, typed dynamically as any here
const actual = await importOriginal<any>()
const mockRead = vi.fn((path, options) => {
if (typeof path === 'string' && (path.includes('video-chunk') || path.includes('out1.webp'))) {
return Buffer.from('chunk-data')
}
return actual.readFileSync(path, options)
})
return {
...actual,
writeFileSync: vi.fn(),
readFileSync: mockRead,
unlinkSync: vi.fn(),
}
})
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
getObject: vi.fn(),
@@ -39,35 +27,11 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
headObject: vi.fn(),
listObjects: vi.fn(),
downloadToFile: vi.fn(),
deleteObject: vi.fn(),
resolveInput: vi.fn().mockImplementation(async (_bucket, key) => `https://mock-storage/${key}`),
},
}))
vi.mock('@shumai/core/src/transcode/transcode', () => ({
transcodeService: {
extractVideoFrames: vi.fn(),
createTempDir: vi.fn().mockReturnValue('/tmp'),
removeDir: vi.fn(),
},
}))
vi.mock('child_process', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock functions dynamically return varying types based on test command calls
const execFileMock: any = vi.fn((file: any, args: any, cb: any) => {
cb(null, '120.0\n', '')
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock functions dynamically return varying types based on test command calls
execFileMock[Symbol.for('nodejs.util.promisify.custom')] = vi.fn(async (file: any) => {
if (file === 'ffprobe') {
return { stdout: '120.0\n', stderr: '' }
}
return { stdout: '', stderr: '' }
})
return {
execFile: execFileMock,
}
})
const mockEmbedContent = vi.fn().mockResolvedValue({
embeddings: [
{
@@ -503,82 +467,6 @@ describe('AI Activities Unit Tests', () => {
}),
).rejects.toThrow('is empty (0 bytes)')
})
describe('extractAiMetadataActivity', () => {
it('should return existing images if they are already in S3 storage', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock returned object cast as any due to partial implementation
vi.mocked(s3Service.headObject).mockResolvedValue({} as any)
vi.mocked(s3Service.listObjects).mockResolvedValue([
'project/ai_metadata/1.webp',
'project/ai_metadata/2.webp',
])
const res = await extractAiMetadataActivity({
assetKey: 'project/video.mp4',
filePath: '/tmp/video.mp4',
type: 'autofill',
isImage: false,
})
expect(res).toEqual(['project/ai_metadata/1.webp', 'project/ai_metadata/2.webp'])
expect(s3Service.headObject).toHaveBeenCalledWith('shumai', 'project/ai_metadata/1.webp')
expect(transcodeService.extractVideoFrames).not.toHaveBeenCalled()
})
it('should extract frames and upload to S3 if not already present', async () => {
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not Found'))
vi.mocked(transcodeService.extractVideoFrames).mockResolvedValue(['/tmp/out1.webp'])
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock returned object cast as any due to partial implementation
vi.mocked(s3Service.putObject).mockResolvedValue({} as any)
const res = await extractAiMetadataActivity({
assetKey: 'project/video.mp4',
filePath: '/tmp/video.mp4',
type: 'autofill',
isImage: false,
})
expect(res).toEqual(['project/ai_metadata/out1.webp'])
expect(transcodeService.extractVideoFrames).toHaveBeenCalledWith({
inputFile: '/tmp/video.mp4',
outputDir: '/tmp',
numFrames: 30,
frameHeight: 720,
isImage: false,
})
expect(s3Service.putObject).toHaveBeenCalledWith(
'shumai',
'project/ai_metadata/out1.webp',
expect.any(Buffer),
expect.any(Number),
'image/webp',
)
})
it('should resolveInput from s3Service when filePath is not provided', async () => {
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not Found'))
vi.mocked(s3Service.resolveInput).mockResolvedValue('https://mock-storage/project/video.mp4')
vi.mocked(transcodeService.extractVideoFrames).mockResolvedValue(['/tmp/out1.webp'])
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(s3Service.putObject).mockResolvedValue({} as any)
const res = await extractAiMetadataActivity({
assetKey: 'project/video.mp4',
type: 'autofill',
isImage: false,
})
expect(res).toEqual(['project/ai_metadata/out1.webp'])
expect(s3Service.resolveInput).toHaveBeenCalledWith('shumai', 'project/video.mp4')
expect(transcodeService.extractVideoFrames).toHaveBeenCalledWith({
inputFile: 'https://mock-storage/project/video.mp4',
outputDir: expect.any(String),
numFrames: 30,
frameHeight: 720,
isImage: false,
})
})
})
})
describe('AI Database Activities Integration', () => {
@@ -887,4 +775,329 @@ describe('AI Database Activities Integration', () => {
expect(after).toHaveLength(0)
})
})
describe('transcodeVideoChunksActivity', () => {
afterEach(() => {
delete process.env.EMBEDDING_TRANSCODE_WAIT_TIMEOUT_MS
})
it('should create a transcode_video_chunks WorkflowTask and await completion', async () => {
const waitForSpy = vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => ({
done: true,
task: {
...task,
status: WorkflowTaskStatus.completed,
output: {
chunks: [
{
startTime: 0,
endTime: 60,
chunkKey: `files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
},
],
},
},
}))
const res = await transcodeVideoChunksActivity({
parentTaskId: 'parent-123',
teamId: team.id,
projectId: 'proj-123',
assetId: asset.id,
assetKey: 'media/video.mp4',
format: 'video',
chunks: [{ startTime: 0, endTime: 60 }],
})
expect(res.chunks).toEqual([
{
startTime: 0,
endTime: 60,
chunkKey: `files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
},
])
expect(waitForSpy).toHaveBeenCalledTimes(1)
expect(waitForSpy).toHaveBeenCalledWith(
expect.objectContaining({
assetId: asset.id,
type: WorkflowTaskType.transcode_video_chunks,
}),
60 * 60 * 1000,
)
const createdTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode_video_chunks },
})
expect(createdTask).toBeDefined()
expect(createdTask?.payload?.videoChunks).toEqual({
parentTaskId: 'parent-123',
assetKey: 'media/video.mp4',
format: 'video',
chunks: [{ startTime: 0, endTime: 60 }],
})
})
it('should honor custom EMBEDDING_TRANSCODE_WAIT_TIMEOUT_MS env var', async () => {
process.env.EMBEDDING_TRANSCODE_WAIT_TIMEOUT_MS = '12345'
const waitForSpy = vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => ({
done: true,
task: {
...task,
status: WorkflowTaskStatus.completed,
output: {
chunks: [
{
startTime: 0,
endTime: 60,
chunkKey: `files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
},
],
},
},
}))
await transcodeVideoChunksActivity({
parentTaskId: 'parent-timeout-env',
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
})
expect(waitForSpy).toHaveBeenCalledWith(expect.anything(), 12345)
})
it('should reuse an existing transcode_video_chunks task with the same parentTaskId on retry', async () => {
const existingChild = await prisma.workflowTask.create({
data: {
assetId: asset.id,
teamId: team.id,
type: WorkflowTaskType.transcode_video_chunks,
status: WorkflowTaskStatus.processing,
payload: {
projectId: '',
videoChunks: {
parentTaskId: 'parent-retry-1',
assetKey: 'media/video.mp4',
format: 'video',
chunks: [{ startTime: 0, endTime: 60 }],
},
},
},
})
const waitForSpy = vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => ({
done: true,
task: {
...task,
status: WorkflowTaskStatus.completed,
output: {
chunks: [
{
startTime: 0,
endTime: 60,
chunkKey: `files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
},
],
},
},
}))
await transcodeVideoChunksActivity({
parentTaskId: 'parent-retry-1',
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
format: 'video',
chunks: [{ startTime: 0, endTime: 60 }],
})
expect(waitForSpy).toHaveBeenCalledWith(
expect.objectContaining({ id: existingChild.id }),
expect.any(Number),
)
const count = await prisma.workflowTask.count({
where: { assetId: asset.id, type: WorkflowTaskType.transcode_video_chunks },
})
expect(count).toBe(1)
})
it('should return empty chunks immediately when chunks array is empty', async () => {
const waitForSpy = vi.spyOn(workflowService, 'waitFor')
const res = await transcodeVideoChunksActivity({
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [],
})
expect(res.chunks).toEqual([])
expect(waitForSpy).not.toHaveBeenCalled()
})
it('should throw non-retryable ApplicationFailure when assetKey is empty', async () => {
await expect(
transcodeVideoChunksActivity({
assetId: asset.id,
assetKey: '',
chunks: [{ startTime: 0, endTime: 60 }],
}),
).rejects.toThrow('assetKey is required for video chunks transcoding')
})
it('should wrap child task failure as non-retryable ApplicationFailure to avoid duplicate child tasks', async () => {
vi.spyOn(workflowService, 'waitFor').mockRejectedValue(
new Error(
'Original video file is archived and no proxy is available. Restore the asset to generate embeddings.',
),
)
expect.assertions(2)
try {
await transcodeVideoChunksActivity({
parentTaskId: 'parent-child-fail',
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
})
} catch (err: unknown) {
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
expect((err as Error).message).toContain('Original video file is archived')
}
})
it('should cancel child task and throw non-retryable ApplicationFailure on timeout', async () => {
const cancelSpy = vi.spyOn(workflowService, 'cancel').mockResolvedValue(undefined)
vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => ({
done: false,
task,
}))
expect.assertions(4)
try {
await transcodeVideoChunksActivity({
parentTaskId: 'parent-timeout-fail',
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
})
} catch (err: unknown) {
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
expect((err as Error).message).toContain('timed out')
}
const childTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode_video_chunks },
})
expect(cancelSpy).toHaveBeenCalledWith(childTask!.id)
expect(childTask?.status).toBe(WorkflowTaskStatus.failed)
})
it('should throw non-retryable ApplicationFailure when completed child task has invalid chunks output', async () => {
vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => ({
done: true,
task: {
...task,
status: WorkflowTaskStatus.completed,
output: {},
},
}))
expect.assertions(2)
try {
await transcodeVideoChunksActivity({
parentTaskId: 'parent-invalid-output',
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
})
} catch (err: unknown) {
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
expect((err as Error).message).toContain('completed without valid chunks output')
}
})
it('should cancel child transcode_video_chunks task when parent workflow is cancelled', async () => {
const parentTaskId = 'parent-cancel-test'
const abortController = new AbortController()
registerLocalTaskAbortController(parentTaskId, abortController)
const cancelSpy = vi.spyOn(workflowService, 'cancel').mockResolvedValue(undefined)
vi.spyOn(workflowService, 'waitFor').mockImplementation(async () => {
abortController.abort()
throw new DBOSError.DBOSWorkflowCancelledError(parentTaskId)
})
try {
await expect(
transcodeVideoChunksActivity({
parentTaskId,
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
}),
).rejects.toThrow()
const childTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode_video_chunks },
})
expect(childTask).toBeDefined()
expect(cancelSpy).toHaveBeenCalledWith(childTask!.id)
expect(childTask?.status).toBe(WorkflowTaskStatus.failed)
} finally {
unregisterLocalTaskAbortController(parentTaskId)
}
})
it('should clean up uploaded chunks from S3 if parent workflow is cancelled just as child completes', async () => {
const parentTaskId = 'parent-cancel-race'
const abortController = new AbortController()
registerLocalTaskAbortController(parentTaskId, abortController)
vi.spyOn(workflowService, 'cancel').mockResolvedValue(undefined)
vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => {
abortController.abort()
return {
done: true,
task: {
...task,
status: WorkflowTaskStatus.completed,
output: {
chunks: [
{
startTime: 0,
endTime: 60,
chunkKey: `files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
},
],
},
},
}
})
try {
await expect(
transcodeVideoChunksActivity({
parentTaskId,
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
}),
).rejects.toThrow('Parent embedding workflow was cancelled before transcode completed')
expect(s3Service.deleteObject).toHaveBeenCalledWith(
'shumai',
`files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
)
} finally {
unregisterLocalTaskAbortController(parentTaskId)
}
})
})
})
+163 -213
View File
@@ -1,18 +1,16 @@
import { GoogleGenAI } from '@google/genai'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/core'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import { execFile } from 'child_process'
import { promisify } from 'util'
import { ulid } from 'ulid'
import { ApplicationFailure, defineStep } from '@shumai/workflow-core'
import { prisma } from '@shumai/db'
import { textEmbeddingService } from '@shumai/core/src/search/text-embedding'
import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import {
ApplicationFailure,
defineStep,
getLocalTaskAbortSignal,
isDbosWorkflowCancelledError,
workflowService,
} from '@shumai/workflow-core'
import sharp from 'sharp'
const execFileAsync = promisify(execFile)
export interface Usage {
inputTokens: number
outputTokens: number
@@ -111,8 +109,6 @@ async function callGemmaEmbeddingServer(input: string | OpenAiEmbeddingItem[]):
}
}
import { textEmbeddingService } from '@shumai/core/src/search/text-embedding'
export interface GenerateTextEmbeddingParams {
text: string
teamId: string
@@ -157,66 +153,6 @@ export const generateTextEmbeddingActivity = defineStep(
},
)
export interface ExtractAiMetadataParams {
assetKey: string
filePath?: string
type: 'autofill'
isImage: boolean
}
export const extractAiMetadataActivity = defineStep(async function extractAiMetadataActivity(
params: ExtractAiMetadataParams,
): Promise<string[]> {
const bucket = process.env.S3_BUCKET || 'shumai'
const assetDir = path.dirname(params.assetKey)
const aiDir = path.join(assetDir, 'ai_metadata')
const generatedFiles: string[] = []
let tmpDir = params.filePath ? path.dirname(params.filePath) : ''
let cleanupTmp = false
if (!tmpDir) {
tmpDir = transcodeService.createTempDir('ai-meta-')
cleanupTmp = true
}
try {
if (params.type === 'autofill') {
const targetKey = path.join(aiDir, '1.webp')
try {
await s3Service.headObject(bucket, targetKey)
const keys = await s3Service.listObjects(bucket, aiDir)
return keys.filter((k) => k.toLowerCase().endsWith('.webp'))
} catch {
// Not found
}
const inputSource = params.filePath || (await s3Service.resolveInput(bucket, params.assetKey))
const files = await transcodeService.extractVideoFrames({
inputFile: inputSource,
outputDir: tmpDir,
numFrames: 30,
frameHeight: 720,
isImage: params.isImage,
})
for (const file of files) {
const name = path.basename(file)
const buffer = fs.readFileSync(file)
const key = path.join(aiDir, name)
await s3Service.putObject(bucket, key, buffer, buffer.length, 'image/webp')
generatedFiles.push(key)
}
}
} finally {
if (cleanupTmp && tmpDir) {
transcodeService.removeDir(tmpDir)
}
}
return generatedFiles
})
export const getEmbeddingContextActivity = defineStep(
async function getEmbeddingContextActivity(params: { teamId: string; assetId: string }) {
const team = await prisma.team.findUnique({
@@ -315,6 +251,7 @@ export const saveAssetEmbeddingsActivity = defineStep(
embedding: number[]
startTime?: number
endTime?: number
sprite?: PrismaJson.VideoChunkSprite
}>
}) {
for (const item of params.embeddings) {
@@ -322,15 +259,16 @@ export const saveAssetEmbeddingsActivity = defineStep(
const is768 = item.embedding.length === 768
if (item.startTime !== undefined && item.endTime !== undefined) {
const sprite = item.sprite ? JSON.stringify(item.sprite) : null
if (is768) {
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding_768, start_time, end_time, updated_at)
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, NOW())
INSERT INTO asset_embeddings (id, asset_id, embedding_768, start_time, end_time, sprite, updated_at)
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, ${sprite}::jsonb, NOW())
`
} else {
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, updated_at)
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, NOW())
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, sprite, updated_at)
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, ${sprite}::jsonb, NOW())
`
}
} else {
@@ -569,168 +507,180 @@ export const generateVideoChunkEmbeddingActivity = defineStep(
},
)
export interface TranscodeVideoChunkParams {
assetId: string
assetKey?: string
filePath?: string
export interface VideoChunkRange {
startTime: number
endTime: number
format?: 'video' | 'frames'
}
export const transcodeVideoChunkActivity = defineStep(async function transcodeVideoChunkActivity(
params: TranscodeVideoChunkParams,
): Promise<{ chunkKey: string }> {
if (!params.filePath && !params.assetKey) {
export interface TranscodedVideoChunk extends VideoChunkRange {
chunkKey: string
sprite?: PrismaJson.VideoChunkSprite
}
export interface TranscodeVideoChunksParams {
parentTaskId?: string
teamId?: string | null
projectId?: string | null
assetId: string
assetKey: string
format?: 'video' | 'frames'
chunks: VideoChunkRange[]
}
const DEFAULT_TRANSCODE_WAIT_TIMEOUT_MS = 60 * 60 * 1000 // 60 minutes
function getTranscodeWaitTimeoutMs(): number {
const parsed = parseInt(process.env.EMBEDDING_TRANSCODE_WAIT_TIMEOUT_MS || '', 10)
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_TRANSCODE_WAIT_TIMEOUT_MS
}
async function cancelChildTranscodeTask(childTaskId: string): Promise<void> {
try {
await workflowService.cancel(childTaskId)
} catch {
// Ignore DBOS cancel errors during cleanup
}
try {
await prisma.workflowTask.updateMany({
where: {
id: childTaskId,
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
data: {
status: WorkflowTaskStatus.failed,
output: { error: 'Parent embedding workflow was cancelled' },
},
})
} catch {
// Ignore DB update errors during cleanup
}
}
export const transcodeVideoChunksActivity = defineStep(async function transcodeVideoChunksActivity(
params: TranscodeVideoChunksParams,
): Promise<{ chunks: TranscodedVideoChunk[] }> {
if (!params.assetKey) {
throw ApplicationFailure.create({
message: 'Neither filePath nor assetKey was provided for video chunk transcoding',
message: 'assetKey is required for video chunks transcoding',
nonRetryable: true,
})
}
if (params.format === 'frames') {
const tmpDir = transcodeService.createTempDir('video-chunk-frames-')
try {
const bucket = process.env.S3_BUCKET || 'shumai'
const inputSource =
params.filePath ||
(params.assetKey ? await s3Service.resolveInput(bucket, params.assetKey) : '')
if (!inputSource) {
throw ApplicationFailure.create({
message: 'Neither filePath nor assetKey was provided for video chunk transcoding',
nonRetryable: true,
})
}
const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://')
const duration = Math.max(0.1, params.endTime - params.startTime)
const fpsFilter = duration > 16 ? `fps=${16 / duration}` : 'fps=1'
const vframesArgs = duration > 16 ? ['-vframes', '16'] : []
await execFileAsync('ffmpeg', [
'-y',
'-loglevel',
'warning',
...(isRemote
? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5']
: []),
'-ss',
params.startTime.toString(),
'-i',
inputSource,
'-map',
'0:V:0',
'-t',
duration.toString(),
'-vf',
fpsFilter,
...vframesArgs,
'-q:v',
'2',
path.join(tmpDir, 'frame_%04d.jpg'),
])
const frameFiles = fs
.readdirSync(tmpDir)
.filter((f) => /\.(jpe?g|png|webp)$/i.test(f))
.sort()
const archiveEntries: Record<string, Buffer> = {}
for (const file of frameFiles) {
archiveEntries[file] = fs.readFileSync(path.join(tmpDir, file))
}
const archive = new Bun.Archive(archiveEntries)
const archiveBytes = await archive.bytes()
const archiveData = Buffer.from(
archiveBytes.buffer,
archiveBytes.byteOffset,
archiveBytes.byteLength,
)
const key = `files/${params.assetId}/tmp-embedding-chunks/frames-${params.startTime}-${params.endTime}-${ulid()}.tar`
await s3Service.putObject(bucket, key, archiveData, archiveData.length, 'application/x-tar')
return { chunkKey: key }
} catch (err) {
if (err instanceof ApplicationFailure) {
throw err
}
throw ApplicationFailure.create({
message: `Failed to extract video chunk frames for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
nonRetryable: false,
})
} finally {
transcodeService.removeDir(tmpDir)
}
if (!params.chunks || params.chunks.length === 0) {
return { chunks: [] }
}
const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}-${ulid()}.mp4`)
let childTask = null
if (params.parentTaskId) {
childTask = await prisma.workflowTask.findFirst({
where: {
assetId: params.assetId,
type: WorkflowTaskType.transcode_video_chunks,
status: {
in: [
WorkflowTaskStatus.pending,
WorkflowTaskStatus.processing,
WorkflowTaskStatus.completed,
],
},
payload: {
path: ['videoChunks', 'parentTaskId'],
equals: params.parentTaskId,
},
},
orderBy: { id: 'desc' },
})
}
if (!childTask) {
childTask = await prisma.workflowTask.create({
data: {
assetId: params.assetId,
teamId: params.teamId ?? null,
projectId: params.projectId ?? null,
type: WorkflowTaskType.transcode_video_chunks,
status: WorkflowTaskStatus.pending,
payload: {
projectId: params.projectId ?? '',
videoChunks: {
parentTaskId: params.parentTaskId,
assetKey: params.assetKey,
format: params.format,
chunks: params.chunks,
},
},
},
})
}
const abortSignal = getLocalTaskAbortSignal(params.parentTaskId)
if (abortSignal?.aborted) {
await cancelChildTranscodeTask(childTask.id)
throw ApplicationFailure.create({
message: 'Parent embedding workflow was cancelled before transcode completed',
nonRetryable: true,
})
}
const onAbort = () => {
void cancelChildTranscodeTask(childTask.id)
}
abortSignal?.addEventListener('abort', onAbort, { once: true })
try {
const bucket = process.env.S3_BUCKET || 'shumai'
const inputSource =
params.filePath ||
(params.assetKey ? await s3Service.resolveInput(bucket, params.assetKey) : '')
if (!inputSource) {
const { task: completedTask, done } = await workflowService.waitFor(
childTask,
getTranscodeWaitTimeoutMs(),
)
if (!done) {
await cancelChildTranscodeTask(childTask.id)
throw ApplicationFailure.create({
message: 'Neither filePath nor assetKey was provided for video chunk transcoding',
message: `Transcode video chunks task ${childTask.id} timed out`,
nonRetryable: true,
})
}
const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://')
// Slice video segment using ffmpeg, force 1fps and remove audio for gemini-embedding-2 optimization
// Note: -ss placed before -i for fast input seeking via demuxer Range requests
await execFileAsync('ffmpeg', [
'-y',
'-loglevel',
'warning',
...(isRemote
? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5']
: []),
'-ss',
params.startTime.toString(),
'-i',
inputSource,
'-map',
'0:V:0',
'-t',
(params.endTime - params.startTime).toString(),
'-vf',
'fps=1',
'-c:v',
'libx264',
'-preset',
'ultrafast',
'-crf',
'28',
'-an',
chunkTmp,
])
const output = completedTask.output as { chunks?: TranscodedVideoChunk[] } | null
if (!output?.chunks || !Array.isArray(output.chunks)) {
throw ApplicationFailure.create({
message: `Transcode video chunks task ${childTask.id} completed without valid chunks output`,
nonRetryable: true,
})
}
const chunkData = fs.readFileSync(chunkTmp)
if (abortSignal?.aborted) {
const bucket = process.env.S3_BUCKET || 'shumai'
for (const chunk of output.chunks) {
try {
await s3Service.deleteObject(bucket, chunk.chunkKey)
} catch {
// Best-effort cleanup on cancellation race
}
}
throw ApplicationFailure.create({
message: 'Parent embedding workflow was cancelled before transcode completed',
nonRetryable: true,
})
}
// Upload to S3
const key = `files/${params.assetId}/tmp-embedding-chunks/chunk-${params.startTime}-${params.endTime}-${ulid()}.mp4`
await s3Service.putObject(bucket, key, chunkData, chunkData.length, 'video/mp4')
return { chunkKey: key }
return { chunks: output.chunks }
} catch (err) {
if (abortSignal?.aborted || isDbosWorkflowCancelledError(err)) {
await cancelChildTranscodeTask(childTask.id)
throw err
}
if (err instanceof ApplicationFailure) {
throw err
}
// The child transcode workflow already applies its own step retry policy;
// fail fast here instead of spawning duplicate child tasks on parent retries.
throw ApplicationFailure.create({
message: `Failed to transcode video chunk for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
nonRetryable: false,
message: err instanceof Error ? err.message : String(err),
nonRetryable: true,
cause: err instanceof Error ? err : undefined,
})
} finally {
if (fs.existsSync(chunkTmp)) {
try {
fs.unlinkSync(chunkTmp)
} catch (e) {
console.error('Failed to cleanup local chunk file:', e)
}
}
abortSignal?.removeEventListener('abort', onAbort)
}
})
+4 -2
View File
@@ -13,15 +13,17 @@ export function initAgentWorkflows() {
export * from './activities/agent'
export {
deleteAssetEmbeddingsActivity,
extractAiMetadataActivity,
generateImageEmbeddingActivity,
generateTextEmbeddingActivity,
generateVideoChunkEmbeddingActivity,
saveAssetEmbeddingsActivity,
transcodeVideoChunksActivity,
type ExistingAssetEmbeddingInfo,
type ExtractAiMetadataParams,
type GeneratedEmbedding,
type GenerateTextEmbeddingParams,
type TranscodedVideoChunk,
type TranscodeVideoChunksParams,
type VideoChunkRange,
} from './activities/ai'
export * from './context/serialize-context'
export * from './operation-tools'
@@ -34,7 +34,7 @@ vi.mock('../activities/ai', async () => {
generateVideoChunkEmbeddingActivity: vi.fn(),
saveAssetEmbeddingsActivity: vi.fn(),
deleteAssetEmbeddingsActivity: vi.fn(),
transcodeVideoChunkActivity: vi.fn(),
transcodeVideoChunksActivity: vi.fn(),
deleteS3ObjectActivity: vi.fn(),
}
})
@@ -60,9 +60,7 @@ describe('Agent Embedding Workflow', () => {
updateTaskUsageActivity: vi.mocked(workflowCore.updateTaskUsageActivity),
createCommentActivity: vi.mocked(agentActivities.createCommentActivity),
updateCommentActivity: vi.mocked(agentActivities.updateCommentActivity),
downloadMediaToTmpActivity: vi.fn(),
cleanupTmpDirActivity: vi.fn(),
transcodeVideoChunkActivity: vi.mocked(aiActivities.transcodeVideoChunkActivity),
transcodeVideoChunksActivity: vi.mocked(aiActivities.transcodeVideoChunksActivity),
deleteS3ObjectActivity: vi.mocked(aiActivities.deleteS3ObjectActivity),
}
@@ -86,19 +84,21 @@ describe('Agent Embedding Workflow', () => {
embedding: [0.3, 0.4],
usage: { inputTokens: 3, outputTokens: 3, model: 'gpt' },
})
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
filePath: '/tmp/test.mp4',
tmpDir: '/tmp/test-dir',
})
mockActivities.transcodeVideoChunkActivity.mockImplementation(
async (params: { assetId: string; startTime: number; endTime: number }) => {
mockActivities.transcodeVideoChunksActivity.mockImplementation(
async (params: {
assetId: string
chunks: Array<{ startTime: number; endTime: number }>
}) => {
return {
chunkKey: `files/${params.assetId}/tmp-embedding-chunks/chunk-${params.startTime}-${params.endTime}.mp4`,
chunks: params.chunks.map((c) => ({
startTime: c.startTime,
endTime: c.endTime,
chunkKey: `files/${params.assetId}/tmp-embedding-chunks/chunk-${c.startTime}-${c.endTime}.mp4`,
})),
}
},
)
mockActivities.deleteS3ObjectActivity.mockResolvedValue(undefined)
mockActivities.cleanupTmpDirActivity.mockResolvedValue(undefined)
})
it('should run agent embedding workflow successfully for image', async () => {
@@ -256,7 +256,7 @@ describe('Agent Embedding Workflow', () => {
)
})
it('should run agent embedding workflow successfully for video in chunks', async () => {
it('should run agent embedding workflow successfully for video in chunks via single batch transcode task', async () => {
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: {
@@ -278,6 +278,7 @@ describe('Agent Embedding Workflow', () => {
status: 'pending',
assetId: 'a1',
teamId: 't1',
projectId: 'p1',
payload: {
projectId: 'p1',
agent: { sessionId: 's1', agentId: 'agent-1' },
@@ -287,28 +288,20 @@ describe('Agent Embedding Workflow', () => {
await agentEmbeddingMedia(task)
// Verify video chunk slicing activity called 3 times on transcode queue
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(3)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(1, {
// Verify batch video chunk slicing activity called once on transcode queue with all 3 chunks
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledTimes(1)
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledWith({
parentTaskId: task.id,
teamId: 't1',
projectId: 'p1',
assetId: 'a1',
assetKey: 'test-transcoded.mp4',
startTime: 0,
endTime: 60,
format: 'video',
})
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(2, {
assetId: 'a1',
assetKey: 'test-transcoded.mp4',
startTime: 55,
endTime: 115,
format: 'video',
})
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(3, {
assetId: 'a1',
assetKey: 'test-transcoded.mp4',
startTime: 110,
endTime: 150,
format: 'video',
chunks: [
{ startTime: 0, endTime: 60 },
{ startTime: 55, endTime: 115 },
{ startTime: 110, endTime: 150 },
],
})
// Verify video chunk embedding generation (3 chunks) on agent queue
@@ -401,6 +394,7 @@ describe('Agent Embedding Workflow', () => {
await agentEmbeddingMedia(task)
expect(mockActivities.transcodeVideoChunksActivity).not.toHaveBeenCalled()
expect(mockActivities.saveAssetEmbeddingsActivity).not.toHaveBeenCalled()
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: task.id,
@@ -469,7 +463,7 @@ describe('Agent Embedding Workflow', () => {
})
})
it('should save completed chunks to DB immediately before subsequent chunk failure', async () => {
it('should save completed chunks to DB immediately and clean up all remaining temporary S3 chunks on failure', async () => {
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: {
@@ -510,6 +504,18 @@ describe('Agent Embedding Workflow', () => {
assetId: 'a1',
embeddings: [{ embedding: [0.1, 0.2], startTime: 0, endTime: 60 }],
})
// All 3 temporary chunks (chunk 1 after success, chunk 2 and chunk 3 in finally) MUST be deleted from S3
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenCalledTimes(3)
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenNthCalledWith(1, {
key: 'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
})
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenNthCalledWith(2, {
key: 'files/a1/tmp-embedding-chunks/chunk-55-115.mp4',
})
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenNthCalledWith(3, {
key: 'files/a1/tmp-embedding-chunks/chunk-110-150.mp4',
})
})
it('should not create redundant chunks when video exactly matches chunk duration', async () => {
@@ -538,12 +544,11 @@ describe('Agent Embedding Workflow', () => {
await agentEmbeddingMedia(task)
// Verify only 1 chunk was created instead of 2 (0-60 and 55-60)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(1)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledWith(
// Verify only 1 chunk was requested instead of 2 (0-60 and 55-60)
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledTimes(1)
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledWith(
expect.objectContaining({
startTime: 0,
endTime: 60,
chunks: [{ startTime: 0, endTime: 60 }],
}),
)
})
@@ -575,11 +580,10 @@ describe('Agent Embedding Workflow', () => {
await agentEmbeddingMedia(task)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledWith(
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledWith(
expect.objectContaining({
startTime: 0,
endTime: 30,
format: 'frames',
chunks: [{ startTime: 0, endTime: 30 }],
}),
)
expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith(
@@ -626,14 +630,14 @@ describe('Agent Embedding Workflow', () => {
await agentEmbeddingMedia(task)
// Chunk 1 (0-60) should be skipped; only chunk 2 (55-115) and chunk 3 (110-150) should be transcoded and embedded
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(2)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(
1,
expect.objectContaining({ startTime: 55, endTime: 115 }),
)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(
2,
expect.objectContaining({ startTime: 110, endTime: 150 }),
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledTimes(1)
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledWith(
expect.objectContaining({
chunks: [
{ startTime: 55, endTime: 115 },
{ startTime: 110, endTime: 150 },
],
}),
)
expect(mockActivities.saveAssetEmbeddingsActivity).toHaveBeenCalledTimes(2)
+66 -47
View File
@@ -1,3 +1,4 @@
import { logger } from '@shumai/core/src/logger'
import type { WorkflowTask } from '@shumai/db'
import {
ApplicationFailure,
@@ -12,8 +13,9 @@ import {
generateVideoChunkEmbeddingActivity,
getEmbeddingContextActivity,
saveAssetEmbeddingsActivity,
transcodeVideoChunkActivity,
transcodeVideoChunksActivity,
type ExistingAssetEmbeddingInfo,
type VideoChunkRange,
} from '../activities/ai'
export interface GeneratedEmbedding {
@@ -148,6 +150,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
const overlap = chunkOverlap ?? 5.0
const step = Math.max(1, limit - overlap)
const missingChunks: VideoChunkRange[] = []
for (let start = 0.0; start < duration; start += step) {
let end = start + limit
if (end >= duration) {
@@ -163,52 +166,8 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
Math.abs(c.endTime - end) < 0.1,
)
if (chunkExists) {
// If this chunk reached the end of the video, stop
if (end >= duration) {
break
}
continue
}
// Step A: Slice chunk on transcode worker and upload to S3
const chunkRes = await transcodeVideoChunkActivity({
assetId: asset.id,
assetKey: embeddingKey,
startTime: start,
endTime: end,
format: isGemmaProvider ? 'frames' : 'video',
})
const { chunkKey } = chunkRes
try {
// Step B: Generate embedding on agent worker
const chunkResult = await generateVideoChunkEmbeddingActivity({
teamId: task.teamId,
chunkKey,
})
// Step C: Save chunk embedding to database immediately
await saveAssetEmbeddingsActivity({
assetId: task.assetId,
embeddings: [
{
embedding: chunkResult.embedding,
startTime: start,
endTime: end,
},
],
})
if (chunkResult.usage) {
usage.inputTokens += chunkResult.usage.inputTokens || 0
usage.outputTokens += chunkResult.usage.outputTokens || 0
}
} finally {
// Step D: Delete temporary chunk from S3
await deleteS3ObjectActivity({
key: chunkKey,
})
if (!chunkExists) {
missingChunks.push({ startTime: start, endTime: end })
}
// If this chunk reached the end of the video, stop to avoid redundant overlapping chunks
@@ -216,6 +175,66 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
break
}
}
if (missingChunks.length > 0) {
// Step A: Slice all missing chunks via batch task on transcode queue and upload to S3
const { chunks: transcodedChunks } = await transcodeVideoChunksActivity({
parentTaskId: task.id,
teamId: task.teamId,
projectId: task.projectId,
assetId: asset.id,
assetKey: embeddingKey,
format: isGemmaProvider ? 'frames' : 'video',
chunks: missingChunks,
})
const remainingChunkKeys = new Set(transcodedChunks.map((c) => c.chunkKey))
try {
for (const chunk of transcodedChunks) {
// Step B: Generate embedding on agent worker
const chunkResult = await generateVideoChunkEmbeddingActivity({
teamId: task.teamId,
chunkKey: chunk.chunkKey,
})
// Step C: Save chunk embedding to database immediately
await saveAssetEmbeddingsActivity({
assetId: task.assetId,
embeddings: [
{
embedding: chunkResult.embedding,
startTime: chunk.startTime,
endTime: chunk.endTime,
...(chunk.sprite && { sprite: chunk.sprite }),
},
],
})
if (chunkResult.usage) {
usage.inputTokens += chunkResult.usage.inputTokens || 0
usage.outputTokens += chunkResult.usage.outputTokens || 0
}
// Step D: Delete temporary chunk from S3 as soon as it is embedded
await deleteS3ObjectActivity({
key: chunk.chunkKey,
})
remainingChunkKeys.delete(chunk.chunkKey)
}
} finally {
for (const key of remainingChunkKeys) {
try {
await deleteS3ObjectActivity({ key })
} catch (cleanupErr) {
logger.error(
{ taskId: task.id, chunkKey: key, err: cleanupErr },
'Failed to delete temporary chunk from S3',
)
}
}
}
}
}
// Update Usage
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/api",
"version": "0.7.0",
"version": "0.7.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+78
View File
@@ -60,6 +60,7 @@ describe('folder api', () => {
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
vi.spyOn(assetService, 'listChildren').mockImplementation(vi.fn())
vi.spyOn(searchService, 'search').mockImplementation(vi.fn())
vi.spyOn(searchService, 'searchByImage').mockResolvedValue({ data: [], pageInfo: { total: 0 } })
})
afterEach(() => {
@@ -329,6 +330,83 @@ describe('folder api', () => {
)
})
describe('POST /folders/:folderId/image-search', () => {
function request(body: Record<string, unknown>) {
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
return app.request('/folders/scope-id/image-search', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
it('checks both permissions and passes a stored image search to Core', async () => {
const res = await request({ sourceAssetId: 'image-id', mediaType: 'video', first: 20 })
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ data: [], pageInfo: { total: 0 } })
expect(vi.mocked(authzService.hasPermission).mock.calls.map(([input]) => input.id)).toEqual([
'scope-id',
'image-id',
])
expect(authzService.hasPermission).toHaveBeenLastCalledWith(
expect.objectContaining({
id: 'image-id',
permission: Permission.Read,
type: ResourceType.Asset,
}),
)
expect(searchService.searchByImage).toHaveBeenCalledWith('scope-id', {
sourceAssetId: 'image-id',
mediaType: 'video',
first: 20,
operator: 'AND',
conditions: [],
})
})
it('checks folder read access before passing image data to Core', async () => {
const conditions = [{ field: 'status', operator: 'eq', value: 'approved' }]
const res = await request({ image: 'aW1hZ2U=', conditions })
expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledTimes(1)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
id: 'scope-id',
permission: Permission.Read,
type: ResourceType.Asset,
}),
)
expect(searchService.searchByImage).toHaveBeenCalledWith('scope-id', {
image: 'aW1hZ2U=',
conditions,
operator: 'AND',
})
})
it('rejects a denied folder or source before running the search', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new HTTPException(403))
expect((await request({ image: 'aW1hZ2U=' })).status).toBe(403)
vi.mocked(authzService.hasPermission)
.mockResolvedValueOnce(undefined)
.mockRejectedValueOnce(new HTTPException(403))
expect((await request({ sourceAssetId: 'image-id' })).status).toBe(403)
expect(searchService.searchByImage).not.toHaveBeenCalled()
})
it('rejects incomplete, ambiguous, and invalid search inputs', async () => {
for (const body of [
{},
{ image: 'aW1hZ2U=', sourceAssetId: 'both' },
{ image: 'invalid!' },
{ sourceAssetId: 'image-id', mediaType: 'audio' },
]) {
expect((await request(body)).status).toBe(400)
}
expect((await request({ image: 'A'.repeat(1_600_000) })).status).toBe(413)
expect(searchService.searchByImage).not.toHaveBeenCalled()
})
})
it('PATCH /folders/:folderId/order', async () => {
vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({
id: 'test-id',
+33 -1
View File
@@ -1,5 +1,6 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { bodyLimit } from 'hono/body-limit'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { assetService } from '@shumai/core/src/asset/asset'
import { searchService } from '@shumai/core/src/search/search'
@@ -11,7 +12,11 @@ import {
updateAgentsMdRequestSchema,
} from '@shumai/dtos'
import { listChildrenRequestSchema, updateAssetOrderRequestSchema, AuditAction } from '@shumai/dtos'
import { searchRequestSchema } from '@shumai/dtos'
import {
imageSearchRequestSchema,
MAX_SEARCH_IMAGE_BASE64_LENGTH,
searchRequestSchema,
} from '@shumai/dtos'
import type { Prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import {
@@ -154,6 +159,33 @@ const route = new Hono<{ Variables: { user: User } }>()
const result = await searchService.search(folderId, req)
return c.json(result)
})
.post(
'/folders/:folderId/image-search',
bodyLimit({ maxSize: MAX_SEARCH_IMAGE_BASE64_LENGTH + 64 * 1024 }),
zValidator('json', imageSearchRequestSchema),
async (c) => {
const folderId = c.req.param('folderId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Asset,
id: folderId,
})
if (req.sourceAssetId) {
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Asset,
id: req.sourceAssetId,
})
}
return c.json(await searchService.searchByImage(folderId, req))
},
)
.get('/folders/:folderId/agentsmd', async (c) => {
const { content } = await runOperation(
getFolderInstructionsOp,
+62
View File
@@ -254,5 +254,67 @@ describe('Upload API', () => {
})
expect(res.status).toBe(404)
})
it('accepts a valid signed local upload URL', async () => {
vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('local')
const putObjectSpy = vi.spyOn(s3Module.s3Service, 'putObject').mockResolvedValue(undefined)
const signedPath = s3Module.signLocalUrl('test-bucket', 'files/test.txt')
const localPath = signedPath.replace(/^\/api/, '')
const localApp = new Hono().route('/', localUploadRoute)
const res = await localApp.request(localPath, {
method: 'PUT',
headers: { 'Content-Type': 'text/plain', 'Content-Length': '5' },
body: 'hello',
})
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ success: true })
expect(putObjectSpy).toHaveBeenCalledWith(
'test-bucket',
'files/test.txt',
expect.anything(),
5,
'text/plain',
)
})
it('returns 403 when local upload URL signature is expired', async () => {
vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('local')
const putObjectSpy = vi.spyOn(s3Module.s3Service, 'putObject').mockResolvedValue(undefined)
const signedPath = s3Module.signLocalUrl('test-bucket', 'files/test.txt', -10)
const localPath = signedPath.replace(/^\/api/, '')
const localApp = new Hono().route('/', localUploadRoute)
const res = await localApp.request(localPath, {
method: 'PUT',
body: 'hello',
})
expect(res.status).toBe(403)
expect(putObjectSpy).not.toHaveBeenCalled()
})
it('returns 403 when Expires query param is missing or invalid', async () => {
vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('local')
const putObjectSpy = vi.spyOn(s3Module.s3Service, 'putObject').mockResolvedValue(undefined)
const localApp = new Hono().route('/', localUploadRoute)
const missingRes = await localApp.request('/upload/local?bucket=b&key=k&Signature=sig', {
method: 'PUT',
body: 'hello',
})
expect(missingRes.status).toBe(403)
const invalidRes = await localApp.request(
'/upload/local?bucket=b&key=k&Signature=sig&Expires=not-a-number',
{
method: 'PUT',
body: 'hello',
},
)
expect(invalidRes.status).toBe(403)
expect(putObjectSpy).not.toHaveBeenCalled()
})
})
})
+3 -3
View File
@@ -27,10 +27,10 @@ export const localUploadRoute = new Hono().put(
return c.text('Not found', 404)
}
const { bucket, key, Signature } = c.req.valid('query')
const { bucket, key, Signature, Expires } = c.req.valid('query')
if (!verifyLocalUrlSignature(bucket, key, Signature)) {
return c.text('Invalid signature', 403)
if (!verifyLocalUrlSignature(bucket, key, Signature, Expires)) {
return c.text('Invalid or expired signature', 403)
}
const contentType = c.req.header('Content-Type')
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/core",
"version": "0.7.0",
"version": "0.7.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1
View File
@@ -137,6 +137,7 @@ export class AssetArchiveService {
WorkflowTaskType.transcode_screenshot,
WorkflowTaskType.transcode_image_annotation,
WorkflowTaskType.transcode_watermark,
WorkflowTaskType.transcode_video_chunks,
],
},
},
+40
View File
@@ -5556,6 +5556,46 @@ describe('AssetService — natural sort by name', () => {
expect(restored?.isDeleted).toBe(false)
expect(restored?.status).toBe(AssetStatus.processed)
})
it('should restore asset with status "processed" even if an auxiliary transcode_video_chunks task is active', async () => {
const team = await prisma.team.create({ data: { name: 'Restore Video Chunks Team' } })
const project = await prisma.project.create({
data: { name: 'Restore Video Chunks Project', teamId: team.id },
})
const rootFolder = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
projectId: project.id,
status: AssetStatus.uploaded,
},
})
const file = await prisma.asset.create({
data: {
name: 'embedding-chunks-video.mp4',
type: AssetType.file,
projectId: project.id,
parentId: rootFolder.id,
status: AssetStatus.trashed,
isDeleted: true,
deletedAt: new Date(),
},
})
await prisma.workflowTask.create({
data: {
assetId: file.id,
type: WorkflowTaskType.transcode_video_chunks,
status: WorkflowTaskStatus.processing,
},
})
await assetService.restoreAssets([file.id])
const restored = await prisma.asset.findUnique({ where: { id: file.id } })
expect(restored?.isDeleted).toBe(false)
expect(restored?.status).toBe(AssetStatus.processed)
})
})
describe('HLS playlists', () => {
+11 -4
View File
@@ -176,10 +176,17 @@ export class AssetService {
async getDescendantFolderIds(folderId: string): Promise<string[]> {
const rows = await this.prismaClient.$queryRaw<{ id: string }[]>`
WITH RECURSIVE descendant AS (
SELECT id, parent_id FROM assets WHERE parent_id = ${folderId}
SELECT id, parent_id
FROM assets
WHERE parent_id = ${folderId}
AND type = 'folder'::"AssetType"
AND is_deleted = false
UNION ALL
SELECT a.id, a.parent_id FROM assets a
SELECT a.id, a.parent_id
FROM assets a
INNER JOIN descendant d ON a.parent_id = d.id
WHERE a.type = 'folder'::"AssetType"
AND a.is_deleted = false
)
SELECT id FROM descendant;
`
@@ -2711,8 +2718,8 @@ export class AssetService {
proxyType,
latestChildren,
preview,
createdAt: a.createdAt.toISOString(),
updatedAt: a.updatedAt.toISOString(),
createdAt: latestVersion.createdAt.toISOString(),
updatedAt: latestVersion.updatedAt.toISOString(),
deletedAt: a.deletedAt ? a.deletedAt.toISOString() : null,
projectId: a.projectId,
creator,
+24
View File
@@ -48,6 +48,30 @@ describe('LruTtlCache', () => {
expect(cache.size).toBe(0)
})
it('should expire items using wall-clock time even when performance.now pauses during sleep', () => {
vi.useRealTimers()
let wallNow = 1_700_000_000_000
let perfNow = 1_000
const dateNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => wallNow)
const perfNowSpy = vi.spyOn(performance, 'now').mockImplementation(() => perfNow)
try {
const cache = new LruTtlCache<string, string>(10)
cache.set('key1', 'value1', 60_000)
expect(cache.get('key1')).toBe('value1')
// Simulate host sleep: wall clock advances past TTL while monotonic clock barely moves
wallNow += 120_000
perfNow += 500
expect(cache.get('key1')).toBeUndefined()
expect(cache.size).toBe(0)
} finally {
dateNowSpy.mockRestore()
perfNowSpy.mockRestore()
}
})
it('should proactively evict expired items on get', () => {
const sampleSize = 5
const cache = new LruTtlCache<string, string>(100, sampleSize)
+3 -2
View File
@@ -101,10 +101,11 @@ export class LruTtlCache<TKey, TValue> {
}
/**
* Monotonic time source to avoid issues with system clock jumps.
* Wall-clock time source so TTLs reflect real elapsed time across host sleep / VM suspend
* and stay aligned with wall-clock expirations such as presigned URL timestamps.
*/
private now(): number {
return performance.now()
return Date.now()
}
get size(): number {
+341 -1
View File
@@ -12,10 +12,13 @@ import {
} from '@aws-sdk/client-s3'
import {
buildContentDisposition,
getPresignedUrlExpirySeconds,
LocalStorageService,
S3StorageService,
signLocalGetUrl,
signLocalUrl,
verifyLocalGetUrlSignature,
verifyLocalUrlSignature,
} from './s3'
const s3ClientConstructorSpy = vi.fn()
@@ -82,7 +85,7 @@ describe('S3Service implementations', () => {
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(GetObjectCommand),
expect.objectContaining({ expiresIn: 18000 }),
expect.objectContaining({ expiresIn: 43200 }),
)
})
@@ -101,6 +104,67 @@ describe('S3Service implementations', () => {
expect(getSignedUrlSpy).toHaveBeenCalledTimes(1)
})
it('should refresh cached default GET presign URLs after half their lifetime', async () => {
let wallNow = 1_700_000_000_000
let perfNow = 1_000
const dateNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => wallNow)
const perfNowSpy = vi.spyOn(performance, 'now').mockImplementation(() => perfNow)
try {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
getSignedUrlSpy.mockClear()
getSignedUrlSpy.mockResolvedValueOnce('http://presigned-url-1')
getSignedUrlSpy.mockResolvedValueOnce('http://presigned-url-2')
const url1 = await s3.presign('bucket', 'key', 'GET')
expect(url1).toBe('http://presigned-url-1')
// Default GET lifetime is 12h; before 6h the cached URL should still be reused
const almostHalfMs = 6 * 3600 * 1000 - 1_000
wallNow += almostHalfMs
perfNow += almostHalfMs
expect(await s3.presign('bucket', 'key', 'GET')).toBe('http://presigned-url-1')
expect(getSignedUrlSpy).toHaveBeenCalledTimes(1)
// Past 6h (half of the 12h lifetime), the cache must expire so callers never get nearly expired URLs
wallNow += 2_000
perfNow += 2_000
expect(await s3.presign('bucket', 'key', 'GET')).toBe('http://presigned-url-2')
expect(getSignedUrlSpy).toHaveBeenCalledTimes(2)
} finally {
dateNowSpy.mockRestore()
perfNowSpy.mockRestore()
}
})
it('should invalidate cached GET presign URLs after system sleep when wall clock advances but monotonic clock pauses', async () => {
let wallNow = 1_700_000_000_000
let perfNow = 1_000
const dateNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => wallNow)
const perfNowSpy = vi.spyOn(performance, 'now').mockImplementation(() => perfNow)
try {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
getSignedUrlSpy.mockClear()
getSignedUrlSpy.mockResolvedValueOnce('http://presigned-url-1')
getSignedUrlSpy.mockResolvedValueOnce('http://presigned-url-2')
const url1 = await s3.presign('bucket', 'sleep-key', 'GET')
expect(url1).toBe('http://presigned-url-1')
// Simulate 15 hours of host sleep: wall clock jumps 15h while performance.now() barely moves
wallNow += 15 * 3600 * 1000
perfNow += 1_000
const url2 = await s3.presign('bucket', 'sleep-key', 'GET')
expect(url2).toBe('http://presigned-url-2')
expect(getSignedUrlSpy).toHaveBeenCalledTimes(2)
} finally {
dateNowSpy.mockRestore()
perfNowSpy.mockRestore()
}
})
it('signs with an explicit lifetime and caches it separately from the default', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
getSignedUrlSpy.mockClear()
@@ -240,6 +304,43 @@ describe('S3Service implementations', () => {
delete process.env.PRESIGNED_URL_EXPIRES_IN
})
it('should support float values for PRESIGNED_URL_EXPIRES_IN and PRESIGNED_UPLOAD_URL_EXPIRES_IN', async () => {
process.env.PRESIGNED_URL_EXPIRES_IN = '0.1'
process.env.PRESIGNED_UPLOAD_URL_EXPIRES_IN = '1.5'
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
getSignedUrlSpy.mockClear()
await s3.presign('bucket', 'key', 'GET')
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(GetObjectCommand),
expect.objectContaining({ expiresIn: 360 }),
)
getSignedUrlSpy.mockClear()
await s3.presign('bucket', 'key', 'PUT')
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(PutObjectCommand),
expect.objectContaining({ expiresIn: 5400 }),
)
getSignedUrlSpy.mockClear()
await s3.presignMultipart('bucket', 'key', {
method: 'PUT',
key: 'key',
fileId: 'file-1',
})
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(PutObjectCommand),
expect.objectContaining({ expiresIn: 5400 }),
)
delete process.env.PRESIGNED_URL_EXPIRES_IN
delete process.env.PRESIGNED_UPLOAD_URL_EXPIRES_IN
})
it('should not set contentDisposition for normal GET presign', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
await s3.presign('bucket', 'key', 'GET')
@@ -807,6 +908,46 @@ describe('S3Service implementations', () => {
expect(urlOther).not.toBe(url1)
})
it('should not return expired local GET presigned URLs after system sleep when wall clock advances but monotonic clock pauses', async () => {
let wallNow = 1_700_000_000_000
let perfNow = 1_000
const dateNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => wallNow)
const perfNowSpy = vi.spyOn(performance, 'now').mockImplementation(() => perfNow)
try {
const url1 = await localS3.presign('my-bucket', 'dir/sleep.png', 'GET')
const parsed1 = new URL(url1)
expect(
verifyLocalGetUrlSignature(
'my-bucket',
'dir/sleep.png',
parsed1.searchParams.get('Signature'),
parsed1.searchParams.get('Expires'),
),
).toBe(true)
// Simulate 15 hours of host sleep: wall clock advances past the 12h expiry while performance.now() pauses
wallNow += 15 * 3600 * 1000
perfNow += 1_000
const url2 = await localS3.presign('my-bucket', 'dir/sleep.png', 'GET')
expect(url2).not.toBe(url1)
const parsed2 = new URL(url2)
expect(
verifyLocalGetUrlSignature(
'my-bucket',
'dir/sleep.png',
parsed2.searchParams.get('Signature'),
parsed2.searchParams.get('Expires'),
),
).toBe(true)
} finally {
dateNowSpy.mockRestore()
perfNowSpy.mockRestore()
}
})
it('should not cache download URLs', async () => {
const url1 = await localS3.presign('my-bucket', 'dir/file.txt', 'GET', true)
const url2 = await localS3.presign('my-bucket', 'dir/file.txt', 'GET', true)
@@ -819,6 +960,102 @@ describe('S3Service implementations', () => {
await expect(localS3.presign('b', 'k', 'POST')).rejects.toThrow()
})
it('should default local GET and PUT presign expiry to 12 hours', async () => {
const fixedNow = 1_700_000_000_000
const dateNowSpy = vi.spyOn(Date, 'now').mockReturnValue(fixedNow)
try {
const expectedExpires = String(Math.floor(fixedNow / 1000) + 12 * 3600)
const getUrl = new URL(await localS3.presign('my-bucket', 'dir/default.txt', 'GET'))
expect(getUrl.searchParams.get('Expires')).toBe(expectedExpires)
const putUrl = new URL(await localS3.presign('my-bucket', 'dir/default.txt', 'PUT'))
expect(putUrl.pathname).toBe('/api/upload/local')
expect(putUrl.searchParams.get('Expires')).toBe(expectedExpires)
expect(
verifyLocalUrlSignature(
'my-bucket',
'dir/default.txt',
putUrl.searchParams.get('Signature'),
putUrl.searchParams.get('Expires'),
),
).toBe(true)
} finally {
dateNowSpy.mockRestore()
}
})
it('should respect PRESIGNED_URL_EXPIRES_IN (including floats) for local GET and PUT fallback', async () => {
const fixedNow = 1_700_000_000_000
const dateNowSpy = vi.spyOn(Date, 'now').mockReturnValue(fixedNow)
process.env.PRESIGNED_URL_EXPIRES_IN = '0.1'
try {
const expectedExpires = String(Math.floor(fixedNow / 1000) + 360)
const getUrl = new URL(await localS3.presign('my-bucket', 'dir/float.txt', 'GET'))
expect(getUrl.searchParams.get('Expires')).toBe(expectedExpires)
const putUrl = new URL(await localS3.presign('my-bucket', 'dir/float.txt', 'PUT'))
expect(putUrl.searchParams.get('Expires')).toBe(expectedExpires)
} finally {
dateNowSpy.mockRestore()
delete process.env.PRESIGNED_URL_EXPIRES_IN
}
})
it('should respect PRESIGNED_UPLOAD_URL_EXPIRES_IN (including floats) for local PUT and presignMultipart', async () => {
const fixedNow = 1_700_000_000_000
const dateNowSpy = vi.spyOn(Date, 'now').mockReturnValue(fixedNow)
process.env.PRESIGNED_URL_EXPIRES_IN = '2'
process.env.PRESIGNED_UPLOAD_URL_EXPIRES_IN = '1.5'
try {
const expectedGetExpires = String(Math.floor(fixedNow / 1000) + 2 * 3600)
const expectedPutExpires = String(Math.floor(fixedNow / 1000) + 5400)
const getUrl = new URL(await localS3.presign('my-bucket', 'dir/upload-env.txt', 'GET'))
expect(getUrl.searchParams.get('Expires')).toBe(expectedGetExpires)
const putUrl = new URL(await localS3.presign('my-bucket', 'dir/upload-env.txt', 'PUT'))
expect(putUrl.searchParams.get('Expires')).toBe(expectedPutExpires)
const { url: multipartUrlStr } = await localS3.presignMultipart(
'my-bucket',
'dir/upload-env.txt',
{
method: 'PUT',
key: 'dir/upload-env.txt',
fileId: 'file-1',
},
)
const multipartUrl = new URL(multipartUrlStr)
expect(multipartUrl.searchParams.get('Expires')).toBe(expectedPutExpires)
} finally {
dateNowSpy.mockRestore()
delete process.env.PRESIGNED_URL_EXPIRES_IN
delete process.env.PRESIGNED_UPLOAD_URL_EXPIRES_IN
}
})
it('should respect explicit expiresInSeconds override for local GET and PUT', async () => {
const fixedNow = 1_700_000_000_000
const dateNowSpy = vi.spyOn(Date, 'now').mockReturnValue(fixedNow)
try {
const expectedExpires = String(Math.floor(fixedNow / 1000) + 600)
const getUrl = new URL(
await localS3.presign('my-bucket', 'dir/custom.txt', 'GET', false, undefined, false, 600),
)
expect(getUrl.searchParams.get('Expires')).toBe(expectedExpires)
const putUrl = new URL(
await localS3.presign('my-bucket', 'dir/custom.txt', 'PUT', false, undefined, false, 600),
)
expect(putUrl.searchParams.get('Expires')).toBe(expectedExpires)
} finally {
dateNowSpy.mockRestore()
}
})
it('should resolveInput to local file path if file exists on disk', async () => {
await localS3.putObject('my-bucket', 'video.mp4', 'dummy content', 13)
const input = await localS3.resolveInput('my-bucket', 'video.mp4')
@@ -978,4 +1215,107 @@ describe('S3Service implementations', () => {
).toBe(false)
})
})
describe('getPresignedUrlExpirySeconds', () => {
it('supports float hours and falls back to 12 hours for invalid values', () => {
expect(getPresignedUrlExpirySeconds('GET')).toBe(12 * 3600)
expect(getPresignedUrlExpirySeconds('PUT')).toBe(12 * 3600)
process.env.PRESIGNED_URL_EXPIRES_IN = '0.1'
expect(getPresignedUrlExpirySeconds('GET')).toBe(360)
expect(getPresignedUrlExpirySeconds('PUT')).toBe(360)
process.env.PRESIGNED_URL_EXPIRES_IN = '0.0001'
expect(getPresignedUrlExpirySeconds('GET')).toBe(1)
for (const invalid of ['0', '-1', 'abc', 'Infinity', 'NaN', ' ']) {
process.env.PRESIGNED_URL_EXPIRES_IN = invalid
expect(getPresignedUrlExpirySeconds('GET')).toBe(12 * 3600)
expect(getPresignedUrlExpirySeconds('PUT')).toBe(12 * 3600)
}
expect(getPresignedUrlExpirySeconds('GET', 120)).toBe(120)
expect(getPresignedUrlExpirySeconds('PUT', -10)).toBe(-10)
})
})
describe('signLocalUrl and verifyLocalUrlSignature', () => {
it('signs and verifies valid local PUT url', () => {
const signed = signLocalUrl('my-bucket', 'files/123/file.mp4')
const parsed = new URL(`http://localhost:3000${signed}`)
const signature = parsed.searchParams.get('Signature')
const expires = parsed.searchParams.get('Expires')
expect(signature).toBeTruthy()
expect(Number(expires)).toBeGreaterThan(Math.floor(Date.now() / 1000))
expect(verifyLocalUrlSignature('my-bucket', 'files/123/file.mp4', signature, expires)).toBe(
true,
)
})
it('rejects expired local PUT url signature', () => {
const signed = signLocalUrl('my-bucket', 'files/123/file.mp4', -10)
const parsed = new URL(`http://localhost:3000${signed}`)
expect(
verifyLocalUrlSignature(
'my-bucket',
'files/123/file.mp4',
parsed.searchParams.get('Signature'),
parsed.searchParams.get('Expires'),
),
).toBe(false)
})
it('rejects tampered bucket, key, or malformed params', () => {
const signed = signLocalUrl('my-bucket', 'files/123/file.mp4')
const parsed = new URL(`http://localhost:3000${signed}`)
const signature = parsed.searchParams.get('Signature')
const expires = parsed.searchParams.get('Expires')
expect(
verifyLocalUrlSignature('other-bucket', 'files/123/file.mp4', signature, expires),
).toBe(false)
expect(verifyLocalUrlSignature('my-bucket', 'files/999/other.mp4', signature, expires)).toBe(
false,
)
expect(
verifyLocalUrlSignature(
'my-bucket',
'files/123/file.mp4',
signature,
String(Number(expires) + 60),
),
).toBe(false)
expect(verifyLocalUrlSignature('my-bucket', 'files/123/file.mp4', undefined, expires)).toBe(
false,
)
expect(verifyLocalUrlSignature('my-bucket', 'files/123/file.mp4', signature, undefined)).toBe(
false,
)
expect(
verifyLocalUrlSignature('my-bucket', 'files/123/file.mp4', signature, `${expires}abc`),
).toBe(false)
})
it('rejects reusing a GET signature for PUT and vice versa', () => {
const { signature: getSig, expires: getExp } = signLocalGetUrl(
'my-bucket',
'files/123/file.mp4',
)
expect(
verifyLocalUrlSignature('my-bucket', 'files/123/file.mp4', getSig, String(getExp)),
).toBe(false)
const signedPut = signLocalUrl('my-bucket', 'files/123/file.mp4')
const parsedPut = new URL(`http://localhost:3000${signedPut}`)
expect(
verifyLocalGetUrlSignature(
'my-bucket',
'files/123/file.mp4',
parsedPut.searchParams.get('Signature'),
parsedPut.searchParams.get('Expires'),
),
).toBe(false)
})
})
})
+63 -36
View File
@@ -26,34 +26,73 @@ import { ulid } from 'ulid'
import { LruTtlCache } from '../cache/lru-ttl-cache'
import { detectSupportedMimeType } from '../utils/mime'
export function signLocalUrl(bucket: string, key: string): string {
const secret = process.env.BETTER_AUTH_SECRET || 'shumai-local-storage-secret'
const hmac = crypto.createHmac('sha256', secret)
hmac.update(`${bucket}/${key}`)
const signature = hmac.digest('hex')
return `/api/upload/local?bucket=${encodeURIComponent(bucket)}&key=${encodeURIComponent(key)}&Signature=${signature}`
export const DEFAULT_PRESIGNED_URL_EXPIRY_HOURS = 12
export function getPresignedUrlExpirySeconds(method: string, expiresInSeconds?: number): number {
if (expiresInSeconds !== undefined) {
return expiresInSeconds
}
const raw =
method === 'PUT'
? process.env.PRESIGNED_UPLOAD_URL_EXPIRES_IN?.trim() ||
process.env.PRESIGNED_URL_EXPIRES_IN?.trim()
: process.env.PRESIGNED_URL_EXPIRES_IN?.trim()
if (raw) {
const hours = Number(raw)
if (Number.isFinite(hours) && hours > 0) {
return Math.max(1, Math.round(hours * 3600))
}
}
return DEFAULT_PRESIGNED_URL_EXPIRY_HOURS * 3600
}
export function verifyLocalUrlSignature(bucket: string, key: string, signature: string): boolean {
export function signLocalUrl(bucket: string, key: string, expiresInSeconds?: number): string {
const lifetimeSeconds = getPresignedUrlExpirySeconds('PUT', expiresInSeconds)
const expires = Math.floor(Date.now() / 1000) + lifetimeSeconds
const secret = process.env.BETTER_AUTH_SECRET || 'shumai-local-storage-secret'
const hmac = crypto.createHmac('sha256', secret)
hmac.update(`${bucket}/${key}`)
hmac.update(`PUT:${bucket}/${key}:${expires}`)
const signature = hmac.digest('hex')
return `/api/upload/local?bucket=${encodeURIComponent(bucket)}&key=${encodeURIComponent(key)}&Signature=${signature}&Expires=${expires}`
}
export function verifyLocalUrlSignature(
bucket: string,
key: string,
signature: string | undefined | null,
expiresStr: string | undefined | null,
): boolean {
if (!signature || !expiresStr) return false
if (!/^-?\d+$/.test(expiresStr)) return false
const expires = parseInt(expiresStr, 10)
if (isNaN(expires)) return false
const now = Math.floor(Date.now() / 1000)
if (now > expires) return false
const secret = process.env.BETTER_AUTH_SECRET || 'shumai-local-storage-secret'
const hmac = crypto.createHmac('sha256', secret)
hmac.update(`PUT:${bucket}/${key}:${expires}`)
const expected = hmac.digest('hex')
try {
return crypto.timingSafeEqual(Buffer.from(signature, 'hex'), Buffer.from(expected, 'hex'))
const sigBuf = Buffer.from(signature, 'hex')
const expBuf = Buffer.from(expected, 'hex')
if (sigBuf.length !== expBuf.length) return false
return crypto.timingSafeEqual(sigBuf, expBuf)
} catch {
return false
}
}
export const DEFAULT_LOCAL_GET_EXPIRY_SECONDS = 12 * 3600
export function signLocalGetUrl(
bucket: string,
key: string,
expiresInSeconds: number = DEFAULT_LOCAL_GET_EXPIRY_SECONDS,
expiresInSeconds?: number,
): { signature: string; expires: number } {
const expires = Math.floor(Date.now() / 1000) + expiresInSeconds
const lifetimeSeconds = getPresignedUrlExpirySeconds('GET', expiresInSeconds)
const expires = Math.floor(Date.now() / 1000) + lifetimeSeconds
const secret = process.env.BETTER_AUTH_SECRET || 'shumai-local-storage-secret'
const hmac = crypto.createHmac('sha256', secret)
hmac.update(`GET:${bucket}/${key}:${expires}`)
@@ -68,6 +107,7 @@ export function verifyLocalGetUrlSignature(
expiresStr: string | undefined | null,
): boolean {
if (!signature || !expiresStr) return false
if (!/^-?\d+$/.test(expiresStr)) return false
const expires = parseInt(expiresStr, 10)
if (isNaN(expires)) return false
@@ -392,7 +432,7 @@ export interface S3Service {
download?: boolean,
filename?: string,
internal?: boolean,
/** URL lifetime; defaults to PRESIGNED_UPLOAD_URL_EXPIRES_IN (12h) for PUT, or PRESIGNED_URL_EXPIRES_IN (5h) for GET, or DEFAULT_LOCAL_GET_EXPIRY_SECONDS (12h) for local. */
/** URL lifetime; defaults to PRESIGNED_UPLOAD_URL_EXPIRES_IN (12h, fallback PRESIGNED_URL_EXPIRES_IN) for PUT, or PRESIGNED_URL_EXPIRES_IN (12h) for GET and other methods. */
expiresInSeconds?: number,
) => Promise<string>
presignMultipart: (
@@ -664,21 +704,12 @@ export class S3StorageService implements S3Service {
internal?: boolean,
expiresInSeconds?: number,
): Promise<string> {
const defaultExpireHours =
method === 'PUT'
? parseInt(
process.env.PRESIGNED_UPLOAD_URL_EXPIRES_IN ||
process.env.PRESIGNED_URL_EXPIRES_IN ||
'12',
10,
)
: parseInt(process.env.PRESIGNED_URL_EXPIRES_IN || '5', 10)
const lifetimeSeconds = expiresInSeconds ?? defaultExpireHours * 3600
// With an explicit (usually short) lifetime, only reuse a cached URL while it has at
// least half of its lifetime left, so callers never receive a nearly expired link.
const cacheTtlMs = expiresInSeconds ? (lifetimeSeconds * 1000) / 2 : lifetimeSeconds * 1000
const lifetimeSeconds = getPresignedUrlExpirySeconds(method, expiresInSeconds)
// Only reuse a cached URL while it has at least half of its lifetime left, so callers
// never receive a nearly expired link.
const cacheTtlMs = (lifetimeSeconds * 1000) / 2
const cacheKey = `${bucket}/${key}?download=${download || false}&filename=${filename || ''}&internal=${internal || false}&expires=${expiresInSeconds ?? 'default'}`
const cacheKey = `${bucket}/${key}?download=${download || false}&filename=${filename || ''}&internal=${internal || false}&expires=${lifetimeSeconds}`
if (method === 'GET' && !download) {
const cached = this.presignCache.get(cacheKey)
if (cached) {
@@ -724,11 +755,7 @@ export class S3StorageService implements S3Service {
key: string,
request: S3SignRequest,
): Promise<{ url: string }> {
const expireHours = parseInt(
process.env.PRESIGNED_UPLOAD_URL_EXPIRES_IN || process.env.PRESIGNED_URL_EXPIRES_IN || '12',
10,
)
const expiresInSeconds = expireHours * 3600
const expiresInSeconds = getPresignedUrlExpirySeconds('PUT')
let url: string
@@ -1094,12 +1121,12 @@ export class LocalStorageService implements S3Service {
throw new Error(`Invalid method: ${method}`)
}
if (method === 'PUT') {
return `${this.endpoint}${signLocalUrl(bucket, key)}`
return `${this.endpoint}${signLocalUrl(bucket, key, expiresInSeconds)}`
}
const lifetimeSeconds = expiresInSeconds ?? DEFAULT_LOCAL_GET_EXPIRY_SECONDS
const lifetimeSeconds = getPresignedUrlExpirySeconds('GET', expiresInSeconds)
const cacheTtlMs = (lifetimeSeconds * 1000) / 2
const cacheKey = `${bucket}/${key}?download=${download || false}&filename=${filename || ''}&expires=${expiresInSeconds ?? 'default'}`
const cacheKey = `${bucket}/${key}?download=${download || false}&filename=${filename || ''}&expires=${lifetimeSeconds}`
if (method === 'GET' && !download) {
const cached = this.presignCache.get(cacheKey)
@@ -166,6 +166,15 @@ describe('EmbeddingService', () => {
projectId: project.id,
},
})
const staleChunkTask = await prisma.workflowTask.create({
data: {
assetId: videoAsset.id,
type: WorkflowTaskType.transcode_video_chunks,
status: WorkflowTaskStatus.processing,
teamId: team.id,
projectId: project.id,
},
})
const initialEmbeddings = await prisma.assetEmbedding.count({
where: { assetId: videoAsset.id },
@@ -179,6 +188,12 @@ describe('EmbeddingService', () => {
expect(result.tasksCreated).toBe(3)
expect(result.skippedTeams).not.toContain('Active Embedding Team')
// Verify old transcode_video_chunks task was also wiped upfront
const remainingChunkTask = await prisma.workflowTask.findUnique({
where: { id: staleChunkTask.id },
})
expect(remainingChunkTask).toBeNull()
// Verify old embeddings were wiped upfront
const remainingEmbeddings = await prisma.assetEmbedding.count({
where: { assetId: videoAsset.id },
@@ -80,7 +80,9 @@ export class EmbeddingService {
await prisma.workflowTask.deleteMany({
where: {
assetId: { in: eligibleAssetIds },
type: WorkflowTaskType.ai_embedding,
type: {
in: [WorkflowTaskType.ai_embedding, WorkflowTaskType.transcode_video_chunks],
},
},
})
@@ -0,0 +1,6 @@
export function getGemmaEmbeddingEndpoint(): string {
const baseUrl = process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL || 'http://localhost:9379/v1'
const url = baseUrl.replace(/\/+$/, '')
if (url.endsWith('/embeddings')) return url
return url.endsWith('/v1') ? `${url}/embeddings` : `${url}/v1/embeddings`
}
@@ -0,0 +1,111 @@
import sharp from 'sharp'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ImageEmbeddingService } from './image-embedding'
const embedContent = vi.fn()
vi.mock('@google/genai', () => ({
// eslint-disable-next-line @typescript-eslint/naming-convention
GoogleGenAI: class {
models = { embedContent }
},
}))
async function jpeg(width = 32, height = 24) {
const buffer = await sharp({
create: { width, height, channels: 3, background: '#ffffff' },
})
.jpeg()
.toBuffer()
return buffer.toString('base64')
}
describe('ImageEmbeddingService', () => {
let service: ImageEmbeddingService
beforeEach(() => {
vi.stubEnv('EMBEDDING_PROVIDER', undefined)
vi.stubEnv('GEMINI_API_KEY', 'fake-key')
embedContent.mockReset()
service = new ImageEmbeddingService()
})
afterEach(() => {
vi.unstubAllEnvs()
vi.unstubAllGlobals()
})
it('embeds JPEG images with Gemini and caches the result by team and image', async () => {
const image = await jpeg()
const embedding = Array<number>(1536).fill(0.02)
embedContent.mockResolvedValue({ embeddings: [{ values: embedding }] })
expect(await service.generateEmbedding(image, 'team-a')).toEqual(embedding)
expect(await service.generateEmbedding(image, 'team-a')).toEqual(embedding)
expect(embedContent).toHaveBeenCalledTimes(1)
expect(embedContent).toHaveBeenCalledWith({
model: 'gemini-embedding-2',
contents: [{ inlineData: { data: image, mimeType: 'image/jpeg' } }],
config: { outputDimensionality: 1536, abortSignal: expect.any(AbortSignal) },
})
await service.generateEmbedding(image, 'team-b')
await service.generateEmbedding(await jpeg(18), 'team-a')
expect(embedContent).toHaveBeenCalledTimes(3)
})
it('uses the configured local Gemma endpoint and accepts portrait images', async () => {
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
vi.stubEnv('GEMMA_EMBEDDING_OPENAI_BASE_URL', 'http://embedding.test/custom/embeddings/')
const image = await jpeg(720, 1280)
const embedding = Array<number>(768).fill(0.02)
const fetchMock = vi.fn().mockResolvedValue(Response.json({ data: [{ embedding }] }))
vi.stubGlobal('fetch', fetchMock)
expect(await service.generateEmbedding(image, 'team-a')).toEqual(embedding)
expect(fetchMock).toHaveBeenCalledWith(
'http://embedding.test/custom/embeddings',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({
model: 'embeddinggemma-2',
input: [
{
type: 'image_url',
// eslint-disable-next-line @typescript-eslint/naming-convention -- OpenAI request field
image_url: { url: `data:image/jpeg;base64,${image}` },
},
],
}),
}),
)
expect(embedContent).not.toHaveBeenCalled()
})
it('rejects invalid, non-JPEG, and oversized images before contacting the provider', async () => {
const png = await sharp({
create: { width: 32, height: 24, channels: 3, background: '#ffffff' },
})
.png()
.toBuffer()
for (const image of ['aW1hZ2U=', png.toString('base64'), await jpeg(1281, 200)]) {
await expect(service.generateEmbedding(image, 'team-a')).rejects.toMatchObject({
status: 400,
})
}
expect(embedContent).not.toHaveBeenCalled()
})
it('reports provider errors and allows the image to be retried', async () => {
const image = await jpeg()
const embedding = Array<number>(1536).fill(0.02)
embedContent
.mockRejectedValueOnce(new Error('Provider failed'))
.mockResolvedValueOnce({ embeddings: [{ values: [1, 2, 3] }] })
.mockResolvedValueOnce({ embeddings: [{ values: embedding }] })
await expect(service.generateEmbedding(image, 'team-a')).rejects.toMatchObject({ status: 502 })
await expect(service.generateEmbedding(image, 'team-a')).rejects.toMatchObject({ status: 502 })
expect(await service.generateEmbedding(image, 'team-a')).toEqual(embedding)
expect(embedContent).toHaveBeenCalledTimes(3)
})
})
@@ -0,0 +1,99 @@
import { createHash } from 'node:crypto'
import { GoogleGenAI } from '@google/genai'
import { LruTtlCache } from '@shumai/core/src/cache/lru-ttl-cache'
import { logger } from '@shumai/core/src/logger'
import { HTTPException } from 'hono/http-exception'
import sharp from 'sharp'
import { getGemmaEmbeddingEndpoint } from './gemma-embedding-endpoint'
export function getImageEmbeddingDimensions(): 768 | 1536 {
return process.env.EMBEDDING_PROVIDER === 'gemma-embedding-2-openai' ? 768 : 1536
}
export class ImageEmbeddingService {
private readonly cache = new LruTtlCache<string, number[]>(100)
async generateEmbedding(image: string, teamId: string): Promise<number[]> {
const dimensions = getImageEmbeddingDimensions()
const digest = createHash('sha256').update(image).digest('hex')
const cacheKey = `${teamId}:${dimensions}:${digest}`
const cached = this.cache.get(cacheKey)
if (cached) return cached
const buffer = Buffer.from(image, 'base64')
const metadata = await sharp(buffer, { limitInputPixels: 1280 * 720 })
.metadata()
.catch(() => null)
if (
metadata?.format !== 'jpeg' ||
Math.max(metadata.width, metadata.height) > 1280 ||
Math.min(metadata.width, metadata.height) > 720
) {
throw new HTTPException(400, { message: 'Provide a JPEG image resized to 720p.' })
}
let embedding: number[] | undefined
try {
const signal = AbortSignal.timeout(15000)
embedding =
dimensions === 768
? await this.embedWithGemma(image, signal)
: await this.embedWithGemini(image, signal)
if (
!embedding ||
embedding.length !== dimensions ||
!embedding.every(Number.isFinite) ||
!embedding.some((value) => value !== 0)
) {
throw new Error('Invalid image embedding returned by provider')
}
} catch (err) {
logger.warn(
{ teamId, dimensions, errorName: err instanceof Error ? err.name : undefined },
'Failed to generate image search embedding',
)
throw new HTTPException(502, { message: 'Failed to generate image search embedding.' })
}
this.cache.set(cacheKey, embedding, 10 * 60 * 1000)
return embedding
}
private async embedWithGemini(image: string, signal: AbortSignal) {
const apiKey = process.env.GEMINI_API_KEY
if (!apiKey) throw new Error('GEMINI_API_KEY environment variable is not configured')
const ai = new GoogleGenAI({ apiKey: process.env[apiKey] || apiKey })
const response = await ai.models.embedContent({
model: 'gemini-embedding-2',
contents: [{ inlineData: { data: image, mimeType: 'image/jpeg' } }],
config: { outputDimensionality: 1536, abortSignal: signal },
})
return response.embeddings?.[0]?.values
}
private async embedWithGemma(image: string, signal: AbortSignal) {
const response = await fetch(getGemmaEmbeddingEndpoint(), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'embeddinggemma-2',
input: [
{
type: 'image_url',
// eslint-disable-next-line @typescript-eslint/naming-convention -- OpenAI request field
image_url: { url: `data:image/jpeg;base64,${image}` },
},
],
}),
signal,
})
if (!response.ok) throw new Error(`Embedding server returned status ${response.status}`)
const result = (await response.json()) as { data?: { embedding?: number[] }[] }
return result.data?.[0]?.embedding
}
}
export const imageEmbeddingService = new ImageEmbeddingService()
@@ -0,0 +1,404 @@
import { AssetType, prisma, Prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { imageSearchRequestSchema } from '@shumai/dtos'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { s3Service } from '@shumai/core/src/s3/s3'
import { versionStackService } from '@shumai/core/src/versionStack/versionStack'
import { imageEmbeddingService } from './image-embedding'
import { searchService } from './search'
function vector(dimensions: number, x: number, y = 0): number[] {
return [x, y, ...Array<number>(dimensions - 2).fill(0)]
}
async function insertEmbedding(
assetId: string,
embedding: number[],
startTime: number | null = null,
endTime: number | null = null,
sprite?: PrismaJson.VideoChunkSprite,
) {
const column = embedding.length === 768 ? Prisma.sql`embedding_768` : Prisma.sql`embedding`
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, ${column}, start_time, end_time, sprite, created_at, updated_at)
VALUES (gen_random_uuid()::text, ${assetId}, ${JSON.stringify(embedding)}::vector,
${startTime}, ${endTime}, ${sprite ? JSON.stringify(sprite) : null}::jsonb, NOW(), NOW())
`
}
async function createProjectAssets() {
const team = await prisma.team.create({ data: { name: 'Image search team' } })
const user = await prisma.user.create({
data: { name: 'Embedding agent', email: 'visual-search-agent@example.com', type: 'agent' },
})
const agent = await prisma.agent.create({
data: {
id: user.id,
teamId: team.id,
type: 'embedding',
config: { provider: 'google', model: 'gemini-embedding-2' },
},
})
const project = await prisma.project.create({ data: { name: 'Visual search', teamId: team.id } })
const root = await prisma.asset.create({
data: { name: 'Root', type: 'root', status: 'processed', projectId: project.id },
})
await prisma.project.update({ where: { id: project.id }, data: { rootFolderId: root.id } })
const subfolder = await prisma.asset.create({
data: {
name: 'Subfolder',
type: 'folder',
status: 'uploaded',
projectId: project.id,
parentId: root.id,
},
})
const file = (name: string, mediaType: string, parentId = root.id) =>
prisma.asset.create({
data: { name, mediaType, parentId, projectId: project.id, type: 'file', status: 'processed' },
})
const source = await file('source.jpg', 'image/jpeg', subfolder.id)
return { team, user, agent, project, root, subfolder, source, file }
}
describe('image search', () => {
setupTestDbHooks()
beforeEach(() => {
vi.stubEnv('ENABLE_EMBEDDING_AGENT', undefined)
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('finds images and video segments across the project using the stored image vector', async () => {
const { root, source, file } = await createProjectAssets()
const image = await file('result.jpg', 'image/jpeg')
const video = await file('result.mp4', 'video/mp4')
const deleted = await file('deleted.jpg', 'image/jpeg')
const audio = await file('audio.mp3', 'audio/mpeg')
await prisma.asset.update({ where: { id: deleted.id }, data: { isDeleted: true } })
await insertEmbedding(source.id, vector(1536, 1))
const firstSprite = { key: 'files/video/chunk-4-12.webp', columns: 5, rows: 2, frameCount: 8 }
const secondSprite = { ...firstSprite, key: 'files/video/chunk-12-20.webp' }
await insertEmbedding(video.id, vector(1536, 1), 4, 12, firstSprite)
await insertEmbedding(video.id, vector(1536, 0, 1), 12, 20, secondSprite)
await insertEmbedding(image.id, vector(1536, 1, 1))
await insertEmbedding(deleted.id, vector(1536, 1))
await insertEmbedding(audio.id, vector(1536, 1))
const provider = vi.spyOn(imageEmbeddingService, 'generateEmbedding')
const request = { sourceAssetId: source.id }
const first = await searchService.searchByImage(
root.id,
imageSearchRequestSchema.parse({ ...request, first: 2 }),
)
expect(first.data.map((item) => item.id)).toEqual([video.id, image.id])
expect(first.data[0]).toMatchObject({
startTime: 4,
endTime: 12,
matchedSprite: { url: expect.stringContaining(firstSprite.key) },
})
expect(first.data[1].matchedSprite).toBeUndefined()
expect(first.pageInfo).toMatchObject({ total: 3, cursor: expect.any(String) })
const next = await searchService.searchByImage(
root.id,
imageSearchRequestSchema.parse({ ...request, first: 2, after: first.pageInfo.cursor }),
)
expect(next.data).toMatchObject([
{
id: video.id,
startTime: 12,
endTime: 20,
matchedSprite: { url: expect.stringContaining(secondSprite.key) },
},
])
expect(next.pageInfo.cursor).toBeUndefined()
const images = await searchService.searchByImage(
root.id,
imageSearchRequestSchema.parse({ ...request, mediaType: 'image' }),
)
const videos = await searchService.searchByImage(
root.id,
imageSearchRequestSchema.parse({ ...request, mediaType: 'video' }),
)
expect(images.data.map((item) => item.id)).toEqual([image.id])
expect(videos.data.map((item) => item.startTime)).toEqual([4, 12])
expect(provider).not.toHaveBeenCalled()
})
it('uses the active provider vector column and reports when an image needs indexing', async () => {
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
const { root, source, file } = await createProjectAssets()
const image = await file('result.jpg', 'image/jpeg')
const req = imageSearchRequestSchema.parse({ sourceAssetId: source.id })
await insertEmbedding(source.id, vector(1536, 1))
await expect(searchService.searchByImage(root.id, req)).rejects.toMatchObject({ status: 409 })
await insertEmbedding(source.id, vector(768, 1))
await insertEmbedding(image.id, vector(768, 1))
const result = await searchService.searchByImage(root.id, req)
expect(result.data.map((item) => item.id)).toEqual([image.id])
})
it.each([
{ startTime: 0, endTime: 10, stored: true, useFullSprite: true },
{ startTime: 0, endTime: 10, stored: false, useFullSprite: false },
{ startTime: 0, endTime: 5, stored: true, useFullSprite: false },
{ startTime: 5, endTime: 10, stored: true, useFullSprite: false },
])(
'picks the preview for $startTime–$endTime when full sprite availability is $stored',
async ({ startTime, endTime, stored, useFullSprite }) => {
const { root, source, file } = await createProjectAssets()
const video = await file('result.mp4', 'video/mp4')
const bucket = process.env.S3_BUCKET || 'shumai'
const fullKey = `files/${video.id}/sprite.webp`
const chunkKey = `files/${video.id}/chunk.webp`
await prisma.asset.update({
where: { id: video.id },
data: {
media: {
duration: 10,
proxyType: 'video',
sprite: { key: fullKey, frames: 100, tileX: 10, tileY: 10 },
} as PrismaJson.MediaInfo,
},
})
if (stored) await s3Service.putObject(bucket, fullKey, 'sprite', 6, 'image/webp')
try {
await insertEmbedding(source.id, vector(1536, 1))
await insertEmbedding(video.id, vector(1536, 1), startTime, endTime, {
key: chunkKey,
columns: 5,
rows: 2,
frameCount: 10,
})
const result = await searchService.searchByImage(
root.id,
imageSearchRequestSchema.parse({ sourceAssetId: source.id }),
)
expect(result.data).toHaveLength(1)
expect(result.data[0]).toMatchObject({
startTime,
endTime,
preview: { spriteUrl: expect.stringContaining(fullKey) },
})
if (useFullSprite) {
expect(result.data[0].matchedSprite).toBeUndefined()
} else {
expect(result.data[0].matchedSprite?.url).toContain(chunkKey)
}
} finally {
if (stored) await s3Service.deleteObject(bucket, fullKey)
}
},
)
it('limits an uploaded-image search to the folder and applies metadata filters', async () => {
const { team, subfolder, source, file } = await createProjectAssets()
const match = await file('approved.png', 'image/png', subfolder.id)
const outside = await file('outside.png', 'image/png')
for (const asset of [match, source, outside]) {
await insertEmbedding(asset.id, vector(1536, 1))
}
for (const asset of [match, outside]) {
await prisma.assetMetadataValue.create({
data: { assetId: asset.id, fieldKey: 'status', stringValue: 'approved' },
})
}
const provider = vi
.spyOn(imageEmbeddingService, 'generateEmbedding')
.mockResolvedValue(vector(1536, 1))
const image = 'aW1hZ2U='
const result = await searchService.searchByImage(
subfolder.id,
imageSearchRequestSchema.parse({
image,
conditions: [{ field: 'status', operator: 'eq', value: 'approved' }],
}),
)
expect(provider).toHaveBeenCalledWith(image, team.id)
expect(result.data.map((item) => item.id)).toEqual([match.id])
})
it('requires a readable image from the project root scope', async () => {
const { team, root, subfolder, source, file } = await createProjectAssets()
const video = await file('video.mp4', 'video/mp4')
const other = await prisma.project.create({ data: { name: 'Other project', teamId: team.id } })
const otherImage = await prisma.asset.create({
data: {
name: 'other.jpeg',
mediaType: 'image/jpeg',
projectId: other.id,
type: 'file',
status: 'processed',
},
})
for (const id of [video.id, otherImage.id]) {
const req = imageSearchRequestSchema.parse({ sourceAssetId: id })
await expect(searchService.searchByImage(root.id, req)).rejects.toMatchObject({ status: 404 })
}
const req = imageSearchRequestSchema.parse({ sourceAssetId: source.id })
await expect(searchService.searchByImage(subfolder.id, req)).rejects.toMatchObject({
status: 400,
})
})
it('rejects both forms of image search when the agent is disabled', async () => {
const { agent, root, source } = await createProjectAssets()
vi.stubEnv('ENABLE_EMBEDDING_AGENT', 'false')
await expect(
searchService.searchByImage(
root.id,
imageSearchRequestSchema.parse({ sourceAssetId: source.id }),
),
).rejects.toMatchObject({ status: 422 })
vi.stubEnv('ENABLE_EMBEDDING_AGENT', undefined)
await prisma.agent.update({ where: { id: agent.id }, data: { enabled: false } })
const provider = vi.spyOn(imageEmbeddingService, 'generateEmbedding')
await expect(
searchService.searchByImage(root.id, imageSearchRequestSchema.parse({ image: 'aW1hZ2U=' })),
).rejects.toMatchObject({ status: 422 })
expect(provider).not.toHaveBeenCalled()
})
it('matches only latest versions in version stacks for image search and find similar', async () => {
const { user, project, root, subfolder, file } = await createProjectAssets()
const firstStackFiles = await Promise.all([
file('stack-a-v5.jpg', 'image/jpeg', root.id),
file('stack-a-v4.jpg', 'image/jpeg', root.id),
file('stack-a-v3.jpg', 'image/jpeg', root.id),
file('stack-a-v2.jpg', 'image/jpeg', root.id),
file('stack-a-v1.jpg', 'image/jpeg', root.id),
])
const stackA = await versionStackService.createVersionStack({
fileIds: firstStackFiles.map((f) => f.id),
projectId: project.id,
creatorId: user.id,
})
const secondStackFiles = await Promise.all([
file('stack-b-v5.jpg', 'image/jpeg', subfolder.id),
file('stack-b-v4.jpg', 'image/jpeg', subfolder.id),
file('stack-b-v3.jpg', 'image/jpeg', subfolder.id),
file('stack-b-v2.jpg', 'image/jpeg', subfolder.id),
file('stack-b-v1.jpg', 'image/jpeg', subfolder.id),
])
const stackB = await versionStackService.createVersionStack({
fileIds: secondStackFiles.map((f) => f.id),
projectId: project.id,
creatorId: user.id,
})
// Stack C has an embedding ONLY on an older version, not its latest version -> should never match
const thirdStackFiles = await Promise.all([
file('stack-c-v2.jpg', 'image/jpeg', root.id),
file('stack-c-v1.jpg', 'image/jpeg', root.id),
])
await versionStackService.createVersionStack({
fileIds: thirdStackFiles.map((f) => f.id),
projectId: project.id,
creatorId: user.id,
})
// Give every version of stackA and stackB an embedding, plus older version of stackC
await insertEmbedding(firstStackFiles[0].id, vector(1536, 1, 0))
for (const f of firstStackFiles.slice(1)) {
await insertEmbedding(f.id, vector(1536, 1, 0))
}
await insertEmbedding(secondStackFiles[0].id, vector(1536, 1, 1))
for (const f of secondStackFiles.slice(1)) {
await insertEmbedding(f.id, vector(1536, 1, 0))
}
await insertEmbedding(thirdStackFiles[1].id, vector(1536, 1, 0))
// 1) Uploaded-image search returns 2 version stacks, not 11 separate files
vi.spyOn(imageEmbeddingService, 'generateEmbedding').mockResolvedValue(vector(1536, 1, 0))
const byImage = await searchService.searchByImage(
root.id,
imageSearchRequestSchema.parse({ image: 'aW1hZ2U=' }),
)
expect(byImage.pageInfo.total).toBe(2)
expect(byImage.data.map((d) => d.id)).toEqual([stackA.id, stackB.id])
expect(byImage.data[0].type).toBe(AssetType.version_stack)
expect(byImage.data[0].name).toBe('stack-a-v5.jpg')
expect(byImage.data[0].versionStack?.versions).toHaveLength(5)
expect(byImage.data[1].type).toBe(AssetType.version_stack)
expect(byImage.data[1].name).toBe('stack-b-v5.jpg')
expect(byImage.data[1].versionStack?.versions).toHaveLength(5)
// 2) Find similar on stackA's latest version excludes stackA completely (all 5 versions)
const similarFromLatest = await searchService.searchByImage(
root.id,
imageSearchRequestSchema.parse({ sourceAssetId: firstStackFiles[0].id }),
)
expect(similarFromLatest.pageInfo.total).toBe(1)
expect(similarFromLatest.data.map((d) => d.id)).toEqual([stackB.id])
expect(similarFromLatest.data[0].versionStack?.versions).toHaveLength(5)
// 3) Find similar on an older version ID of stackA also excludes stackA completely
const similarFromOlder = await searchService.searchByImage(
root.id,
imageSearchRequestSchema.parse({ sourceAssetId: firstStackFiles[4].id }),
)
expect(similarFromOlder.pageInfo.total).toBe(1)
expect(similarFromOlder.data.map((d) => d.id)).toEqual([stackB.id])
})
it('reuses full stored video sprite for full-range match on a video version stack', async () => {
const { user, project, root, source, file } = await createProjectAssets()
const v2 = await file('clip-v2.mp4', 'video/mp4')
const v1 = await file('clip-v1.mp4', 'video/mp4')
const stack = await versionStackService.createVersionStack({
fileIds: [v2.id, v1.id],
projectId: project.id,
creatorId: user.id,
})
const bucket = process.env.S3_BUCKET || 'shumai'
const fullKey = `files/${v2.id}/sprite.webp`
const chunkKey = `files/${v2.id}/chunk.webp`
await prisma.asset.update({
where: { id: v2.id },
data: {
media: {
duration: 10,
proxyType: 'video',
sprite: { key: fullKey, frames: 100, tileX: 10, tileY: 10 },
} as PrismaJson.MediaInfo,
},
})
await s3Service.putObject(bucket, fullKey, 'sprite', 6, 'image/webp')
try {
await insertEmbedding(source.id, vector(1536, 1))
await insertEmbedding(v2.id, vector(1536, 1), 0, 10, {
key: chunkKey,
columns: 5,
rows: 2,
frameCount: 10,
})
await insertEmbedding(v1.id, vector(1536, 1), 0, 10)
const result = await searchService.searchByImage(
root.id,
imageSearchRequestSchema.parse({ sourceAssetId: source.id }),
)
expect(result.pageInfo.total).toBe(1)
expect(result.data).toHaveLength(1)
expect(result.data[0].id).toBe(stack.id)
expect(result.data[0].type).toBe(AssetType.version_stack)
expect(result.data[0].versionStack?.versions).toHaveLength(2)
expect(result.data[0].preview?.spriteUrl).toContain(fullKey)
expect(result.data[0].matchedSprite).toBeUndefined()
} finally {
await s3Service.deleteObject(bucket, fullKey)
}
})
})
+604 -1
View File
@@ -6,8 +6,10 @@ import { SearchConditionOperator } from '@shumai/dtos'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { textEmbeddingService } from './text-embedding'
import { AssetType } from '@shumai/db'
import { AssetStatus, AssetType } from '@shumai/db'
import { assetService } from '@shumai/core/src/asset/asset'
import { versionStackService } from '@shumai/core/src/versionStack/versionStack'
import { s3Service } from '@shumai/core/src/s3/s3'
describe('SearchService', () => {
setupTestDbHooks()
@@ -805,6 +807,22 @@ describe('SearchService', () => {
)
`
const sprite = { key: 'files/video-a/chunk-0-10.webp', columns: 5, rows: 2, frameCount: 7 }
await prisma.assetEmbedding.update({ where: { id: 'chunk-a1' }, data: { sprite } })
const unsignedKey = 'files/video-b/chunk-5-15.webp'
await prisma.assetEmbedding.update({
where: { id: 'chunk-b1' },
data: { sprite: { ...sprite, key: unsignedKey } },
})
const presign = s3Service.presign.bind(s3Service)
const signSprite = vi
.spyOn(s3Service, 'presign')
.mockImplementation((bucket, key, method) =>
key === unsignedKey
? Promise.reject(new Error('Signing failed'))
: presign(bucket, key, method),
)
// Mock the embedding generation
// Our query vector points along the first dimension [1, 0, 0...]
const queryVector = Array(1536).fill(0)
@@ -838,17 +856,26 @@ describe('SearchService', () => {
expect(result.data[0].id).toBe(videoAssetA.id)
expect(result.data[0].startTime).toBe(0)
expect(result.data[0].endTime).toBe(10)
expect(result.data[0].matchedSprite).toEqual({
url: expect.stringContaining(sprite.key),
columns: 5,
rows: 2,
frameCount: 7,
})
// 2nd: Chunk B1
expect(result.data[1].id).toBe(videoAssetB.id)
expect(result.data[1].startTime).toBe(5)
expect(result.data[1].endTime).toBe(15)
expect(result.data[1].matchedSprite).toBeUndefined()
// 3rd: Chunk A2
expect(result.data[2].id).toBe(videoAssetA.id)
expect(result.data[2].startTime).toBe(10)
expect(result.data[2].endTime).toBe(20)
expect(result.data[2].matchedSprite).toBeUndefined()
signSprite.mockRestore()
mockGenerateEmbedding.mockRestore()
})
@@ -1280,3 +1307,579 @@ describe('SearchService — natural sort by name', () => {
spy.mockRestore()
})
})
describe('SearchService — version stacks', () => {
setupTestDbHooks()
let searchService: SearchService
beforeEach(() => {
searchService = new SearchService()
})
const setupVersionStacks = async () => {
const user = await prisma.user.create({
data: { name: 'stack-user', email: 'stack-search-user@example.com', type: 'human' },
})
const team = await prisma.team.create({ data: { name: 'stack-search-team' } })
const project = await prisma.project.create({
data: { name: 'stack-search-proj', teamId: team.id },
})
const rootFolder = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.root,
projectId: project.id,
creatorId: user.id,
status: 'uploaded',
},
})
await prisma.project.update({
where: { id: project.id },
data: { rootFolderId: rootFolder.id },
})
const subFolder = await prisma.asset.create({
data: {
name: 'subfolder',
type: AssetType.folder,
projectId: project.id,
parentId: rootFolder.id,
creatorId: user.id,
status: 'uploaded',
},
})
const createFile = (data: {
name: string
parentId: string
sizeByte: number
createdAt: Date
status?: AssetStatus
mediaType?: string
}) =>
prisma.asset.create({
data: {
name: data.name,
type: AssetType.file,
projectId: project.id,
parentId: data.parentId,
creatorId: user.id,
sizeByte: data.sizeByte,
createdAt: data.createdAt,
status: data.status ?? AssetStatus.processed,
mediaType: data.mediaType ?? 'image/png',
},
})
// Stack A (in rootFolder): 5 versions, v5 is latest (index 0)
const firstStackFiles = [
await createFile({
name: 'hero_final.png',
parentId: rootFolder.id,
sizeByte: 500,
createdAt: new Date('2026-05-10T10:00:00Z'),
}),
await createFile({
name: 'hero_draft_4.png',
parentId: rootFolder.id,
sizeByte: 400,
createdAt: new Date('2026-05-04T10:00:00Z'),
}),
await createFile({
name: 'hero_draft_3.png',
parentId: rootFolder.id,
sizeByte: 300,
createdAt: new Date('2026-05-03T10:00:00Z'),
}),
await createFile({
name: 'hero_draft_2.png',
parentId: rootFolder.id,
sizeByte: 200,
createdAt: new Date('2026-05-02T10:00:00Z'),
}),
await createFile({
name: 'old_only_keyword.png',
parentId: rootFolder.id,
sizeByte: 100,
createdAt: new Date('2026-05-01T10:00:00Z'),
status: AssetStatus.archived,
}),
]
const stackA = await versionStackService.createVersionStack({
fileIds: firstStackFiles.map((f) => f.id),
projectId: project.id,
creatorId: user.id,
})
// Stack B (in subFolder): 5 versions, v5 is latest (index 0)
const secondStackFiles = [
await createFile({
name: 'hero_banner.png',
parentId: subFolder.id,
sizeByte: 800,
createdAt: new Date('2026-05-12T10:00:00Z'),
}),
await createFile({
name: 'hero_old_4.png',
parentId: subFolder.id,
sizeByte: 200,
createdAt: new Date('2026-05-04T10:00:00Z'),
}),
await createFile({
name: 'hero_old_3.png',
parentId: subFolder.id,
sizeByte: 200,
createdAt: new Date('2026-05-03T10:00:00Z'),
}),
await createFile({
name: 'hero_old_2.png',
parentId: subFolder.id,
sizeByte: 200,
createdAt: new Date('2026-05-02T10:00:00Z'),
}),
await createFile({
name: 'hero_old_1.png',
parentId: subFolder.id,
sizeByte: 200,
createdAt: new Date('2026-05-01T10:00:00Z'),
}),
]
const stackB = await versionStackService.createVersionStack({
fileIds: secondStackFiles.map((f) => f.id),
projectId: project.id,
creatorId: user.id,
})
const standalone = await createFile({
name: 'standalone.png',
parentId: rootFolder.id,
sizeByte: 50,
createdAt: new Date('2026-05-05T10:00:00Z'),
})
// Metadata on latest versions vs older versions
await metadataService.updateAssetMetadata(stackA.id, [{ key: 'status', value: 'approved' }])
await metadataService.updateAssetMetadata(stackB.id, [{ key: 'status', value: 'approved' }])
await metadataService.updateAssetMetadata(firstStackFiles[4].id, [
{ key: 'tag', value: 'legacy' },
])
return {
user,
team,
project,
rootFolder,
subFolder,
stackA,
firstStackFiles,
stackB,
secondStackFiles,
standalone,
}
}
it('returns 2 version stacks instead of 10 individual versions in recursive and non-recursive search', async () => {
const { rootFolder, stackA, stackB, standalone } = await setupVersionStacks()
const recursive = await searchService.search(rootFolder.id, {
recursively: true,
assetType: 'file',
operator: 'AND',
conditions: [],
isSemantic: false,
})
expect(recursive.pageInfo.total).toBe(3)
expect(recursive.pageInfo.totalSize).toBe(500 + 800 + 50)
expect(recursive.data.map((a) => a.id).sort()).toEqual(
[stackA.id, stackB.id, standalone.id].sort(),
)
const returnedA = recursive.data.find((a) => a.id === stackA.id)!
const returnedB = recursive.data.find((a) => a.id === stackB.id)!
expect(returnedA.type).toBe(AssetType.version_stack)
expect(returnedA.name).toBe('hero_final.png')
expect(returnedA.versionStack?.id).toBe(stackA.id)
expect(returnedA.versionStack?.versions).toHaveLength(5)
expect(returnedB.type).toBe(AssetType.version_stack)
expect(returnedB.name).toBe('hero_banner.png')
expect(returnedB.versionStack?.versions).toHaveLength(5)
const nonRecursive = await searchService.search(rootFolder.id, {
recursively: false,
assetType: 'file',
operator: 'AND',
conditions: [],
isSemantic: false,
})
expect(nonRecursive.pageInfo.total).toBe(2)
expect(nonRecursive.pageInfo.totalSize).toBe(500 + 50)
expect(nonRecursive.data.map((a) => a.id).sort()).toEqual([stackA.id, standalone.id].sort())
})
it('matches name contains (n-gram) against latest version only and updates when latest version changes', async () => {
const { rootFolder, stackA, firstStackFiles, stackB } = await setupVersionStacks()
const heroSearch = await searchService.search(rootFolder.id, {
recursively: true,
operator: 'AND',
conditions: [{ field: 'name', operator: 'contains', value: 'hero' }],
isSemantic: false,
})
expect(heroSearch.pageInfo.total).toBe(2)
expect(heroSearch.pageInfo.totalSize).toBe(500 + 800)
expect(heroSearch.data.map((a) => a.id).sort()).toEqual([stackA.id, stackB.id].sort())
expect(heroSearch.data.every((a) => a.type === AssetType.version_stack)).toBe(true)
// Non-recursive name filter matches stackA in rootFolder
const rootOnlyHero = await searchService.search(rootFolder.id, {
recursively: false,
operator: 'AND',
conditions: [{ field: 'name', operator: 'contains', value: 'hero' }],
isSemantic: false,
})
expect(rootOnlyHero.data.map((a) => a.id)).toEqual([stackA.id])
// Keyword present only on older version v1 does NOT match
const oldOnly = await searchService.search(rootFolder.id, {
recursively: true,
operator: 'AND',
conditions: [{ field: 'name', operator: 'contains', value: 'old_only_keyword' }],
isSemantic: false,
})
expect(oldOnly.pageInfo.total).toBe(0)
expect(oldOnly.data).toHaveLength(0)
// Promote v1 to latest version -> now stackA matches
await versionStackService.changeStackFileVersion({
stackId: stackA.id,
fileId: firstStackFiles[4].id,
beforeId: firstStackFiles[0].id,
})
const promoted = await searchService.search(rootFolder.id, {
recursively: true,
operator: 'AND',
conditions: [{ field: 'name', operator: 'contains', value: 'old_only_keyword' }],
isSemantic: false,
})
expect(promoted.pageInfo.total).toBe(1)
expect(promoted.data).toHaveLength(1)
expect(promoted.data[0].id).toBe(stackA.id)
expect(promoted.data[0].type).toBe(AssetType.version_stack)
expect(promoted.data[0].name).toBe('old_only_keyword.png')
})
it('evaluates metadata, isArchived, sizeByte, createdAt filters and sorting against latest version only', async () => {
const { rootFolder, stackA, firstStackFiles, stackB, standalone } = await setupVersionStacks()
// Metadata on latest version matches both stacks once
const approved = await searchService.search(rootFolder.id, {
recursively: true,
operator: 'AND',
conditions: [{ field: 'status', operator: 'eq', value: 'approved' }],
isSemantic: false,
})
expect(approved.pageInfo.total).toBe(2)
expect(approved.data.map((a) => a.id).sort()).toEqual([stackA.id, stackB.id].sort())
// Metadata only on older version does not match
const legacy = await searchService.search(rootFolder.id, {
recursively: true,
operator: 'AND',
conditions: [{ field: 'tag', operator: 'eq', value: 'legacy' }],
isSemantic: false,
})
expect(legacy.pageInfo.total).toBe(0)
// isArchived = true: only v1 of stackA is archived, not latest v5 -> 0 matches
const archivedBefore = await searchService.search(rootFolder.id, {
recursively: true,
operator: 'AND',
conditions: [{ field: 'isArchived', operator: 'eq', value: true }],
isSemantic: false,
})
expect(archivedBefore.pageInfo.total).toBe(0)
// Archive latest version of stackA -> returns stackA once (not both stack and child file)
await prisma.asset.update({
where: { id: firstStackFiles[0].id },
data: { status: AssetStatus.archived },
})
const archivedAfter = await searchService.search(rootFolder.id, {
recursively: true,
operator: 'AND',
conditions: [{ field: 'isArchived', operator: 'eq', value: true }],
isSemantic: false,
})
expect(archivedAfter.pageInfo.total).toBe(1)
expect(archivedAfter.data.map((a) => a.id)).toEqual([stackA.id])
// sizeByte evaluates latest version (stackA latest = 500, cumulative = 1500; stackB latest = 800)
const largeFiles = await searchService.search(rootFolder.id, {
recursively: true,
operator: 'AND',
conditions: [{ field: 'sizeByte', operator: 'gt', value: 600 }],
isSemantic: false,
})
expect(largeFiles.data.map((a) => a.id)).toEqual([stackB.id])
// createdAt evaluates latest version
const recentFiles = await searchService.search(rootFolder.id, {
recursively: true,
operator: 'AND',
conditions: [{ field: 'createdAt', operator: 'gte', value: '2026-05-11' }],
isSemantic: false,
})
expect(recentFiles.data.map((a) => a.id)).toEqual([stackB.id])
// Sort by name asc uses latest version name
const byName = await searchService.search(rootFolder.id, {
recursively: true,
operator: 'AND',
conditions: [],
isSemantic: false,
sort: { field: 'name', order: 'asc' },
})
expect(byName.data.map((a) => a.name)).toEqual([
'hero_banner.png',
'hero_final.png',
'standalone.png',
])
// Sort by sizeByte desc uses latest version size
const bySize = await searchService.search(rootFolder.id, {
recursively: true,
operator: 'AND',
conditions: [],
isSemantic: false,
sort: { field: 'sizeByte', order: 'desc' },
})
expect(bySize.data.map((a) => a.id)).toEqual([stackB.id, stackA.id, standalone.id])
// Sort by createdAt desc uses latest version createdAt
const byCreatedAt = await searchService.search(rootFolder.id, {
recursively: true,
operator: 'AND',
conditions: [],
isSemantic: false,
sort: { field: 'createdAt', order: 'desc' },
})
expect(byCreatedAt.data.map((a) => a.id)).toEqual([stackB.id, stackA.id, standalone.id])
})
it('semantic text search matches latest version embeddings only and returns version_stack items', async () => {
const { team, rootFolder, stackA, firstStackFiles, stackB, secondStackFiles } =
await setupVersionStacks()
const botUser = await prisma.user.create({
data: { name: 'Stack Emb Bot', email: 'stack-emb@example.com', type: 'agent' },
})
await prisma.agent.create({
data: {
id: botUser.id,
teamId: team.id,
type: 'embedding',
enabled: true,
config: { provider: 'google', model: 'gemini' },
},
})
const vec = (x: number, y: number) => {
const arr = Array<number>(1536).fill(0)
arr[0] = x
arr[1] = y
return JSON.stringify(arr)
}
// Insert embeddings for ALL 5 versions of stackA (older version v1 has exact match [1,0], latest v5 has [1,1])
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, created_at, updated_at)
VALUES ('sa-v5', ${firstStackFiles[0].id}, ${vec(1, 1)}::vector, NOW(), NOW())
`
for (let i = 1; i < firstStackFiles.length; i++) {
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, created_at, updated_at)
VALUES (${`sa-v${5 - i}`}, ${firstStackFiles[i].id}, ${vec(1, 0)}::vector, NOW(), NOW())
`
}
// Insert 2 video chunk embeddings on stackB's latest version + 1 embedding on an older version
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, created_at, updated_at)
VALUES ('sb-v5-c1', ${secondStackFiles[0].id}, ${vec(1, 0)}::vector, 5, 15, NOW(), NOW())
`
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, created_at, updated_at)
VALUES ('sb-v5-c2', ${secondStackFiles[0].id}, ${vec(0, 1)}::vector, 20, 30, NOW(), NOW())
`
for (let i = 1; i < secondStackFiles.length; i++) {
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, created_at, updated_at)
VALUES (${`sb-v${5 - i}`}, ${secondStackFiles[i].id}, ${vec(1, 0)}::vector, NOW(), NOW())
`
}
const queryVec = Array<number>(1536).fill(0)
queryVec[0] = 1
const mockEmb = vi
.spyOn(textEmbeddingService, 'generateEmbedding')
.mockResolvedValue({ embedding: queryVec })
try {
const result = await searchService.search(rootFolder.id, {
recursively: true,
operator: 'AND',
conditions: [],
query: 'hero shot',
isSemantic: true,
})
// Expect 3 results total: stackB chunk 1 (dist 0), stackA latest (dist 0.293), stackB chunk 2 (dist 1.0)
// None of the 8 older versions should appear
expect(result.pageInfo.total).toBe(3)
expect(result.data).toHaveLength(3)
expect(
result.data.map((d) => ({ id: d.id, startTime: d.startTime, endTime: d.endTime })),
).toEqual([
{ id: stackB.id, startTime: 5, endTime: 15 },
{ id: stackA.id, startTime: null, endTime: null },
{ id: stackB.id, startTime: 20, endTime: 30 },
])
expect(result.data[0].type).toBe(AssetType.version_stack)
expect(result.data[0].versionStack?.versions).toHaveLength(5)
expect(result.data[1].type).toBe(AssetType.version_stack)
expect(result.data[1].versionStack?.versions).toHaveLength(5)
} finally {
mockEmb.mockRestore()
}
})
it('finds a file moved between projects in the same team via semantic text search', async () => {
const { user, team, rootFolder, standalone } = await setupVersionStacks()
const botUser = await prisma.user.create({
data: { name: 'Moved Emb Bot', email: 'moved-emb@example.com', type: 'agent' },
})
await prisma.agent.create({
data: {
id: botUser.id,
teamId: team.id,
type: 'embedding',
enabled: true,
config: { provider: 'google', model: 'gemini' },
},
})
const destProject = await prisma.project.create({
data: { name: 'dest-project', teamId: team.id },
})
const destRoot = await prisma.asset.create({
data: {
name: 'dest-root',
type: AssetType.root,
projectId: destProject.id,
creatorId: user.id,
status: 'uploaded',
},
})
const vec = Array<number>(1536).fill(0)
vec[0] = 1
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, created_at, updated_at)
VALUES ('moved-file-emb', ${standalone.id}, ${JSON.stringify(vec)}::vector, NOW(), NOW())
`
await assetService.reparentAssets({
assetIds: [standalone.id],
newParentId: destRoot.id,
creatorId: user.id,
})
const mockEmb = vi
.spyOn(textEmbeddingService, 'generateEmbedding')
.mockResolvedValue({ embedding: vec })
try {
const destResult = await searchService.search(destRoot.id, {
recursively: true,
operator: 'AND',
conditions: [],
query: 'moved asset',
isSemantic: true,
})
expect(destResult.pageInfo.total).toBe(1)
expect(destResult.data.map((d) => d.id)).toEqual([standalone.id])
const sourceResult = await searchService.search(rootFolder.id, {
recursively: true,
operator: 'AND',
conditions: [],
query: 'moved asset',
isSemantic: true,
})
expect(sourceResult.pageInfo.total).toBe(0)
} finally {
mockEmb.mockRestore()
}
})
it('returns the latest version createdAt and updatedAt on date-filtered version stacks', async () => {
const { user, project, rootFolder } = await setupVersionStacks()
const latestCreatedAt = new Date('2020-01-15T10:00:00Z')
const latestUpdatedAt = new Date('2020-01-20T12:30:00Z')
const v2 = await prisma.asset.create({
data: {
name: 'archival_v2.png',
type: AssetType.file,
projectId: project.id,
parentId: rootFolder.id,
creatorId: user.id,
sizeByte: 300,
status: AssetStatus.processed,
createdAt: latestCreatedAt,
updatedAt: latestUpdatedAt,
},
})
const v1 = await prisma.asset.create({
data: {
name: 'archival_v1.png',
type: AssetType.file,
projectId: project.id,
parentId: rootFolder.id,
creatorId: user.id,
sizeByte: 200,
status: AssetStatus.processed,
createdAt: new Date('2019-06-01T00:00:00Z'),
updatedAt: new Date('2019-06-01T00:00:00Z'),
},
})
const stack = await versionStackService.createVersionStack({
fileIds: [v2.id, v1.id],
projectId: project.id,
creatorId: user.id,
})
// Restore explicit updatedAt on v2 after reparenting into stack
await prisma.$executeRaw`
UPDATE assets SET updated_at = ${latestUpdatedAt} WHERE id = ${v2.id}
`
const result = await searchService.search(rootFolder.id, {
recursively: true,
operator: 'AND',
conditions: [{ field: 'createdAt', operator: 'eq', value: '2020-01-15' }],
isSemantic: false,
})
expect(result.pageInfo.total).toBe(1)
expect(result.data).toHaveLength(1)
expect(result.data[0].id).toBe(stack.id)
expect(result.data[0].createdAt).toBe(latestCreatedAt.toISOString())
expect(result.data[0].updatedAt).toBe(latestUpdatedAt.toISOString())
})
})
+426 -274
View File
@@ -1,11 +1,14 @@
import { prisma } from '@shumai/db'
import { Prisma, AssetType } from '@shumai/db'
import { AssetService, assetService } from '@shumai/core/src/asset/asset'
import { AssetInfo } from '@shumai/dtos'
import { SearchRequest } from '@shumai/dtos'
import type { AssetInfo, ImageSearchRequest, SearchRequest } from '@shumai/dtos'
import { logger } from '@shumai/core/src/logger'
import { s3Service } from '@shumai/core/src/s3/s3'
import { hasStoredVideoSprite, isFullVideoRange } from '@shumai/core/src/transcode/video-sprite'
import { PaginatedData, decodeCursor, encodeCursor, PageInfo } from '@shumai/core/src/pagination'
import { generateSearchNgrams } from '@shumai/core/src/utils/ngram'
import { HTTPException } from 'hono/http-exception'
import { getImageEmbeddingDimensions, imageEmbeddingService } from './image-embedding'
import { SqlQueryBuilder } from './sql-query-builder'
import { TextEmbeddingService, textEmbeddingService } from './text-embedding'
@@ -20,231 +23,44 @@ export class SearchService {
const targetFolderIds =
req.recursively === false ? [folderId] : await this.assetSvc.getDescendantFolderIds(folderId)
const targetTypes =
req.assetType === 'folder' ? [AssetType.folder] : [AssetType.file, AssetType.version_stack]
const isFolderSearch = req.assetType === 'folder'
// ----------------------------------------------------------------------
// AI Semantic search
// ----------------------------------------------------------------------
if (req.query && req.isSemantic) {
// 1. Check if embedding agent exists and is enabled
const team = await this.prismaClient.asset.findUnique({
const folder = await this.prismaClient.asset.findUnique({
where: { id: folderId },
select: { project: { select: { teamId: true } } },
})
const teamId = team?.project?.teamId
const teamId = folder?.project?.teamId
if (!teamId) throw new Error('Team ID not found for folder')
await this.requireEmbeddingAgent(teamId)
if (process.env.ENABLE_EMBEDDING_AGENT === 'false') {
throw new HTTPException(422, {
message: 'Embedding agent not configured or disabled for this team.',
})
}
const embeddingAgent = await this.prismaClient.agent.findFirst({
where: { teamId, type: 'embedding', enabled: true },
})
if (!embeddingAgent) {
throw new HTTPException(422, {
message: 'Embedding agent not configured or disabled for this team.',
})
}
// 2. Generate query embedding directly using configured environment provider
let queryVector: number[]
let vector: number[]
try {
const result = await this.embeddingSvc.generateEmbedding(req.query, {
teamId,
})
queryVector = result.embedding
const result = await this.embeddingSvc.generateEmbedding(req.query, { teamId })
vector = result.embedding
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
throw new HTTPException(502, {
message: `Failed to generate query embedding: ${msg}`,
})
}
if (!queryVector || queryVector.length === 0) {
if (!vector || vector.length === 0) {
throw new HTTPException(502, {
message: 'Failed to generate query embedding: empty vector returned',
})
}
// 3. Construct raw SQL using SqlQueryBuilder
const vectorJson = JSON.stringify(queryVector)
const is768 = queryVector.length === 768
const distanceExpr = is768
? Prisma.sql`(ae.embedding_768 <=> ${vectorJson}::vector)`
: Prisma.sql`(ae.embedding <=> ${vectorJson}::vector)`
const notNullCond = is768
? Prisma.sql`ae.embedding_768 IS NOT NULL`
: Prisma.sql`ae.embedding IS NOT NULL`
const builder = new SqlQueryBuilder()
.select(
Prisma.sql`a.id as "assetId", ae.start_time as "startTime", ae.end_time as "endTime", ${distanceExpr} as "distance"`,
)
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
.addWhere(Prisma.sql`a.is_deleted = false`)
.addWhere(notNullCond)
if (targetFolderIds.length > 0) {
builder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
builder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
builder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
builder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
const nameCond = req.conditions?.find((c) => c.field === 'name' && c.operator === 'contains')
if (nameCond) {
const valStr = String(nameCond.value)
const ngrams = generateSearchNgrams(valStr)
if (ngrams.length > 0) {
builder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
} else {
builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
}
builder.orderBy(Prisma.sql`distance ASC`)
// 4. Paginate in SQL using limit/offset
let limit = req.first || 20
if (limit <= 0 || limit > 200) {
limit = 20
}
let offset = 0
if (req.after) {
offset = decodeCursor(req.after)
}
builder.limit(limit + 1).offset(offset)
// 5. Execute raw SQL query
const query = builder.build()
const semanticMatches = await this.prismaClient.$queryRaw<
{
assetId: string
startTime: number | null
endTime: number | null
distance: number
}[]
>(query)
const hasNextPage = semanticMatches.length > limit
const finalMatches = hasNextPage ? semanticMatches.slice(0, limit) : semanticMatches
// 6. Map back to full rich metadata and return time-based duplicate segments
const uniqueIds = Array.from(new Set(finalMatches.map((m) => m.assetId)))
const fetchedInfos = await this.assetSvc.listAssetsByIds(uniqueIds, req.previewFormat)
const assetInfosMap = new Map<string, AssetInfo>()
for (const info of fetchedInfos) {
assetInfosMap.set(info.id, info)
}
const data: AssetInfo[] = []
for (const match of finalMatches) {
const baseInfo = assetInfosMap.get(match.assetId)
if (baseInfo) {
data.push({
...baseInfo,
startTime: match.startTime,
endTime: match.endTime,
})
}
}
const pageInfo: PageInfo = {}
const countBuilder = new SqlQueryBuilder()
.select(Prisma.sql`COUNT(*)`)
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
.addWhere(Prisma.sql`a.is_deleted = false`)
.addWhere(notNullCond)
if (targetFolderIds.length > 0) {
countBuilder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
countBuilder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
countBuilder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
countBuilder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
if (nameCond) {
const valStr = String(nameCond.value)
const ngrams = generateSearchNgrams(valStr)
if (ngrams.length > 0) {
countBuilder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
} else {
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
}
const countRes = await this.prismaClient.$queryRaw<{ count: bigint }[]>(countBuilder.build())
const totalCount = Number(countRes[0]?.count || 0)
pageInfo.total = totalCount
if (totalCount < 2000) {
countBuilder.select(Prisma.sql`SUM(COALESCE(a.size_byte, 0))::bigint as sum`)
const sumRes = await this.prismaClient.$queryRaw<{ sum: bigint | null }[]>(
countBuilder.build(),
)
pageInfo.totalSize = Number(sumRes[0]?.sum || 0)
} else {
pageInfo.totalSize = -1
}
if (hasNextPage) {
pageInfo.cursor = encodeCursor(offset + limit)
}
return { data, pageInfo }
return this.searchByEmbedding(
targetFolderIds,
req,
JSON.stringify(vector),
vector.length === 768 ? 768 : 1536,
)
}
// ----------------------------------------------------------------------
// Non-semantic search (using SqlQueryBuilder)
// ----------------------------------------------------------------------
const builder = new SqlQueryBuilder()
.select(Prisma.sql`a.id as "assetId"`)
.from(Prisma.sql`assets a`)
.addWhere(Prisma.sql`a.is_deleted = false`)
if (targetFolderIds.length > 0) {
builder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
builder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
builder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
builder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
// name contains n-grams / Switching Search Optimization
let countOverride: number | undefined
let useNgram = false
@@ -260,23 +76,12 @@ export class SearchService {
if (ngrams.length > 0) {
const PROBE_LIMIT = 10001
// Build SQL probe query to limit and fetch selective IDs
const probeBuilder = new SqlQueryBuilder()
.select(Prisma.sql`a.id`)
.from(Prisma.sql`assets a`)
.addWhere(Prisma.sql`a.is_deleted = false`)
if (targetFolderIds.length > 0) {
probeBuilder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
probeBuilder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
probeBuilder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
// Build SQL probe query to limit and fetch selective IDs using the GIN index first
const probeBuilder = isFolderSearch
? this.createFolderBaseBuilder(targetFolderIds, req.showSymlink).select(Prisma.sql`a.id`)
: this.createLatestFileGinBuilder(targetFolderIds, req.showSymlink).select(
Prisma.sql`CASE WHEN p.type = 'version_stack'::"AssetType" THEN p.id ELSE a.id END as id`,
)
if (req.conditions && req.conditions.length > 0) {
probeBuilder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
@@ -300,6 +105,23 @@ export class SearchService {
}
}
const useGinDriver = !isFolderSearch && Boolean(nameCond && useNgram && ngrams.length > 0)
const builder = isFolderSearch
? this.createFolderBaseBuilder(targetFolderIds, req.showSymlink).select(
Prisma.sql`a.id as "assetId"`,
)
: useGinDriver
? this.createLatestFileGinBuilder(targetFolderIds, req.showSymlink).select(
Prisma.sql`CASE WHEN p.type = 'version_stack'::"AssetType" THEN p.id ELSE a.id END as "assetId"`,
)
: this.createScopedFilesBuilder(targetFolderIds, req.showSymlink).select(
Prisma.sql`sa."returnId" as "assetId"`,
)
if (req.conditions && req.conditions.length > 0) {
builder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
if (nameCond) {
if (useNgram && ngrams.length > 0) {
builder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
@@ -310,11 +132,22 @@ export class SearchService {
}
// Sorting
let orderSql = Prisma.sql`a.sort_index ASC`
const customSortSql = isFolderSearch
? Prisma.sql`a.sort_index ASC`
: useGinDriver
? Prisma.sql`CASE WHEN p.type = 'version_stack'::"AssetType" THEN p.sort_index ELSE a.sort_index END ASC`
: Prisma.sql`sa."customSortIndex" ASC`
const fallbackSortSql = isFolderSearch
? Prisma.sql`a.id DESC`
: useGinDriver
? Prisma.sql`CASE WHEN p.type = 'version_stack'::"AssetType" THEN p.id ELSE a.id END DESC`
: Prisma.sql`sa."returnId" DESC`
let orderSql = customSortSql
if (req.sort) {
const direction = req.sort.order === 'desc' ? Prisma.raw('DESC') : Prisma.raw('ASC')
if (req.sort.field === 'custom') {
orderSql = Prisma.sql`a.sort_index ASC`
orderSql = customSortSql
} else if (req.sort.field === 'name') {
orderSql = Prisma.sql`a.name ${direction}`
} else if (req.sort.field === 'created_at' || req.sort.field === 'createdAt') {
@@ -322,7 +155,7 @@ export class SearchService {
} else if (req.sort.field === 'size_byte' || req.sort.field === 'sizeByte') {
orderSql = Prisma.sql`a.size_byte ${direction}`
} else {
orderSql = Prisma.sql`a.id DESC`
orderSql = fallbackSortSql
}
}
builder.orderBy(orderSql)
@@ -363,34 +196,29 @@ export class SearchService {
}
}
const createAggregateBuilder = () => {
const aggBuilder = isFolderSearch
? this.createFolderBaseBuilder(targetFolderIds, req.showSymlink)
: useGinDriver
? this.createLatestFileGinBuilder(targetFolderIds, req.showSymlink)
: this.createScopedFilesBuilder(targetFolderIds, req.showSymlink)
if (req.conditions && req.conditions.length > 0) {
aggBuilder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
if (nameCond) {
if (useNgram && ngrams.length > 0) {
aggBuilder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
}
aggBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
return aggBuilder
}
const pageInfo: PageInfo = {}
let totalCount = countOverride
if (totalCount === undefined) {
const countBuilder = new SqlQueryBuilder()
.select(Prisma.sql`COUNT(*)`)
.from(Prisma.sql`assets a`)
.addWhere(Prisma.sql`a.is_deleted = false`)
if (targetFolderIds.length > 0) {
countBuilder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
countBuilder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
countBuilder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
countBuilder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
if (nameCond) {
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
const countBuilder = createAggregateBuilder().select(Prisma.sql`COUNT(*)`)
const countRes = await this.prismaClient.$queryRaw<{ count: bigint }[]>(countBuilder.build())
totalCount = Number(countRes[0]?.count || 0)
pageInfo.total = totalCount
@@ -407,33 +235,11 @@ export class SearchService {
} else {
pageInfo.total = totalCount
if (totalCount < 2000) {
const countBuilder = new SqlQueryBuilder()
.select(Prisma.sql`SUM(COALESCE(a.size_byte, 0))::bigint as sum`)
.from(Prisma.sql`assets a`)
.addWhere(Prisma.sql`a.is_deleted = false`)
if (targetFolderIds.length > 0) {
countBuilder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
countBuilder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
countBuilder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
countBuilder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
if (nameCond) {
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
const sumBuilder = createAggregateBuilder().select(
Prisma.sql`SUM(COALESCE(a.size_byte, 0))::bigint as sum`,
)
const sumRes = await this.prismaClient.$queryRaw<{ sum: bigint | null }[]>(
countBuilder.build(),
sumBuilder.build(),
)
pageInfo.totalSize = Number(sumRes[0]?.sum || 0)
} else {
@@ -447,6 +253,352 @@ export class SearchService {
return { data, pageInfo }
}
async searchByImage(
folderId: string,
req: ImageSearchRequest,
): Promise<PaginatedData<AssetInfo[]>> {
const folder = await this.prismaClient.asset.findFirst({
where: { id: folderId, type: { in: [AssetType.root, AssetType.folder] }, isDeleted: false },
select: { project: { select: { id: true, teamId: true, rootFolderId: true } } },
})
const project = folder?.project
if (!project) throw new HTTPException(404, { message: 'Project folder not found.' })
await this.requireEmbeddingAgent(project.teamId)
const dimensions = getImageEmbeddingDimensions()
let vector: string
let excludeAssetId: string | undefined
if (req.sourceAssetId) {
if (folderId !== project.rootFolderId) {
throw new HTTPException(400, { message: 'Find similar requires the project root folder.' })
}
const column = dimensions === 768 ? Prisma.sql`embedding_768` : Prisma.sql`embedding`
const [source] = await this.prismaClient.$queryRaw<
{ vector: string | null; excludeAssetId: string }[]
>`
SELECT
(
SELECT ${column}::text
FROM asset_embeddings
WHERE asset_id = a.id AND ${column} IS NOT NULL
ORDER BY id DESC
LIMIT 1
) AS vector,
CASE
WHEN p.type = 'version_stack'::"AssetType" THEN p.id
ELSE a.id
END AS "excludeAssetId"
FROM assets a
LEFT JOIN assets p ON p.id = a.parent_id AND p.is_deleted = false
WHERE a.id = ${req.sourceAssetId} AND a.project_id = ${project.id}
AND a.type = 'file' AND a.media_type LIKE 'image/%' AND a.is_deleted = false
`
if (!source) throw new HTTPException(404, { message: 'Source image not found.' })
if (!source.vector) {
throw new HTTPException(409, { message: 'The source image is waiting to be indexed.' })
}
vector = source.vector
excludeAssetId = source.excludeAssetId
} else if (req.image) {
vector = JSON.stringify(
await imageEmbeddingService.generateEmbedding(req.image, project.teamId),
)
} else {
throw new HTTPException(400, { message: 'Provide a search image or source asset.' })
}
const folders = await this.assetSvc.getDescendantFolderIds(folderId)
return this.searchByEmbedding(folders, req, vector, dimensions, {
projectId: project.id,
mediaType: req.mediaType,
excludeAssetId,
})
}
private createFolderBaseBuilder(folderIds: string[], showSymlink?: boolean): SqlQueryBuilder {
const targetTypes = [AssetType.folder]
const builder = new SqlQueryBuilder()
.from(Prisma.sql`assets a`)
.addWhere(Prisma.sql`a.is_deleted = false`)
if (folderIds.length > 0) {
builder.addWhere(Prisma.sql`a.parent_id = ANY(${folderIds})`)
}
if (showSymlink) {
builder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]) AND is_deleted = false)))
`)
} else {
builder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
return builder
}
private buildScopedFilesCte(folderIds: string[], showSymlink?: boolean): Prisma.Sql {
const directTypeCondition = showSymlink
? Prisma.sql`(d.type = 'file'::"AssetType" OR (d.type = 'symlink'::"AssetType" AND d.target_id IN (SELECT id FROM assets WHERE type = ANY(ARRAY['file', 'version_stack']::"AssetType"[]) AND is_deleted = false)))`
: Prisma.sql`d.type = 'file'::"AssetType"`
return Prisma.sql`scoped_assets AS (
SELECT
d.id AS "returnId",
d.id AS "matchId",
d.sort_index AS "customSortIndex"
FROM assets d
WHERE d.is_deleted = false
AND d.parent_id = ANY(${folderIds})
AND ${directTypeCondition}
UNION ALL
SELECT
s.id AS "returnId",
lv.id AS "matchId",
s.sort_index AS "customSortIndex"
FROM assets s
CROSS JOIN LATERAL (
SELECT v.id
FROM assets v
WHERE v.parent_id = s.id
AND v.is_deleted = false
AND v.type = 'file'::"AssetType"
ORDER BY v.sort_index ASC, v.id ASC
LIMIT 1
) lv
WHERE s.is_deleted = false
AND s.parent_id = ANY(${folderIds})
AND s.type = 'version_stack'::"AssetType"
)`
}
private createScopedFilesBuilder(folderIds: string[], showSymlink?: boolean): SqlQueryBuilder {
return new SqlQueryBuilder()
.with(this.buildScopedFilesCte(folderIds, showSymlink))
.from(Prisma.sql`scoped_assets sa JOIN assets a ON a.id = sa."matchId"`)
.addWhere(Prisma.sql`a.is_deleted = false`)
}
private buildLatestFileScopeCondition(folderIds: string[], showSymlink?: boolean): Prisma.Sql {
const directTypeCondition = showSymlink
? Prisma.sql`(a.type = 'file'::"AssetType" OR (a.type = 'symlink'::"AssetType" AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(ARRAY['file', 'version_stack']::"AssetType"[]) AND is_deleted = false)))`
: Prisma.sql`a.type = 'file'::"AssetType"`
return Prisma.sql`(
(p.type <> 'version_stack'::"AssetType" AND a.parent_id = ANY(${folderIds}) AND ${directTypeCondition})
OR (
p.type = 'version_stack'::"AssetType"
AND p.parent_id = ANY(${folderIds})
AND a.type = 'file'::"AssetType"
AND a.id = (
SELECT v.id
FROM assets v
WHERE v.parent_id = p.id
AND v.is_deleted = false
AND v.type = 'file'::"AssetType"
ORDER BY v.sort_index ASC, v.id ASC
LIMIT 1
)
)
)`
}
private createLatestFileGinBuilder(folderIds: string[], showSymlink?: boolean): SqlQueryBuilder {
return new SqlQueryBuilder()
.from(Prisma.sql`assets a JOIN assets p ON p.id = a.parent_id AND p.is_deleted = false`)
.addWhere(Prisma.sql`a.is_deleted = false`)
.addWhere(this.buildLatestFileScopeCondition(folderIds, showSymlink))
}
private async requireEmbeddingAgent(teamId: string): Promise<void> {
const agent =
process.env.ENABLE_EMBEDDING_AGENT === 'false'
? null
: await this.prismaClient.agent.findFirst({
where: { teamId, type: 'embedding', enabled: true },
select: { id: true },
})
if (!agent) {
throw new HTTPException(422, {
message: 'Embedding agent not configured or disabled for this team.',
})
}
}
private async searchByEmbedding(
folderIds: string[],
req: Pick<
SearchRequest,
'assetType' | 'showSymlink' | 'conditions' | 'operator' | 'first' | 'after' | 'previewFormat'
>,
vector: string,
dimensions: 768 | 1536,
visual?: {
projectId: string
mediaType?: ImageSearchRequest['mediaType']
excludeAssetId?: string
},
): Promise<PaginatedData<AssetInfo[]>> {
const column = dimensions === 768 ? Prisma.sql`ae.embedding_768` : Prisma.sql`ae.embedding`
const distance = Prisma.sql`(${column} <=> ${vector}::vector)`
const isFolderSearch = !visual && req.assetType === 'folder'
const applyCommonEmbeddingFilters = (target: SqlQueryBuilder) => {
target.addWhere(Prisma.sql`a.is_deleted = false`).addWhere(Prisma.sql`${column} IS NOT NULL`)
if (visual) {
target
.addWhere(Prisma.sql`a.project_id = ${visual.projectId}`)
.addWhere(
visual.mediaType
? Prisma.sql`a.media_type LIKE ${visual.mediaType + '/%'}`
: Prisma.sql`(a.media_type LIKE 'image/%' OR a.media_type LIKE 'video/%')`,
)
}
target.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
const nameCond = req.conditions?.find((c) => c.field === 'name' && c.operator === 'contains')
if (nameCond) {
const name = String(nameCond.value)
const ngrams = generateSearchNgrams(name)
if (ngrams.length > 0) target.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
target.addWhere(Prisma.sql`a.name ILIKE ${'%' + name + '%'}`)
}
return target
}
// Main result query drives from the pgvector HNSW index on asset_embeddings
const resultBuilder = isFolderSearch
? new SqlQueryBuilder()
.from(Prisma.sql`asset_embeddings ae JOIN assets a ON a.id = ae.asset_id`)
.addWhere(Prisma.sql`a.parent_id = ANY(${folderIds})`)
.addWhere(
req.showSymlink
? Prisma.sql`(a.type = 'folder'::"AssetType" OR (a.type = 'symlink'::"AssetType" AND a.target_id IN (SELECT id FROM assets WHERE type = 'folder'::"AssetType" AND is_deleted = false)))`
: Prisma.sql`a.type = 'folder'::"AssetType"`,
)
: new SqlQueryBuilder()
.from(
Prisma.sql`asset_embeddings ae JOIN assets a ON a.id = ae.asset_id JOIN assets p ON p.id = a.parent_id AND p.is_deleted = false`,
)
.addWhere(this.buildLatestFileScopeCondition(folderIds, !visual && req.showSymlink))
applyCommonEmbeddingFilters(resultBuilder)
if (visual?.excludeAssetId) {
resultBuilder.addWhere(
Prisma.sql`a.id <> ${visual.excludeAssetId} AND p.id <> ${visual.excludeAssetId}`,
)
}
// Count/size query drives from the scoped folder/version_stack CTE + asset_embeddings(asset_id) index
const aggBuilder = isFolderSearch
? new SqlQueryBuilder()
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
.addWhere(Prisma.sql`a.parent_id = ANY(${folderIds})`)
.addWhere(
req.showSymlink
? Prisma.sql`(a.type = 'folder'::"AssetType" OR (a.type = 'symlink'::"AssetType" AND a.target_id IN (SELECT id FROM assets WHERE type = 'folder'::"AssetType" AND is_deleted = false)))`
: Prisma.sql`a.type = 'folder'::"AssetType"`,
)
: new SqlQueryBuilder()
.with(this.buildScopedFilesCte(folderIds, !visual && req.showSymlink))
.from(
Prisma.sql`scoped_assets sa JOIN assets a ON a.id = sa."matchId" JOIN asset_embeddings ae ON ae.asset_id = a.id`,
)
applyCommonEmbeddingFilters(aggBuilder)
if (visual?.excludeAssetId && !isFolderSearch) {
aggBuilder.addWhere(Prisma.sql`sa."returnId" <> ${visual.excludeAssetId}`)
}
const countQuery = aggBuilder.select(Prisma.sql`COUNT(*)`).build()
const sizeQuery = aggBuilder
.select(Prisma.sql`SUM(COALESCE(a.size_byte, 0))::bigint as sum`)
.build()
const requestedLimit = req.first || 20
const limit = requestedLimit <= 0 || requestedLimit > 200 ? 20 : requestedLimit
const offset = req.after ? decodeCursor(req.after) : 0
const returnAssetIdSql = isFolderSearch
? Prisma.sql`a.id as "assetId"`
: Prisma.sql`CASE WHEN p.type = 'version_stack'::"AssetType" THEN p.id ELSE a.id END as "assetId"`
const resultQuery = resultBuilder
.select(
Prisma.sql`${returnAssetIdSql}, ae.start_time as "startTime", ae.end_time as "endTime", ae.sprite,
a.media -> 'duration' as "videoDuration", a.media #>> '{sprite,key}' as "fullSpriteKey",
${distance} as "distance"`,
)
.orderBy(visual ? Prisma.sql`distance ASC, ae.id ASC` : Prisma.sql`distance ASC`)
.limit(limit + 1)
.offset(offset)
.build()
const matches = await this.prismaClient.$queryRaw<
{
assetId: string
startTime: number | null
endTime: number | null
sprite: PrismaJson.VideoChunkSprite | null
videoDuration: unknown
fullSpriteKey: string | null
}[]
>(resultQuery)
const page = matches.slice(0, limit)
const assetIds = [...new Set(page.map((match) => match.assetId))]
const infos = await this.assetSvc.listAssetsByIds(assetIds, req.previewFormat)
const byId = new Map(infos.map((item) => [item.id, item]))
const bucket = process.env.S3_BUCKET || 'shumai'
const results = await Promise.all(
page.map(
async ({
assetId,
startTime,
endTime,
sprite,
videoDuration,
fullSpriteKey,
}): Promise<AssetInfo | undefined> => {
const item = byId.get(assetId)
if (!item) return
const match = { ...item, startTime, endTime }
if (!sprite) return match
// A stack's preview comes from its latest version (which is the matched asset here);
// symlinks can still point to a different asset.
if (
(item.type === AssetType.file || item.type === AssetType.version_stack) &&
item.preview?.spriteUrl &&
fullSpriteKey &&
isFullVideoRange(startTime, endTime, videoDuration) &&
(await hasStoredVideoSprite(bucket, fullSpriteKey))
) {
return match
}
const { key, ...layout } = sprite
try {
const url = await s3Service.presign(bucket, key, 'GET')
return { ...match, matchedSprite: { ...layout, url } }
} catch (err) {
logger.warn({ err, assetId, key }, 'Failed to sign video chunk sprite')
return match
}
},
),
)
const data = results.filter((item) => item !== undefined)
const counts = await this.prismaClient.$queryRaw<{ count: bigint }[]>(countQuery)
const total = Number(counts[0]?.count ?? 0)
const sizes =
total < 2000 ? await this.prismaClient.$queryRaw<{ sum: bigint | null }[]>(sizeQuery) : []
const pageInfo: PageInfo = { total, totalSize: total < 2000 ? Number(sizes[0]?.sum ?? 0) : -1 }
if (matches.length > limit) pageInfo.cursor = encodeCursor(offset + limit)
return { data, pageInfo }
}
}
export const searchService = new SearchService()
@@ -36,6 +36,18 @@ describe('SqlQueryBuilder', () => {
expect(() => builder.build()).toThrow('FROM clause is required')
})
it('prepends WITH clause when provided', () => {
const builder = new SqlQueryBuilder()
.with(Prisma.sql`scoped AS (SELECT id FROM assets WHERE is_deleted = false)`)
.select(Prisma.sql`s.id`)
.from(Prisma.sql`scoped s`)
const query = builder.build()
expect(query.text).toBe(
'WITH scoped AS (SELECT id FROM assets WHERE is_deleted = false) SELECT s.id FROM scoped s',
)
})
describe('Bug Reproduction Tests for buildSqlCondition', () => {
it('Bug 1: createdAt eq date should match full day range (>= startOfDay AND <= endOfDay)', () => {
const builder = new SqlQueryBuilder()
+14 -6
View File
@@ -2,6 +2,7 @@ import { Prisma } from '@shumai/db'
import { SearchCondition } from '@shumai/dtos'
export class SqlQueryBuilder {
private withSql: Prisma.Sql | null = null
private selectSql: Prisma.Sql = Prisma.sql`*`
private fromSql: Prisma.Sql | null = null
private wheres: Prisma.Sql[] = []
@@ -9,6 +10,11 @@ export class SqlQueryBuilder {
private limitCount: number | null = null
private offsetCount: number | null = null
with(cte: Prisma.Sql): this {
this.withSql = cte
return this
}
select(fields: Prisma.Sql): this {
this.selectSql = fields
return this
@@ -70,12 +76,14 @@ export class SqlQueryBuilder {
throw new Error('FROM clause is required in SqlQueryBuilder')
}
const queryParts: Prisma.Sql[] = [
Prisma.sql`SELECT`,
this.selectSql,
Prisma.sql`FROM`,
this.fromSql,
]
const queryParts: Prisma.Sql[] = []
if (this.withSql) {
queryParts.push(Prisma.sql`WITH`)
queryParts.push(this.withSql)
}
queryParts.push(Prisma.sql`SELECT`, this.selectSql, Prisma.sql`FROM`, this.fromSql)
if (this.wheres.length > 0) {
queryParts.push(Prisma.sql`WHERE`)
+2 -9
View File
@@ -1,6 +1,7 @@
import { GoogleGenAI } from '@google/genai'
import { LruTtlCache } from '@shumai/core/src/cache/lru-ttl-cache'
import { logger } from '@shumai/core/src/logger'
import { getGemmaEmbeddingEndpoint } from './gemma-embedding-endpoint'
export interface TextEmbeddingUsage {
model: string
@@ -143,15 +144,7 @@ export class TextEmbeddingService {
model: string,
signal: AbortSignal,
): Promise<TextEmbeddingResult> {
const rawBaseUrl = process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL || 'http://localhost:9379/v1'
const normalized = rawBaseUrl.replace(/\/+$/, '')
const endpoint = normalized.endsWith('/embeddings')
? normalized
: normalized.endsWith('/v1')
? `${normalized}/embeddings`
: `${normalized}/v1/embeddings`
const response = await fetch(endpoint, {
const response = await fetch(getGemmaEmbeddingEndpoint(), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -0,0 +1,37 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import sharp from 'sharp'
import { describe, expect, it } from 'vitest'
import { composeVideoChunkSprite } from './video-chunk-sprite'
describe('composeVideoChunkSprite', () => {
it('fills tiles in frame order and counts only the tiles with frames', async () => {
const directory = await mkdtemp(join(tmpdir(), 'chunk-sprite-test-'))
try {
const colors = ['red', 'red', 'red', 'red', 'red', 'blue']
const frames = await Promise.all(
colors.map(async (background, index) => {
const frame = join(directory, `frame-${index}.png`)
await sharp({ create: { width: 48, height: 32, channels: 3, background } }).toFile(frame)
return frame
}),
)
const sprite = await composeVideoChunkSprite(frames)
expect(sprite).toMatchObject({ columns: 5, rows: 2, frameCount: 6 })
const { data, info } = await sharp(sprite!.image).raw().toBuffer({ resolveWithObject: true })
expect(info).toMatchObject({ width: 240, height: 64, channels: 3 })
const pixel = (x: number, y: number) => (y * info.width + x) * info.channels
expect(data[pixel(24, 16)]).toBeGreaterThan(200)
expect(data[pixel(24, 48) + 2]).toBeGreaterThan(200)
expect(data[pixel(72, 48) + 2]).toBeLessThan(10)
} finally {
await rm(directory, { recursive: true, force: true })
}
})
it('omits preview metadata when the chunk contains no frames', async () => {
await expect(composeVideoChunkSprite([])).resolves.toBeUndefined()
})
})
@@ -0,0 +1,78 @@
import { execFile } from 'node:child_process'
import { mkdtemp, readdir, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { promisify } from 'node:util'
import type { SpriteLayout } from '@shumai/dtos'
import sharp from 'sharp'
const execFileAsync = promisify(execFile)
const MAX_TILE_SIDE = 240
const MAX_COLUMNS = 5
const MAX_SAMPLED_FRAMES = 15
export async function composeVideoChunkSprite(
frames: string[],
): Promise<(SpriteLayout & { image: Buffer }) | undefined> {
if (!frames.length) return
const { width, height } = await sharp(frames[0]).metadata()
const scale = Math.min(1, MAX_TILE_SIDE / Math.max(width, height))
const tileWidth = Math.max(1, Math.round(width * scale))
const tileHeight = Math.max(1, Math.round(height * scale))
const frameCount = frames.length
const columns = Math.min(MAX_COLUMNS, frameCount)
const rows = Math.ceil(frameCount / columns)
const tiles = await Promise.all(
frames.map(async (frame, index) => ({
input: await sharp(frame)
.resize(tileWidth, tileHeight, { fit: 'contain', background: 'black' })
.png()
.toBuffer(),
left: (index % columns) * tileWidth,
top: Math.floor(index / columns) * tileHeight,
})),
)
const image = await sharp({
create: {
width: columns * tileWidth,
height: rows * tileHeight,
channels: 3,
background: 'black',
},
})
.composite(tiles)
.webp()
.toBuffer()
return { image, columns, rows, frameCount }
}
export async function sampleVideoChunkSprite(
clip: string,
duration: number,
signal?: AbortSignal,
): ReturnType<typeof composeVideoChunkSprite> {
const dir = await mkdtemp(join(tmpdir(), 'video-chunk-sprite-'))
try {
const fps = Math.min(1, MAX_SAMPLED_FRAMES / duration)
await execFileAsync(
'ffmpeg',
[
'-loglevel',
'error',
'-i',
clip,
'-vf',
`fps=${fps}:round=up,scale=w='min(iw,240)':h='min(ih,240)':force_original_aspect_ratio=decrease`,
'-frames:v',
String(MAX_SAMPLED_FRAMES),
join(dir, 'frame_%04d.jpg'),
],
{ signal },
)
const files = (await readdir(dir)).sort()
return await composeVideoChunkSprite(files.map((file) => join(dir, file)))
} finally {
await rm(dir, { recursive: true, force: true })
}
}
@@ -0,0 +1,20 @@
import { s3Service } from '@shumai/core/src/s3/s3'
export function isFullVideoRange(
startTime: number | null,
endTime: number | null,
duration: unknown,
): boolean {
return (
startTime === 0 &&
typeof duration === 'number' &&
Number.isFinite(duration) &&
duration > 0 &&
endTime === duration
)
}
export async function hasStoredVideoSprite(bucket: string, key: string): Promise<boolean> {
const size = await s3Service.getObjectSize(bucket, key).catch(() => 0)
return size > 0
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/db",
"version": "0.7.0",
"version": "0.7.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "WorkflowTaskType" ADD VALUE 'transcode_video_chunks';
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "asset_embeddings" ADD COLUMN "sprite" JSONB;
@@ -0,0 +1,5 @@
-- CreateIndex
CREATE INDEX "asset_embeddings_asset_id_idx" ON "asset_embeddings"("asset_id");
-- CreateIndex
CREATE INDEX "assets_parent_id_is_deleted_sort_index_id_idx" ON "assets"("parent_id", "is_deleted", "sort_index", "id");
+5
View File
@@ -125,6 +125,7 @@ enum WorkflowTaskType {
transcode_image_annotation
transcode_watermark
transcode_3d
transcode_video_chunks
ai_metadata_autofill
chat
ai_embedding
@@ -615,6 +616,7 @@ model Asset {
@@index([agentId])
@@index([name], name: "assets_name_idx")
@@index([nameNgram], type: Gin)
@@index([parentId, isDeleted, sortIndex, id])
@@unique([parentId, targetId], name: "parentIdTargetId")
}
@@ -732,12 +734,15 @@ model AssetEmbedding {
embedding768 Unsupported("vector(768)")? @map("embedding_768")
startTime Float? @map("start_time")
endTime Float? @map("end_time")
/// [VideoChunkSprite]
sprite Json?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
assetId String @map("asset_id")
asset Asset @relation("AssetToEmbedding", fields: [assetId], references: [id], onDelete: Cascade)
@@index([assetId])
@@index([embedding], name: "AssetEmbedding_embedding_idx")
@@index([embedding768], name: "AssetEmbedding_embedding_768_idx")
@@map("asset_embeddings")
+1
View File
@@ -154,6 +154,7 @@ export const WorkflowTaskType = {
transcode_image_annotation: 'transcode_image_annotation',
transcode_watermark: 'transcode_watermark',
transcode_3d: 'transcode_3d',
transcode_video_chunks: 'transcode_video_chunks',
ai_metadata_autofill: 'ai_metadata_autofill',
chat: 'chat',
ai_embedding: 'ai_embedding',
File diff suppressed because one or more lines are too long
@@ -5356,6 +5356,7 @@ export const AssetEmbeddingScalarFieldEnum = {
id: 'id',
startTime: 'startTime',
endTime: 'endTime',
sprite: 'sprite',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
assetId: 'assetId'
@@ -456,6 +456,7 @@ export const AssetEmbeddingScalarFieldEnum = {
id: 'id',
startTime: 'startTime',
endTime: 'endTime',
sprite: 'sprite',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
assetId: 'assetId'
+33 -1
View File
@@ -60,6 +60,7 @@ export type AssetEmbeddingCountAggregateOutputType = {
id: number
startTime: number
endTime: number
sprite: number
createdAt: number
updatedAt: number
assetId: number
@@ -99,6 +100,7 @@ export type AssetEmbeddingCountAggregateInputType = {
id?: true
startTime?: true
endTime?: true
sprite?: true
createdAt?: true
updatedAt?: true
assetId?: true
@@ -195,6 +197,7 @@ export type AssetEmbeddingGroupByOutputType = {
id: string
startTime: number | null
endTime: number | null
sprite:PrismaJson.VideoChunkSprite | null
createdAt: Date
updatedAt: Date
assetId: string
@@ -227,6 +230,7 @@ export type AssetEmbeddingWhereInput = {
id?: Prisma.StringFilter<"AssetEmbedding"> | string
startTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
endTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
sprite?: Prisma.JsonNullableFilter<"AssetEmbedding">
createdAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
updatedAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
assetId?: Prisma.StringFilter<"AssetEmbedding"> | string
@@ -237,6 +241,7 @@ export type AssetEmbeddingOrderByWithRelationInput = {
id?: Prisma.SortOrder
startTime?: Prisma.SortOrderInput | Prisma.SortOrder
endTime?: Prisma.SortOrderInput | Prisma.SortOrder
sprite?: Prisma.SortOrderInput | Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
assetId?: Prisma.SortOrder
@@ -250,6 +255,7 @@ export type AssetEmbeddingWhereUniqueInput = Prisma.AtLeast<{
NOT?: Prisma.AssetEmbeddingWhereInput | Prisma.AssetEmbeddingWhereInput[]
startTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
endTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
sprite?: Prisma.JsonNullableFilter<"AssetEmbedding">
createdAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
updatedAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
assetId?: Prisma.StringFilter<"AssetEmbedding"> | string
@@ -260,6 +266,7 @@ export type AssetEmbeddingOrderByWithAggregationInput = {
id?: Prisma.SortOrder
startTime?: Prisma.SortOrderInput | Prisma.SortOrder
endTime?: Prisma.SortOrderInput | Prisma.SortOrder
sprite?: Prisma.SortOrderInput | Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
assetId?: Prisma.SortOrder
@@ -277,6 +284,7 @@ export type AssetEmbeddingScalarWhereWithAggregatesInput = {
id?: Prisma.StringWithAggregatesFilter<"AssetEmbedding"> | string
startTime?: Prisma.FloatNullableWithAggregatesFilter<"AssetEmbedding"> | number | null
endTime?: Prisma.FloatNullableWithAggregatesFilter<"AssetEmbedding"> | number | null
sprite?: Prisma.JsonNullableWithAggregatesFilter<"AssetEmbedding">
createdAt?: Prisma.DateTimeWithAggregatesFilter<"AssetEmbedding"> | Date | string
updatedAt?: Prisma.DateTimeWithAggregatesFilter<"AssetEmbedding"> | Date | string
assetId?: Prisma.StringWithAggregatesFilter<"AssetEmbedding"> | string
@@ -286,6 +294,7 @@ export type AssetEmbeddingCreateInput = {
id?: string
startTime?: number | null
endTime?: number | null
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
createdAt?: Date | string
updatedAt?: Date | string
asset: Prisma.AssetCreateNestedOneWithoutEmbeddingsInput
@@ -295,6 +304,7 @@ export type AssetEmbeddingUncheckedCreateInput = {
id?: string
startTime?: number | null
endTime?: number | null
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
createdAt?: Date | string
updatedAt?: Date | string
assetId: string
@@ -304,6 +314,7 @@ export type AssetEmbeddingUpdateInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
asset?: Prisma.AssetUpdateOneRequiredWithoutEmbeddingsNestedInput
@@ -313,6 +324,7 @@ export type AssetEmbeddingUncheckedUpdateInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
assetId?: Prisma.StringFieldUpdateOperationsInput | string
@@ -322,6 +334,7 @@ export type AssetEmbeddingCreateManyInput = {
id?: string
startTime?: number | null
endTime?: number | null
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
createdAt?: Date | string
updatedAt?: Date | string
assetId: string
@@ -331,6 +344,7 @@ export type AssetEmbeddingUpdateManyMutationInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -339,6 +353,7 @@ export type AssetEmbeddingUncheckedUpdateManyInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
assetId?: Prisma.StringFieldUpdateOperationsInput | string
@@ -358,6 +373,7 @@ export type AssetEmbeddingCountOrderByAggregateInput = {
id?: Prisma.SortOrder
startTime?: Prisma.SortOrder
endTime?: Prisma.SortOrder
sprite?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder
assetId?: Prisma.SortOrder
@@ -437,6 +453,7 @@ export type AssetEmbeddingCreateWithoutAssetInput = {
id?: string
startTime?: number | null
endTime?: number | null
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
createdAt?: Date | string
updatedAt?: Date | string
}
@@ -445,6 +462,7 @@ export type AssetEmbeddingUncheckedCreateWithoutAssetInput = {
id?: string
startTime?: number | null
endTime?: number | null
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
createdAt?: Date | string
updatedAt?: Date | string
}
@@ -482,6 +500,7 @@ export type AssetEmbeddingScalarWhereInput = {
id?: Prisma.StringFilter<"AssetEmbedding"> | string
startTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
endTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
sprite?: Prisma.JsonNullableFilter<"AssetEmbedding">
createdAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
updatedAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
assetId?: Prisma.StringFilter<"AssetEmbedding"> | string
@@ -491,6 +510,7 @@ export type AssetEmbeddingCreateManyAssetInput = {
id?: string
startTime?: number | null
endTime?: number | null
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
createdAt?: Date | string
updatedAt?: Date | string
}
@@ -499,6 +519,7 @@ export type AssetEmbeddingUpdateWithoutAssetInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -507,6 +528,7 @@ export type AssetEmbeddingUncheckedUpdateWithoutAssetInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -515,6 +537,7 @@ export type AssetEmbeddingUncheckedUpdateManyWithoutAssetInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -525,6 +548,7 @@ export type AssetEmbeddingSelect<ExtArgs extends runtime.Types.Extensions.Intern
id?: boolean
startTime?: boolean
endTime?: boolean
sprite?: boolean
createdAt?: boolean
updatedAt?: boolean
assetId?: boolean
@@ -535,6 +559,7 @@ export type AssetEmbeddingSelectCreateManyAndReturn<ExtArgs extends runtime.Type
id?: boolean
startTime?: boolean
endTime?: boolean
sprite?: boolean
createdAt?: boolean
updatedAt?: boolean
assetId?: boolean
@@ -545,6 +570,7 @@ export type AssetEmbeddingSelectUpdateManyAndReturn<ExtArgs extends runtime.Type
id?: boolean
startTime?: boolean
endTime?: boolean
sprite?: boolean
createdAt?: boolean
updatedAt?: boolean
assetId?: boolean
@@ -555,12 +581,13 @@ export type AssetEmbeddingSelectScalar = {
id?: boolean
startTime?: boolean
endTime?: boolean
sprite?: boolean
createdAt?: boolean
updatedAt?: boolean
assetId?: boolean
}
export type AssetEmbeddingOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "startTime" | "endTime" | "createdAt" | "updatedAt" | "assetId", ExtArgs["result"]["assetEmbedding"]>
export type AssetEmbeddingOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "startTime" | "endTime" | "sprite" | "createdAt" | "updatedAt" | "assetId", ExtArgs["result"]["assetEmbedding"]>
export type AssetEmbeddingInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
asset?: boolean | Prisma.AssetDefaultArgs<ExtArgs>
}
@@ -580,6 +607,10 @@ export type $AssetEmbeddingPayload<ExtArgs extends runtime.Types.Extensions.Inte
id: string
startTime: number | null
endTime: number | null
/**
* [VideoChunkSprite]
*/
sprite:PrismaJson.VideoChunkSprite | null
createdAt: Date
updatedAt: Date
assetId: string
@@ -1010,6 +1041,7 @@ export interface AssetEmbeddingFieldRefs {
readonly id: Prisma.FieldRef<"AssetEmbedding", 'String'>
readonly startTime: Prisma.FieldRef<"AssetEmbedding", 'Float'>
readonly endTime: Prisma.FieldRef<"AssetEmbedding", 'Float'>
readonly sprite: Prisma.FieldRef<"AssetEmbedding", 'Json'>
readonly createdAt: Prisma.FieldRef<"AssetEmbedding", 'DateTime'>
readonly updatedAt: Prisma.FieldRef<"AssetEmbedding", 'DateTime'>
readonly assetId: Prisma.FieldRef<"AssetEmbedding", 'String'>
+13
View File
@@ -217,6 +217,8 @@ declare global {
resolutions: VideoTranscode[]
}
export type VideoChunkSprite = import('@shumai/dtos').SpriteLayout & { key: string }
export interface MediaInfo {
duration: number
filesize: number
@@ -360,6 +362,16 @@ declare global {
annotations?: AnnotationList | null
}
export interface VideoChunksSpec {
parentTaskId?: string
assetKey?: string
format?: 'video' | 'frames'
chunks: Array<{
startTime: number
endTime: number
}>
}
export interface WorkflowTaskPayload {
projectId: string
transcode?: TaskSpec
@@ -370,6 +382,7 @@ declare global {
screenshot?: ScreenshotSpec
imageAnnotation?: ImageAnnotationSpec
pdfPages?: PdfPagesSpec
videoChunks?: VideoChunksSpec
/** Render that produced this result, if any (set by the read_asset pipeline). */
assetRead?: AssetReadRequest
watermark?: WatermarkTaskPayload
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/dtos",
"version": "0.7.0",
"version": "0.7.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+11
View File
@@ -25,6 +25,16 @@ export const previewInfoSchema = z.object({
})
export type PreviewInfo = z.infer<typeof previewInfoSchema>
const spriteLayoutSchema = z.object({
columns: z.number().int().positive(),
rows: z.number().int().positive(),
frameCount: z.number().int().positive(),
})
export type SpriteLayout = z.infer<typeof spriteLayoutSchema>
const matchedSpriteSchema = spriteLayoutSchema.extend({ url: z.string() })
export type MatchedSprite = z.infer<typeof matchedSpriteSchema>
export const childPreviewSchema = z.object({
type: z.string().nullable(),
preview: previewInfoSchema.nullable(),
@@ -90,6 +100,7 @@ export const assetInfoSchema = z.object({
sortIndex: z.string().optional().nullable(),
startTime: z.number().optional().nullable(),
endTime: z.number().optional().nullable(),
matchedSprite: matchedSpriteSchema.optional(),
hasAgentsMd: z.boolean().optional(),
commentsCount: z.number().optional(),
+18
View File
@@ -63,3 +63,21 @@ export type SearchFilter = z.infer<typeof searchFilterSchema>
export const searchRequestSchema = searchFilterSchema.extend(paginationParamsSchema.shape)
export type SearchRequest = z.infer<typeof searchRequestSchema>
export const MAX_SEARCH_IMAGE_BASE64_LENGTH = 1_500_000
export const imageSearchMediaTypeSchema = z.enum(['image', 'video'])
export type ImageSearchMediaType = z.infer<typeof imageSearchMediaTypeSchema>
export const imageSearchRequestSchema = searchFilterSchema
.pick({ conditions: true, operator: true, previewFormat: true })
.extend({
...paginationParamsSchema.shape,
mediaType: imageSearchMediaTypeSchema.optional(),
image: z.base64().min(1).max(MAX_SEARCH_IMAGE_BASE64_LENGTH).optional(),
sourceAssetId: z.string().min(1).optional(),
})
.refine(({ image, sourceAssetId }) => Boolean(image) !== Boolean(sourceAssetId), {
message: 'Provide one search image or source asset.',
})
export type ImageSearchRequest = z.infer<typeof imageSearchRequestSchema>
+1
View File
@@ -100,6 +100,7 @@ export const localUploadQuerySchema = z.object({
bucket: z.string(),
key: z.string(),
Signature: z.string(),
Expires: z.string().optional(),
})
export type LocalUploadQuery = z.infer<typeof localUploadQuerySchema>
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/e2e",
"version": "0.7.0",
"version": "0.7.1",
"private": true,
"type": "module",
"dependencies": {
+203 -115
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
import { describe, it, expect, beforeAll, afterEach, afterAll, vi } from 'vitest'
import { prisma, WorkflowTaskStatus } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { workflowService, TaskQueueAgent, TaskQueueTranscode } from '@shumai/workflow-core'
@@ -8,6 +8,7 @@ import { s3Service } from '@shumai/core/src/s3/s3'
import { fileURLToPath } from 'url'
import * as path from 'path'
import * as fs from 'fs'
import sharp from 'sharp'
const mockEmbedContent = vi.fn().mockResolvedValue({
embeddings: [
@@ -46,6 +47,11 @@ describe('Workflow E2E - agentEmbeddingMedia', () => {
await workflowService.startWorkers([TaskQueueAgent, TaskQueueTranscode])
})
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllEnvs()
})
afterAll(async () => {
await workflowService.shutdownWorkers()
workflowService.close()
@@ -196,134 +202,216 @@ describe('Workflow E2E - agentEmbeddingMedia', () => {
expect(dbEmbeddings[0].endTime).toBeNull()
}, 50000)
it('should run agentEmbeddingMedia workflow for a video asset successfully', async () => {
// 1. Seed Database
const team = await prisma.team.create({
data: { name: 'E2E Video Embedding Team' },
})
it.each([
['gemini-embedding-2', 'no sprite metadata'],
['gemma-embedding-2-openai', 'no sprite metadata'],
['gemini-embedding-2', 'available full sprite'],
['gemma-embedding-2-openai', 'available full sprite'],
['gemma-embedding-2-openai', 'missing full sprite object'],
])(
'indexes an entire video with %s and %s',
async (embeddingProvider, fullSpriteState) => {
vi.stubEnv('EMBEDDING_PROVIDER', embeddingProvider)
if (embeddingProvider === 'gemma-embedding-2-openai') {
const endpoint = 'https://embedding.example.com/v1/embeddings'
vi.stubEnv('GEMMA_EMBEDDING_OPENAI_BASE_URL', endpoint)
const fetch = globalThis.fetch
vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) =>
input === endpoint
? Promise.resolve(
Response.json({ data: [{ embedding: Array<number>(768).fill(0.2) }] }),
)
: fetch(input, init),
)
}
// 1. Seed Database
const team = await prisma.team.create({
data: { name: 'E2E Video Embedding Team' },
})
const project = await prisma.project.create({
data: { name: 'E2E Video Embedding Project', teamId: team.id },
})
const project = await prisma.project.create({
data: { name: 'E2E Video Embedding Project', teamId: team.id },
})
const agentUser = await prisma.user.create({
data: {
name: 'E2E Video Embedding Agent User',
email: 'e2e-vid-emb-agent@shumai.ai',
type: 'agent',
},
})
await prisma.teamMember.create({
data: {
teamId: team.id,
userId: agentUser.id,
role: 'editor',
},
})
const provider = await prisma.provider.create({
data: {
name: 'google',
teamId: team.id,
config: { api: 'google-generative-ai', apiKey: 'dummy-google-api-key' },
},
})
const model = await prisma.model.create({
data: {
modelId: 'gemini',
name: 'Gemini',
providerId: provider.id,
config: {
input: ['text', 'image'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 8192,
maxTokens: 2048,
reasoning: false,
const agentUser = await prisma.user.create({
data: {
name: 'E2E Video Embedding Agent User',
email: 'e2e-vid-emb-agent@shumai.ai',
type: 'agent',
},
},
})
})
await prisma.agent.create({
data: {
id: agentUser.id,
teamId: team.id,
type: 'embedding',
enabled: true,
providerId: provider.id,
modelId: model.id,
config: {
provider: 'google',
model: 'gemini',
await prisma.teamMember.create({
data: {
teamId: team.id,
userId: agentUser.id,
role: 'editor',
},
},
})
})
const storageKey = await prisma.storageKey.create({
data: {
key: 'projects/e2e/test-video.mp4',
},
})
const provider = await prisma.provider.create({
data: {
name: 'google',
teamId: team.id,
config: { api: 'google-generative-ai', apiKey: 'dummy-google-api-key' },
},
})
const asset = await prisma.asset.create({
data: {
name: 'test-video.mp4',
type: 'file',
status: 'uploaded',
mediaType: 'video/mp4',
media: { duration: 1.0 } as unknown as PrismaJson.MediaInfo, // 1-second video
projectId: project.id,
storageKeyId: storageKey.id,
},
})
const model = await prisma.model.create({
data: {
modelId: 'gemini',
name: 'Gemini',
providerId: provider.id,
config: {
input: ['text', 'image'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 8192,
maxTokens: 2048,
reasoning: false,
},
},
})
// 2. Seed S3 Storage from Fixture
const mp4Path = path.join(fixturesDir, 'small.mp4')
const mp4Buffer = fs.readFileSync(mp4Path)
await s3Service.putObject(
'shumai-e2e-test-bucket-embedding',
'projects/e2e/test-video.mp4',
mp4Buffer,
mp4Buffer.length,
'video/mp4',
)
await prisma.agent.create({
data: {
id: agentUser.id,
teamId: team.id,
type: 'embedding',
enabled: true,
providerId: provider.id,
modelId: model.id,
config: {
provider: 'google',
model: 'gemini',
},
},
})
// 3. Create Workflow Task (ai_embedding, pending)
const task = await prisma.workflowTask.create({
data: {
type: 'ai_embedding',
status: 'pending',
assetId: asset.id,
projectId: project.id,
teamId: team.id,
payload: {
const storageKey = await prisma.storageKey.create({
data: {
key: 'projects/e2e/test-video.mp4',
},
})
const bucket = 'shumai-e2e-test-bucket-embedding'
const fullSpriteKey = `projects/e2e/${storageKey.id}-full.webp`
const hasFullSprite = fullSpriteState === 'available full sprite'
if (hasFullSprite) {
const fullSprite = await sharp({
create: { width: 640, height: 640, channels: 3, background: 'blue' },
})
.webp()
.toBuffer()
await s3Service.putObject(
bucket,
fullSpriteKey,
fullSprite,
fullSprite.length,
'image/webp',
)
}
const asset = await prisma.asset.create({
data: {
name: 'test-video.mp4',
type: 'file',
status: 'uploaded',
mediaType: 'video/mp4',
media: {
duration: 1,
proxyType: 'video',
...(fullSpriteState !== 'no sprite metadata' && {
sprite: { key: fullSpriteKey, frames: 100, tileX: 10, tileY: 10 },
}),
} as PrismaJson.MediaInfo,
projectId: project.id,
agent: { agentId: agentUser.id },
storageKeyId: storageKey.id,
},
},
})
})
// 4. Wait for workflow to complete
console.log(
`Submitted E2E Video Embedding Workflow Task. ID: ${task.id}. Awaiting completion...`,
)
const completedTask = await workflowService.executeWait(task, 45000)
// 2. Seed S3 Storage from Fixture
const mp4Path = path.join(fixturesDir, 'small.mp4')
const mp4Buffer = fs.readFileSync(mp4Path)
await s3Service.putObject(
'shumai-e2e-test-bucket-embedding',
'projects/e2e/test-video.mp4',
mp4Buffer,
mp4Buffer.length,
'video/mp4',
)
// 5. Verification
expect(completedTask.status).toBe('completed')
// 3. Create Workflow Task (ai_embedding, pending)
const task = await prisma.workflowTask.create({
data: {
type: 'ai_embedding',
status: 'pending',
assetId: asset.id,
projectId: project.id,
teamId: team.id,
payload: {
projectId: project.id,
agent: { agentId: agentUser.id },
},
},
})
// Verify raw embedding is saved in DB with start and end times
const dbEmbeddings = (await prisma.$queryRaw`
SELECT id, asset_id as "assetId", start_time as "startTime", end_time as "endTime"
FROM asset_embeddings
WHERE asset_id = ${asset.id}
ORDER BY start_time ASC
`) as { id: string; startTime: number | null; endTime: number | null }[]
expect(dbEmbeddings.length).toBeGreaterThan(0)
expect(dbEmbeddings[0].startTime).toBe(0)
expect(dbEmbeddings[0].endTime).toBe(1)
}, 50000)
// 4. Wait for workflow to complete
console.log(
`Submitted E2E Video Embedding Workflow Task. ID: ${task.id}. Awaiting completion...`,
)
const completedTask = await workflowService.executeWait(task, 45000)
// 5. Verification
expect(completedTask.status).toBe('completed')
// Verify batch transcode_video_chunks task was created and completed on TaskQueueTranscode
const chunkTasks = await prisma.workflowTask.findMany({
where: {
assetId: asset.id,
type: 'transcode_video_chunks',
},
})
expect(chunkTasks).toHaveLength(1)
expect(chunkTasks[0].status).toBe(WorkflowTaskStatus.completed)
expect(chunkTasks[0].payload?.videoChunks?.parentTaskId).toBe(task.id)
const dbEmbeddings = await prisma.assetEmbedding.findMany({ where: { assetId: asset.id } })
expect(dbEmbeddings).toHaveLength(1)
expect(dbEmbeddings[0].startTime).toBe(0)
expect(dbEmbeddings[0].endTime).toBe(1)
const sprite = dbEmbeddings[0].sprite
const format = embeddingProvider === 'gemma-embedding-2-openai' ? 'frames' : 'video'
if (hasFullSprite) {
expect(sprite).toBeNull()
expect(
await s3Service.listObjects(bucket, `projects/e2e/chunk-sprites/${asset.id}/`),
).toEqual([])
await s3Service.deleteObject(bucket, fullSpriteKey)
} else {
expect(chunkTasks[0].output).toMatchObject({
chunks: [{ sprite: { columns: 1, rows: 1, frameCount: 1 } }],
})
expect(sprite).toEqual({
key: `projects/e2e/chunk-sprites/${asset.id}/${format}-0-1.webp`,
columns: 1,
rows: 1,
frameCount: 1,
})
const { buffer } = await s3Service.getObject(bucket, sprite!.key)
expect(await sharp(buffer).metadata()).toMatchObject({
format: 'webp',
width: 64,
height: 64,
})
}
// Verify all temporary embedding chunk files were cleaned up from S3
const remainingTmpChunks = await s3Service.listObjects(
'shumai-e2e-test-bucket-embedding',
`files/${asset.id}/tmp-embedding-chunks/`,
)
expect(remainingTmpChunks).toEqual([])
},
50000,
)
it('should fail agentEmbeddingMedia workflow for an unsupported audio asset', async () => {
// 1. Seed Database
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/operations",
"version": "0.7.0",
"version": "0.7.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/tableprinter",
"version": "0.7.0",
"version": "0.7.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/transcode",
"version": "0.7.0",
"version": "0.7.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
@@ -1,16 +1,25 @@
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { s3Service } from '@shumai/core/src/s3/s3'
import { prisma } from '@shumai/db'
import { prisma, AssetStatus, AssetType } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import {
registerLocalTaskAbortController,
unregisterLocalTaskAbortController,
} from '@shumai/workflow-core'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { transcodeService } from '@shumai/core/src/transcode/transcode'
import { sampleVideoChunkSprite } from '@shumai/core/src/transcode/video-chunk-sprite'
import * as child_process from 'child_process'
import * as fs from 'fs'
vi.mock('child_process', () => ({
execFile: vi.fn(),
}))
vi.mock('@shumai/core/src/transcode/video-chunk-sprite', () => ({
composeVideoChunkSprite: vi.fn(),
sampleVideoChunkSprite: vi.fn(),
}))
import {
ensureLocalMediaFile,
getMediaInfoActivity,
@@ -1234,6 +1243,42 @@ describe('Transcode Activities', () => {
})
describe('Video Chunk Activities', () => {
it('returns the embedding clip when the optional sprite upload fails', async () => {
vi.mocked(child_process.execFile).mockImplementation(
// The activity awaits the promisified callback overload.
((_file: string, _args: string[], callback: (err: null) => void) => {
callback(null)
}) as typeof child_process.execFile,
)
vi.mocked(sampleVideoChunkSprite).mockResolvedValueOnce({
image: Buffer.from('mock sprite'),
columns: 1,
rows: 1,
frameCount: 1,
})
vi.mocked(s3Service.putObject)
.mockResolvedValueOnce(undefined)
.mockRejectedValueOnce(new Error('Sprite storage unavailable'))
const chunk = await transcodeVideoChunkActivity({
assetId: 'asset-abc',
assetKey: 'files/storage-id/proxy.mp4',
originalKey: 'files/storage-id/original.mp4',
startTime: 0,
endTime: 1,
})
expect(chunk.chunkKey).toMatch(/\.mp4$/)
expect(chunk.sprite).toBeUndefined()
expect(s3Service.putObject).toHaveBeenLastCalledWith(
'shumai',
'files/storage-id/chunk-sprites/asset-abc/video-0-1.webp',
expect.any(Buffer),
expect.any(Number),
'image/webp',
)
})
it('should transcode video chunk using ffmpeg and upload to S3', async () => {
// Mock child_process.execFile to simulate ffmpeg succeeding
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -1464,6 +1509,109 @@ describe('Transcode Activities', () => {
}
})
it('should fail fast with non-retryable error when task is already cancelled', async () => {
const taskId = 'task-chunk-pre-aborted'
const abortController = new AbortController()
abortController.abort()
registerLocalTaskAbortController(taskId, abortController)
try {
expect.assertions(3)
try {
await transcodeVideoChunkActivity({
taskId,
assetId: 'asset-abc',
filePath: '/tmp/test.mp4',
startTime: 0,
endTime: 10,
})
} catch (err: unknown) {
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
expect((err as Error).message).toContain('Video chunk transcoding cancelled')
}
expect(child_process.execFile).not.toHaveBeenCalled()
} finally {
unregisterLocalTaskAbortController(taskId)
}
})
it('should pass AbortSignal to ffmpeg and throw non-retryable error on in-flight cancellation', async () => {
const taskId = 'task-chunk-inflight-abort'
const abortController = new AbortController()
registerLocalTaskAbortController(taskId, abortController)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- execFile mockImplementation uses 4-arg overload with options
;(child_process.execFile as any).mockImplementation(
(
_file: string,
_args: string[],
options: { signal?: AbortSignal },
cb: (err: Error | null, result: { stdout: string; stderr: string }) => void,
) => {
expect(options?.signal).toBe(abortController.signal)
abortController.abort()
const abortErr = new Error('The operation was aborted') as Error & { code?: string }
abortErr.code = 'ABORT_ERR'
cb(abortErr, { stdout: '', stderr: '' })
},
)
try {
expect.assertions(4)
try {
await transcodeVideoChunkActivity({
taskId,
assetId: 'asset-abc',
filePath: '/tmp/test.mp4',
startTime: 0,
endTime: 10,
})
} catch (err: unknown) {
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
expect((err as Error).message).toContain('Video chunk transcoding cancelled')
}
expect(s3Service.putObject).not.toHaveBeenCalled()
} finally {
unregisterLocalTaskAbortController(taskId)
}
})
it('should fail with non-retryable error before S3 upload if asset is pending_purge', async () => {
const purgingAsset = await prisma.asset.create({
data: {
name: 'purging-video.mp4',
type: AssetType.file,
status: AssetStatus.pending_purge,
mediaType: 'video/mp4',
},
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- execFile mockImplementation returns void rather than ChildProcess
;(child_process.execFile as any).mockImplementation(
(
_file: string,
_args: string[],
cb: (err: Error | null, result: { stdout: string; stderr: string }) => void,
) => {
cb(null, { stdout: '', stderr: '' })
},
)
expect.assertions(3)
try {
await transcodeVideoChunkActivity({
assetId: purgingAsset.id,
assetKey: 'files/proxy-720p.mp4',
startTime: 0,
endTime: 10,
})
} catch (err: unknown) {
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
expect((err as Error).message).toContain('pending purge')
}
expect(s3Service.putObject).not.toHaveBeenCalled()
})
it('should return existing poster if already present in S3', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(s3Service.headObject).mockResolvedValue({} as any)
+114 -6
View File
@@ -8,6 +8,11 @@ import {
} from '@shumai/core/src/transcode/transcode'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { getDerivedArtifactDirectory, stemFromKey } from '@shumai/core/src/utils/filename'
import {
composeVideoChunkSprite,
sampleVideoChunkSprite,
} from '@shumai/core/src/transcode/video-chunk-sprite'
import { hasStoredVideoSprite } from '@shumai/core/src/transcode/video-sprite'
import {
gotenbergService,
type GotenbergConvertOptions,
@@ -1580,18 +1585,72 @@ export const createAutofillTaskIfEnabledActivity = defineStep(
},
)
async function ensureAssetNotPurgingByIdOrKey(assetId: string, assetKey?: string): Promise<void> {
const asset = await prisma.asset.findUnique({
where: { id: assetId },
select: { status: true, storageKey: { select: { status: true } } },
})
if (
asset &&
(asset.status === AssetStatus.pending_purge || asset.storageKey?.status === 'purging')
) {
throw ApplicationFailure.create({
message: 'Asset or storage key has been purged or is pending purge',
nonRetryable: true,
})
}
if (assetKey) {
await ensureAssetNotPurging(assetKey)
}
}
export interface TranscodeVideoChunkParams {
taskId?: string
assetId: string
assetKey?: string
originalKey?: string
filePath?: string
startTime: number
endTime: number
format?: 'video' | 'frames'
fullSpriteKey?: string
}
async function uploadVideoChunkSprite(
params: TranscodeVideoChunkParams,
render: () => ReturnType<typeof composeVideoChunkSprite>,
signal?: AbortSignal,
): Promise<PrismaJson.VideoChunkSprite | undefined> {
if (signal?.aborted) return
try {
const bucket = process.env.S3_BUCKET || 'shumai'
if (params.fullSpriteKey && (await hasStoredVideoSprite(bucket, params.fullSpriteKey))) return
if (signal?.aborted) return
const sprite = await render()
if (!sprite || signal?.aborted) return
const originalKey = params.originalKey ?? params.assetKey
const directory = getDerivedArtifactDirectory(originalKey ?? '', params.assetId)
const format = params.format ?? 'video'
const key = `${directory}/chunk-sprites/${params.assetId}/${format}-${params.startTime}-${params.endTime}.webp`
await ensureAssetNotPurgingByIdOrKey(params.assetId, originalKey)
const { image, ...layout } = sprite
await s3Service.putObject(bucket, key, image, image.length, 'image/webp')
return { key, ...layout }
} catch (err) {
if (!signal?.aborted) {
logger.warn(
{ err, assetId: params.assetId, startTime: params.startTime, endTime: params.endTime },
'Failed to generate video chunk sprite',
)
}
}
}
export const transcodeVideoChunkActivity = defineStep(async function transcodeVideoChunkActivity(
params: TranscodeVideoChunkParams,
): Promise<{ chunkKey: string }> {
): Promise<{ chunkKey: string; sprite?: PrismaJson.VideoChunkSprite }> {
if (!params.filePath && !params.assetKey) {
throw ApplicationFailure.create({
message: 'Neither filePath nor assetKey was provided for video chunk transcoding',
@@ -1599,6 +1658,28 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
})
}
const signal = getActivityCancellationSignal(params.taskId)
if (signal?.aborted) {
throw ApplicationFailure.create({
message: 'Video chunk transcoding cancelled',
nonRetryable: true,
})
}
const runFfmpeg = (args: string[]) =>
signal ? execFileAsync('ffmpeg', args, { signal }) : execFileAsync('ffmpeg', args)
const isAbortError = (err: unknown): boolean => {
const { code, message } = getErrorDetails(err)
const lowerMsg = message.toLowerCase()
return (
Boolean(signal?.aborted) ||
code === 'ABORT_ERR' ||
message.includes('aborted') ||
lowerMsg.includes('abort')
)
}
if (params.format === 'frames') {
const tmpDir = transcodeService.createTempDir('video-chunk-frames-')
try {
@@ -1618,7 +1699,7 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
const fpsFilter = duration > 16 ? `fps=${16 / duration}` : 'fps=1'
const vframesArgs = duration > 16 ? ['-vframes', '16'] : []
await execFileAsync('ffmpeg', [
await runFfmpeg([
'-y',
'-loglevel',
'warning',
@@ -1658,14 +1739,27 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
archiveBytes.byteOffset,
archiveBytes.byteLength,
)
await ensureAssetNotPurgingByIdOrKey(params.assetId, params.assetKey)
const key = `files/${params.assetId}/tmp-embedding-chunks/frames-${params.startTime}-${params.endTime}-${ulid()}.tar`
await s3Service.putObject(bucket, key, archiveData, archiveData.length, 'application/x-tar')
return { chunkKey: key }
const sprite = await uploadVideoChunkSprite(
params,
() => composeVideoChunkSprite(frameFiles.map((file) => path.join(tmpDir, file))),
signal,
)
return sprite ? { chunkKey: key, sprite } : { chunkKey: key }
} catch (err) {
if (err instanceof ApplicationFailure) {
throw err
}
if (isAbortError(err)) {
throw ApplicationFailure.create({
message: 'Video chunk transcoding cancelled',
nonRetryable: true,
cause: err instanceof Error ? err : undefined,
})
}
throw ApplicationFailure.create({
message: `Failed to extract video chunk frames for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
nonRetryable: false,
@@ -1691,7 +1785,7 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
// Slice video segment using ffmpeg, force 1fps and remove audio for gemini-embedding-2 optimization
// Note: -ss placed before -i for fast input seeking via demuxer Range requests
await execFileAsync('ffmpeg', [
await runFfmpeg([
'-y',
'-loglevel',
'warning',
@@ -1720,16 +1814,30 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
const chunkData = fs.readFileSync(chunkTmp)
await ensureAssetNotPurgingByIdOrKey(params.assetId, params.assetKey)
// Upload to S3
const key = `files/${params.assetId}/tmp-embedding-chunks/chunk-${params.startTime}-${params.endTime}-${ulid()}.mp4`
await s3Service.putObject(bucket, key, chunkData, chunkData.length, 'video/mp4')
return { chunkKey: key }
const sprite = await uploadVideoChunkSprite(
params,
() => sampleVideoChunkSprite(chunkTmp, params.endTime - params.startTime, signal),
signal,
)
return sprite ? { chunkKey: key, sprite } : { chunkKey: key }
} catch (err) {
if (err instanceof ApplicationFailure) {
throw err
}
if (isAbortError(err)) {
throw ApplicationFailure.create({
message: 'Video chunk transcoding cancelled',
nonRetryable: true,
cause: err instanceof Error ? err : undefined,
})
}
throw ApplicationFailure.create({
message: `Failed to transcode video chunk for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
nonRetryable: false,
@@ -1739,7 +1847,7 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
try {
fs.unlinkSync(chunkTmp)
} catch (e) {
console.error('Failed to cleanup local chunk file:', e)
logger.error({ err: e, chunkTmp }, 'Failed to cleanup local chunk file')
}
}
}
+3
View File
@@ -8,6 +8,7 @@ import { takeVideoScreenshotsWorkflow } from './workflows/take-video-screenshots
import { overlayImageAnnotationWorkflow } from './workflows/overlay-image-annotation'
import { transcodeWatermarkWorkflow } from './workflows/transcode-watermark'
import { transcode3dWorkflow } from './workflows/transcode-3d'
import { transcodeVideoChunksWorkflow } from './workflows/transcode-video-chunks'
import { transcodeMedia } from './workflows/transcode'
import { archiveAssetWorkflow } from './workflows/archive-asset'
import { restoreAssetWorkflow } from './workflows/restore-asset'
@@ -22,6 +23,7 @@ export function initTranscodeWorkflows() {
registerWorkflow(WorkflowTaskType.transcode_screenshot, takeVideoScreenshotsWorkflow)
registerWorkflow(WorkflowTaskType.transcode_image_annotation, overlayImageAnnotationWorkflow)
registerWorkflow(WorkflowTaskType.transcode_watermark, transcodeWatermarkWorkflow)
registerWorkflow(WorkflowTaskType.transcode_video_chunks, transcodeVideoChunksWorkflow)
registerWorkflow(WorkflowTaskType.archive_asset, archiveAssetWorkflow)
registerWorkflow(WorkflowTaskType.restore_asset, restoreAssetWorkflow)
}
@@ -30,6 +32,7 @@ export * from './transcoder'
export * from './workflows/transcode'
export * from './workflows/transcode-3d'
export * from './workflows/transcode-watermark'
export * from './workflows/transcode-video-chunks'
export * from './workflows/archive-asset'
export * from './workflows/restore-asset'
export * from './activities/transcode'
@@ -0,0 +1,274 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { transcodeVideoChunksWorkflow } from './transcode-video-chunks'
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import { getAssetActivity, updateTaskStatusActivity } from '@shumai/workflow-core'
import { deleteS3ObjectActivity, transcodeVideoChunkActivity } from '../activities/transcode'
vi.mock('@shumai/workflow-core', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
return {
...actual,
updateTaskStatusActivity: vi.fn(),
getAssetActivity: vi.fn(),
}
})
vi.mock('../activities/transcode', () => ({
transcodeVideoChunkActivity: vi.fn(),
deleteS3ObjectActivity: vi.fn(),
}))
function createMockTask(overrides?: Partial<WorkflowTask>): WorkflowTask {
return {
id: 'task-video-chunks',
assetId: 'asset-video',
type: WorkflowTaskType.transcode_video_chunks,
status: WorkflowTaskStatus.pending,
sessionId: null,
output: null,
payload: {
projectId: 'proj-1',
videoChunks: {
parentTaskId: 'parent-emb-1',
assetKey: 'files/asset-video/proxy.mp4',
format: 'video',
chunks: [
{ startTime: 0, endTime: 60 },
{ startTime: 55, endTime: 110 },
],
},
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-uid',
model: null,
inputTokens: 0,
outputTokens: 0,
...overrides,
}
}
describe('transcodeVideoChunksWorkflow', () => {
const mockActivities = {
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
getAssetActivity: vi.mocked(getAssetActivity),
transcodeVideoChunkActivity: vi.mocked(transcodeVideoChunkActivity),
deleteS3ObjectActivity: vi.mocked(deleteS3ObjectActivity),
}
beforeEach(() => {
vi.clearAllMocks()
mockActivities.updateTaskStatusActivity.mockResolvedValue({} as never)
mockActivities.deleteS3ObjectActivity.mockResolvedValue(undefined)
})
it('should transcode all requested video chunks and complete with chunk keys', async () => {
const task = createMockTask()
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-video',
status: 'processed',
storageKey: { key: 'files/asset-video/raw.mp4', isArchived: false },
mediaType: 'video/mp4',
media: { duration: 110, sprite: { key: 'files/asset-video/sprite.webp' } },
} as unknown as Awaited<ReturnType<typeof getAssetActivity>>)
const sprite = {
key: 'files/asset-video/chunk-sprites/asset-video/video-0-60.webp',
columns: 5,
rows: 3,
frameCount: 15,
}
mockActivities.transcodeVideoChunkActivity
.mockResolvedValueOnce({
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
sprite,
})
.mockResolvedValueOnce({
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-55-110.mp4',
})
await transcodeVideoChunksWorkflow(task)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(2)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(1, {
taskId: 'task-video-chunks',
assetId: 'asset-video',
assetKey: 'files/asset-video/proxy.mp4',
originalKey: 'files/asset-video/raw.mp4',
startTime: 0,
endTime: 60,
format: 'video',
})
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(2, {
taskId: 'task-video-chunks',
assetId: 'asset-video',
assetKey: 'files/asset-video/proxy.mp4',
originalKey: 'files/asset-video/raw.mp4',
startTime: 55,
endTime: 110,
format: 'video',
})
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-video-chunks',
status: WorkflowTaskStatus.completed,
output: {
chunks: [
{
startTime: 0,
endTime: 60,
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
sprite,
},
{
startTime: 55,
endTime: 110,
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-55-110.mp4',
},
],
},
})
})
it('should fall back to videoTranscodes proxy when assetKey is omitted and support frames format on archived assets', async () => {
const task = createMockTask({
payload: {
projectId: 'proj-1',
videoChunks: {
parentTaskId: 'parent-emb-2',
format: 'frames',
chunks: [{ startTime: 0, endTime: 30 }],
},
},
})
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-video',
status: 'archived',
storageKey: { key: 'files/asset-video/raw.mp4', isArchived: true },
mediaType: 'video/mp4',
media: {
videoTranscodes: [{ key: 'files/asset-video/proxy-720p.mp4' }],
},
} as unknown as Awaited<ReturnType<typeof getAssetActivity>>)
mockActivities.transcodeVideoChunkActivity.mockResolvedValueOnce({
chunkKey: 'files/asset-video/tmp-embedding-chunks/frames-0-30.tar',
})
await transcodeVideoChunksWorkflow(task)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledWith({
taskId: 'task-video-chunks',
assetId: 'asset-video',
assetKey: 'files/asset-video/proxy-720p.mp4',
originalKey: 'files/asset-video/raw.mp4',
startTime: 0,
endTime: 30,
format: 'frames',
})
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-video-chunks',
status: WorkflowTaskStatus.completed,
output: {
chunks: [
{
startTime: 0,
endTime: 30,
chunkKey: 'files/asset-video/tmp-embedding-chunks/frames-0-30.tar',
},
],
},
})
})
it('should fail with non-retryable ApplicationFailure when payload is invalid', async () => {
const task = createMockTask({
payload: {
projectId: 'proj-1',
},
})
await expect(transcodeVideoChunksWorkflow(task)).rejects.toThrow(
'Invalid payload for videoChunks task',
)
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-video-chunks',
status: WorkflowTaskStatus.failed,
output: { error: 'Invalid payload for videoChunks task' },
})
})
it('should fail fast when asset is archived and no videoTranscodes proxy is available', async () => {
const task = createMockTask({
payload: {
projectId: 'proj-1',
videoChunks: {
assetKey: 'files/asset-video/raw.mp4',
format: 'video',
chunks: [{ startTime: 0, endTime: 60 }],
},
},
})
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-video',
status: 'archived',
storageKey: { key: 'files/asset-video/raw.mp4', isArchived: true },
mediaType: 'video/mp4',
media: {
videoTranscodes: [],
},
} as unknown as Awaited<ReturnType<typeof getAssetActivity>>)
await expect(transcodeVideoChunksWorkflow(task)).rejects.toThrow(
'Original video file is archived and no proxy is available. Restore the asset to generate embeddings.',
)
expect(mockActivities.transcodeVideoChunkActivity).not.toHaveBeenCalled()
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-video-chunks',
status: WorkflowTaskStatus.failed,
output: {
error:
'Original video file is archived and no proxy is available. Restore the asset to generate embeddings.',
},
})
})
it('should clean up already-uploaded chunk files in S3 if a subsequent chunk fails', async () => {
const task = createMockTask()
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-video',
status: 'processed',
storageKey: { key: 'files/asset-video/raw.mp4', isArchived: false },
mediaType: 'video/mp4',
} as unknown as Awaited<ReturnType<typeof getAssetActivity>>)
mockActivities.transcodeVideoChunkActivity
.mockResolvedValueOnce({
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
})
.mockRejectedValueOnce(new Error('ffmpeg slice failed on chunk 2'))
await expect(transcodeVideoChunksWorkflow(task)).rejects.toThrow(
'ffmpeg slice failed on chunk 2',
)
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenCalledTimes(1)
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenCalledWith({
key: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
})
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-video-chunks',
status: WorkflowTaskStatus.failed,
output: { error: 'ffmpeg slice failed on chunk 2' },
})
})
})
@@ -0,0 +1,85 @@
import { logger } from '@shumai/core/src/logger'
import { isFullVideoRange } from '@shumai/core/src/transcode/video-sprite'
import type { WorkflowTask } from '@shumai/db'
import { ApplicationFailure } from '@shumai/workflow-core'
import { deleteS3ObjectActivity, transcodeVideoChunkActivity } from '../activities/transcode'
import { completeTask, failTask, fetchAssetWithKey, startTask } from './common'
export interface TranscodedVideoChunkItem {
startTime: number
endTime: number
chunkKey: string
sprite?: PrismaJson.VideoChunkSprite
}
export async function transcodeVideoChunksWorkflow(task: WorkflowTask): Promise<void> {
const uploadedChunkKeys: string[] = []
try {
await startTask(task)
const payload = task.payload
if (!payload?.videoChunks || !Array.isArray(payload.videoChunks.chunks)) {
throw ApplicationFailure.create({
message: 'Invalid payload for videoChunks task',
nonRetryable: true,
})
}
const { asset, key } = await fetchAssetWithKey(task.assetId)
let targetKey = payload.videoChunks.assetKey || key
if (!payload.videoChunks.assetKey && asset?.media) {
const mediaInfo = asset.media as unknown as PrismaJson.MediaInfo
if (mediaInfo.videoTranscodes && mediaInfo.videoTranscodes.length > 0) {
const transcode = mediaInfo.videoTranscodes[0]
if (transcode?.key) {
targetKey = transcode.key
}
}
}
if (targetKey === key && (asset.storageKey?.isArchived || asset.status === 'archived')) {
throw ApplicationFailure.create({
message:
'Original video file is archived and no proxy is available. Restore the asset to generate embeddings.',
nonRetryable: true,
})
}
const chunks: TranscodedVideoChunkItem[] = []
for (const range of payload.videoChunks.chunks) {
const fullSpriteKey = isFullVideoRange(range.startTime, range.endTime, asset.media?.duration)
? asset.media?.sprite?.key
: undefined
const chunk = await transcodeVideoChunkActivity({
taskId: task.id,
assetId: asset.id,
assetKey: targetKey,
originalKey: key,
startTime: range.startTime,
endTime: range.endTime,
format: payload.videoChunks.format,
...(fullSpriteKey && { fullSpriteKey }),
})
uploadedChunkKeys.push(chunk.chunkKey)
chunks.push({ ...range, ...chunk })
}
await completeTask(task.id, { chunks })
} catch (err) {
logger.error({ taskId: task.id, err }, 'transcodeVideoChunksWorkflow failed')
for (const chunkKey of uploadedChunkKeys) {
try {
await deleteS3ObjectActivity({ key: chunkKey })
} catch (cleanupErr) {
logger.error(
{ taskId: task.id, chunkKey, err: cleanupErr },
'Failed to clean up partial chunk',
)
}
}
await failTask(task.id, err)
throw err
}
}
@@ -25,9 +25,10 @@ import {
ArrowRight,
Copy,
Layers,
ScanSearch,
} from 'lucide-react'
import { CopyContextMenuSub } from './copy-submenu'
import type { CopyKind } from './copy-options'
import { isImageItem, type CopyKind } from './copy-options'
interface FileBrowserContextMenuProps {
item: AssetInfo | null
@@ -36,6 +37,7 @@ interface FileBrowserContextMenuProps {
onDelete: (items: AssetInfo[]) => void
onDownload: (items: AssetInfo[]) => void
onCopy?: (kind: CopyKind, items: AssetInfo[]) => void
onFindSimilar?: (item: AssetInfo) => void
onRestore: (items: AssetInfo[]) => void
onArchive?: (items: AssetInfo[]) => void
onRestoreArchive?: (items: AssetInfo[]) => void
@@ -69,6 +71,7 @@ export function FileBrowserContextMenu({
onDelete,
onDownload,
onCopy,
onFindSimilar,
onRestore,
onArchive,
onRestoreArchive,
@@ -222,6 +225,15 @@ export function FileBrowserContextMenu({
)
}
const findSimilarItem = onFindSimilar &&
(item.type === 'file' || item.type === 'version_stack') &&
isImageItem(item) && (
<ContextMenuItem onSelect={() => onFindSimilar(item)}>
<ScanSearch className="mr-2 h-4 w-4" />
<span>{m.find_similar()}</span>
</ContextMenuItem>
)
const contextMenuContent =
isItemSelected && selectedIds.size > 1 ? (
<ContextMenuContent
@@ -234,6 +246,7 @@ export function FileBrowserContextMenu({
<Download className="mr-2 h-4 w-4" />
<span>{m.download()}</span>
</ContextMenuItem>
{findSimilarItem}
<CopyContextMenuSub
items={itemsToModify}
context={{
@@ -331,6 +344,7 @@ export function FileBrowserContextMenu({
<Download className="mr-2 h-4 w-4" />
<span>{m.download()}</span>
</ContextMenuItem>
{findSimilarItem}
<CopyContextMenuSub
items={itemsToModify}
context={{
@@ -29,6 +29,8 @@ import { ManageVersionsDialog } from '../manage-versions-dialog'
import { FilePreviewDialog } from '../file-preview-dialog'
import { FileBrowserContentSkeleton } from '../loading-skeletons'
import { FileBrowserContextMenu } from './context-menu'
import { FindSimilarDialog } from '../search/find-similar-dialog'
import { useSemanticSearchEnabled } from '../search/use-semantic-search-enabled'
import {
AlertDialog,
@@ -156,6 +158,13 @@ export function FileBrowser({
allowDownload = true,
}: FileBrowserProps) {
const [contextMenuItem, setContextMenuItem] = useState<AssetInfo | null>(null)
const [similarImage, setSimilarImage] = useState<AssetInfo | null>(null)
const semanticSearchEnabled = useSemanticSearchEnabled(
teamId,
Boolean(
rootFolderId && !isShareView && !isPublic && !isRecents && !isRecentlyDeleted && !collection,
),
)
const [manageVersionsStackId, setManageVersionsStackId] = useState<string | null>(null)
const [moveCopyMode, setMoveCopyMode] = useState<'move' | 'copy' | null>(null)
const [itemsToMoveCopy, setItemsToMoveCopy] = useState<AssetInfo[]>([])
@@ -1179,6 +1188,7 @@ export function FileBrowser({
onDelete={handleDelete}
onDownload={handleDownload}
onCopy={handleCopy}
onFindSimilar={semanticSearchEnabled && rootFolderId ? setSimilarImage : undefined}
onNewFolder={handleNewFolder}
onUploadFile={handleUploadFilesClick}
onUploadFolder={handleUploadFolderClick}
@@ -1239,6 +1249,16 @@ export function FileBrowser({
)}
{renderContent()}
{semanticSearchEnabled && similarImage && rootFolderId && (
<FindSimilarDialog
image={similarImage}
folderId={rootFolderId}
teamId={teamId}
projectId={projectId}
onClose={() => setSimilarImage(null)}
/>
)}
{moveCopyMode && (
<MoveCopyDialog
isOpen={!!moveCopyMode}
@@ -308,7 +308,9 @@ export function FileCard({
// A preview (poster thumbnail and/or sprite) can be available before transcoding finishes,
// since the poster/sprite are generated and persisted ahead of the proxy transcodes.
const hasPreview = Boolean(displayItem.preview?.thumbnailUrl || displayItem.preview?.spriteUrl)
const hasPreview = Boolean(
item.matchedSprite || displayItem.preview?.thumbnailUrl || displayItem.preview?.spriteUrl,
)
const isFailed = displayItem.status === 'failed'
const isLocalUploader = Boolean(fileUploadState)
const isUploadFailed = fileUploadState?.status === 'failed'
@@ -520,9 +522,10 @@ export function FileCard({
<FilePreview
item={displayItem}
showDuration={!isProcessing && !isFailed}
matchedSprite={item.matchedSprite}
matchDuration={
displayItem.startTime != null && displayItem.endTime != null
? { startTime: displayItem.startTime, endTime: displayItem.endTime }
item.startTime != null && item.endTime != null
? { startTime: item.startTime, endTime: item.endTime }
: null
}
/>
@@ -569,8 +572,8 @@ export function FileCard({
item={displayItem}
showDuration
matchDuration={
displayItem.startTime != null && displayItem.endTime != null
? { startTime: displayItem.startTime, endTime: displayItem.endTime }
item.startTime != null && item.endTime != null
? { startTime: item.startTime, endTime: item.endTime }
: null
}
/>
@@ -1,4 +1,5 @@
import { File, Folder, AudioLines } from 'lucide-react'
import type { MatchedSprite } from '@shumai/dtos'
import { SpriteScrubber } from '../sprite-scrubber'
import { formatTime } from '../viewers/video/utils'
@@ -20,13 +21,19 @@ type FilePreviewItem = {
interface FilePreviewProps {
item: FilePreviewItem
showDuration?: boolean
matchedSprite?: MatchedSprite
matchDuration?: {
startTime?: number | null
endTime?: number | null
} | null
}
export const FilePreview = ({ item, showDuration = false, matchDuration }: FilePreviewProps) => {
export const FilePreview = ({
item,
showDuration = false,
matchedSprite,
matchDuration,
}: FilePreviewProps) => {
const proxyType = item.preview?.proxyType || item.proxyType
const isVideo = proxyType === 'video'
const isAudio = proxyType === 'audio'
@@ -56,21 +63,27 @@ export const FilePreview = ({ item, showDuration = false, matchDuration }: FileP
</span>
) : null
const isMediaWithSprite =
(isVideo || isPdf || is3D) &&
item.preview?.spriteUrl &&
item.preview.thumbnailUrl &&
item.preview.originalWidth &&
item.preview.originalHeight
const chunkSprite = hasMatchedChunk ? matchedSprite : undefined
const canShowFullSprite =
hasMatchedChunk ||
((isVideo || isPdf || is3D) &&
item.preview?.thumbnailUrl &&
item.preview.originalWidth &&
item.preview.originalHeight)
const fullSpriteUrl = canShowFullSprite ? item.preview?.spriteUrl : undefined
const spriteUrl = chunkSprite?.url || fullSpriteUrl
if (isMediaWithSprite && item.preview) {
if (spriteUrl) {
return (
<>
<SpriteScrubber
spriteUrl={item.preview.spriteUrl!}
thumbnailUrl={item.preview.thumbnailUrl!}
videoWidth={item.preview.originalWidth!}
videoHeight={item.preview.originalHeight!}
spriteUrl={spriteUrl}
spriteLayout={chunkSprite}
showFirstFrame={Boolean(chunkSprite)}
fallbackSpriteUrl={chunkSprite && fullSpriteUrl ? fullSpriteUrl : undefined}
thumbnailUrl={item.preview?.thumbnailUrl}
videoWidth={item.preview?.originalWidth}
videoHeight={item.preview?.originalHeight}
reverse={is3D}
/>
{overlay}
@@ -112,8 +125,9 @@ export const FilePreview = ({ item, showDuration = false, matchDuration }: FileP
}
return (
<div className="w-full h-full flex items-center justify-center">
<div className="relative w-full h-full flex items-center justify-center">
<File className="w-8 h-8 fill-primary/60 stroke-0" />
{overlay}
</div>
)
}
@@ -0,0 +1,138 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { AssetInfo } from '@shumai/dtos'
import React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { FindSimilarDialog } from './find-similar-dialog'
vi.mock('@dnd-kit/react', () => ({
useDraggable: () => ({ ref: vi.fn(), isDragging: false }),
useDroppable: () => ({ ref: vi.fn(), isDropTarget: false }),
}))
const mockSearchByImage = vi.fn()
vi.mock('./search-by-image', () => ({
searchByImage: (...args: unknown[]) => mockSearchByImage(...args),
}))
describe('FindSimilarDialog', () => {
let queryClient: QueryClient
let windowOpenSpy: ReturnType<typeof vi.spyOn>
beforeEach(() => {
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
windowOpenSpy = vi.spyOn(window, 'open').mockImplementation(() => null)
})
afterEach(() => {
cleanup()
vi.clearAllMocks()
windowOpenSpy.mockRestore()
})
it('renders version badge for version_stack similar results and opens the stack page on click', async () => {
const sourceStack: AssetInfo = {
id: 'source-stack',
name: 'source_v3.jpg',
type: 'version_stack',
status: 'processed',
createdAt: '2026-01-03T00:00:00Z',
updatedAt: '2026-01-03T00:00:00Z',
versionStack: {
id: 'source-stack',
versions: [
{
id: 'source-v3',
name: 'source_v3.jpg',
version: 3,
current: true,
status: 'processed',
previewUrl: null,
createdAt: '2026-01-03T00:00:00Z',
},
{
id: 'source-v2',
name: 'source_v2.jpg',
version: 2,
current: false,
status: 'processed',
previewUrl: null,
createdAt: '2026-01-02T00:00:00Z',
},
{
id: 'source-v1',
name: 'source_v1.jpg',
version: 1,
current: false,
status: 'processed',
previewUrl: null,
createdAt: '2026-01-01T00:00:00Z',
},
],
},
} as AssetInfo
const matchedStack: AssetInfo = {
id: 'matched-stack',
name: 'similar_v5.jpg',
type: 'version_stack',
status: 'processed',
createdAt: '2026-01-05T00:00:00Z',
updatedAt: '2026-01-05T00:00:00Z',
preview: {
proxyType: 'image',
thumbnailUrl: 'https://example.com/similar_v5.jpg',
},
versionStack: {
id: 'matched-stack',
versions: Array.from({ length: 5 }, (_, idx) => ({
id: `matched-v${5 - idx}`,
name: `similar_v${5 - idx}.jpg`,
version: 5 - idx,
current: idx === 0,
status: 'processed' as const,
previewUrl: null,
createdAt: '2026-01-05T00:00:00Z',
})),
},
} as AssetInfo
mockSearchByImage.mockResolvedValueOnce({
data: [matchedStack],
pageInfo: { total: 1 },
})
render(
<QueryClientProvider client={queryClient}>
<FindSimilarDialog
image={sourceStack}
folderId="root-folder"
teamId="team-1"
projectId="proj-1"
onClose={vi.fn()}
/>
</QueryClientProvider>,
)
await waitFor(() => {
expect(screen.getByText('similar_v5.jpg')).toBeTruthy()
})
expect(mockSearchByImage).toHaveBeenCalledWith(
'root-folder',
expect.objectContaining({ sourceAssetId: 'source-v3' }),
expect.any(AbortSignal),
)
expect(screen.getByText('v5')).toBeTruthy()
const card = screen.getByText('similar_v5.jpg').closest('[data-testid="file-card"]')!
fireEvent.click(card)
expect(windowOpenSpy).toHaveBeenCalledWith(
'/projects/proj-1/files/matched-stack',
'_blank',
'noopener,noreferrer',
)
})
})
@@ -0,0 +1,124 @@
import type { AssetInfo, ImageSearchMediaType } from '@shumai/dtos'
import { useInfiniteQuery } from '@tanstack/react-query'
import { Loader2 } from 'lucide-react'
import { useEffect, useState } from 'react'
import { useInView } from 'react-intersection-observer'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import { ToggleGroup, ToggleGroupItem } from '@/ui/components/ui/toggle-group'
import { m } from '@/ui/paraglide/messages.js'
import { searchByImage } from './search-by-image'
import { SearchResultCards } from './search-result-cards'
type MediaFilter = ImageSearchMediaType | 'all'
export function FindSimilarDialog({
image,
folderId,
teamId,
projectId,
onClose,
}: {
image: AssetInfo
folderId: string
teamId: string
projectId: string
onClose: () => void
}) {
const [filter, setFilter] = useState<MediaFilter>('all')
const sourceAssetId =
image.versionStack?.versions.find((version) => version.current)?.id ?? image.id
const { ref, inView } = useInView()
const { data, error, isLoading, hasNextPage, isFetchingNextPage, fetchNextPage } =
useInfiniteQuery({
queryKey: ['find-similar', folderId, sourceAssetId, filter],
queryFn: ({ pageParam, signal }) =>
searchByImage(
folderId,
{
sourceAssetId,
conditions: [],
operator: 'AND',
mediaType: filter === 'all' ? undefined : filter,
first: 20,
after: pageParam,
},
signal,
),
initialPageParam: undefined as string | undefined,
getNextPageParam: (page) => page.pageInfo.cursor,
retry: false,
})
useEffect(() => {
if (inView && hasNextPage && !isFetchingNextPage && !error) void fetchNextPage()
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage, error])
const results = data?.pages.flatMap((page) => page.data) ?? []
const total = data?.pages[0]?.pageInfo.total
return (
<Dialog
open
onOpenChange={(open) => {
if (!open) onClose()
}}
>
<DialogContent className="flex h-[85vh] flex-col overflow-hidden p-0 sm:max-w-4xl">
<DialogHeader className="px-6 pt-5 pr-12">
<DialogTitle>{m.find_similar()}</DialogTitle>
<DialogDescription className="truncate">{image.name}</DialogDescription>
</DialogHeader>
<div className="flex flex-wrap items-center justify-between gap-2 border-b px-6 pb-4">
<ToggleGroup
aria-label={m.image_search_media_filter()}
type="single"
variant="outline"
value={filter}
onValueChange={(value) => {
if (value === 'all' || value === 'image' || value === 'video') setFilter(value)
}}
>
<ToggleGroupItem value="all">{m.all()}</ToggleGroupItem>
<ToggleGroupItem value="image">{m.image_search_images()}</ToggleGroupItem>
<ToggleGroupItem value="video">{m.image_search_videos()}</ToggleGroupItem>
</ToggleGroup>
{total != null && (
<span className="text-xs text-muted-foreground">
{m.matched_items({ count: String(total) })}
</span>
)}
</div>
<ScrollArea className="min-h-0 flex-1 [&>div>div]:block!">
<div className="p-6">
{(isLoading || isFetchingNextPage) && (
<p
role="status"
className="flex items-center gap-2 py-2 text-sm text-muted-foreground"
>
<Loader2 className="size-4 animate-spin" />
{m.loading()}
</p>
)}
{error && (
<p role="alert" className="py-2 text-sm text-destructive">
{error.message}
</p>
)}
{!isLoading && !error && results.length === 0 && (
<p className="py-2 text-sm text-muted-foreground">{m.no_records_matched()}</p>
)}
<SearchResultCards teamId={teamId} projectId={projectId} results={results} />
{hasNextPage && !error && <div ref={ref} className="h-1" />}
</div>
</ScrollArea>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,21 @@
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import type { ImageSearchRequest } from '@shumai/dtos'
export async function searchByImage(
folderId: string,
request: ImageSearchRequest,
signal: AbortSignal,
) {
const res = await client.api.folders[':folderId']['image-search'].$post(
{ param: { folderId }, json: request },
{ init: { signal } },
)
if (!res.ok) {
if (res.status === 409) throw new Error(m.image_search_waiting_for_index())
if (res.status === 422) throw new Error(m.enable_embedding_agent_hint())
if (res.status === 400 || res.status === 413) throw new Error(m.image_search_invalid_image())
throw new Error(m.search_failed())
}
return res.json()
}
@@ -325,4 +325,101 @@ describe('SearchFilterDialog', () => {
expect(badges[0].textContent).toBe('00:10 - 00:30')
expect(badges[1].textContent).toBe('02:00 - 02:30')
})
it('renders version badge for version_stack results and opens the stack page on click', async () => {
const mockStack: AssetInfo = {
id: 'stack-1',
name: 'hero_final.png',
type: 'version_stack',
status: 'processed',
createdAt: '2026-01-01T00:00:00Z',
updatedAt: '2026-01-01T00:00:00Z',
preview: {
proxyType: 'image',
thumbnailUrl: 'https://example.com/hero_final.jpg',
},
versionStack: {
id: 'stack-1',
versions: [
{
id: 'file-v5',
name: 'hero_final.png',
version: 5,
current: true,
status: 'processed',
previewUrl: 'https://example.com/hero_final.jpg',
createdAt: '2026-01-05T00:00:00Z',
},
{
id: 'file-v4',
name: 'hero_v4.png',
version: 4,
current: false,
status: 'processed',
previewUrl: null,
createdAt: '2026-01-04T00:00:00Z',
},
{
id: 'file-v3',
name: 'hero_v3.png',
version: 3,
current: false,
status: 'processed',
previewUrl: null,
createdAt: '2026-01-03T00:00:00Z',
},
{
id: 'file-v2',
name: 'hero_v2.png',
version: 2,
current: false,
status: 'processed',
previewUrl: null,
createdAt: '2026-01-02T00:00:00Z',
},
{
id: 'file-v1',
name: 'hero_v1.png',
version: 1,
current: false,
status: 'processed',
previewUrl: null,
createdAt: '2026-01-01T00:00:00Z',
},
],
},
} as AssetInfo
mockSearchPost.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [mockStack],
pageInfo: { total: 1 },
}),
})
render(
<QueryClientProvider client={queryClient}>
<SearchFilterDialog
{...defaultProps}
initialConditions={[{ field: 'name', operator: 'contains', value: 'hero' }]}
/>
</QueryClientProvider>,
)
await waitFor(() => {
expect(screen.getByText('hero_final.png')).toBeTruthy()
})
expect(screen.getByText('v5')).toBeTruthy()
const card = screen.getByText('hero_final.png').closest('[data-testid="file-card"]')!
fireEvent.click(card)
expect(windowOpenSpy).toHaveBeenCalledWith(
'/projects/proj-1/files/stack-1',
'_blank',
'noopener,noreferrer',
)
})
})
@@ -9,15 +9,17 @@ import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label'
import { Switch } from '@/ui/components/ui/switch'
import { cn } from '@/ui/lib/utils'
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { AlertCircle, ChevronDown, ChevronUp, Loader2, Search, X } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { useInView } from 'react-intersection-observer'
import { toast } from 'sonner'
import { FileCard } from '@/ui/components/file-browser/file-card'
import { FolderCard } from '@/ui/components/file-browser/folder-card'
import { FilterPanel } from './filter-panel'
import { SearchImagePicker, type SearchImage } from './search-image-picker'
import { SearchResultCards } from './search-result-cards'
import { useSemanticSearchEnabled } from './use-semantic-search-enabled'
import { searchByImage } from './search-by-image'
import { m } from '@/ui/paraglide/messages.js'
interface SearchFilterDialogProps {
@@ -59,22 +61,15 @@ export function SearchFilterDialog({
const [triggerQuery, setTriggerQuery] = useState(initialKeyword)
const [isSemantic, setIsSemantic] = useState<boolean>(false)
const { data: teamSettings } = useQuery({
queryKey: ['team-settings', teamId],
queryFn: async () => {
const res = await client.api.teams[':teamId'].settings.$get({
param: { teamId },
})
if (!res.ok) throw new Error(m.failed_load_settings())
return (await res.json()) as { semanticSearchEnabled: boolean }
},
enabled: open,
})
const semanticSearchEnabled = teamSettings?.semanticSearchEnabled ?? false
const [attachedImage, setAttachedImage] = useState<SearchImage | null>(null)
const [imageSubmitted, setImageSubmitted] = useState(false)
const submittedImage = imageSubmitted ? attachedImage : null
const semanticSearchEnabled = useSemanticSearchEnabled(teamId, open)
// Sync back if changed from outside, clear on close
useEffect(() => {
setAttachedImage(null)
setImageSubmitted(false)
if (open) {
setSearchInput(initialKeyword)
setTriggerQuery(initialKeyword)
@@ -101,10 +96,9 @@ export function SearchFilterDialog({
return result
}, [isSemantic, triggerQuery, conditions])
const hasActiveCriteria = useMemo(() => {
const activeText = triggerQuery
return activeText.trim() !== '' || conditions.some((c) => String(c.value || '').trim() !== '')
}, [triggerQuery, conditions])
const hasActiveCriteria = attachedImage
? Boolean(submittedImage && semanticSearchEnabled)
: triggerQuery.trim() !== '' || conditions.some((c) => String(c.value || '').trim() !== '')
const { mutate: saveAsCollection, isPending: isSaving } = useMutation({
mutationFn: async () => {
@@ -157,11 +151,33 @@ export function SearchFilterDialog({
isLoading,
isFetchingNextPage,
fetchNextPage,
refetch,
hasNextPage,
error: searchError,
} = useInfiniteQuery({
queryKey: ['search-preview', teamId, assetId, combinedConditions, isSemantic, triggerQuery],
queryFn: async ({ pageParam }) => {
queryKey: [
'search-preview',
teamId,
assetId,
combinedConditions,
isSemantic,
triggerQuery,
submittedImage?.id,
],
queryFn: async ({ pageParam, signal }) => {
if (submittedImage) {
return searchByImage(
assetId,
{
image: submittedImage.base64,
conditions: combinedConditions,
operator: 'AND',
first: 20,
after: pageParam || undefined,
},
signal,
)
}
const activeText = triggerQuery
const res = await client.api.folders[':folderId'].search.$post({
param: { folderId: assetId },
@@ -186,16 +202,17 @@ export function SearchFilterDialog({
},
enabled: open && hasActiveCriteria,
staleTime: 500,
gcTime: submittedImage ? 0 : undefined,
retry: false,
initialPageParam: '',
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
})
useEffect(() => {
if (inView && hasNextPage && !isFetchingNextPage) {
if (inView && hasNextPage && !isFetchingNextPage && !searchError) {
fetchNextPage()
}
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage, searchError])
const flattenedResults = useMemo(() => {
return searchResults?.pages.flatMap((page) => page.data) || []
@@ -217,20 +234,6 @@ export function SearchFilterDialog({
setConditions([])
}
const handleResultClick = (item: AssetInfo) => {
if (item.type === 'folder') {
window.open(`/projects/${projectId}/folders/${item.id}`, '_blank', 'noopener,noreferrer')
} else {
const fileId = item.versionStack ? item.versionStack.id : item.id!
const searchParams = new URLSearchParams()
if (item.startTime !== undefined && item.startTime !== null && item.startTime > 0) {
searchParams.set('start', String(item.startTime))
}
const query = searchParams.toString() ? `?${searchParams.toString()}` : ''
window.open(`/projects/${projectId}/files/${fileId}${query}`, '_blank', 'noopener,noreferrer')
}
}
const activeFiltersCount = conditions.filter((c) => c.value !== '').length
return (
@@ -244,37 +247,72 @@ export function SearchFilterDialog({
<form
onSubmit={(e) => {
e.preventDefault()
setTriggerQuery(searchInput.trim())
if (attachedImage) {
if (!semanticSearchEnabled) return
if (imageSubmitted) void refetch()
else setImageSubmitted(true)
} else {
setTriggerQuery(searchInput.trim())
}
}}
className="flex flex-col gap-3 mt-2"
>
<div className="relative">
<Input
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
placeholder={
isSemantic ? m.search_by_content_placeholder() : m.search_by_name_placeholder()
}
className="w-full pl-4 pr-24 py-3 bg-background border-border rounded-xl text-sm h-12 focus-visible:ring-2 focus-visible:ring-primary/20 shadow-sm"
/>
{searchInput && (
<button
type="button"
onClick={() => {
setSearchInput('')
setTriggerQuery('')
}}
className="absolute right-20 top-1/2 -translate-y-1/2 p-1 rounded-md text-muted-foreground hover:text-foreground transition-colors"
>
<X className="w-4 h-4" />
</button>
{attachedImage ? (
<div className="flex h-12 items-center gap-2 rounded-xl border bg-background pl-2 pr-36 shadow-sm">
<img
alt=""
src={`data:image/jpeg;base64,${attachedImage.base64}`}
className="size-8 rounded-sm object-cover"
/>
<span className="truncate text-sm">{attachedImage.name}</span>
</div>
) : (
<Input
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
placeholder={
isSemantic ? m.search_by_content_placeholder() : m.search_by_name_placeholder()
}
className={cn(
'h-12 w-full rounded-xl border-border bg-background py-3 pl-4 text-sm shadow-sm focus-visible:ring-2 focus-visible:ring-primary/20',
isSemantic && semanticSearchEnabled ? 'pr-36' : 'pr-28',
)}
/>
)}
<button
type="submit"
className="absolute right-1.5 top-1.5 bottom-1.5 px-4 bg-primary hover:bg-primary/90 text-primary-foreground text-xs font-semibold rounded-lg flex items-center justify-center transition-colors shadow-sm"
>
{m.search_button()}
</button>
<div className="absolute inset-y-1.5 right-1.5 flex items-center gap-1">
{(searchInput || attachedImage) && (
<button
type="button"
aria-label={attachedImage ? m.image_search_remove() : m.clear_search()}
onClick={() => {
setAttachedImage(null)
setImageSubmitted(false)
setSearchInput('')
setTriggerQuery('')
}}
className="rounded-md p-1 text-muted-foreground transition-colors hover:text-foreground"
>
<X className="size-4" />
</button>
)}
{isSemantic && semanticSearchEnabled && (
<SearchImagePicker
onSelect={(image) => {
setAttachedImage(image)
setImageSubmitted(false)
setSearchInput('')
setTriggerQuery('')
}}
/>
)}
<button
type="submit"
className="flex h-full items-center justify-center rounded-lg bg-primary px-4 text-xs font-semibold text-primary-foreground transition-colors hover:bg-primary/90"
>
{m.search_button()}
</button>
</div>
</div>
<div className="flex items-center gap-3 py-1">
@@ -286,6 +324,8 @@ export function SearchFilterDialog({
setIsSemantic(checked)
setSearchInput('')
setTriggerQuery('')
setAttachedImage(null)
setImageSubmitted(false)
setConditions([])
}}
disabled={!semanticSearchEnabled}
@@ -380,9 +420,9 @@ export function SearchFilterDialog({
<Search className="w-10 h-10 text-muted-foreground/30 mb-2" />
<h3 className="text-sm font-semibold text-foreground/80">{m.ready_to_search()}</h3>
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
{m.type_query_instruction()}
{attachedImage ? m.image_search_submit_instruction() : m.type_query_instruction()}
</p>
{isSemantic && (
{isSemantic && !attachedImage && (
<p className="text-xs text-muted-foreground/80 max-w-md mt-4 mx-auto border-t border-border/60 pt-3">
{m.semantic_search_note()}
</p>
@@ -420,42 +460,16 @@ export function SearchFilterDialog({
{m.no_records_matched()}
</h3>
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
{m.try_adjusting_spelling()}
{!attachedImage && m.try_adjusting_spelling()}
</p>
</div>
) : (
<>
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
{flattenedResults.map((record) => {
const itemKey =
record.startTime != null && record.endTime != null
? `${record.id}-${record.startTime}-${record.endTime}`
: record.id
if (record.type === 'folder') {
return (
<FolderCard
key={itemKey}
item={record}
hideCheckbox
hideActions
disabled
onSelect={() => handleResultClick(record)}
/>
)
}
return (
<FileCard
key={itemKey}
teamId={teamId}
item={record}
hideCheckbox
hideActions
disabled
onSelect={() => handleResultClick(record)}
/>
)
})}
</div>
<SearchResultCards
results={flattenedResults}
teamId={teamId}
projectId={projectId}
/>
{(hasNextPage || isFetchingNextPage) && (
<div ref={ref} className="p-4 flex justify-center items-center">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
@@ -0,0 +1,155 @@
import { MAX_SEARCH_IMAGE_BASE64_LENGTH } from '@shumai/dtos'
import { ImagePlus, Loader2 } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { ulid } from 'ulid'
import { Button } from '@/ui/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/ui/components/ui/dialog'
import { m } from '@/ui/paraglide/messages.js'
export interface SearchImage {
id: string
name: string
base64: string
}
async function resizeImage(file: File): Promise<SearchImage> {
if (file.type && !file.type.startsWith('image/')) throw new Error('Invalid file type')
const bitmap = await createImageBitmap(file)
try {
const landscape = bitmap.width >= bitmap.height
const scale = Math.min(
1,
(landscape ? 1280 : 720) / bitmap.width,
(landscape ? 720 : 1280) / bitmap.height,
)
const canvas = document.createElement('canvas')
canvas.width = Math.max(1, Math.round(bitmap.width * scale))
canvas.height = Math.max(1, Math.round(bitmap.height * scale))
const context = canvas.getContext('2d')
if (!context) throw new Error('Unable to resize image')
context.fillStyle = '#fff'
context.fillRect(0, 0, canvas.width, canvas.height)
context.drawImage(bitmap, 0, 0, canvas.width, canvas.height)
const dataUrl = canvas.toDataURL('image/jpeg', 0.85)
const base64 = dataUrl.split(',')[1]
if (!base64 || base64.length > MAX_SEARCH_IMAGE_BASE64_LENGTH) {
throw new Error('Invalid resized image')
}
return { id: ulid(), name: file.name, base64 }
} finally {
bitmap.close()
}
}
export function SearchImagePicker({ onSelect }: { onSelect: (image: SearchImage) => void }) {
const [open, setOpen] = useState(false)
const [error, setError] = useState(false)
const [processing, setProcessing] = useState(false)
const input = useRef<HTMLInputElement>(null)
const pending = useRef<AbortController | null>(null)
useEffect(() => () => pending.current?.abort(), [])
function setPickerOpen(next: boolean) {
if (!next) {
pending.current?.abort()
pending.current = null
setError(false)
setProcessing(false)
}
setOpen(next)
}
async function selectFile(file: File) {
if (pending.current) return
const controller = new AbortController()
pending.current = controller
setError(false)
setProcessing(true)
try {
const image = await resizeImage(file)
if (controller.signal.aborted) return
onSelect(image)
setPickerOpen(false)
} catch {
if (!controller.signal.aborted) setError(true)
} finally {
if (pending.current === controller) {
pending.current = null
setProcessing(false)
}
}
}
return (
<Dialog open={open} onOpenChange={setPickerOpen}>
<DialogTrigger asChild>
<Button type="button" variant="ghost" size="icon-sm" aria-label={m.image_search_attach()}>
<ImagePlus className="size-4" />
</Button>
</DialogTrigger>
<DialogContent
onPaste={(event) => {
event.stopPropagation()
const image = Array.from(event.clipboardData.files).find((file) =>
file.type.startsWith('image/'),
)
if (!image) return
event.preventDefault()
void selectFile(image)
}}
>
<DialogHeader>
<DialogTitle>{m.image_search_attach()}</DialogTitle>
<DialogDescription>{m.image_search_select_description()}</DialogDescription>
</DialogHeader>
<input
ref={input}
type="file"
accept="image/*"
hidden
onChange={(event) => {
const file = event.currentTarget.files?.[0]
event.currentTarget.value = ''
if (file) void selectFile(file)
}}
/>
<Button
type="button"
variant="outline"
className="h-28 w-full border-dashed"
disabled={processing}
onClick={() => input.current?.click()}
onDragOver={(event) => {
event.preventDefault()
event.stopPropagation()
}}
onDrop={(event) => {
event.preventDefault()
event.stopPropagation()
const files = event.dataTransfer.files
if (files.length === 1) void selectFile(files[0])
else setError(true)
}}
>
{processing && <Loader2 className="size-4 animate-spin" />}
{m.image_search_choose_image()}
</Button>
{error && (
<p role="alert" className="text-sm text-destructive">
{m.image_search_invalid_image()}
</p>
)}
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,55 @@
import type { AssetInfo } from '@shumai/dtos'
import { FileCard } from '@/ui/components/file-browser/file-card'
import { FolderCard } from '@/ui/components/file-browser/folder-card'
export function SearchResultCards({
results,
teamId,
projectId,
}: {
results: AssetInfo[]
teamId: string
projectId: string
}) {
function openResult(item: AssetInfo) {
const projectPath = `/projects/${projectId}`
if (item.type === 'folder') {
window.open(`${projectPath}/folders/${item.id}`, '_blank', 'noopener,noreferrer')
return
}
const fileId = item.versionStack?.id ?? item.id
const query = item.startTime != null && item.startTime > 0 ? `?start=${item.startTime}` : ''
window.open(`${projectPath}/files/${fileId}${query}`, '_blank', 'noopener,noreferrer')
}
return (
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
{results.map((item) => {
const key =
item.startTime != null && item.endTime != null
? `${item.id}-${item.startTime}-${item.endTime}`
: item.id
return item.type === 'folder' ? (
<FolderCard
key={key}
item={item}
hideCheckbox
hideActions
disabled
onSelect={() => openResult(item)}
/>
) : (
<FileCard
key={key}
teamId={teamId}
item={item}
hideCheckbox
hideActions
disabled
onSelect={() => openResult(item)}
/>
)
})}
</div>
)
}
@@ -0,0 +1,17 @@
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import { useQuery } from '@tanstack/react-query'
export function useSemanticSearchEnabled(teamId: string, enabled: boolean): boolean {
const { data } = useQuery({
queryKey: ['team-settings', teamId],
queryFn: async () => {
const res = await client.api.teams[':teamId'].settings.$get({ param: { teamId } })
if (!res.ok) throw new Error(m.failed_load_settings())
return await res.json()
},
enabled,
})
return data?.semanticSearchEnabled ?? false
}
@@ -1,6 +1,11 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render } from '@testing-library/react'
import { act, cleanup, fireEvent, render } from '@testing-library/react'
import React from 'react'
import {
mockIsIntersecting,
resetIntersectionMocking,
setupIntersectionMocking,
} from 'react-intersection-observer/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { SpriteScrubber } from './sprite-scrubber'
import { FilePreview } from './file-browser/file-preview'
@@ -15,8 +20,116 @@ globalThis.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserv
describe('SpriteScrubber', () => {
afterEach(() => {
cleanup()
resetIntersectionMocking()
vi.unstubAllGlobals()
})
it.each(['chunk', 'full video', 'thumbnail'])('uses the %s preview on hover', (expected) => {
setupIntersectionMocking(vi.fn)
const chunkUrl = 'https://example.com/match.webp'
const fullUrl = 'https://example.com/full.webp'
const requests: string[] = []
const image = {
naturalWidth: 500,
naturalHeight: 200,
onload: null as (() => void) | null,
onerror: null as (() => void) | null,
set src(url: string) {
requests.push(url)
},
}
vi.stubGlobal(
'Image',
class {
constructor() {
return image
}
},
)
const { getByTestId, getByAltText, queryByAltText, container } = render(
<FilePreview
item={{
preview: { proxyType: 'video', spriteUrl: fullUrl, thumbnailUrl: '/poster.webp' },
}}
matchDuration={{ startTime: 0, endTime: 7 }}
matchedSprite={{ url: chunkUrl, columns: 5, rows: 2, frameCount: 7 }}
/>,
)
const scrubber = getByTestId('sprite-scrubber')
vi.spyOn(scrubber, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 100, 100))
expect(requests).toEqual([])
act(() => mockIsIntersecting(scrubber, true))
expect(requests).toEqual([chunkUrl])
if (expected === 'chunk') {
act(() => image.onload?.())
expect(queryByAltText('Thumbnail')).toBeNull()
expect(scrubber).toHaveProperty('dataset.frame', '0')
} else {
act(() => image.onerror?.())
expect(requests).toEqual([chunkUrl])
expect(getByAltText('Thumbnail').className).toContain('opacity-100')
}
fireEvent.mouseEnter(scrubber)
fireEvent.mouseMove(scrubber, { clientX: 100 })
expect(scrubber).toHaveProperty('dataset.frame', '6')
if (expected === 'chunk') {
expect(requests).toEqual([chunkUrl])
} else {
expect(requests).toEqual([chunkUrl, fullUrl])
}
if (expected === 'thumbnail') {
act(() => image.onerror?.())
expect(getByAltText('Thumbnail').className).toContain('opacity-100')
expect(container.querySelector('.animate-spin')).toBeNull()
} else if (expected === 'full video') {
act(() => image.onload?.())
expect(getByAltText('Thumbnail').className).toContain('opacity-0')
expect(scrubber).toHaveProperty('dataset.frame', '99')
}
fireEvent.mouseLeave(scrubber)
expect(scrubber).toHaveProperty('dataset.frame', '0')
if (expected === 'chunk') {
expect(queryByAltText('Thumbnail')).toBeNull()
} else {
expect(getByAltText('Thumbnail').className).toContain('opacity-100')
}
})
it('keeps the regular cover and waits for hover when a match has no chunk sprite', () => {
const load = vi.fn()
vi.stubGlobal('Image', load)
const { getByAltText } = render(
<FilePreview
item={{
preview: { proxyType: 'video', spriteUrl: '/full.webp', thumbnailUrl: '/poster.webp' },
}}
matchDuration={{ startTime: 0, endTime: 10 }}
/>,
)
expect(getByAltText('Thumbnail').getAttribute('src')).toBe('/poster.webp')
expect(load).not.toHaveBeenCalled()
})
it.each(['video', undefined] as const)(
'uses the full sprite for a legacy video match with proxy type %s and no poster or dimensions',
(proxyType) => {
const { getByTestId } = render(
<FilePreview
item={{ preview: { proxyType, spriteUrl: '/full.webp' } }}
matchDuration={{ startTime: 0, endTime: 10 }}
/>,
)
expect(getByTestId('sprite-scrubber')).toBeTruthy()
},
)
it('scrubs forward by default when hovering from left to right', () => {
const { getByTestId } = render(
<SpriteScrubber
+96 -64
View File
@@ -1,14 +1,20 @@
import type { SpriteLayout } from '@shumai/dtos'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useInView } from 'react-intersection-observer'
interface SpriteScrubberProps {
/** The URL of the 10x10 sprite sheet */
spriteUrl: string
spriteLayout?: SpriteLayout
/** Load the primary sprite when visible and show its first frame at rest. */
showFirstFrame?: boolean
/** A full-asset 10x10 sprite to try when the primary sprite fails. */
fallbackSpriteUrl?: string
/** The URL of the static thumbnail */
thumbnailUrl: string
thumbnailUrl?: string
/** The width of the original video source */
videoWidth: number
videoWidth?: number
/** The height of the original video source */
videoHeight: number
videoHeight?: number
/** The fixed width of a single frame in the sprite sheet (default 480) */
frameWidth?: number
/** Optional custom class name for the container */
@@ -22,33 +28,79 @@ interface Dimensions {
height: number
}
const GRID_COLS = 10
const GRID_ROWS = 10
const TOTAL_FRAMES = GRID_COLS * GRID_ROWS
const FULL_SPRITE_LAYOUT: SpriteLayout = { columns: 10, rows: 10, frameCount: 100 }
interface SpriteImage extends Dimensions {
url: string
}
function useSpriteImage(url: string | undefined) {
const [result, setResult] = useState<{ url: string; image: SpriteImage | null }>()
useEffect(() => {
if (!url) return
const img = new Image()
img.onload = () =>
setResult({ url, image: { url, width: img.naturalWidth, height: img.naturalHeight } })
img.onerror = () => setResult({ url, image: null })
img.src = url
return () => {
img.onload = null
img.onerror = null
}
}, [url])
return result?.url === url ? result?.image : undefined
}
export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
spriteUrl,
spriteLayout = FULL_SPRITE_LAYOUT,
showFirstFrame = false,
fallbackSpriteUrl,
thumbnailUrl,
videoWidth,
videoHeight,
videoWidth = 1,
videoHeight = 1,
className = '',
reverse = false,
}) => {
const containerRef = useRef<HTMLDivElement>(null)
const { ref: observeVisibility, inView } = useInView({
skip: !showFirstFrame,
triggerOnce: true,
fallbackInView: true,
})
const setContainerRef = useCallback(
(element: HTMLDivElement | null) => {
containerRef.current = element
observeVisibility(element)
},
[observeVisibility],
)
const [containerSize, setContainerSize] = useState<Dimensions>({
width: 0,
height: 0,
})
const [naturalSize, setNaturalSize] = useState<Dimensions>({
width: 0,
height: 0,
})
const [isHovering, setIsHovering] = useState(false)
const [spriteLoaded, setSpriteLoaded] = useState(false)
const [loadingSprite, setLoadingSprite] = useState(false)
const [currentFrame, setCurrentFrame] = useState(0)
const [hasHovered, setHasHovered] = useState(false)
const [cursorX, setCursorX] = useState(0)
const [progress, setProgress] = useState<number>()
const loadPrimary = hasHovered || (showFirstFrame && inView)
const primary = useSpriteImage(loadPrimary ? spriteUrl : undefined)
const fallbackUrl =
hasHovered && primary === null && fallbackSpriteUrl !== spriteUrl
? fallbackSpriteUrl
: undefined
const fallback = useSpriteImage(fallbackUrl)
const sprite = primary ?? fallback
const spriteVisible = Boolean(sprite && (isHovering || (showFirstFrame && primary)))
const spriteLoading =
primary === undefined || (fallbackUrl !== undefined && fallback === undefined)
const { columns, rows, frameCount } = fallback ? FULL_SPRITE_LAYOUT : spriteLayout
const frame = Math.min(Math.floor((progress ?? 0) * frameCount), frameCount - 1)
const cursorFrame = reverse && progress !== undefined ? frameCount - 1 - frame : frame
const currentFrame = showFirstFrame && !isHovering ? 0 : cursorFrame
useEffect(() => {
if (!containerRef.current) return
@@ -66,26 +118,9 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
return () => observer.disconnect()
}, [])
const loadSprite = useCallback(() => {
if (spriteLoaded || loadingSprite) return
setLoadingSprite(true)
const img = new Image()
img.src = spriteUrl
img.onload = () => {
setNaturalSize({ width: img.naturalWidth, height: img.naturalHeight })
setSpriteLoaded(true)
setLoadingSprite(false)
}
img.onerror = () => {
console.error('Failed to load sprite image')
setLoadingSprite(false)
}
}, [spriteUrl, spriteLoaded, loadingSprite])
const handleMouseEnter = () => {
setIsHovering(true)
loadSprite()
setHasHovered(true)
}
const handleMouseLeave = () => {
@@ -100,22 +135,17 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
const clampedX = Math.max(0, Math.min(x, rect.width))
setCursorX(clampedX)
const percentage = clampedX / rect.width
const rawFrame = Math.min(Math.floor(percentage * TOTAL_FRAMES), TOTAL_FRAMES - 1)
const frameIndex = reverse ? TOTAL_FRAMES - 1 - rawFrame : rawFrame
setCurrentFrame(frameIndex)
setProgress(rect.width > 0 ? clampedX / rect.width : 0)
}
// Calculate styles for the inner sprite frame box
const spriteStyle: React.CSSProperties = useMemo(() => {
if (containerSize.width === 0 || containerSize.height === 0) return {}
if (!sprite || containerSize.width === 0 || containerSize.height === 0) return {}
let sourceAspect = videoWidth / videoHeight
if (naturalSize.width > 0 && naturalSize.height > 0) {
const singleFrameNaturalW = naturalSize.width / GRID_COLS
const singleFrameNaturalH = naturalSize.height / GRID_ROWS
if (sprite.width > 0 && sprite.height > 0) {
const singleFrameNaturalW = sprite.width / columns
const singleFrameNaturalH = sprite.height / rows
sourceAspect = singleFrameNaturalW / singleFrameNaturalH
}
@@ -139,17 +169,17 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
// IMPORTANT: We calculate the sheet size based on the SNAPPED frame size.
// This slightly stretches the sprite if needed but ensures that every frame
// falls exactly on an integer pixel boundary, preventing "shaking" during playback.
const bgWidth = finalW * GRID_COLS
const bgHeight = finalH * GRID_ROWS
const bgWidth = finalW * columns
const bgHeight = finalH * rows
const colIndex = currentFrame % GRID_COLS
const rowIndex = Math.floor(currentFrame / GRID_COLS)
const colIndex = currentFrame % columns
const rowIndex = Math.floor(currentFrame / columns)
const bgPosX = -(colIndex * finalW)
const bgPosY = -(rowIndex * finalH)
return {
backgroundImage: `url(${spriteUrl})`,
backgroundImage: `url(${sprite.url})`,
backgroundSize: `${bgWidth}px ${bgHeight}px`,
backgroundPosition: `${bgPosX}px ${bgPosY}px`,
backgroundRepeat: 'no-repeat',
@@ -158,11 +188,11 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
// Optional: helps with crisp edges on some screens, though default is usually fine
imageRendering: 'auto',
}
}, [containerSize, videoWidth, videoHeight, currentFrame, spriteUrl, naturalSize])
}, [containerSize, videoWidth, videoHeight, currentFrame, sprite, columns, rows])
return (
<div
ref={containerRef}
ref={setContainerRef}
data-testid="sprite-scrubber"
data-frame={currentFrame}
className={`relative w-full h-full overflow-hidden cursor-pointer group bg-black select-none ${className}`}
@@ -170,32 +200,34 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
onMouseLeave={handleMouseLeave}
onMouseMove={handleMouseMove}
>
<img
src={thumbnailUrl}
alt="Thumbnail"
className={`absolute inset-0 w-full h-full object-contain transition-opacity duration-200 ${
isHovering && spriteLoaded ? 'opacity-0' : 'opacity-100'
}`}
draggable={false}
/>
{thumbnailUrl && (!showFirstFrame || primary === null) && (
<img
src={thumbnailUrl}
alt="Thumbnail"
className={`absolute inset-0 w-full h-full object-contain transition-opacity duration-200 ${
spriteVisible ? 'opacity-0' : 'opacity-100'
}`}
draggable={false}
/>
)}
{isHovering && !spriteLoaded && (
{isHovering && spriteLoading && (
<div className="absolute inset-0 flex items-center justify-center bg-black/50 z-10 pointer-events-none">
<div className="w-6 h-6 border-2 border-white/30 border-t-white rounded-full animate-spin" />
</div>
)}
{spriteLoaded && (
{sprite && (
<div
className={`absolute inset-0 flex items-center justify-center transition-opacity duration-75 ${
isHovering ? 'opacity-100' : 'opacity-0'
spriteVisible ? 'opacity-100' : 'opacity-0'
}`}
>
<div style={spriteStyle} />
</div>
)}
{isHovering && (
{isHovering && (spriteLoading || sprite) && (
<div
className="absolute top-0 bottom-0 w-0.5 bg-red-500 shadow-[0_0_4px_rgba(255,0,0,0.8)] z-20 pointer-events-none"
style={{ transform: `translateX(${cursorX}px)` }}
@@ -15,6 +15,11 @@ test.describe('Uploader Resilience E2E Tests', () => {
test('keeps upload active on network drop and automatically resumes on reconnection', async ({
page,
}) => {
let isOffline = false
let markFirstSignStarted: () => void = () => {}
const firstSignStarted = new Promise<void>((resolve) => {
markFirstSignStarted = resolve
})
let releaseSign: () => void = () => {}
const signGate = new Promise<void>((resolve) => {
releaseSign = resolve
@@ -24,32 +29,46 @@ test.describe('Uploader Resilience E2E Tests', () => {
await page.route('**/api/teams/**/upload/sign', async (route) => {
signCalls++
if (signCalls === 1) {
// Wait until offline event is dispatched before releasing first sign call
markFirstSignStarted()
// Wait until the browser is offline before failing the in-flight sign request
await signGate
}
route.fulfill({
if (isOffline) {
// Playwright route.fulfill() bypasses context.setOffline(true) in Chromium,
// so explicitly abort mocked requests while offline to simulate a real network drop.
await route.abort('internetdisconnected').catch(() => {})
return
}
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ url: 'http://localhost:5199/mock-upload' }),
})
})
await page.route('**/mock-upload', (route) =>
route.fulfill({
await page.route('**/mock-upload', async (route) => {
if (isOffline) {
await route.abort('internetdisconnected').catch(() => {})
return
}
await route.fulfill({
status: 200,
headers: { ['ETag']: '"test-etag"' },
}),
)
})
})
await page.goto('/?view=uploader')
await expect(page.getByTestId('upload-status')).toHaveText('idle')
// Start upload
// Start upload and wait until the first sign request is in flight
await page.getByTestId('start-upload-btn').click()
await expect(page.getByTestId('upload-status')).toHaveText('uploading')
await firstSignStarted
// Simulate cutting the connection
isOffline = true
await page.context().setOffline(true)
await expect.poll(() => page.evaluate(() => navigator.onLine)).toBe(false)
releaseSign()
// Status remains 'uploading' during offline state and no error toast appears
@@ -58,10 +77,12 @@ test.describe('Uploader Resilience E2E Tests', () => {
await expect(page.locator('[data-sonner-toast][data-type="error"]')).toHaveCount(0)
// Reconnect network
isOffline = false
await page.context().setOffline(false)
// Upload automatically resumes and completes
await expect(page.getByTestId('upload-status')).toHaveText('completed', { timeout: 15_000 })
expect(signCalls).toBeGreaterThanOrEqual(2)
await expect(page.locator('[data-sonner-toast][data-type="error"]')).toHaveCount(0)
})
+11
View File
@@ -1100,6 +1100,17 @@
"search_by_content_placeholder": "Search records by content...",
"search_by_name_placeholder": "Search records by name...",
"search_button": "Search",
"find_similar": "Find similar",
"image_search_images": "Images",
"image_search_videos": "Videos",
"image_search_media_filter": "Media type",
"image_search_attach": "Attach an image",
"image_search_select_description": "Choose an image, drag it here, or paste it from your clipboard.",
"image_search_choose_image": "Choose image",
"image_search_remove": "Remove image",
"image_search_invalid_image": "Choose a supported image file.",
"image_search_waiting_for_index": "This image is waiting to be indexed. Try again after processing finishes.",
"image_search_submit_instruction": "Select Search to find matches for this image.",
"semantic_search": "Semantic Search",
"semantic_search_requires_embedding": "* Semantic search requires an enabled embedding agent.",
"active_filters": "active",
+11
View File
@@ -1055,6 +1055,17 @@
"search_by_content_placeholder": "콘텐츠로 레코드 검색...",
"search_by_name_placeholder": "이름으로 레코드 검색...",
"search_button": "검색",
"find_similar": "유사한 미디어 찾기",
"image_search_images": "이미지",
"image_search_videos": "동영상",
"image_search_media_filter": "미디어 유형",
"image_search_attach": "이미지 첨부",
"image_search_select_description": "이미지를 선택하거나 여기로 끌어다 놓거나 클립보드에서 붙여넣으세요.",
"image_search_choose_image": "이미지 선택",
"image_search_remove": "이미지 제거",
"image_search_invalid_image": "지원되는 이미지 파일을 선택하세요.",
"image_search_waiting_for_index": "이미지가 인덱싱 대기 중입니다. 처리가 끝나면 다시 시도하세요.",
"image_search_submit_instruction": "검색을 선택하여 이 이미지와 유사한 미디어를 찾으세요.",
"semantic_search": "시맨틱 검색",
"semantic_search_requires_embedding": "* 시맨틱 검색을 사용하려면 임베딩 에이전트를 활성화해야 합니다.",
"active_filters": "개 적용됨",
+11
View File
@@ -1100,6 +1100,17 @@
"search_by_content_placeholder": "按内容搜索记录...",
"search_by_name_placeholder": "按名称搜索记录...",
"search_button": "搜索",
"find_similar": "查找相似素材",
"image_search_images": "图片",
"image_search_videos": "视频",
"image_search_media_filter": "媒体类型",
"image_search_attach": "添加图片",
"image_search_select_description": "选择图片、将图片拖到此处,或从剪贴板粘贴图片。",
"image_search_choose_image": "选择图片",
"image_search_remove": "移除图片",
"image_search_invalid_image": "请选择支持的图片文件。",
"image_search_waiting_for_index": "此图片正在等待建立索引。请在处理完成后重试。",
"image_search_submit_instruction": "点击搜索以查找与此图片相似的素材。",
"semantic_search": "语义搜索",
"semantic_search_requires_embedding": "* 语义搜索需要启用嵌入智能体。",
"active_filters": "个激活",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/webui",
"version": "0.7.0",
"version": "0.7.1",
"private": true,
"type": "module",
"main": "./index.html",
+1 -1
View File
@@ -1 +1 @@
export const APP_VERSION = '0.7.0'
export const APP_VERSION = '0.7.1'
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/workflow-core",
"version": "0.7.0",
"version": "0.7.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
@@ -42,6 +42,7 @@ describe('DbosExecutor Tests', () => {
expect(getQueueForTaskType(WorkflowTaskType.transcode)).toBe(TaskQueueTranscode)
expect(getQueueForTaskType(WorkflowTaskType.transcode_video)).toBe(TaskQueueTranscode)
expect(getQueueForTaskType(WorkflowTaskType.transcode_image)).toBe(TaskQueueTranscode)
expect(getQueueForTaskType(WorkflowTaskType.transcode_video_chunks)).toBe(TaskQueueTranscode)
expect(getQueueForTaskType(WorkflowTaskType.ai_embedding)).toBe(TaskQueueAgent)
expect(getQueueForTaskType(WorkflowTaskType.chat)).toBe(TaskQueueAgent)
expect(getQueueForTaskType(WorkflowTaskType.archive_asset)).toBe(TaskQueueArchive)
@@ -69,6 +69,7 @@ export function getQueueForTaskType(type: string | null | undefined): string {
case WorkflowTaskType.transcode_image_annotation:
case WorkflowTaskType.transcode_watermark:
case WorkflowTaskType.transcode_3d:
case WorkflowTaskType.transcode_video_chunks:
return TaskQueueTranscode
case WorkflowTaskType.archive_asset:
case WorkflowTaskType.restore_asset: