mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 03:14:11 +00:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b7b273f2e | ||
|
|
90f076f3ba | ||
|
|
fee6f39828 | ||
|
|
1066900c78 | ||
|
|
f2febaf652 | ||
|
|
5a1655e4ef | ||
|
|
e32445684f | ||
|
|
9c8eb16259 | ||
|
|
dc9adcf9ac | ||
|
|
5f6f3799fb | ||
|
|
6c71de4160 | ||
|
|
db628e65fa | ||
|
|
eeb41fee03 | ||
|
|
aabf59cbe7 | ||
|
|
3943407093 |
@@ -125,7 +125,7 @@ An **Operation** is defined once and exposed across built-in agent tools, the MC
|
||||
- **Route Code-Splitting**: Split all routes into `[route].tsx` (route definition and loaders) and `[route].lazy.tsx` (UI component and heavy imports).
|
||||
- **Radix / Shadcn UI**: Set `modal={false}` on `<DropdownMenu>` when triggering a `Dialog` or `AlertDialog` from inside it to prevent focus-trap UI freezes. Use `ScrollArea` (`@/ui/components/ui/scroll-area`) for scrollable containers.
|
||||
- **Pagination & Infinite Scroll**: Use `useInfiniteQuery` + `react-intersection-observer` with default `limit: 20` and the API's `total` field. Backend list APIs use `paginateQuery` from `packages/core/src/pagination.ts` (default `limit: 20`).
|
||||
- **Internationalization (i18n)**: Hardcoded UI text is strictly forbidden. Add `snake_case` keys to both `packages/webui/messages/en.json` and `packages/webui/messages/zh.json`, run `bun run i18n:compile` (or `bun run i18n:watch`), and import `m` from `@/ui/paraglide/messages.js`.
|
||||
- **Internationalization (i18n)**: Hardcoded UI text is strictly forbidden. Add `snake_case` keys to **all** locale files in `packages/webui/messages/*.json` (do not assume only `en.json` and `zh.json` exist; check the directory for all supported languages), run `bun run i18n:compile` (or `bun run i18n:watch`), and import `m` from `@/ui/paraglide/messages.js`.
|
||||
|
||||
## Database & Prisma (`packages/db`)
|
||||
|
||||
|
||||
@@ -8,10 +8,39 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
### Added
|
||||
|
||||
- **comments**: Add Internal Comments with a Public/Internal selector in the comment composer so team and project members can have private discussions (marked with a lock icon) that never appear on public share links.
|
||||
- **comments**: Allow comment authors to edit their comments inline from the comment menu, including updating text, switching between Public and Internal, removing timestamps, and adding or removing attachments.
|
||||
|
||||
- **comments**: Add a "Print Comments" option in the comments menu (available in both project file views and public share links) that opens a dedicated print-friendly page with asset metadata, comment thumbnails, visual markup overlays, replies, completion status, emoji reactions, and attachments.
|
||||
|
||||
- **share**: See view counts, last viewed times, and activity for public share links, including file and folder views, downloads, and comments.
|
||||
|
||||
- **share**: Add options to create a share link or add to existing share links directly from the media view dropdown menu, and open a quick share dialog with inline renaming, one-click link copying, and security settings upon creation.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **video**: Pause playback while dragging the seekbar and show a lightweight preview in the player until the selected frame is ready.
|
||||
- **comments**: Keep password-protected print links on the share password prompt, keep private folder names out of shared print data, and wait for thumbnails and reply drawings before printing.
|
||||
- **security**: Security improvements.
|
||||
|
||||
### 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
|
||||
@@ -20,6 +49,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
### Fixed
|
||||
|
||||
- **video**: Fix playback stalling after tapping or clicking the progress bar on slow connections, and stop the hidden seek preview from downloading the whole video in the background.
|
||||
- **cli**: Fix release publication failing to find staged standalone downloads.
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/premiere-uxp",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"private": true,
|
||||
"type": "commonjs",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
+11
-1
@@ -77,8 +77,13 @@ apps/web/e2e/
|
||||
| Owner deletes a file, finds it in recently deleted, and restores it | `tests/project/delete-restore.spec.ts` |
|
||||
| Owner deletes a folder and still sees its contents preview and countdown in recently deleted | `tests/project/delete-restore.spec.ts` |
|
||||
| Owner deletes a version stack and restores it from recently deleted | `tests/project/delete-restore.spec.ts` |
|
||||
| Owner creates a share link from a file context menu and lands on the share page | `tests/project/create-share-link.spec.ts` |
|
||||
| Owner creates a share link from a file context menu, edits it in the quick dialog, and opens advanced settings | `tests/project/create-share-link.spec.ts` |
|
||||
| Owner creates a share link and adds to an existing share link from media view | `tests/project/create-share-link.spec.ts` |
|
||||
| Owner protects a share with a password; guests must enter it to view | `tests/project/share-password.spec.ts` |
|
||||
| Guests can unlock a protected printable comments link directly | `tests/project/share-password.spec.ts` |
|
||||
| Public page views and share activity appear in both management sidebars | `tests/project/share-activity.spec.ts` |
|
||||
| Opening a direct historical version link records the selected version | `tests/project/share-activity.spec.ts` |
|
||||
| Concurrent public opens count every view and deduplicate matching activity | `tests/project/share-activity.spec.ts` |
|
||||
| Owner creates a collection from the sidebar; the collection shows project files | `tests/project/create-collection.spec.ts` |
|
||||
| Owner invites a member to a project; the member only sees the invited project | `tests/project/invite-member.spec.ts` |
|
||||
| Owner changes a project member role in the members dialog and permissions update | `tests/project/change-member-role.spec.ts` |
|
||||
@@ -95,6 +100,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` |
|
||||
@@ -110,6 +118,8 @@ apps/web/e2e/
|
||||
| Upload an image file, wait for transcode, and create a comment with draw | `tests/file/image-draw-comment.spec.ts` |
|
||||
| Upload a video file, wait for transcode, and create a comment with draw at a non-zero timestamp | `tests/file/video-draw-comment.spec.ts` |
|
||||
| Upload an audio file, wait for transcode, and create a comment at a non-zero timestamp | `tests/file/audio-timestamp-comment.spec.ts` |
|
||||
| Create internal and public comments, verify internal comments are hidden on public share links | `tests/file/internal-comment-and-edit.spec.ts` |
|
||||
| Author edits comment text, switches to internal, removes timestamp, and updates attachments | `tests/file/internal-comment-and-edit.spec.ts` |
|
||||
| Show a breathing poster preview and "Preparing..." while a video is still transcoding | `tests/file/processing-preview.spec.ts` |
|
||||
| Show a preparing circle before the poster is generated | `tests/file/processing-preview.spec.ts` |
|
||||
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
import { expect, test } from '../../fixtures'
|
||||
import { apiAddAssetsToShare, apiCreateShare, fileCard } from '../../helpers/files'
|
||||
|
||||
test('internal comments show lock icon in workspace and are hidden on public share pages', async ({
|
||||
browser,
|
||||
file,
|
||||
prisma,
|
||||
}) => {
|
||||
const { context, page, projectId, fileId, fileName } = file
|
||||
const publicText = `Public note ${Date.now()}`
|
||||
const internalText = `Internal secret ${Date.now()}`
|
||||
|
||||
await page.goto(`/projects/${projectId}/files/${fileId}`)
|
||||
|
||||
const editor = page.locator('[contenteditable="true"]').first()
|
||||
const sendBtn = page.locator('button:has(svg.lucide-arrow-up)').last()
|
||||
const visibilityTrigger = page.getByTestId('comment-visibility-trigger')
|
||||
|
||||
// Default visibility is Public
|
||||
await expect(visibilityTrigger).toBeVisible()
|
||||
await expect(visibilityTrigger).toContainText('Public')
|
||||
|
||||
// Post a public comment
|
||||
await editor.fill(publicText)
|
||||
await sendBtn.click()
|
||||
await expect(page.getByText(publicText)).toBeVisible()
|
||||
|
||||
// Switch to Internal and post an internal comment
|
||||
await visibilityTrigger.click()
|
||||
await page.getByTestId('comment-visibility-internal').click()
|
||||
await expect(visibilityTrigger).toContainText('Internal')
|
||||
|
||||
await editor.fill(internalText)
|
||||
await sendBtn.click()
|
||||
await expect(page.getByText(internalText)).toBeVisible()
|
||||
|
||||
// Visibility pill resets to Public after sending
|
||||
await expect(visibilityTrigger).toContainText('Public')
|
||||
|
||||
// Internal comment shows lock icon, public comment does not
|
||||
await expect(page.getByTestId('internal-comment-icon')).toHaveCount(1)
|
||||
|
||||
// Verify DB persisted isInternal flags
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const comments = await prisma.assetComment.findMany({
|
||||
where: { assetId: fileId },
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
return comments.map((c) => ({ message: c.message, isInternal: c.isInternal }))
|
||||
})
|
||||
.toEqual([
|
||||
{ message: publicText, isInternal: false },
|
||||
{ message: internalText, isInternal: true },
|
||||
])
|
||||
|
||||
// Create a public share link for this file
|
||||
const share = await apiCreateShare(context.request, projectId, 'External Review Share')
|
||||
await apiAddAssetsToShare(context.request, share.id, [fileId])
|
||||
|
||||
// Open public share page as an unauthenticated guest
|
||||
const guestContext = await browser.newContext()
|
||||
try {
|
||||
const guestPage = await guestContext.newPage()
|
||||
await guestPage.goto(`/share/${share.id}`)
|
||||
|
||||
// File card comment badge should only count the 1 public comment
|
||||
const card = fileCard(guestPage, fileName)
|
||||
await expect(card).toBeVisible()
|
||||
await expect(card).toContainText('1')
|
||||
|
||||
// Open the shared file
|
||||
await card.dblclick()
|
||||
await expect(guestPage.getByText(publicText)).toBeVisible()
|
||||
await expect(guestPage.getByText(internalText)).toHaveCount(0)
|
||||
await expect(guestPage.getByTestId('comment-visibility-trigger')).toHaveCount(0)
|
||||
} finally {
|
||||
await guestContext.close()
|
||||
}
|
||||
})
|
||||
|
||||
test.describe('author edits comment with timestamp and attachments', () => {
|
||||
test.use({ fileOptions: { mediaType: 'audio' } })
|
||||
|
||||
test('author edits comment text, switches to internal, removes timestamp, and updates attachments', async ({
|
||||
file,
|
||||
prisma,
|
||||
}) => {
|
||||
const { page, projectId, fileId } = file
|
||||
const originalText = `Initial audio note ${Date.now()}`
|
||||
const editedText = `Edited private note ${Date.now()}`
|
||||
|
||||
// Wait for audio transcode completion
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const asset = await prisma.asset.findUnique({ where: { id: fileId } })
|
||||
return asset?.status
|
||||
},
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
.toBe('processed')
|
||||
|
||||
await page.goto(`/projects/${projectId}/files/${fileId}`)
|
||||
|
||||
const mediaEl = page.locator('audio, video').first()
|
||||
await expect(mediaEl).toBeVisible({ timeout: 30_000 })
|
||||
|
||||
// Seek to non-zero timestamp
|
||||
await page.evaluate(() => {
|
||||
const el = document.querySelector('audio, video') as HTMLMediaElement | null
|
||||
if (el) el.currentTime = 1
|
||||
})
|
||||
await page.waitForTimeout(500)
|
||||
|
||||
// Attach initial file in composer
|
||||
const composerFileInput = page.locator('input[type="file"]').last()
|
||||
await composerFileInput.setInputFiles({
|
||||
name: 'old-attachment.txt',
|
||||
mimeType: 'text/plain',
|
||||
buffer: Buffer.from('old attachment content'),
|
||||
})
|
||||
await expect(page.getByText('old-attachment.txt')).toBeVisible()
|
||||
|
||||
// Submit public comment with timestamp and attachment
|
||||
const editor = page.locator('[contenteditable="true"]').first()
|
||||
await editor.fill(originalText)
|
||||
const sendBtn = page.locator('button:has(svg.lucide-arrow-up)').last()
|
||||
await expect(sendBtn).toBeEnabled()
|
||||
await sendBtn.click()
|
||||
|
||||
await expect(page.getByText(originalText)).toBeVisible()
|
||||
await expect(page.getByText('old-attachment.txt')).toBeVisible()
|
||||
|
||||
// Wait for DB persistence
|
||||
await expect
|
||||
.poll(async () => {
|
||||
return prisma.assetComment.findFirst({
|
||||
where: { assetId: fileId, message: originalText },
|
||||
})
|
||||
})
|
||||
.not.toBeNull()
|
||||
|
||||
// Open three-dot menu on comment card and click Edit
|
||||
const moreBtn = page.getByRole('button', { name: 'More options' }).last()
|
||||
await moreBtn.click({ force: true })
|
||||
await page.getByRole('menuitem', { name: 'Edit' }).click()
|
||||
|
||||
const editForm = page.getByTestId('comment-edit-form')
|
||||
await expect(editForm).toBeVisible()
|
||||
|
||||
// Remove timestamp
|
||||
await expect(editForm.getByTestId('edit-comment-timestamp')).toBeVisible()
|
||||
await editForm.getByTestId('edit-comment-remove-timestamp').click()
|
||||
await expect(editForm.getByTestId('edit-comment-timestamp')).toHaveCount(0)
|
||||
|
||||
// Remove existing attachment
|
||||
await editForm.getByTestId('edit-existing-attachment').locator('button').click()
|
||||
await expect(editForm.getByTestId('edit-existing-attachment')).toHaveCount(0)
|
||||
|
||||
// Add a new attachment
|
||||
await editForm.getByTestId('edit-comment-file-input').setInputFiles({
|
||||
name: 'new-attachment.txt',
|
||||
mimeType: 'text/plain',
|
||||
buffer: Buffer.from('new attachment content'),
|
||||
})
|
||||
await expect(editForm.getByText('new-attachment.txt')).toBeVisible()
|
||||
|
||||
// Switch Public -> Internal
|
||||
await editForm.getByTestId('comment-visibility-trigger').click()
|
||||
await page.getByTestId('comment-visibility-internal').click()
|
||||
await expect(editForm.getByTestId('comment-visibility-trigger')).toContainText('Internal')
|
||||
|
||||
// Change comment text
|
||||
const editInput = editForm.getByTestId('edit-comment-input')
|
||||
await editInput.click()
|
||||
await page.keyboard.press('ControlOrMeta+a')
|
||||
await page.keyboard.type(editedText)
|
||||
|
||||
// Save
|
||||
const saveBtn = editForm.getByTestId('edit-comment-save')
|
||||
await expect(saveBtn).toBeEnabled()
|
||||
await saveBtn.click()
|
||||
|
||||
await expect(editForm).toHaveCount(0)
|
||||
await expect(page.getByText(editedText)).toBeVisible()
|
||||
await expect(page.getByText('new-attachment.txt')).toBeVisible()
|
||||
await expect(page.getByText('old-attachment.txt')).toHaveCount(0)
|
||||
await expect(page.getByTestId('internal-comment-icon')).toHaveCount(1)
|
||||
|
||||
// Reload and verify persistence in UI and DB
|
||||
await page.reload()
|
||||
await expect(page.getByText(editedText)).toBeVisible()
|
||||
await expect(page.getByText('new-attachment.txt')).toBeVisible()
|
||||
await expect(page.getByTestId('internal-comment-icon')).toHaveCount(1)
|
||||
|
||||
const updated = await prisma.assetComment.findFirst({
|
||||
where: { assetId: fileId, message: editedText },
|
||||
include: { attachments: { include: { asset: true } } },
|
||||
})
|
||||
expect(updated).not.toBeNull()
|
||||
expect(updated?.isInternal).toBe(true)
|
||||
expect(updated?.second).toBeNull()
|
||||
expect(updated?.attachments.map((a) => a.asset.name)).toEqual(['new-attachment.txt'])
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
import { expect, test } from '../../fixtures'
|
||||
import { fileCard } from '../../helpers/files'
|
||||
import { apiCreateShare, fileCard } from '../../helpers/files'
|
||||
|
||||
test('owner creates a share link from a file context menu and lands on the share page', async ({
|
||||
test('owner creates a share link from a file context menu, edits it in the quick dialog, and opens advanced settings', async ({
|
||||
file,
|
||||
prisma,
|
||||
}) => {
|
||||
@@ -14,19 +14,38 @@ test('owner creates a share link from a file context menu and lands on the share
|
||||
await fileCard(page, fileName).click({ button: 'right' })
|
||||
await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
|
||||
|
||||
// The toast offers a "View" action that navigates to the share page
|
||||
const toast = page.locator('[data-sonner-toast]').filter({ hasText: 'Share link created' })
|
||||
await expect(toast).toBeVisible()
|
||||
await toast.getByRole('button', { name: 'View' }).click()
|
||||
// Quick share dialog opens with share name, URL, security controls, and footer actions
|
||||
const dialog = page.getByRole('dialog')
|
||||
await expect(dialog).toBeVisible()
|
||||
await expect(dialog.getByText(fileName)).toBeVisible()
|
||||
await expect(dialog.getByRole('button', { name: 'Copy Link' }).last()).toBeVisible()
|
||||
await expect(dialog.getByRole('button', { name: 'Done' })).toBeVisible()
|
||||
|
||||
// Rename share link inline via the pen icon
|
||||
await dialog.getByRole('button', { name: 'Rename Share Link' }).click()
|
||||
const nameInput = dialog.getByRole('textbox', { name: 'Rename Share Link' })
|
||||
await expect(nameInput).toBeVisible()
|
||||
await nameInput.fill('Client Review Cut')
|
||||
await nameInput.press('Enter')
|
||||
await expect(dialog.getByText('Client Review Cut')).toBeVisible()
|
||||
|
||||
// Toggle Allow download off in quick security settings
|
||||
const allowDownloadRow = dialog.getByText('Allow download').locator('..')
|
||||
await allowDownloadRow.getByRole('switch').click()
|
||||
await expect(page.getByText('Settings updated')).toBeVisible()
|
||||
|
||||
// Navigate to full settings via Advanced settings
|
||||
await dialog.getByRole('button', { name: 'Advanced settings' }).click()
|
||||
await expect(page).toHaveURL(/\/projects\/[^/]+\/shares\/[^/]+/)
|
||||
|
||||
// The shared file is listed in the share contents
|
||||
await expect(fileCard(page, fileName)).toBeVisible()
|
||||
|
||||
// DB: the share exists and the file is symlinked under the share root
|
||||
// DB: the share exists with updated settings and the file is symlinked under the share root
|
||||
const share = await prisma.shareLink.findFirst({ where: { projectId } })
|
||||
expect(share).not.toBeNull()
|
||||
expect(share?.name).toBe('Client Review Cut')
|
||||
expect(share?.allowDownload).toBe(false)
|
||||
|
||||
const symlink = await prisma.asset.findFirst({
|
||||
where: { parentId: share?.rootFolderId, targetId: fileId },
|
||||
@@ -34,3 +53,58 @@ test('owner creates a share link from a file context menu and lands on the share
|
||||
expect(symlink).not.toBeNull()
|
||||
expect(symlink?.type).toBe('symlink')
|
||||
})
|
||||
|
||||
test('owner creates a share link and adds to an existing share link from media view', async ({
|
||||
file,
|
||||
prisma,
|
||||
}) => {
|
||||
const { context, page, projectId, fileName, fileId } = file
|
||||
|
||||
// Seed an existing share link so "Add to Share Links" submenu is available
|
||||
const existingShare = await apiCreateShare(context.request, projectId, 'Existing Client Share')
|
||||
|
||||
await page.goto(`/projects/${projectId}/files/${fileId}`)
|
||||
const headerTrigger = page.getByRole('button', { name: fileName })
|
||||
await expect(headerTrigger).toBeVisible()
|
||||
|
||||
// Open the media view header arrow dropdown and create a new share link
|
||||
await headerTrigger.click()
|
||||
await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
|
||||
|
||||
const dialog = page.getByRole('dialog')
|
||||
await expect(dialog).toBeVisible()
|
||||
await expect(dialog.getByText(fileName)).toBeVisible()
|
||||
await expect(page).toHaveURL(new RegExp(`/projects/${projectId}/files/${fileId}$`))
|
||||
|
||||
// Close the dialog with Done and stay on the media view
|
||||
await dialog.getByRole('button', { name: 'Done' }).click()
|
||||
await expect(dialog).toBeHidden()
|
||||
await expect(page).toHaveURL(new RegExp(`/projects/${projectId}/files/${fileId}$`))
|
||||
|
||||
// DB: new share link created with symlink to the file
|
||||
const createdShare = await prisma.shareLink.findFirst({
|
||||
where: { projectId, id: { not: existingShare.id } },
|
||||
})
|
||||
expect(createdShare).not.toBeNull()
|
||||
expect(createdShare?.name).toBe(fileName)
|
||||
|
||||
const createdSymlink = await prisma.asset.findFirst({
|
||||
where: { parentId: createdShare?.rootFolderId, targetId: fileId },
|
||||
})
|
||||
expect(createdSymlink).not.toBeNull()
|
||||
expect(createdSymlink?.type).toBe('symlink')
|
||||
|
||||
// Open the header dropdown again and add the file to the existing share link
|
||||
await headerTrigger.click()
|
||||
await page.getByRole('menuitem', { name: 'Add to Share Links' }).hover()
|
||||
await page.getByRole('menuitem', { name: 'Existing Client Share' }).click()
|
||||
|
||||
const addedToast = page.locator('[data-sonner-toast]').filter({ hasText: 'Added to share link' })
|
||||
await expect(addedToast).toBeVisible()
|
||||
|
||||
const addedSymlink = await prisma.asset.findFirst({
|
||||
where: { parentId: existingShare.rootFolderId, targetId: fileId },
|
||||
})
|
||||
expect(addedSymlink).not.toBeNull()
|
||||
expect(addedSymlink?.type).toBe('symlink')
|
||||
})
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import { expect, test } from '../../fixtures'
|
||||
import { apiAddAssetsToShare, apiCreateShare, fileCard } from '../../helpers/files'
|
||||
|
||||
test('counts public page views and shows activity in both share management sidebars', async ({
|
||||
file,
|
||||
browser,
|
||||
prisma,
|
||||
}) => {
|
||||
const { context, page, projectId, rootFolderId, fileId, fileName } = file
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Review Folder',
|
||||
projectId,
|
||||
parentId: rootFolderId,
|
||||
type: 'folder',
|
||||
status: 'processed',
|
||||
},
|
||||
})
|
||||
await prisma.asset.update({ where: { id: fileId }, data: { parentId: folder.id } })
|
||||
const share = await apiCreateShare(context.request, projectId, 'Client Review')
|
||||
await apiAddAssetsToShare(context.request, share.id, [folder.id])
|
||||
const password = 'review-password'
|
||||
const lock = await context.request.put(`/api/shares/${share.id}`, { data: { password } })
|
||||
expect(lock.ok()).toBe(true)
|
||||
const readShare = () => prisma.shareLink.findUniqueOrThrow({ where: { id: share.id } })
|
||||
|
||||
await page.goto(`/projects/${projectId}/shares`)
|
||||
await expect(page.getByText('Never viewed')).toBeVisible()
|
||||
|
||||
const guest = await browser.newContext()
|
||||
try {
|
||||
const guestPage = await guest.newPage()
|
||||
await guestPage.goto(`/share/${share.id}`)
|
||||
await guestPage.getByPlaceholder('Enter password').fill(password)
|
||||
await guestPage.getByRole('button', { name: 'Access Share' }).click()
|
||||
await expect(fileCard(guestPage, folder.name)).toBeVisible()
|
||||
await expect.poll(async () => (await readShare()).views).toBe(1)
|
||||
await fileCard(guestPage, folder.name).click()
|
||||
await expect(fileCard(guestPage, fileName)).toBeVisible()
|
||||
await expect.poll(async () => (await readShare()).views).toBe(2)
|
||||
await fileCard(guestPage, fileName).click()
|
||||
await expect.poll(async () => (await readShare()).views).toBe(3)
|
||||
const beforeReload = (await readShare()).lastViewedAt
|
||||
await guestPage.reload()
|
||||
await expect.poll(async () => (await readShare()).views).toBe(4)
|
||||
expect((await readShare()).lastViewedAt!.getTime()).toBeGreaterThan(beforeReload!.getTime())
|
||||
|
||||
const downloadResponse = guestPage.waitForResponse((response) =>
|
||||
response.url().endsWith('/download-url'),
|
||||
)
|
||||
await guestPage.getByTestId('default-viewer-download-button').click()
|
||||
const download = await downloadResponse
|
||||
expect(download.status()).toBe(200)
|
||||
|
||||
const comment = await context.request.post(`/api/shares/${share.id}/files/${fileId}/comments`, {
|
||||
headers: { 'x-share-password': password },
|
||||
data: { message: 'Ready for review', attachmentIds: [] },
|
||||
})
|
||||
expect(comment.status()).toBe(201)
|
||||
} finally {
|
||||
await guest.close()
|
||||
}
|
||||
|
||||
await page.reload()
|
||||
const row = page.getByRole('row').filter({ hasText: share.name })
|
||||
await expect(row.getByRole('cell', { name: '4', exact: true })).toBeVisible()
|
||||
await expect(row.locator('time')).toContainText('Today')
|
||||
await row.getByRole('button', { name: 'View Activity' }).click()
|
||||
const sidebar = page.getByRole('dialog', { name: 'Activity' })
|
||||
await expect(sidebar.getByText('Opened Share Link')).toHaveCount(1)
|
||||
await expect(sidebar.getByText('Viewed Asset')).toHaveCount(2)
|
||||
await expect(sidebar.getByText(folder.name)).toBeVisible()
|
||||
await expect(sidebar.getByText('Downloaded')).toBeVisible()
|
||||
await expect(sidebar.getByText('Commented')).toBeVisible()
|
||||
await expect(sidebar.getByText('Someone').first()).toBeVisible()
|
||||
|
||||
await page.goto(`/projects/${projectId}/shares/${share.id}`)
|
||||
await expect(page.getByRole('tab', { name: 'Settings' })).toHaveAttribute('aria-selected', 'true')
|
||||
await page.getByRole('tab', { name: 'Activity' }).click()
|
||||
const tab = page.getByRole('tabpanel', { name: 'Activity' })
|
||||
await expect(tab.getByText('Opened Share Link')).toHaveCount(1)
|
||||
await expect(tab.getByText('Viewed Asset')).toHaveCount(2)
|
||||
await expect(tab.getByText('Commented')).toBeVisible()
|
||||
})
|
||||
|
||||
test('a direct historical version link records the version as the viewed asset', async ({
|
||||
file,
|
||||
browser,
|
||||
prisma,
|
||||
}) => {
|
||||
const { context, projectId, rootFolderId, fileId } = file
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Review Versions',
|
||||
projectId,
|
||||
parentId: rootFolderId,
|
||||
type: 'version_stack',
|
||||
status: 'processed',
|
||||
},
|
||||
})
|
||||
await prisma.asset.update({
|
||||
where: { id: fileId },
|
||||
data: { parentId: stack.id, sortIndex: 'a' },
|
||||
})
|
||||
const oldVersion = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Earlier Cut',
|
||||
projectId,
|
||||
parentId: stack.id,
|
||||
sortIndex: 'b',
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
},
|
||||
})
|
||||
const share = await apiCreateShare(context.request, projectId, 'Version Review')
|
||||
await apiAddAssetsToShare(context.request, share.id, [stack.id])
|
||||
const guest = await browser.newContext()
|
||||
try {
|
||||
const page = await guest.newPage()
|
||||
await page.goto(`/share/${share.id}/files/${stack.id}?version=${oldVersion.id}`)
|
||||
await expect
|
||||
.poll(() => prisma.shareActivity.count({ where: { shareLinkId: share.id } }))
|
||||
.toBe(2)
|
||||
const activities = await prisma.shareActivity.findMany({ where: { shareLinkId: share.id } })
|
||||
expect(activities).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ kind: 'share_viewed', assetId: null }),
|
||||
expect.objectContaining({ kind: 'asset_viewed', assetId: oldVersion.id }),
|
||||
]),
|
||||
)
|
||||
const link = await prisma.shareLink.findUniqueOrThrow({ where: { id: share.id } })
|
||||
expect(link.views).toBe(1)
|
||||
} finally {
|
||||
await guest.close()
|
||||
}
|
||||
})
|
||||
|
||||
test('concurrent authorized page opens add every view and one matching activity', async ({
|
||||
project,
|
||||
browser,
|
||||
prisma,
|
||||
}) => {
|
||||
const share = await apiCreateShare(
|
||||
project.context.request,
|
||||
project.projectId,
|
||||
'Concurrent Review',
|
||||
)
|
||||
const guest = await browser.newContext()
|
||||
try {
|
||||
const responses = await Promise.all(
|
||||
Array.from({ length: 8 }, () =>
|
||||
guest.request.post(`/api/shares/${share.id}/views`, { data: {} }),
|
||||
),
|
||||
)
|
||||
expect(responses.map((response) => response.status())).toEqual(Array(8).fill(204))
|
||||
const link = await prisma.shareLink.findUniqueOrThrow({ where: { id: share.id } })
|
||||
expect(link).toMatchObject({ views: 8, lastViewedAt: expect.any(Date) })
|
||||
const activities = await prisma.shareActivity.findMany({ where: { shareLinkId: share.id } })
|
||||
expect(activities).toMatchObject([{ kind: 'share_viewed', userId: null, assetId: null }])
|
||||
} finally {
|
||||
await guest.close()
|
||||
}
|
||||
})
|
||||
@@ -49,3 +49,33 @@ test('owner protects a share with a password and guests must enter it to view',
|
||||
await guestContext.close()
|
||||
}
|
||||
})
|
||||
|
||||
test('a guest can unlock a protected printable comments link directly', async ({
|
||||
file,
|
||||
browser,
|
||||
}) => {
|
||||
const { context, projectId, fileName, fileId } = file
|
||||
const share = await apiCreateShare(context.request, projectId, 'Shared Print')
|
||||
await apiAddAssetsToShare(context.request, share.id, [fileId])
|
||||
const res = await context.request.put(`/api/shares/${share.id}`, {
|
||||
data: { password: 'secret123' },
|
||||
})
|
||||
expect(res.ok()).toBe(true)
|
||||
|
||||
const guestContext = await browser.newContext()
|
||||
const page = await guestContext.newPage()
|
||||
try {
|
||||
await page.goto(`/print/comments/${fileId}?shareId=${share.id}`)
|
||||
const passwordInput = page.getByPlaceholder('Enter password')
|
||||
await expect(passwordInput).toBeVisible()
|
||||
await passwordInput.fill('wrong-password')
|
||||
await page.getByRole('button', { name: 'Confirm' }).click()
|
||||
await expect(page.getByText('Incorrect password. Please try again.')).toBeVisible()
|
||||
await passwordInput.fill('secret123')
|
||||
await page.getByRole('button', { name: 'Confirm' }).click()
|
||||
await expect(page.getByTitle(fileName)).toBeVisible()
|
||||
await expect(page).toHaveURL(`/print/comments/${fileId}?shareId=${share.id}`)
|
||||
} finally {
|
||||
await guestContext.close()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -147,8 +147,10 @@ test('dissolving a shared version stack renders the remaining standalone file na
|
||||
// Share the version stack
|
||||
await fileCard(page, fileB.name).click({ button: 'right' })
|
||||
await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
|
||||
const toast = page.locator('[data-sonner-toast]').filter({ hasText: 'Share link created' })
|
||||
await expect(toast).toBeVisible()
|
||||
const shareDialog = page.getByRole('dialog')
|
||||
await expect(shareDialog).toBeVisible()
|
||||
await shareDialog.getByRole('button', { name: 'Done' }).click()
|
||||
await expect(shareDialog).toBeHidden()
|
||||
|
||||
const share = await prisma.shareLink.findFirstOrThrow({
|
||||
where: { projectId },
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
|
||||
@@ -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:*",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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` |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ Shumai allows you to collaborate with external stakeholders who do not have acco
|
||||
|
||||
1. Select the files or folders you want to share, then right-click and choose **Create New Share Link**.
|
||||
2. Click the newly created **Share Link** in the project sidebar to open its settings page.
|
||||
3. Configure the share link in the right sidebar. You can:
|
||||
3. Use the **Settings** tab in the right sidebar to configure the share link.
|
||||
- Add password protection
|
||||
- Set an expiration date
|
||||
- Allow or disallow downloads
|
||||
@@ -33,6 +33,16 @@ Once a share link is created, you can easily add more files or folders to it wit
|
||||
|
||||
---
|
||||
|
||||
## Viewing Share Activity
|
||||
|
||||
Open **All Share Links** in the project sidebar to see **Views** and **Last Viewed** for each link. Click **View Activity** on a link’s row to open its history, or select the **Activity** tab on that link’s settings page.
|
||||
|
||||
The history groups share opens, file and folder views, downloads, and comments by day. It shows the visitor’s name when available and **Someone** for anonymous activity. A download entry appears when a visitor starts an authorized download.
|
||||
|
||||
Every successful open of the share, a shared folder, or a shared file adds one view and updates **Last Viewed**, including reloads. The history shows matching actions once within 30 minutes. A match uses the share link, action, visitor, and asset when there is one. For this check, all anonymous visitors are treated as the same visitor. For example, if a visitor opens the same file twice in ten minutes, **Views** increases by two and the history shows one **Viewed Asset** entry.
|
||||
|
||||
---
|
||||
|
||||
## Security and Settings
|
||||
|
||||
### Expiration Date
|
||||
|
||||
@@ -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`(默认) |
|
||||
|
||||
### 本地存储端口配置
|
||||
|
||||
|
||||
@@ -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` |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ Shumai 支持与未注册工作区账号的外部利益相关者协作。借助*
|
||||
|
||||
1. 选中要分享的文件或文件夹,右键单击并选择**创建新分享链接**。
|
||||
2. 在项目侧边栏中点击刚创建的**分享链接**,进入其配置页面。
|
||||
3. 在右侧边栏中配置分享链接参数:
|
||||
3. 在右侧边栏的**设置**选项卡中配置分享链接。
|
||||
- 添加密码保护
|
||||
- 设置过期时间
|
||||
- 开启或禁止文件下载
|
||||
@@ -33,6 +33,16 @@ Shumai 支持与未注册工作区账号的外部利益相关者协作。借助*
|
||||
|
||||
---
|
||||
|
||||
## 查看分享活动
|
||||
|
||||
在项目侧边栏打开**所有分享链接**,即可看到每条链接的**浏览次数**和**最近浏览**时间。点击对应行的**查看活动**,或在该链接的配置页面切换到**活动**选项卡,即可查看活动记录。
|
||||
|
||||
活动按天分组,包括打开分享链接、浏览文件和文件夹、下载以及发表评论。可以识别访客时显示其姓名,匿名活动显示为**有人**。访客开始下载且通过权限验证后,系统会记录下载活动。
|
||||
|
||||
每次成功打开分享页面、共享文件夹或共享文件(包括刷新页面)都会增加一次**浏览次数**,并更新**最近浏览**时间。系统根据分享链接、操作、访客和相关资产(如有)判断活动是否重复,30 分钟内的重复活动只显示一次。判断时,所有匿名访客视为同一位访客。例如,同一位访客在十分钟内两次打开同一文件,**浏览次数**会增加两次,活动列表显示一条**浏览了素材**的记录。
|
||||
|
||||
---
|
||||
|
||||
## 安全与权限配置
|
||||
|
||||
### 有效期
|
||||
|
||||
+1
-1
@@ -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
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "shumai",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"repository": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -601,6 +601,7 @@ export const createCommentActivity = defineStep(
|
||||
sessionId?: string | null
|
||||
agentId?: string | null
|
||||
replyToId?: string | null
|
||||
isInternal?: boolean
|
||||
}) {
|
||||
if (params.sessionId) {
|
||||
const agentId = params.agentId && params.agentId !== 'default' ? params.agentId : 'default'
|
||||
@@ -669,6 +670,7 @@ export const createCommentActivity = defineStep(
|
||||
sessionId: params.sessionId ?? null,
|
||||
creatorId: params.agentId && params.agentId !== 'default' ? params.agentId : null,
|
||||
replyToId: params.replyToId,
|
||||
isInternal: params.isInternal ?? false,
|
||||
},
|
||||
})
|
||||
},
|
||||
|
||||
@@ -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
@@ -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)
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -205,6 +205,43 @@ describe('Agent Chat Workflow', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('marks agent placeholder reply as internal when user comment is internal', async () => {
|
||||
mockActivities.getCommentActivity.mockResolvedValue({
|
||||
id: 'c-internal',
|
||||
message: 'hello agent privately',
|
||||
assetId: 'a1',
|
||||
creatorId: 'user-c1',
|
||||
second: null,
|
||||
annotation: null,
|
||||
replyToId: null,
|
||||
isInternal: true,
|
||||
attachments: [],
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: { userCommentId: 'c-internal', agentId: 'b1' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await agentChat(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'a1',
|
||||
message: '__CHAT__',
|
||||
sessionId: 'pending',
|
||||
agentId: 'b1',
|
||||
replyToId: 'c-internal',
|
||||
isInternal: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('should skip session initialization if sessionId is already provided', async () => {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
|
||||
@@ -85,6 +85,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
sessionId: sessionId || 'pending',
|
||||
agentId: agentId,
|
||||
replyToId: userComment.replyToId ?? userComment.id,
|
||||
...(userComment.isInternal ? { isInternal: true } : {}),
|
||||
})
|
||||
placeholderCommentId = placeholder.id
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/api",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -6,6 +6,7 @@ import { AssetType } from '@shumai/db'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock
|
||||
@@ -84,4 +85,28 @@ describe('Attachment API', () => {
|
||||
itemId: 'asset1',
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the upload key inside the attachment folder', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(assetService.createAsset).mockResolvedValue({ id: 'asset1' } as any)
|
||||
vi.mocked(s3Service.presign).mockResolvedValue('http://mock-s3-url')
|
||||
|
||||
const fileName = '../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov'
|
||||
const res = await app.request('/projects/project1/attachments', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ fileName, contentType: 'video/quicktime', size: 100 }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const key = vi.mocked(assetService.createAsset).mock.lastCall?.[0].key as string
|
||||
const parts = key.split('/')
|
||||
expect(parts[0]).toBe('attachments')
|
||||
expect(parts).toHaveLength(3)
|
||||
expect(parts).not.toContain('..')
|
||||
expect(s3Service.presign).toHaveBeenCalledWith(expect.any(String), key, 'PUT')
|
||||
expect(assetService.createAsset).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: fileName }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -7,6 +7,7 @@ import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { AssetType } from '@shumai/db'
|
||||
import { ulid } from 'ulid'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
@@ -27,7 +28,7 @@ const route = new Hono<{ Variables: { user: User } }>().post(
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const key = `attachments/${ulid()}/${req.fileName}`
|
||||
const key = `attachments/${ulid()}/${sanitizeFilename(req.fileName)}`
|
||||
|
||||
const assetInfo = await assetService.createAsset({
|
||||
name: req.fileName,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Hono, type Context, type Next } from 'hono'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import fileRoute from './file'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { commentFrameService } from '@shumai/core/src/comment/comment-frame'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
@@ -81,6 +82,7 @@ describe('file api', () => {
|
||||
vi.spyOn(assetService, 'updateAssetName').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'createComment').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'updateComment').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'completeComment').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'deleteComment').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'addCommentReaction').mockImplementation(vi.fn())
|
||||
@@ -90,7 +92,10 @@ describe('file api', () => {
|
||||
assetId: 'file1',
|
||||
} as unknown as Awaited<ReturnType<typeof assetService.getComment>>)
|
||||
vi.spyOn(assetService, 'listComments').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'listAllComments').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'getProjectNameForAsset').mockResolvedValue('Demo Project')
|
||||
vi.spyOn(assetService, 'exportComments').mockImplementation(vi.fn())
|
||||
vi.spyOn(commentFrameService, 'extractFrame').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn())
|
||||
vi.spyOn(notificationService, 'create').mockImplementation(vi.fn())
|
||||
@@ -287,6 +292,7 @@ describe('file api', () => {
|
||||
updatedAt: new Date().toISOString(),
|
||||
sessionId: null,
|
||||
isCompleted: false,
|
||||
isInternal: false,
|
||||
completionLastChangedBy: null,
|
||||
reactionCounts: [],
|
||||
})
|
||||
@@ -347,6 +353,7 @@ describe('file api', () => {
|
||||
updatedAt: new Date().toISOString(),
|
||||
sessionId: null,
|
||||
isCompleted: false,
|
||||
isInternal: false,
|
||||
completionLastChangedBy: null,
|
||||
reactionCounts: [],
|
||||
})
|
||||
@@ -404,6 +411,7 @@ describe('file api', () => {
|
||||
updatedAt: new Date().toISOString(),
|
||||
sessionId: null,
|
||||
isCompleted: false,
|
||||
isInternal: false,
|
||||
completionLastChangedBy: null,
|
||||
reactionCounts: [],
|
||||
},
|
||||
@@ -549,6 +557,7 @@ describe('file api', () => {
|
||||
updatedAt: new Date().toISOString(),
|
||||
sessionId: null,
|
||||
isCompleted: true,
|
||||
isInternal: false,
|
||||
completionLastChangedBy: { id: 'user1', name: 'Test User' },
|
||||
reactionCounts: [],
|
||||
})
|
||||
@@ -575,6 +584,110 @@ describe('file api', () => {
|
||||
expect(assetService.getComment).toHaveBeenCalledWith('comment-id', 'user1')
|
||||
})
|
||||
|
||||
it('POST /files/:fileId/comments forwards isInternal', async () => {
|
||||
vi.mocked(assetService.createComment).mockResolvedValue({
|
||||
id: 'comment-internal-id',
|
||||
assetId: 'test-id',
|
||||
message: 'internal note',
|
||||
annotations: null,
|
||||
second: null,
|
||||
creator: { id: 'user1', name: 'Test User' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
sessionId: null,
|
||||
isCompleted: false,
|
||||
isInternal: true,
|
||||
completionLastChangedBy: null,
|
||||
reactionCounts: [],
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/test-id/comments', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ message: 'internal note', attachmentIds: [], isInternal: true }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
const json = await res.json()
|
||||
expect(json.isInternal).toBe(true)
|
||||
expect(assetService.createComment).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetId: 'test-id',
|
||||
userId: 'user1',
|
||||
message: 'internal note',
|
||||
isInternal: true,
|
||||
}),
|
||||
expect.anything(),
|
||||
)
|
||||
})
|
||||
|
||||
it('PATCH /comments/:commentId updates comment and logs comment_update audit entry', async () => {
|
||||
vi.mocked(assetService.updateComment).mockResolvedValue({
|
||||
id: 'comment-id',
|
||||
assetId: 'file-id',
|
||||
message: 'edited text',
|
||||
annotations: null,
|
||||
second: null,
|
||||
creator: { id: 'user1', name: 'Test User' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
sessionId: null,
|
||||
isCompleted: false,
|
||||
isInternal: true,
|
||||
completionLastChangedBy: null,
|
||||
reactionCounts: [],
|
||||
})
|
||||
vi.mocked(assetService.getAssetContext).mockResolvedValue({
|
||||
teamId: 'test-team',
|
||||
projectId: 'proj-1',
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/comments/comment-id', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
message: 'edited text',
|
||||
isInternal: true,
|
||||
second: null,
|
||||
attachmentIds: ['att-1'],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.message).toBe('edited text')
|
||||
expect(json.isInternal).toBe(true)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Comment,
|
||||
id: 'comment-id',
|
||||
})
|
||||
expect(assetService.updateComment).toHaveBeenCalledWith({
|
||||
commentId: 'comment-id',
|
||||
userId: 'user1',
|
||||
message: 'edited text',
|
||||
isInternal: true,
|
||||
second: null,
|
||||
attachmentIds: ['att-1'],
|
||||
})
|
||||
expect(auditLogService.logAction).toHaveBeenCalledWith({
|
||||
action: 'comment_update',
|
||||
teamId: 'test-team',
|
||||
userId: 'user1',
|
||||
projectId: 'proj-1',
|
||||
itemId: 'comment-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /comments/:commentId/complete reopens with isCompleted false', async () => {
|
||||
vi.mocked(runOperation).mockResolvedValue({ commentId: 'comment-id', resolved: false })
|
||||
vi.mocked(assetService.getComment).mockResolvedValue({
|
||||
@@ -1095,4 +1208,90 @@ describe('file api', () => {
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /files/:fileId/comments/print and /frame routes', () => {
|
||||
it('returns asset, top-down breadcrumbs, and all comments for printing', async () => {
|
||||
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||
id: 'file-1',
|
||||
name: 'demo.mp4',
|
||||
sizeByte: 100,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'active',
|
||||
proxyType: 'video',
|
||||
ancestorFolders: [
|
||||
{ id: 'f2', name: 'Inner' },
|
||||
{ id: 'f1', name: 'Outer' },
|
||||
],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
vi.mocked(assetService.getProjectNameForAsset).mockResolvedValue('My Project')
|
||||
vi.mocked(assetService.listAllComments).mockResolvedValue([
|
||||
{
|
||||
id: 'c1',
|
||||
assetId: 'file-1',
|
||||
message: 'Looks great',
|
||||
annotations: null,
|
||||
second: 1.5,
|
||||
creator: { id: 'u1', name: 'Alice' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
sessionId: null,
|
||||
isCompleted: false,
|
||||
isInternal: false,
|
||||
completionLastChangedBy: null,
|
||||
reactionCounts: [],
|
||||
},
|
||||
])
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/file-1/comments/print')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.breadcrumbs).toEqual(['My Project', 'Outer', 'Inner'])
|
||||
expect(body.comments).toHaveLength(1)
|
||||
expect(body.asset.id).toBe('file-1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'file-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('streams extracted frame image with cache headers', async () => {
|
||||
const buf = Buffer.from('mock-webp-bytes')
|
||||
vi.mocked(commentFrameService.extractFrame).mockResolvedValue({
|
||||
buffer: buf,
|
||||
mimeType: 'image/webp',
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/file-1/comments/frame?second=2.5&width=400')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('content-type')).toBe('image/webp')
|
||||
expect(res.headers.get('cache-control')).toBe('private, max-age=300')
|
||||
const arr = new Uint8Array(await res.arrayBuffer())
|
||||
expect(Buffer.from(arr).toString()).toBe('mock-webp-bytes')
|
||||
expect(commentFrameService.extractFrame).toHaveBeenCalledWith({
|
||||
assetId: 'file-1',
|
||||
second: 2.5,
|
||||
width: 400,
|
||||
signal: expect.any(AbortSignal),
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects invalid second query parameter with 400', async () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/file-1/comments/frame?second=-5')
|
||||
expect(res.status).toBe(400)
|
||||
expect(commentFrameService.extractFrame).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,6 +3,7 @@ import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { commentService } from '@shumai/core/src/comment/comment'
|
||||
import { commentFrameService } from '@shumai/core/src/comment/comment-frame'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
import {
|
||||
archiveAssetsRequestSchema,
|
||||
createCommentRequestSchema,
|
||||
updateCommentRequestSchema,
|
||||
deleteFilesRequestSchema,
|
||||
batchGetFilesRequestSchema,
|
||||
paginationParamsSchema,
|
||||
@@ -29,6 +31,7 @@ import {
|
||||
getDownloadLinksRequestSchema,
|
||||
getStoragePathsRequestSchema,
|
||||
completeCommentRequestSchema,
|
||||
commentFrameQuerySchema,
|
||||
exportCommentsRequestSchema,
|
||||
addCommentReactionRequestSchema,
|
||||
removeCommentReactionRequestSchema,
|
||||
@@ -197,6 +200,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
annotations: req.annotations,
|
||||
second: req.second,
|
||||
attachmentIds: req.attachmentIds,
|
||||
isInternal: req.isInternal,
|
||||
})
|
||||
|
||||
const context = await assetService.getAssetContext(fileId)
|
||||
@@ -248,6 +252,60 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
return c.body(result.content)
|
||||
},
|
||||
)
|
||||
.get('/files/:fileId/comments/print', async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const [asset, projectName, comments] = await Promise.all([
|
||||
assetService.getAsset({ assetId: fileId }),
|
||||
assetService.getProjectNameForAsset(fileId),
|
||||
assetService.listAllComments(fileId, user.id),
|
||||
])
|
||||
|
||||
const folderNames = (asset.ancestorFolders ?? [])
|
||||
.slice()
|
||||
.reverse()
|
||||
.map((f) => f.name)
|
||||
.filter((name): name is string => Boolean(name))
|
||||
const breadcrumbs = projectName ? [projectName, ...folderNames] : folderNames
|
||||
|
||||
return c.json({
|
||||
asset,
|
||||
breadcrumbs,
|
||||
comments,
|
||||
})
|
||||
})
|
||||
.get('/files/:fileId/comments/frame', zValidator('query', commentFrameQuerySchema), async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const { second, width } = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const result = await commentFrameService.extractFrame({
|
||||
assetId: fileId,
|
||||
second,
|
||||
width,
|
||||
signal: c.req.raw.signal,
|
||||
})
|
||||
|
||||
return c.body(new Uint8Array(result.buffer), 200, {
|
||||
'Content-Type': result.mimeType,
|
||||
'Cache-Control': 'private, max-age=300',
|
||||
})
|
||||
})
|
||||
.post(
|
||||
'/comments/:commentId/reactions',
|
||||
zValidator('json', addCommentReactionRequestSchema),
|
||||
@@ -305,6 +363,38 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
return c.json(await assetService.getComment(commentId, user.id))
|
||||
},
|
||||
)
|
||||
.patch('/comments/:commentId', zValidator('json', updateCommentRequestSchema), async (c) => {
|
||||
const commentId = c.req.param('commentId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Comment,
|
||||
id: commentId,
|
||||
})
|
||||
|
||||
const updated = await assetService.updateComment({
|
||||
commentId,
|
||||
userId: user.id,
|
||||
message: req.message,
|
||||
isInternal: req.isInternal,
|
||||
second: req.second,
|
||||
attachmentIds: req.attachmentIds,
|
||||
})
|
||||
|
||||
const context = await assetService.getAssetContext(updated.assetId)
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.comment_update,
|
||||
teamId: context.teamId,
|
||||
userId: user.id,
|
||||
projectId: context.projectId,
|
||||
itemId: commentId,
|
||||
})
|
||||
|
||||
return c.json(updated)
|
||||
})
|
||||
.delete('/comments/:commentId', async (c) => {
|
||||
const commentId = c.req.param('commentId')
|
||||
const user = c.get('user')
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -30,7 +30,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const attachment = await kanbanService.createAttachment(teamId, req)
|
||||
const attachment = await kanbanService.createAttachment(teamId, user.id, req)
|
||||
return c.json(attachment)
|
||||
},
|
||||
)
|
||||
@@ -123,7 +123,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: taskId,
|
||||
})
|
||||
|
||||
const events = await kanbanService.listEvents(taskId)
|
||||
const events = await kanbanService.listEvents(taskId, user.id)
|
||||
return c.json({ data: events })
|
||||
})
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ import { kanbanService } from '@shumai/core/src/kanban/kanban'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { KanbanTaskStatus, KanbanTaskPriority } from '@shumai/db/enums'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
import kanbanRoute from './index'
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
@@ -19,6 +21,7 @@ vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
ResourceType: {
|
||||
Team: 'team',
|
||||
Project: 'project',
|
||||
Asset: 'asset',
|
||||
KanbanGoal: 'kanbanGoal',
|
||||
KanbanTask: 'kanbanTask',
|
||||
},
|
||||
@@ -51,6 +54,7 @@ describe('Kanban API Routes', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
vi.mocked(auditLogService.logAction).mockResolvedValue({} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(notificationService.notifyKanbanTaskEvent).mockResolvedValue(undefined as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
app = new Hono()
|
||||
@@ -218,6 +222,7 @@ describe('Kanban API Routes', () => {
|
||||
status: 'READY',
|
||||
goalId: 'goal-1',
|
||||
}),
|
||||
'user-1',
|
||||
)
|
||||
})
|
||||
|
||||
@@ -248,7 +253,7 @@ describe('Kanban API Routes', () => {
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe(taskId)
|
||||
expect(mockGet).toHaveBeenCalledWith(taskId)
|
||||
expect(mockGet).toHaveBeenCalledWith(taskId, 'user-1')
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/kanban/tasks/:taskId', async () => {
|
||||
@@ -493,6 +498,74 @@ describe('Kanban API Routes', () => {
|
||||
expect(mockLinkAssets).toHaveBeenCalledWith(teamId, taskId, ['asset-1', 'asset-2'])
|
||||
})
|
||||
|
||||
describe('linking files the caller cannot read', () => {
|
||||
const denyAsset = (deniedAssetId: string) =>
|
||||
vi.mocked(authzService.hasPermission).mockImplementation(async (req) => {
|
||||
if (req.type === 'asset' && req.id === deniedAssetId) {
|
||||
throw new HTTPException(403, { message: 'User has only project scope' })
|
||||
}
|
||||
})
|
||||
|
||||
it('checks Read on every file linked to a task', async () => {
|
||||
const mockLinkAssets = vi.spyOn(kanbanService, 'linkAssets').mockResolvedValue(undefined)
|
||||
denyAsset('asset-2')
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}/assets`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ assetIds: ['asset-1', 'asset-2'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(mockLinkAssets).not.toHaveBeenCalled()
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: 'asset', id: 'asset-1', permission: 'Read' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('checks Read on the file when linking it from the file side', async () => {
|
||||
const mockLinkAsset = vi.spyOn(kanbanService, 'linkAsset').mockResolvedValue(undefined)
|
||||
denyAsset('asset-1')
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/assets/asset-1/tasks`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ taskId }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(mockLinkAsset).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('checks Read on files passed when updating a task', async () => {
|
||||
const mockUpdate = vi.spyOn(kanbanService, 'updateTask')
|
||||
denyAsset('asset-9')
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ assetIds: ['asset-9'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(mockUpdate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('checks Read on files passed when creating a task', async () => {
|
||||
const mockCreate = vi.spyOn(kanbanService, 'createTask')
|
||||
denyAsset('asset-9')
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/tasks`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: 'Task', assetIds: ['asset-9'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(mockCreate).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/kanban/tasks/:taskId/assets/:assetId', async () => {
|
||||
const mockUnlinkAsset = vi.spyOn(kanbanService, 'unlinkAsset').mockResolvedValue(undefined)
|
||||
|
||||
@@ -530,7 +603,7 @@ describe('Kanban API Routes', () => {
|
||||
const json = await res.json()
|
||||
expect(json.total).toBe(1)
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(mockListTasksForAsset).toHaveBeenCalledWith(teamId, 'asset-1')
|
||||
expect(mockListTasksForAsset).toHaveBeenCalledWith(teamId, 'asset-1', 'user-1')
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/kanban/assets/:assetId/tasks', async () => {
|
||||
@@ -585,7 +658,7 @@ describe('Kanban API Routes', () => {
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('att-1')
|
||||
expect(mockAttachment).toHaveBeenCalledWith(teamId, {
|
||||
expect(mockAttachment).toHaveBeenCalledWith(teamId, 'user-1', {
|
||||
fileName: 'test.png',
|
||||
size: 1024,
|
||||
contentType: 'image/png',
|
||||
@@ -683,7 +756,7 @@ describe('Kanban API Routes', () => {
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(mockEvents).toHaveBeenCalledWith(taskId)
|
||||
expect(mockEvents).toHaveBeenCalledWith(taskId, 'user-1')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -22,6 +22,21 @@ import { HTTPException } from 'hono/http-exception'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
/**
|
||||
* Linking a file to a task shows its name, folder path and thumbnail to everyone
|
||||
* who can read the task, so the caller must be able to read each linked file.
|
||||
*/
|
||||
async function assertCanReadAssets(user: User, assetIds: string[] | undefined) {
|
||||
for (const id of new Set(assetIds ?? [])) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/kanban/tasks', zValidator('json', createKanbanTaskSchema), async (c) => {
|
||||
const { teamId } = c.req.param()
|
||||
@@ -40,6 +55,8 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
throw new HTTPException(403, { message: 'User is not a member of the team' })
|
||||
}
|
||||
|
||||
await assertCanReadAssets(user, req.assetIds)
|
||||
|
||||
const task = await kanbanService.createTask(teamId, req, user.id, role)
|
||||
|
||||
await auditLogService.logAction({
|
||||
@@ -89,7 +106,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const result = await kanbanService.listTasks(teamId, req)
|
||||
const result = await kanbanService.listTasks(teamId, req, user.id)
|
||||
return c.json(result)
|
||||
},
|
||||
)
|
||||
@@ -104,7 +121,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: taskId,
|
||||
})
|
||||
|
||||
const task = await kanbanService.getTask(taskId)
|
||||
const task = await kanbanService.getTask(taskId, user.id)
|
||||
return c.json(task)
|
||||
})
|
||||
.patch(
|
||||
@@ -122,6 +139,8 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: taskId,
|
||||
})
|
||||
|
||||
await assertCanReadAssets(user, req.assetIds)
|
||||
|
||||
const existing = await kanbanService.getTask(taskId)
|
||||
const role = await resolveEffectiveRole(teamId, existing.projectId ?? undefined, user.id)
|
||||
const task = await kanbanService.updateTask(taskId, req, user.id, role)
|
||||
@@ -262,6 +281,8 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: taskId,
|
||||
})
|
||||
|
||||
await assertCanReadAssets(user, req.assetIds)
|
||||
|
||||
await kanbanService.linkAssets(teamId, taskId, req.assetIds)
|
||||
return c.json({ success: true })
|
||||
},
|
||||
@@ -291,7 +312,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const tasks = await kanbanService.listTasksForAsset(teamId, assetId)
|
||||
const tasks = await kanbanService.listTasksForAsset(teamId, assetId, user.id)
|
||||
return c.json({ data: tasks, total: tasks.length })
|
||||
})
|
||||
.post(
|
||||
@@ -309,6 +330,8 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: req.taskId,
|
||||
})
|
||||
|
||||
await assertCanReadAssets(user, [assetId])
|
||||
|
||||
await kanbanService.linkAsset(teamId, req.taskId, assetId)
|
||||
return c.json({ success: true })
|
||||
},
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import publicShareRoute from './public-share'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { commentFrameService } from '@shumai/core/src/comment/comment-frame'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { auth } from '@shumai/core/src/auth/auth'
|
||||
import { ShareLinkPasswordInvalidError } from '@shumai/core/src/share/errors'
|
||||
|
||||
describe('public share print comments and frame api', () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(auth.api, 'getSession').mockResolvedValue(null)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /shares/:shareId/files/:fileId/comments/print returns share-scoped breadcrumbs and comments', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
id: 'share-1',
|
||||
name: 'Client Review',
|
||||
rootFolderId: 'share-root',
|
||||
projectId: 'proj-1',
|
||||
watermarkConfigId: null,
|
||||
fieldVisibility: { status: true, internalNote: false },
|
||||
} as never)
|
||||
|
||||
vi.spyOn(assetService, 'getAsset').mockResolvedValue({
|
||||
id: 'file-1',
|
||||
name: 'spot.mp4',
|
||||
sizeByte: 100,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'active',
|
||||
proxyType: 'video',
|
||||
fieldValues: [
|
||||
{ fieldId: 'status', value: 'Approved' },
|
||||
{ fieldId: 'internalNote', value: 'Private note' },
|
||||
{ fieldId: 'rating', value: 3 },
|
||||
],
|
||||
ancestorFolders: [
|
||||
{ id: 'inner', name: 'Inner Folder' },
|
||||
{ id: 'share-root', name: 'Share Root' },
|
||||
{ id: 'private-parent', name: 'Secret Project Folder' },
|
||||
],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
vi.spyOn(assetService, 'resolveLatestVersionId').mockResolvedValue('file-1')
|
||||
vi.spyOn(assetService, 'resolveTargetAssetId').mockResolvedValue('file-1')
|
||||
vi.spyOn(assetService, 'listAllComments').mockResolvedValue([
|
||||
{
|
||||
id: 'c1',
|
||||
assetId: 'file-1',
|
||||
message: 'Great cut!',
|
||||
annotations: null,
|
||||
second: 3,
|
||||
creator: { id: 'u1', name: 'Guest' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
sessionId: null,
|
||||
isCompleted: false,
|
||||
isInternal: false,
|
||||
completionLastChangedBy: null,
|
||||
reactionCounts: [],
|
||||
},
|
||||
])
|
||||
|
||||
const app = new Hono().route('/', publicShareRoute)
|
||||
const res = await app.request('/shares/share-1/files/file-1/comments/print', {
|
||||
headers: { 'x-share-password': 'secret' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(assetService.listAllComments).toHaveBeenCalledWith('file-1', undefined, {
|
||||
excludeInternal: true,
|
||||
})
|
||||
const body = await res.json()
|
||||
expect(body.breadcrumbs).toEqual(['Client Review', 'Inner Folder'])
|
||||
expect(body.asset.ancestorFolders).toEqual([{ id: 'inner', name: 'Inner Folder' }])
|
||||
expect(body.asset.fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }])
|
||||
expect(JSON.stringify(body)).not.toContain('Secret Project Folder')
|
||||
expect(JSON.stringify(body)).not.toContain('private-parent')
|
||||
expect(body.comments).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('GET /shares/:shareId/files/:fileId/comments/print returns 401 on invalid password', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockRejectedValue(
|
||||
new ShareLinkPasswordInvalidError('Invalid password'),
|
||||
)
|
||||
|
||||
const app = new Hono().route('/', publicShareRoute)
|
||||
const res = await app.request('/shares/share-1/files/file-1/comments/print')
|
||||
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('GET /shares/:shareId/files/:fileId/comments/frame passes watermarkConfigId and password query param', async () => {
|
||||
const verifySpy = vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
id: 'share-1',
|
||||
name: 'Watermarked Review',
|
||||
rootFolderId: 'share-root',
|
||||
projectId: 'proj-1',
|
||||
watermarkConfigId: 'wm-1',
|
||||
} as never)
|
||||
vi.spyOn(assetService, 'resolveTargetAssetId').mockResolvedValue('target-file-1')
|
||||
const extractSpy = vi.spyOn(commentFrameService, 'extractFrame').mockResolvedValue({
|
||||
buffer: Buffer.from('wm-webp'),
|
||||
mimeType: 'image/webp',
|
||||
})
|
||||
vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map())
|
||||
|
||||
const app = new Hono().route('/', publicShareRoute)
|
||||
const res = await app.request(
|
||||
'/shares/share-1/files/file-1/comments/frame?second=4.2&width=400&p=pw123',
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('content-type')).toBe('image/webp')
|
||||
expect(verifySpy).toHaveBeenCalledWith('share-1', 'file-1', 'pw123')
|
||||
expect(extractSpy).toHaveBeenCalledWith({
|
||||
assetId: 'target-file-1',
|
||||
second: 4.2,
|
||||
width: 400,
|
||||
watermarkConfigId: 'wm-1',
|
||||
signal: expect.any(AbortSignal),
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /shares/:shareId/files/:fileId/comments excludes internal comments', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
id: 'share-1',
|
||||
rootFolderId: 'share-root',
|
||||
projectId: 'proj-1',
|
||||
} as never)
|
||||
vi.spyOn(assetService, 'resolveTargetAssetId').mockResolvedValue('file-1')
|
||||
const listSpy = vi.spyOn(assetService, 'listComments').mockResolvedValue({
|
||||
data: [],
|
||||
pageInfo: { cursor: undefined, total: 0 },
|
||||
})
|
||||
|
||||
const app = new Hono().route('/', publicShareRoute)
|
||||
const res = await app.request('/shares/share-1/files/file-1/comments')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(listSpy).toHaveBeenCalledWith('file-1', expect.anything(), undefined, {
|
||||
excludeInternal: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /shares/:shareId/files/:fileId/comments rejects isInternal=true with 400', async () => {
|
||||
const app = new Hono().route('/', publicShareRoute)
|
||||
const res = await app.request('/shares/share-1/files/file-1/comments', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ message: 'secret', attachmentIds: [], isInternal: true }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
})
|
||||
@@ -1,11 +1,19 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Context } from 'hono'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { getCookie } from 'hono/cookie'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import { shareActivityService } from '@shumai/core/src/share/share-activity'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { commentFrameService } from '@shumai/core/src/comment/comment-frame'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { paginationParamsSchema, assetTypeFilterSchema } from '@shumai/dtos'
|
||||
import {
|
||||
paginationParamsSchema,
|
||||
assetTypeFilterSchema,
|
||||
commentFrameQuerySchema,
|
||||
recordShareViewRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { z } from 'zod'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { FieldInfo } from '@shumai/dtos'
|
||||
@@ -115,6 +123,20 @@ async function applyWatermarkToAssetMedia(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps only the custom field values the share link is configured to show.
|
||||
* Fields are hidden by default; `fieldVisibility` lists the keys turned on
|
||||
* for this share, matching what `GET /shares/:shareId/fields` returns.
|
||||
*/
|
||||
function filterSharedFieldValues(asset: AssetInfo, fieldVisibility: unknown): AssetInfo {
|
||||
if (!asset.fieldValues) return asset
|
||||
const visibility = (fieldVisibility || {}) as Record<string, boolean>
|
||||
return {
|
||||
...asset,
|
||||
fieldValues: asset.fieldValues.filter((fv) => Boolean(visibility[fv.fieldId])),
|
||||
}
|
||||
}
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
function toFieldInfo(
|
||||
@@ -133,6 +155,9 @@ function toFieldInfo(
|
||||
}
|
||||
|
||||
export function handlePublicShareError(c: Context, err: unknown) {
|
||||
if (err instanceof HTTPException) {
|
||||
throw err
|
||||
}
|
||||
if (err instanceof ShareLinkPasswordInvalidError) {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
@@ -156,7 +181,36 @@ const sharedChildrenRequestSchema = paginationParamsSchema.extend({
|
||||
assetType: assetTypeFilterSchema.optional().default('file'),
|
||||
})
|
||||
|
||||
async function getPublicShareUserId(c: Context, shareId: string) {
|
||||
const session = await auth.api.getSession({ headers: c.req.raw.headers })
|
||||
if (session?.user) return session.user.id
|
||||
|
||||
const token = getCookie(c, `shumai_guest_${shareId}`) || getCookie(c, 'shumai_guest')
|
||||
const verified = token && verifyGuestToken(token, shareId)
|
||||
if (!verified) return undefined
|
||||
|
||||
const guestUser = await userService.getUserById(verified.userId)
|
||||
return guestUser?.guestEmail ? guestUser.id : undefined
|
||||
}
|
||||
|
||||
const route = app
|
||||
.post('/shares/:shareId/views', zValidator('json', recordShareViewRequestSchema), async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const { assetId, isShareEntry } = c.req.valid('json')
|
||||
try {
|
||||
const share = await shareService.verifyPublicAccess(shareId, assetId, password)
|
||||
const targetId =
|
||||
assetId && assetId !== share.rootFolderId
|
||||
? await assetService.resolveLatestVersionId(assetId)
|
||||
: undefined
|
||||
const userId = await getPublicShareUserId(c, shareId)
|
||||
await shareActivityService.recordView(shareId, { assetId: targetId, isShareEntry, userId })
|
||||
return c.body(null, 204)
|
||||
} catch (err) {
|
||||
return handlePublicShareError(c, err)
|
||||
}
|
||||
})
|
||||
.get('/shares/:shareId/info', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const password = c.req.header('x-share-password')
|
||||
@@ -222,13 +276,16 @@ const route = app
|
||||
order = parts[1]
|
||||
}
|
||||
|
||||
const res = await assetService.listChildren({
|
||||
...req,
|
||||
assetId: folderId,
|
||||
assetType: req.assetType || 'file',
|
||||
sort,
|
||||
order,
|
||||
})
|
||||
const res = await assetService.listChildren(
|
||||
{
|
||||
...req,
|
||||
assetId: folderId,
|
||||
assetType: req.assetType || 'file',
|
||||
sort,
|
||||
order,
|
||||
},
|
||||
{ excludeInternalComments: true },
|
||||
)
|
||||
|
||||
if (shareLink.watermarkConfigId && res.data.length > 0) {
|
||||
// Resolve symlink targets once and reuse for the media lookup, so each
|
||||
@@ -260,6 +317,8 @@ const route = app
|
||||
}
|
||||
}
|
||||
|
||||
res.data = res.data.map((item) => filterSharedFieldValues(item, shareLink.fieldVisibility))
|
||||
|
||||
return c.json(res)
|
||||
} catch (err) {
|
||||
return handlePublicShareError(c, err)
|
||||
@@ -274,7 +333,10 @@ const route = app
|
||||
try {
|
||||
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||
|
||||
let asset = await assetService.getAsset({ assetId: fileId })
|
||||
let asset = await assetService.getAsset(
|
||||
{ assetId: fileId },
|
||||
{ excludeInternalComments: true },
|
||||
)
|
||||
|
||||
// Only video/image/3d assets are subject to watermark protection; skip the
|
||||
// watermark lookup entirely for other media types (pdf, audio, ...).
|
||||
@@ -298,19 +360,25 @@ const route = app
|
||||
asset.media.hls.url = `/api/shares/${shareLink.id}/files/${asset.id}/m3u8/master.m3u8${pwQuery}`
|
||||
}
|
||||
|
||||
return c.json(asset)
|
||||
return c.json(filterSharedFieldValues(asset, shareLink.fieldVisibility))
|
||||
} catch (err) {
|
||||
return handlePublicShareError(c, err)
|
||||
}
|
||||
})
|
||||
.post(
|
||||
'/shares/:shareId/files/:fileId/download-url',
|
||||
zValidator('json', z.object({ key: z.string().min(1) })),
|
||||
zValidator(
|
||||
'json',
|
||||
z.object({
|
||||
key: z.string().min(1),
|
||||
purpose: z.enum(['download', 'prepare', 'clipboard']).default('download'),
|
||||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const { key } = c.req.valid('json')
|
||||
const { key, purpose } = c.req.valid('json')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||
@@ -323,7 +391,16 @@ const route = app
|
||||
return c.json({ error: 'Invalid key' }, 400)
|
||||
}
|
||||
|
||||
const url = await assetService.getDownloadUrl(fileId, key)
|
||||
const { url, assetId } = await assetService.getDownloadUrlWithAsset(fileId, key)
|
||||
if (assetId !== fileId) await shareService.verifyPublicAccess(shareId, assetId, password)
|
||||
if (purpose === 'download') {
|
||||
const userId = await getPublicShareUserId(c, shareId)
|
||||
await shareActivityService.recordEvent(shareId, {
|
||||
kind: 'asset_downloaded',
|
||||
assetId,
|
||||
userId,
|
||||
})
|
||||
}
|
||||
return c.json({ url })
|
||||
} catch (err) {
|
||||
return handlePublicShareError(c, err)
|
||||
@@ -343,32 +420,107 @@ const route = app
|
||||
await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||
|
||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||
let userId: string | undefined
|
||||
const session = await auth.api.getSession({
|
||||
headers: c.req.raw.headers,
|
||||
const userId = await getPublicShareUserId(c, shareId)
|
||||
const res = await assetService.listComments(targetFileId, req, userId, {
|
||||
excludeInternal: true,
|
||||
})
|
||||
if (session?.user) {
|
||||
userId = session.user.id
|
||||
} else {
|
||||
const cookieName = `shumai_guest_${shareId}`
|
||||
const token = getCookie(c, cookieName) || getCookie(c, 'shumai_guest')
|
||||
if (token) {
|
||||
const verified = verifyGuestToken(token, shareId)
|
||||
if (verified) {
|
||||
const guestUser = await userService.getUserById(verified.userId)
|
||||
if (guestUser && guestUser.guestEmail) {
|
||||
userId = guestUser.id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const res = await assetService.listComments(targetFileId, req, userId)
|
||||
return c.json(res)
|
||||
} catch (err) {
|
||||
return handlePublicShareError(c, err)
|
||||
}
|
||||
},
|
||||
)
|
||||
.get('/shares/:shareId/files/:fileId/comments/print', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||
let asset = await assetService.getAsset(
|
||||
{ assetId: fileId },
|
||||
{ excludeInternalComments: true },
|
||||
)
|
||||
const targetAssetId = await assetService.resolveLatestVersionId(fileId)
|
||||
|
||||
if (
|
||||
shareLink.watermarkConfigId &&
|
||||
(asset.proxyType === 'video' || asset.proxyType === 'image' || asset.proxyType === '3d')
|
||||
) {
|
||||
const wfMap = await watermarkService.getCompletedWatermarkMediaMap(
|
||||
[targetAssetId],
|
||||
shareLink.watermarkConfigId,
|
||||
)
|
||||
asset = await applyWatermarkToAssetMedia(
|
||||
asset,
|
||||
wfMap.get(targetAssetId) ?? null,
|
||||
shareLink.id,
|
||||
password,
|
||||
)
|
||||
}
|
||||
|
||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||
const userId = await getPublicShareUserId(c, shareId)
|
||||
const comments = await assetService.listAllComments(targetFileId, userId, {
|
||||
excludeInternal: true,
|
||||
})
|
||||
|
||||
// Scope breadcrumbs strictly to folders inside the share link root so private
|
||||
// project and parent folder names are never leaked.
|
||||
const ancestors = asset.ancestorFolders ?? []
|
||||
const rootIndex = ancestors.findIndex((f) => f.id === shareLink.rootFolderId)
|
||||
const scopedAncestors = rootIndex !== -1 ? ancestors.slice(0, rootIndex) : []
|
||||
const scopedFolders = [...scopedAncestors]
|
||||
.reverse()
|
||||
.map((f) => f.name)
|
||||
.filter((name): name is string => Boolean(name))
|
||||
const breadcrumbs = shareLink.name ? [shareLink.name, ...scopedFolders] : scopedFolders
|
||||
|
||||
return c.json({
|
||||
asset: {
|
||||
...filterSharedFieldValues(asset, shareLink.fieldVisibility),
|
||||
ancestorFolders: scopedAncestors,
|
||||
},
|
||||
breadcrumbs,
|
||||
comments,
|
||||
})
|
||||
} catch (err) {
|
||||
return handlePublicShareError(c, err)
|
||||
}
|
||||
})
|
||||
.get(
|
||||
'/shares/:shareId/files/:fileId/comments/frame',
|
||||
zValidator('query', commentFrameQuerySchema),
|
||||
async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const password =
|
||||
c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
|
||||
const { second, width } = c.req.valid('query')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||
const result = await commentFrameService.extractFrame({
|
||||
assetId: targetFileId,
|
||||
second,
|
||||
width,
|
||||
watermarkConfigId: shareLink.watermarkConfigId,
|
||||
signal: c.req.raw.signal,
|
||||
})
|
||||
|
||||
return c.body(new Uint8Array(result.buffer), 200, {
|
||||
'Content-Type': result.mimeType,
|
||||
'Cache-Control': 'private, max-age=300',
|
||||
})
|
||||
} catch (err) {
|
||||
if (err instanceof HTTPException) {
|
||||
throw err
|
||||
}
|
||||
return handlePublicShareError(c, err)
|
||||
}
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/shares/:shareId/files/:fileId/comments',
|
||||
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })),
|
||||
@@ -382,49 +534,36 @@ const route = app
|
||||
return c.json({ error: 'Attachments are not allowed on public share comments' }, 400)
|
||||
}
|
||||
|
||||
if (req.isInternal) {
|
||||
return c.json({ error: 'Internal comments are not allowed on public share links' }, 400)
|
||||
}
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||
|
||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||
|
||||
const teamId = await projectService.getProjectTeam(shareLink.projectId)
|
||||
|
||||
// Identify user
|
||||
let userId: string | null = null
|
||||
const session = await auth.api.getSession({
|
||||
headers: c.req.raw.headers,
|
||||
})
|
||||
|
||||
if (session?.user) {
|
||||
userId = session.user.id
|
||||
} else {
|
||||
const cookieName = `shumai_guest_${shareId}`
|
||||
const token = getCookie(c, cookieName) || getCookie(c, 'shumai_guest')
|
||||
if (token) {
|
||||
const verified = verifyGuestToken(token, shareId)
|
||||
if (verified) {
|
||||
const guestUser = await userService.getUserById(verified.userId)
|
||||
if (guestUser && guestUser.guestEmail) {
|
||||
userId = guestUser.id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const userId = await getPublicShareUserId(c, shareId)
|
||||
|
||||
if (!userId) {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
|
||||
const comment = await assetService.createComment({
|
||||
assetId: targetFileId,
|
||||
userId: userId,
|
||||
replyToId: req.replyToId,
|
||||
message: req.message,
|
||||
annotations: req.annotations,
|
||||
second: req.second,
|
||||
attachmentIds: req.attachmentIds,
|
||||
})
|
||||
const comment = await assetService.createComment(
|
||||
{
|
||||
assetId: targetFileId,
|
||||
userId,
|
||||
replyToId: req.replyToId,
|
||||
message: req.message,
|
||||
annotations: req.annotations,
|
||||
second: req.second,
|
||||
attachmentIds: req.attachmentIds,
|
||||
isInternal: false,
|
||||
},
|
||||
{ shareLinkId: shareId },
|
||||
)
|
||||
|
||||
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
|
||||
|
||||
|
||||
@@ -4,9 +4,15 @@ import shareRoute from './share'
|
||||
import publicShareRoute from './public-share'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import { shareActivityService } from '@shumai/core/src/share/share-activity'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { ShareLinkPasswordInvalidError, ShareLinkExpiredError } from '@shumai/core/src/share/errors'
|
||||
import {
|
||||
ShareLinkPasswordInvalidError,
|
||||
ShareLinkExpiredError,
|
||||
ShareLinkNotFoundError,
|
||||
} from '@shumai/core/src/share/errors'
|
||||
import { createGuestToken } from '@shumai/core/src/auth/guest-token'
|
||||
import { userService } from '@shumai/core/src/user/user'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
@@ -93,6 +99,82 @@ describe('Share API', () => {
|
||||
})
|
||||
|
||||
// Public Routes
|
||||
describe('POST /shares/:shareId/views', () => {
|
||||
test('attributes an authorized asset view to a verified guest', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
rootFolderId: 'folder1',
|
||||
} as Awaited<ReturnType<typeof shareService.verifyPublicAccess>>)
|
||||
vi.spyOn(assetService, 'resolveLatestVersionId').mockResolvedValue('asset1')
|
||||
vi.spyOn(userService, 'getUserById').mockResolvedValue({
|
||||
id: 'guest1',
|
||||
guestEmail: 'alice@example.com',
|
||||
} as Awaited<ReturnType<typeof userService.getUserById>>)
|
||||
const record = vi.spyOn(shareActivityService, 'recordView').mockResolvedValue(undefined)
|
||||
const token = createGuestToken({ userId: 'guest1', shareId: 'share1' })
|
||||
|
||||
const res = await app.request('/shares/share1/views', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-share-password': 'pass',
|
||||
Cookie: `shumai_guest_share1=${token}`,
|
||||
},
|
||||
body: JSON.stringify({ assetId: 'alias1', isShareEntry: true }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'alias1', 'pass')
|
||||
expect(record).toHaveBeenCalledWith('share1', {
|
||||
assetId: 'asset1',
|
||||
isShareEntry: true,
|
||||
userId: 'guest1',
|
||||
})
|
||||
})
|
||||
|
||||
test('a rejected view leaves the counter and history alone', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockRejectedValue(
|
||||
new ShareLinkPasswordInvalidError('Incorrect password'),
|
||||
)
|
||||
const record = vi.spyOn(shareActivityService, 'recordView').mockResolvedValue(undefined)
|
||||
const res = await app.request('/shares/share1/views', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: '{}',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(401)
|
||||
expect(record).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /shares/:shareId/activities', () => {
|
||||
test('returns the requested page to a share reader', async () => {
|
||||
const list = vi.spyOn(shareActivityService, 'list').mockResolvedValue({
|
||||
data: [],
|
||||
pageInfo: { total: 0 },
|
||||
})
|
||||
const res = await app.request('/shares/share1/activities?first=20')
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ data: [], pageInfo: { total: 0 } })
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: 'share1',
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Share,
|
||||
}),
|
||||
)
|
||||
expect(list).toHaveBeenCalledWith('share1', { first: 20 })
|
||||
})
|
||||
|
||||
test('denies access to activity without share read permission', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new HTTPException(403))
|
||||
const list = vi.spyOn(shareActivityService, 'list')
|
||||
const res = await app.request('/shares/share1/activities')
|
||||
expect(res.status).toBe(403)
|
||||
expect(list).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /shares/:shareId/info', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
@@ -101,6 +183,8 @@ describe('Share API', () => {
|
||||
isDisabled: false,
|
||||
allowDownload: false,
|
||||
isExpired: false,
|
||||
views: 0,
|
||||
lastViewedAt: null,
|
||||
hasPassword: true,
|
||||
rootFolderId: 'folder1',
|
||||
projectId: 'project1',
|
||||
@@ -134,6 +218,8 @@ describe('Share API', () => {
|
||||
isDisabled: false,
|
||||
allowDownload: false,
|
||||
isExpired: false,
|
||||
views: 0,
|
||||
lastViewedAt: null,
|
||||
hasPassword: true,
|
||||
rootFolderId: 'folder1',
|
||||
projectId: 'project1',
|
||||
@@ -161,6 +247,8 @@ describe('Share API', () => {
|
||||
isDisabled: false,
|
||||
allowDownload: false,
|
||||
isExpired: false,
|
||||
views: 0,
|
||||
lastViewedAt: null,
|
||||
hasPassword: true,
|
||||
rootFolderId: 'folder1',
|
||||
projectId: 'project1',
|
||||
@@ -217,6 +305,7 @@ describe('Share API', () => {
|
||||
sort: 'name',
|
||||
order: 'asc',
|
||||
}),
|
||||
{ excludeInternalComments: true },
|
||||
)
|
||||
})
|
||||
|
||||
@@ -350,6 +439,119 @@ describe('Share API', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('public share field values', () => {
|
||||
const shareLinkWithFields = {
|
||||
id: 'share1',
|
||||
name: 'My Share',
|
||||
isDisabled: false,
|
||||
allowDownload: false,
|
||||
rootFolderId: 'folder1',
|
||||
projectId: 'project1',
|
||||
password: null,
|
||||
expireAt: null,
|
||||
watermarkConfigId: null,
|
||||
fieldVisibility: { status: true, internalNote: false },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any
|
||||
|
||||
const assetWithFields = {
|
||||
id: 'file1',
|
||||
name: 'a.png',
|
||||
sizeByte: 1,
|
||||
fileCount: 0,
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
proxyType: 'pdf',
|
||||
fieldValues: [
|
||||
{ fieldId: 'status', value: 'Approved' },
|
||||
{ fieldId: 'internalNote', value: 'not for guests' },
|
||||
{ fieldId: 'rating', value: 3 },
|
||||
],
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any
|
||||
|
||||
test('children only include field values visible on the share', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithFields)
|
||||
vi.spyOn(assetService, 'listChildren').mockResolvedValue({
|
||||
data: [assetWithFields],
|
||||
pageInfo: { total: 1, cursor: undefined },
|
||||
})
|
||||
|
||||
const res = await app.request('/shares/share1/folders/folder1/children?assetType=file')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data[0].fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }])
|
||||
})
|
||||
|
||||
test('children with watermark only include field values visible on the share', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
...shareLinkWithFields,
|
||||
watermarkConfigId: 'cfg1',
|
||||
})
|
||||
vi.spyOn(assetService, 'listChildren').mockResolvedValue({
|
||||
data: [assetWithFields],
|
||||
pageInfo: { total: 1, cursor: undefined },
|
||||
})
|
||||
vi.spyOn(assetService, 'resolveLatestVersionId').mockImplementation(async (id) => id)
|
||||
vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map())
|
||||
|
||||
const res = await app.request('/shares/share1/folders/folder1/children?assetType=file')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data[0].fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }])
|
||||
})
|
||||
|
||||
test('children include no field values when the share shows no fields', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
...shareLinkWithFields,
|
||||
fieldVisibility: null,
|
||||
})
|
||||
vi.spyOn(assetService, 'listChildren').mockResolvedValue({
|
||||
data: [assetWithFields],
|
||||
pageInfo: { total: 1, cursor: undefined },
|
||||
})
|
||||
|
||||
const res = await app.request('/shares/share1/folders/folder1/children?assetType=file')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data[0].fieldValues).toEqual([])
|
||||
})
|
||||
|
||||
test('file detail only includes field values visible on the share', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithFields)
|
||||
vi.spyOn(assetService, 'getAsset').mockResolvedValue(assetWithFields)
|
||||
|
||||
const res = await app.request('/shares/share1/files/file1')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }])
|
||||
})
|
||||
|
||||
test('file detail with watermark only includes field values visible on the share', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
...shareLinkWithFields,
|
||||
watermarkConfigId: 'cfg1',
|
||||
})
|
||||
vi.spyOn(assetService, 'getAsset').mockResolvedValue({
|
||||
...assetWithFields,
|
||||
proxyType: 'image',
|
||||
media: { proxyType: 'image', videoTranscodes: [], imageTranscodes: [] },
|
||||
})
|
||||
vi.spyOn(assetService, 'resolveLatestVersionId').mockResolvedValue('file1')
|
||||
vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map())
|
||||
|
||||
const res = await app.request('/shares/share1/files/file1')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /shares/:shareId/files/:fileId', () => {
|
||||
const shareLinkWithWatermark = {
|
||||
id: 'share1',
|
||||
@@ -712,6 +914,8 @@ describe('Share API', () => {
|
||||
rootFolderId: 'root1',
|
||||
projectId: 'project1',
|
||||
isExpired: false,
|
||||
views: 0,
|
||||
lastViewedAt: null,
|
||||
hasPassword: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
@@ -756,6 +960,8 @@ describe('Share API', () => {
|
||||
rootFolderId: 'root1',
|
||||
projectId: 'project1',
|
||||
isExpired: false,
|
||||
views: 0,
|
||||
lastViewedAt: null,
|
||||
hasPassword: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
@@ -813,6 +1019,8 @@ describe('Share API', () => {
|
||||
rootFolderId: 'root1',
|
||||
projectId: 'project1',
|
||||
isExpired: false,
|
||||
views: 0,
|
||||
lastViewedAt: null,
|
||||
hasPassword: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
@@ -844,6 +1052,8 @@ describe('Share API', () => {
|
||||
rootFolderId: 'root1',
|
||||
projectId: 'project1',
|
||||
isExpired: false,
|
||||
views: 0,
|
||||
lastViewedAt: null,
|
||||
hasPassword: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
@@ -888,6 +1098,8 @@ describe('Share API', () => {
|
||||
rootFolderId: 'root1',
|
||||
projectId: 'project1',
|
||||
isExpired: false,
|
||||
views: 0,
|
||||
lastViewedAt: null,
|
||||
hasPassword: false,
|
||||
watermarkStatus: 'processing',
|
||||
watermarkConfigId: 'cfg1',
|
||||
@@ -976,12 +1188,60 @@ describe('Share API', () => {
|
||||
})
|
||||
|
||||
describe('POST /shares/:shareId/files/:fileId/download-url', () => {
|
||||
test('requires share access to the concrete asset selected for download', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess')
|
||||
.mockResolvedValueOnce({
|
||||
allowDownload: true,
|
||||
} as Awaited<ReturnType<typeof shareService.verifyPublicAccess>>)
|
||||
.mockRejectedValueOnce(new ShareLinkNotFoundError('Asset is not shared'))
|
||||
vi.spyOn(assetService, 'getDownloadUrlWithAsset').mockResolvedValue({
|
||||
url: 'https://s3.example.com/download',
|
||||
assetId: 'unshared',
|
||||
})
|
||||
const record = vi.spyOn(shareActivityService, 'recordEvent').mockResolvedValue(undefined)
|
||||
const res = await app.request('/shares/share1/files/file1/download-url', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key: 'files/download.png' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
expect(await res.json()).toEqual({ error: 'Asset is not shared' })
|
||||
expect(record).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test.each(['prepare', 'clipboard'])(
|
||||
'does not count a URL requested for %s',
|
||||
async (purpose) => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
allowDownload: true,
|
||||
} as Awaited<ReturnType<typeof shareService.verifyPublicAccess>>)
|
||||
vi.spyOn(assetService, 'getDownloadUrlWithAsset').mockResolvedValue({
|
||||
url: 'https://s3.example.com/download',
|
||||
assetId: 'target1',
|
||||
})
|
||||
const record = vi.spyOn(shareActivityService, 'recordEvent').mockResolvedValue(undefined)
|
||||
const res = await app.request('/shares/share1/files/symlink1/download-url', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key: 'files/target1/fly.png', purpose }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(record).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
test('Success for symlink asset in share', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
allowDownload: true,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
vi.spyOn(assetService, 'getDownloadUrl').mockResolvedValue('https://s3.example.com/download')
|
||||
vi.spyOn(assetService, 'getDownloadUrlWithAsset').mockResolvedValue({
|
||||
url: 'https://s3.example.com/download',
|
||||
assetId: 'target1',
|
||||
})
|
||||
const record = vi.spyOn(shareActivityService, 'recordEvent').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/shares/share1/files/symlink1/download-url', {
|
||||
method: 'POST',
|
||||
@@ -993,7 +1253,15 @@ describe('Share API', () => {
|
||||
const body = await res.json()
|
||||
expect(body.url).toBe('https://s3.example.com/download')
|
||||
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'symlink1', undefined)
|
||||
expect(assetService.getDownloadUrl).toHaveBeenCalledWith('symlink1', 'files/target1/fly.png')
|
||||
expect(assetService.getDownloadUrlWithAsset).toHaveBeenCalledWith(
|
||||
'symlink1',
|
||||
'files/target1/fly.png',
|
||||
)
|
||||
expect(record).toHaveBeenCalledWith('share1', {
|
||||
kind: 'asset_downloaded',
|
||||
assetId: 'target1',
|
||||
userId: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
test('Rejects when allowDownload is disabled', async () => {
|
||||
@@ -1004,8 +1272,8 @@ describe('Share API', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
const getDownloadUrlSpy = vi
|
||||
.spyOn(assetService, 'getDownloadUrl')
|
||||
.mockResolvedValue('https://s3.example.com/download')
|
||||
.spyOn(assetService, 'getDownloadUrlWithAsset')
|
||||
.mockResolvedValue({ url: 'https://s3.example.com/download', assetId: 'target1' })
|
||||
|
||||
const res = await app.request('/shares/share1/files/symlink1/download-url', {
|
||||
method: 'POST',
|
||||
@@ -1173,6 +1441,7 @@ describe('Share API', () => {
|
||||
userId: 'guest1',
|
||||
message: 'hello from alice',
|
||||
}),
|
||||
{ shareLinkId: 'share1' },
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
@@ -2,11 +2,13 @@ import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import { shareActivityService } from '@shumai/core/src/share/share-activity'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import {
|
||||
createShareLinkRequestSchema,
|
||||
updateShareLinkRequestSchema,
|
||||
listShareLinksRequestSchema,
|
||||
paginationParamsSchema,
|
||||
addAssetToShareRequestSchema,
|
||||
updateShareLinkWatermarkRequestSchema,
|
||||
AuditAction,
|
||||
@@ -90,6 +92,16 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
return c.json(shareLink)
|
||||
})
|
||||
.get('/shares/:shareId/activities', zValidator('query', paginationParamsSchema), async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
await authzService.hasPermission({
|
||||
user: c.get('user'),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Share,
|
||||
id: shareId,
|
||||
})
|
||||
return c.json(await shareActivityService.list(shareId, c.req.valid('query')))
|
||||
})
|
||||
.put('/shares/:shareId', zValidator('json', updateShareLinkRequestSchema), async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/core",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -137,6 +137,7 @@ export class AssetArchiveService {
|
||||
WorkflowTaskType.transcode_screenshot,
|
||||
WorkflowTaskType.transcode_image_annotation,
|
||||
WorkflowTaskType.transcode_watermark,
|
||||
WorkflowTaskType.transcode_video_chunks,
|
||||
],
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { getPrismaTestingHelper, prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
|
||||
@@ -941,7 +941,7 @@ describe('AssetService', () => {
|
||||
).resolves.not.toThrow()
|
||||
})
|
||||
|
||||
it('deleteComment cleans up S3 attachment files and database records', async () => {
|
||||
it('cleans up deleted comment attachments through the asset cleanup job', async () => {
|
||||
const { user, project, assets } = await setupBasicAssets()
|
||||
|
||||
// 1. Create StorageKey and Asset for attachment
|
||||
@@ -949,15 +949,15 @@ describe('AssetService', () => {
|
||||
data: {
|
||||
key: 'attachments/test-attachment-file.png',
|
||||
status: 'active',
|
||||
createdAt: new Date(Date.now() - 60_000),
|
||||
},
|
||||
})
|
||||
|
||||
const attachmentAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test-attachment-file.png',
|
||||
type: AssetType.file,
|
||||
type: AssetType.attachment,
|
||||
projectId: project.id,
|
||||
parentId: assets.root.id,
|
||||
creatorId: user.id,
|
||||
storageKeyId: storageKey.id,
|
||||
sizeByte: 100,
|
||||
@@ -988,18 +988,278 @@ describe('AssetService', () => {
|
||||
// 5. Verify the comment is deleted from DB
|
||||
await expect(prisma.assetComment.findUnique({ where: { id: comment.id } })).resolves.toBeNull()
|
||||
|
||||
// 6. Verify that the attachment Asset and StorageKey are deleted from DB
|
||||
// 6. The attachment is removed immediately; the storage cleanup owns object deletion.
|
||||
await expect(prisma.asset.findUnique({ where: { id: attachmentAsset.id } })).resolves.toBeNull()
|
||||
expect(s3Service.deleteObject).not.toHaveBeenCalled()
|
||||
|
||||
await assetService.emptyTrash(project.id)
|
||||
|
||||
await expect(prisma.storageKey.findUnique({ where: { id: storageKey.id } })).resolves.toBeNull()
|
||||
|
||||
// 7. Verify S3 deletion was called
|
||||
const { s3Service } = await import('@shumai/core/src/s3/s3')
|
||||
expect(s3Service.deleteObject).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'attachments/test-attachment-file.png',
|
||||
)
|
||||
})
|
||||
|
||||
describe('comment attachments', () => {
|
||||
const addProjectReviewer = async (teamId: string) => {
|
||||
const reviewer = await prisma.user.create({
|
||||
data: { name: 'Reviewer', type: 'human', email: `reviewer-${Date.now()}@example.com` },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId, userId: reviewer.id, role: 'reviewer' },
|
||||
})
|
||||
return reviewer
|
||||
}
|
||||
|
||||
const createUpload = async (projectId: string, creatorId: string, name: string) => {
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: { key: `attachments/${name}`, status: 'active' },
|
||||
})
|
||||
return await prisma.asset.create({
|
||||
data: {
|
||||
name,
|
||||
type: AssetType.attachment,
|
||||
projectId,
|
||||
creatorId,
|
||||
sizeByte: 1,
|
||||
status: 'uploaded',
|
||||
storageKeyId: storageKey.id,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
it('only attaches comment uploads made by the commenter', async () => {
|
||||
const { user, project, assets } = await setupBasicAssets()
|
||||
const reviewer = await addProjectReviewer(project.teamId)
|
||||
const ownerUpload = await createUpload(project.id, user.id, 'owner-upload.png')
|
||||
const reviewerUpload = await createUpload(project.id, reviewer.id, 'reviewer-upload.png')
|
||||
|
||||
const comment = await assetService.createComment({
|
||||
assetId: assets.fileA1.id,
|
||||
userId: reviewer.id,
|
||||
message: 'looks good',
|
||||
attachmentIds: [assets.fileA2.id, ownerUpload.id, reviewerUpload.id],
|
||||
})
|
||||
|
||||
const links = await prisma.assetCommentAttachment.findMany({
|
||||
where: { commentId: comment.id },
|
||||
})
|
||||
expect(links.map((l) => l.assetId)).toEqual([reviewerUpload.id])
|
||||
})
|
||||
|
||||
it('does not attach an upload that already belongs to another comment', async () => {
|
||||
const { user, assets, project } = await setupBasicAssets()
|
||||
const upload = await createUpload(project.id, user.id, 'shared.png')
|
||||
|
||||
await assetService.createComment({
|
||||
assetId: assets.fileA1.id,
|
||||
userId: user.id,
|
||||
message: 'first',
|
||||
attachmentIds: [upload.id],
|
||||
})
|
||||
const second = await assetService.createComment({
|
||||
assetId: assets.fileA1.id,
|
||||
userId: user.id,
|
||||
message: 'second',
|
||||
attachmentIds: [upload.id],
|
||||
})
|
||||
|
||||
const links = await prisma.assetCommentAttachment.findMany({
|
||||
where: { commentId: second.id },
|
||||
})
|
||||
expect(links).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('allows only one concurrent comment to claim an upload', async () => {
|
||||
// The normal test proxy serializes transactions on a single connection.
|
||||
const db = getPrismaTestingHelper().getUnderlyingClient() as typeof prisma
|
||||
const service = new AssetService(db)
|
||||
const { user, team, project, file, upload } = await db.$transaction(async (tx) => {
|
||||
const user = await tx.user.create({
|
||||
data: { name: 'Commenter', email: `attachment-race-${crypto.randomUUID()}@example.com` },
|
||||
})
|
||||
const team = await tx.team.create({ data: { name: 'Attachment race' } })
|
||||
const project = await tx.project.create({ data: { name: 'Project', teamId: team.id } })
|
||||
const file = await tx.asset.create({
|
||||
data: {
|
||||
name: 'File',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
projectId: project.id,
|
||||
creatorId: user.id,
|
||||
},
|
||||
})
|
||||
const upload = await tx.asset.create({
|
||||
data: {
|
||||
name: 'Upload',
|
||||
type: AssetType.attachment,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
creatorId: user.id,
|
||||
},
|
||||
})
|
||||
return { user, team, project, file, upload }
|
||||
})
|
||||
|
||||
let claims: Promise<PromiseSettledResult<unknown>[]> | undefined
|
||||
try {
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.$queryRaw`SELECT id FROM assets WHERE id = ${upload.id} FOR UPDATE`
|
||||
claims = Promise.allSettled(
|
||||
['First comment', 'Second comment'].map((message) =>
|
||||
service.createComment(
|
||||
{ assetId: file.id, userId: user.id, message, attachmentIds: [upload.id] },
|
||||
{ triggerAgents: false },
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
// Release the upload only after both requests are waiting on its row lock.
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
const [waiters] = await tx.$queryRaw<{ count: number }[]>`
|
||||
WITH RECURSIVE waiters(pid) AS (
|
||||
SELECT pg_backend_pid()
|
||||
UNION
|
||||
SELECT pending.pid
|
||||
FROM waiters
|
||||
JOIN (SELECT DISTINCT pid FROM pg_locks WHERE NOT granted) pending
|
||||
ON waiters.pid = ANY(pg_blocking_pids(pending.pid))
|
||||
)
|
||||
SELECT count(*)::int - 1 AS count FROM waiters
|
||||
`
|
||||
expect(waiters.count).toBe(2)
|
||||
},
|
||||
{ timeout: 3_000 },
|
||||
)
|
||||
})
|
||||
|
||||
expect(await claims).toEqual([
|
||||
expect.objectContaining({ status: 'fulfilled' }),
|
||||
expect.objectContaining({ status: 'fulfilled' }),
|
||||
])
|
||||
await expect(
|
||||
db.assetCommentAttachment.count({ where: { assetId: upload.id } }),
|
||||
).resolves.toBe(1)
|
||||
} finally {
|
||||
await claims
|
||||
await db.asset.deleteMany({ where: { projectId: project.id } })
|
||||
await db.project.delete({ where: { id: project.id } })
|
||||
await db.team.delete({ where: { id: team.id } })
|
||||
await db.user.delete({ where: { id: user.id } })
|
||||
}
|
||||
})
|
||||
|
||||
it('deleteComment keeps project files that are linked to the comment', async () => {
|
||||
const { project, assets } = await setupBasicAssets()
|
||||
const reviewer = await addProjectReviewer(project.teamId)
|
||||
const fileKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/01JAAAAAAAAAAAAAAAAAAAAAAA/deliverable.mov', status: 'active' },
|
||||
})
|
||||
await prisma.asset.update({
|
||||
where: { id: assets.fileA2.id },
|
||||
data: { storageKeyId: fileKey.id },
|
||||
})
|
||||
|
||||
const comment = await assetService.createComment({
|
||||
assetId: assets.fileA1.id,
|
||||
userId: reviewer.id,
|
||||
message: 'note',
|
||||
attachmentIds: [],
|
||||
})
|
||||
// A link to a project file, as comments created before attachment checks could hold.
|
||||
await prisma.assetCommentAttachment.create({
|
||||
data: { commentId: comment.id, assetId: assets.fileA2.id },
|
||||
})
|
||||
|
||||
await assetService.deleteComment({ commentId: comment.id, userId: reviewer.id })
|
||||
|
||||
await expect(
|
||||
prisma.assetComment.findUnique({ where: { id: comment.id } }),
|
||||
).resolves.toBeNull()
|
||||
await expect(
|
||||
prisma.asset.findUnique({ where: { id: assets.fileA2.id } }),
|
||||
).resolves.not.toBeNull()
|
||||
await expect(
|
||||
prisma.storageKey.findUnique({ where: { id: fileKey.id } }),
|
||||
).resolves.not.toBeNull()
|
||||
expect(s3Service.deleteObject).not.toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'files/01JAAAAAAAAAAAAAAAAAAAAAAA/deliverable.mov',
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps an attachment object until the original and copied comments are deleted', async () => {
|
||||
const { user, project, assets } = await setupBasicAssets()
|
||||
const upload = await createUpload(project.id, user.id, 'copied-upload.png')
|
||||
const originalComment = await assetService.createComment({
|
||||
assetId: assets.fileA1.id,
|
||||
userId: user.id,
|
||||
message: 'Original comment',
|
||||
attachmentIds: [upload.id],
|
||||
})
|
||||
const [copiedFileId] = await assetService.copyAssets({
|
||||
assetIds: [assets.fileA1.id],
|
||||
newParentId: assets.root3.id,
|
||||
creatorId: user.id,
|
||||
withComments: true,
|
||||
})
|
||||
const copiedComment = await prisma.assetComment.findFirstOrThrow({
|
||||
where: { assetId: copiedFileId },
|
||||
})
|
||||
const storageKey = await prisma.storageKey.findFirstOrThrow({
|
||||
where: { key: 'attachments/copied-upload.png' },
|
||||
})
|
||||
await prisma.storageKey.update({
|
||||
where: { id: storageKey.id },
|
||||
data: { createdAt: new Date(Date.now() - 60_000) },
|
||||
})
|
||||
|
||||
await assetService.deleteComment({ commentId: copiedComment.id, userId: user.id })
|
||||
await assetService.emptyTrash(project.id)
|
||||
|
||||
const survivingUpload = await prisma.asset.findUniqueOrThrow({ where: { id: upload.id } })
|
||||
expect(survivingUpload.storageKeyId).toBe(storageKey.id)
|
||||
expect(s3Service.deleteObject).not.toHaveBeenCalledWith(expect.any(String), storageKey.key)
|
||||
|
||||
await assetService.deleteComment({ commentId: originalComment.id, userId: user.id })
|
||||
await assetService.emptyTrash(project.id)
|
||||
|
||||
await expect(
|
||||
prisma.storageKey.findUnique({ where: { id: storageKey.id } }),
|
||||
).resolves.toBeNull()
|
||||
expect(s3Service.deleteObject).toHaveBeenCalledWith(expect.any(String), storageKey.key)
|
||||
})
|
||||
|
||||
it('keeps a legacy attachment asset while another comment still links to it', async () => {
|
||||
const { user, project, assets } = await setupBasicAssets()
|
||||
const upload = await createUpload(project.id, user.id, 'legacy-upload.png')
|
||||
const first = await assetService.createComment({
|
||||
assetId: assets.fileA1.id,
|
||||
userId: user.id,
|
||||
message: 'First comment',
|
||||
attachmentIds: [upload.id],
|
||||
})
|
||||
const second = await assetService.createComment({
|
||||
assetId: assets.fileA1.id,
|
||||
userId: user.id,
|
||||
message: 'Second comment',
|
||||
attachmentIds: [],
|
||||
})
|
||||
await prisma.assetCommentAttachment.create({
|
||||
data: { assetId: upload.id, commentId: second.id },
|
||||
})
|
||||
|
||||
await assetService.deleteComment({ commentId: first.id, userId: user.id })
|
||||
await expect(prisma.asset.findUnique({ where: { id: upload.id } })).resolves.not.toBeNull()
|
||||
|
||||
await assetService.deleteComment({ commentId: second.id, userId: user.id })
|
||||
await expect(prisma.asset.findUnique({ where: { id: upload.id } })).resolves.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
it('can create and retrieve comments with video timestamp', async () => {
|
||||
const { user, assets } = await setupBasicAssets()
|
||||
|
||||
@@ -5556,6 +5816,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', () => {
|
||||
@@ -5664,4 +5964,367 @@ describe('AssetService — natural sort by name', () => {
|
||||
expect(variant).toContain('http://mock-s3-url')
|
||||
})
|
||||
})
|
||||
|
||||
describe('internal comments and comment editing', () => {
|
||||
async function setupCommentFixture() {
|
||||
const team = await prisma.team.create({ data: { name: 'Comment Team' } })
|
||||
const author = await prisma.user.create({
|
||||
data: { name: 'Author', email: `author-${Date.now()}-${Math.random()}@test.com` },
|
||||
})
|
||||
const owner = await prisma.user.create({
|
||||
data: { name: 'Owner', email: `owner-${Date.now()}-${Math.random()}@test.com` },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: author.id, role: 'editor' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: owner.id, role: 'owner' },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Comment 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: 'clip.mp4',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
parentId: rootFolder.id,
|
||||
creatorId: author.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
return { team, author, owner, project, rootFolder, file }
|
||||
}
|
||||
|
||||
async function createAttachmentAsset(projectId: string, creatorId: string, name: string) {
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: { key: `files/attachments/${Date.now()}-${Math.random()}-${name}` },
|
||||
})
|
||||
return prisma.asset.create({
|
||||
data: {
|
||||
name,
|
||||
type: AssetType.attachment,
|
||||
projectId,
|
||||
creatorId,
|
||||
status: AssetStatus.uploaded,
|
||||
storageKeyId: storageKey.id,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
it('creates public (default) and internal comments, and enforces internal replies on internal parents', async () => {
|
||||
const { author, owner, file } = await setupCommentFixture()
|
||||
|
||||
const pub = await assetService.createComment(
|
||||
{ assetId: file.id, userId: author.id, message: 'Public feedback', attachmentIds: [] },
|
||||
{ triggerAgents: false },
|
||||
)
|
||||
expect(pub.isInternal).toBe(false)
|
||||
|
||||
const internal = await assetService.createComment(
|
||||
{
|
||||
assetId: file.id,
|
||||
userId: author.id,
|
||||
message: 'Internal note',
|
||||
attachmentIds: [],
|
||||
isInternal: true,
|
||||
},
|
||||
{ triggerAgents: false },
|
||||
)
|
||||
expect(internal.isInternal).toBe(true)
|
||||
|
||||
// Replying to an internal parent forces isInternal: true even if false is passed
|
||||
const replyToInternal = await assetService.createComment(
|
||||
{
|
||||
assetId: file.id,
|
||||
userId: owner.id,
|
||||
replyToId: internal.id,
|
||||
message: 'Internal reply',
|
||||
attachmentIds: [],
|
||||
isInternal: false,
|
||||
},
|
||||
{ triggerAgents: false },
|
||||
)
|
||||
expect(replyToInternal.isInternal).toBe(true)
|
||||
|
||||
// Replying internally to a public parent is allowed
|
||||
const internalReplyOnPublic = await assetService.createComment(
|
||||
{
|
||||
assetId: file.id,
|
||||
userId: owner.id,
|
||||
replyToId: pub.id,
|
||||
message: 'Private side note',
|
||||
attachmentIds: [],
|
||||
isInternal: true,
|
||||
},
|
||||
{ triggerAgents: false },
|
||||
)
|
||||
expect(internalReplyOnPublic.isInternal).toBe(true)
|
||||
|
||||
const publicReplyOnPublic = await assetService.createComment(
|
||||
{
|
||||
assetId: file.id,
|
||||
userId: author.id,
|
||||
replyToId: pub.id,
|
||||
message: 'Public reply',
|
||||
attachmentIds: [],
|
||||
isInternal: false,
|
||||
},
|
||||
{ triggerAgents: false },
|
||||
)
|
||||
expect(publicReplyOnPublic.isInternal).toBe(false)
|
||||
|
||||
// Authenticated list includes everything
|
||||
const allListed = await assetService.listComments(file.id, { first: 20 }, author.id)
|
||||
expect(allListed.data).toHaveLength(2)
|
||||
expect(allListed.data[0].replies).toHaveLength(2)
|
||||
expect(allListed.data[1].replies).toHaveLength(1)
|
||||
|
||||
// Public share list excludes internal comments and internal replies
|
||||
const publicListed = await assetService.listComments(file.id, { first: 20 }, undefined, {
|
||||
excludeInternal: true,
|
||||
})
|
||||
expect(publicListed.data).toHaveLength(1)
|
||||
expect(publicListed.data[0].id).toBe(pub.id)
|
||||
expect(publicListed.data[0].replies.map((r) => r.id)).toEqual([publicReplyOnPublic.id])
|
||||
|
||||
// listAllComments with excludeInternal matches
|
||||
const publicAll = await assetService.listAllComments(file.id, undefined, {
|
||||
excludeInternal: true,
|
||||
})
|
||||
expect(publicAll).toHaveLength(1)
|
||||
expect(publicAll[0].replies.map((r) => r.id)).toEqual([publicReplyOnPublic.id])
|
||||
})
|
||||
|
||||
it('excludes internal comments and replies under internal parents from public share commentsCount', async () => {
|
||||
const { author, rootFolder, file } = await setupCommentFixture()
|
||||
|
||||
const pub = await assetService.createComment(
|
||||
{ assetId: file.id, userId: author.id, message: 'Public', attachmentIds: [] },
|
||||
{ triggerAgents: false },
|
||||
)
|
||||
await assetService.createComment(
|
||||
{
|
||||
assetId: file.id,
|
||||
userId: author.id,
|
||||
replyToId: pub.id,
|
||||
message: 'Internal reply on public',
|
||||
attachmentIds: [],
|
||||
isInternal: true,
|
||||
},
|
||||
{ triggerAgents: false },
|
||||
)
|
||||
const internal = await assetService.createComment(
|
||||
{
|
||||
assetId: file.id,
|
||||
userId: author.id,
|
||||
message: 'Internal root',
|
||||
attachmentIds: [],
|
||||
isInternal: true,
|
||||
},
|
||||
{ triggerAgents: false },
|
||||
)
|
||||
await assetService.createComment(
|
||||
{
|
||||
assetId: file.id,
|
||||
userId: author.id,
|
||||
replyToId: internal.id,
|
||||
message: 'Reply on internal',
|
||||
attachmentIds: [],
|
||||
isInternal: true,
|
||||
},
|
||||
{ triggerAgents: false },
|
||||
)
|
||||
|
||||
const allChildren = await assetService.listChildren({
|
||||
assetId: rootFolder.id,
|
||||
assetType: 'file',
|
||||
})
|
||||
expect(allChildren.data.find((a) => a.id === file.id)?.commentsCount).toBe(4)
|
||||
|
||||
const publicChildren = await assetService.listChildren(
|
||||
{ assetId: rootFolder.id, assetType: 'file' },
|
||||
{ excludeInternalComments: true },
|
||||
)
|
||||
expect(publicChildren.data.find((a) => a.id === file.id)?.commentsCount).toBe(1)
|
||||
|
||||
const publicFile = await assetService.getAsset(
|
||||
{ assetId: file.id },
|
||||
{ excludeInternalComments: true },
|
||||
)
|
||||
expect(publicFile.commentsCount).toBe(1)
|
||||
})
|
||||
|
||||
it('rejects replying to an internal comment from a public share link', async () => {
|
||||
const { author, file } = await setupCommentFixture()
|
||||
const internal = await assetService.createComment(
|
||||
{
|
||||
assetId: file.id,
|
||||
userId: author.id,
|
||||
message: 'Internal only',
|
||||
attachmentIds: [],
|
||||
isInternal: true,
|
||||
},
|
||||
{ triggerAgents: false },
|
||||
)
|
||||
|
||||
await expect(
|
||||
assetService.createComment(
|
||||
{
|
||||
assetId: file.id,
|
||||
userId: author.id,
|
||||
replyToId: internal.id,
|
||||
message: 'Guest reply attempt',
|
||||
attachmentIds: [],
|
||||
},
|
||||
{ triggerAgents: false, shareLinkId: 'share-1' },
|
||||
),
|
||||
).rejects.toMatchObject({ status: 404 })
|
||||
})
|
||||
|
||||
it('allows author to edit text, visibility, remove timestamp, and add/delete attachments', async () => {
|
||||
const { author, project, file } = await setupCommentFixture()
|
||||
const att1 = await createAttachmentAsset(project.id, author.id, 'old.png')
|
||||
const att2 = await createAttachmentAsset(project.id, author.id, 'keep.pdf')
|
||||
const att3 = await createAttachmentAsset(project.id, author.id, 'new.png')
|
||||
|
||||
const created = await assetService.createComment(
|
||||
{
|
||||
assetId: file.id,
|
||||
userId: author.id,
|
||||
message: 'Original message',
|
||||
second: 12.5,
|
||||
attachmentIds: [att1.id, att2.id],
|
||||
isInternal: false,
|
||||
},
|
||||
{ triggerAgents: false },
|
||||
)
|
||||
|
||||
const updated = await assetService.updateComment({
|
||||
commentId: created.id,
|
||||
userId: author.id,
|
||||
message: 'Updated message',
|
||||
isInternal: true,
|
||||
second: null,
|
||||
attachmentIds: [att2.id, att3.id],
|
||||
})
|
||||
|
||||
expect(updated.message).toBe('Updated message')
|
||||
expect(updated.isInternal).toBe(true)
|
||||
expect(updated.second).toBeNull()
|
||||
expect(updated.attachments.map((a) => a.assetId).sort()).toEqual([att2.id, att3.id].sort())
|
||||
|
||||
// Removed attachment asset should be cleaned up since no comment references it anymore
|
||||
expect(await prisma.asset.findUnique({ where: { id: att1.id } })).toBeNull()
|
||||
expect(await prisma.asset.findUnique({ where: { id: att2.id } })).not.toBeNull()
|
||||
expect(await prisma.asset.findUnique({ where: { id: att3.id } })).not.toBeNull()
|
||||
})
|
||||
|
||||
it('enforces author-only edit, parent-internal reply constraint, non-empty validation, and preserves reply flags', async () => {
|
||||
const { author, owner, file } = await setupCommentFixture()
|
||||
|
||||
const parent = await assetService.createComment(
|
||||
{
|
||||
assetId: file.id,
|
||||
userId: author.id,
|
||||
message: 'Parent comment',
|
||||
attachmentIds: [],
|
||||
isInternal: true,
|
||||
},
|
||||
{ triggerAgents: false },
|
||||
)
|
||||
const reply = await assetService.createComment(
|
||||
{
|
||||
assetId: file.id,
|
||||
userId: author.id,
|
||||
replyToId: parent.id,
|
||||
message: 'Internal reply',
|
||||
attachmentIds: [],
|
||||
isInternal: true,
|
||||
},
|
||||
{ triggerAgents: false },
|
||||
)
|
||||
|
||||
// Non-author (even team owner) cannot edit
|
||||
await expect(
|
||||
assetService.updateComment({
|
||||
commentId: parent.id,
|
||||
userId: owner.id,
|
||||
message: 'Owner edit attempt',
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 403 })
|
||||
|
||||
// Reply cannot be made public while parent is internal
|
||||
await expect(
|
||||
assetService.updateComment({
|
||||
commentId: reply.id,
|
||||
userId: author.id,
|
||||
isInternal: false,
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 400 })
|
||||
|
||||
// Empty comment without attachments or annotations is rejected
|
||||
await expect(
|
||||
assetService.updateComment({
|
||||
commentId: parent.id,
|
||||
userId: author.id,
|
||||
message: ' ',
|
||||
attachmentIds: [],
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 400 })
|
||||
|
||||
// Toggling parent Internal -> Public keeps reply's own isInternal flag intact
|
||||
const toggledParent = await assetService.updateComment({
|
||||
commentId: parent.id,
|
||||
userId: author.id,
|
||||
isInternal: false,
|
||||
})
|
||||
expect(toggledParent.isInternal).toBe(false)
|
||||
expect(toggledParent.replies[0].isInternal).toBe(true)
|
||||
|
||||
// Agent comments cannot be edited
|
||||
const agentUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Bot',
|
||||
email: `bot-${Date.now()}-${Math.random()}@test.com`,
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
const agent = await prisma.agent.create({
|
||||
data: {
|
||||
id: agentUser.id,
|
||||
teamId: (await prisma.project.findUniqueOrThrow({ where: { id: file.projectId! } }))
|
||||
.teamId,
|
||||
type: 'chat',
|
||||
config: { provider: 'openai', model: 'gpt-4' },
|
||||
},
|
||||
})
|
||||
const session = await prisma.agentSession.create({
|
||||
data: { agentId: agent.id, cwd: '/tmp' },
|
||||
})
|
||||
const agentComment = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: file.id,
|
||||
creatorId: author.id,
|
||||
sessionId: session.id,
|
||||
message: 'Agent generated reply',
|
||||
},
|
||||
})
|
||||
await expect(
|
||||
assetService.updateComment({
|
||||
commentId: agentComment.id,
|
||||
userId: author.id,
|
||||
message: 'Try edit agent',
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 403 })
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -61,6 +61,7 @@ import { dedupeSymlinksToTarget } from './symlink'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { shareActivityService } from '@shumai/core/src/share/share-activity'
|
||||
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
|
||||
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
@@ -176,10 +177,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;
|
||||
`
|
||||
@@ -735,7 +743,10 @@ export class AssetService {
|
||||
}
|
||||
}
|
||||
|
||||
async listChildren(req: ListChildrenRequest): Promise<PaginatedData<AssetInfo[]>> {
|
||||
async listChildren(
|
||||
req: ListChildrenRequest,
|
||||
options?: { excludeInternalComments?: boolean },
|
||||
): Promise<PaginatedData<AssetInfo[]>> {
|
||||
let typesToQuery: AssetType[]
|
||||
if (req.assetType === 'file') {
|
||||
typesToQuery = [AssetType.file, AssetType.version_stack]
|
||||
@@ -823,6 +834,7 @@ export class AssetService {
|
||||
|
||||
const infos = await this.toAssetInfos(assets, undefined, {
|
||||
includeDeletedChildren: req.showDeleted,
|
||||
excludeInternalComments: options?.excludeInternalComments,
|
||||
})
|
||||
|
||||
return { data: infos, pageInfo }
|
||||
@@ -1099,7 +1111,10 @@ export class AssetService {
|
||||
return this.getAsset({ assetId: asset.id })
|
||||
}
|
||||
|
||||
async getAsset(req: GetAssetRequest): Promise<AssetInfo> {
|
||||
async getAsset(
|
||||
req: GetAssetRequest,
|
||||
options?: { excludeInternalComments?: boolean },
|
||||
): Promise<AssetInfo> {
|
||||
const a = await this.prismaClient.asset.findUnique({
|
||||
where: { id: req.assetId },
|
||||
include: assetInclude,
|
||||
@@ -1122,7 +1137,9 @@ export class AssetService {
|
||||
afs.push({ id: row.id, name: row.name })
|
||||
}
|
||||
|
||||
const infos = await this.toAssetInfos([a])
|
||||
const infos = await this.toAssetInfos([a], undefined, {
|
||||
excludeInternalComments: options?.excludeInternalComments,
|
||||
})
|
||||
const info = infos[0]
|
||||
info.ancestorFolders = afs
|
||||
|
||||
@@ -1950,6 +1967,27 @@ export class AssetService {
|
||||
}
|
||||
}
|
||||
|
||||
private async lockCommentAttachments(
|
||||
tx: Prisma.TransactionClient,
|
||||
attachmentIds: string[],
|
||||
owner?: { projectId: string | null; userId: string },
|
||||
): Promise<string[]> {
|
||||
if (attachmentIds.length === 0) return []
|
||||
|
||||
// Lock the same rows in the same order when claiming or removing attachments.
|
||||
const ownerFilter = owner
|
||||
? Prisma.sql`AND project_id IS NOT DISTINCT FROM ${owner.projectId} AND creator_id = ${owner.userId}`
|
||||
: Prisma.empty
|
||||
const attachments = await tx.$queryRaw<{ id: string }[]>`
|
||||
SELECT id FROM assets
|
||||
WHERE id IN (${Prisma.join(attachmentIds)}) AND type = 'attachment'
|
||||
${ownerFilter}
|
||||
ORDER BY id
|
||||
FOR NO KEY UPDATE
|
||||
`
|
||||
return attachments.map(({ id }) => id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a comment or reply. Mentions of agents (`<@agentId>`) start a chat with them
|
||||
* unless `triggerAgents` is false, which keeps an agent's own comments from starting
|
||||
@@ -1957,7 +1995,7 @@ export class AssetService {
|
||||
*/
|
||||
async createComment(
|
||||
req: CreateCommentRequest,
|
||||
options: { triggerAgents?: boolean } = {},
|
||||
options: { triggerAgents?: boolean; shareLinkId?: string } = {},
|
||||
): Promise<CommentInfo> {
|
||||
const triggerAgents = options.triggerAgents ?? true
|
||||
let commentId = ''
|
||||
@@ -1972,16 +2010,43 @@ export class AssetService {
|
||||
|
||||
let actualReplyToId = req.replyToId
|
||||
let parentComment = null
|
||||
let parentIsInternal = false
|
||||
if (req.replyToId) {
|
||||
parentComment = await tx.assetComment.findUnique({
|
||||
where: { id: req.replyToId },
|
||||
include: { creator: true },
|
||||
include: {
|
||||
creator: true,
|
||||
replyTo: { select: { id: true, isInternal: true } },
|
||||
},
|
||||
})
|
||||
if (options.shareLinkId) {
|
||||
if (
|
||||
!parentComment ||
|
||||
parentComment.assetId !== a.id ||
|
||||
parentComment.isInternal ||
|
||||
parentComment.replyTo?.isInternal
|
||||
) {
|
||||
throw new HTTPException(404, { message: 'Comment not found' })
|
||||
}
|
||||
}
|
||||
if (parentComment?.replyToId) {
|
||||
actualReplyToId = parentComment.replyToId
|
||||
parentIsInternal = Boolean(parentComment.isInternal || parentComment.replyTo?.isInternal)
|
||||
} else if (parentComment) {
|
||||
parentIsInternal = parentComment.isInternal
|
||||
}
|
||||
}
|
||||
|
||||
const isInternal = options.shareLinkId
|
||||
? false
|
||||
: parentIsInternal
|
||||
? true
|
||||
: Boolean(req.isInternal)
|
||||
|
||||
const attachmentIds = await this.lockCommentAttachments(tx, req.attachmentIds, {
|
||||
projectId: a.projectId,
|
||||
userId: req.userId,
|
||||
})
|
||||
const comment = await tx.assetComment.create({
|
||||
data: {
|
||||
assetId: a.id,
|
||||
@@ -1990,27 +2055,28 @@ export class AssetService {
|
||||
annotation: req.annotations,
|
||||
second: req.second,
|
||||
replyToId: actualReplyToId,
|
||||
isInternal,
|
||||
},
|
||||
})
|
||||
commentId = comment.id
|
||||
|
||||
for (const attachmentId of req.attachmentIds) {
|
||||
const attachmentAsset = await tx.asset.findUnique({
|
||||
where: { id: attachmentId },
|
||||
if (attachmentIds.length > 0) {
|
||||
// Read the links after acquiring the locks to see any claims that committed while waiting.
|
||||
const unclaimed = await tx.asset.findMany({
|
||||
where: { id: { in: attachmentIds }, commentAttachments: { none: {} } },
|
||||
select: { id: true },
|
||||
})
|
||||
if (
|
||||
attachmentAsset &&
|
||||
(attachmentAsset.type === AssetType.attachment ||
|
||||
attachmentAsset.type === AssetType.file) &&
|
||||
attachmentAsset.projectId === a.projectId
|
||||
) {
|
||||
await tx.assetCommentAttachment.create({
|
||||
data: {
|
||||
assetId: attachmentAsset.id,
|
||||
commentId: comment.id,
|
||||
},
|
||||
})
|
||||
}
|
||||
await tx.assetCommentAttachment.createMany({
|
||||
data: unclaimed.map(({ id }) => ({ assetId: id, commentId: comment.id })),
|
||||
})
|
||||
}
|
||||
|
||||
if (options.shareLinkId) {
|
||||
await shareActivityService.recordEvent(
|
||||
options.shareLinkId,
|
||||
{ kind: 'comment_created', assetId: a.id, userId: req.userId },
|
||||
tx,
|
||||
)
|
||||
}
|
||||
|
||||
if (!triggerAgents) return
|
||||
@@ -2188,22 +2254,154 @@ export class AssetService {
|
||||
return this.getComment(commentId, userId)
|
||||
}
|
||||
|
||||
async updateComment(params: {
|
||||
commentId: string
|
||||
userId: string
|
||||
message?: string
|
||||
isInternal?: boolean
|
||||
second?: number | null
|
||||
attachmentIds?: string[]
|
||||
}): Promise<CommentInfo> {
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
const comment = await tx.assetComment.findUnique({
|
||||
where: { id: params.commentId },
|
||||
select: {
|
||||
id: true,
|
||||
creatorId: true,
|
||||
sessionId: true,
|
||||
message: true,
|
||||
annotation: true,
|
||||
second: true,
|
||||
isInternal: true,
|
||||
attachments: { select: { assetId: true } },
|
||||
replyTo: { select: { isInternal: true } },
|
||||
asset: { select: { projectId: true } },
|
||||
},
|
||||
})
|
||||
|
||||
if (!comment) {
|
||||
throw new HTTPException(404, { message: 'Comment not found' })
|
||||
}
|
||||
|
||||
if (comment.sessionId !== null || comment.creatorId !== params.userId) {
|
||||
throw new HTTPException(403, { message: 'Only the comment author can edit this comment' })
|
||||
}
|
||||
|
||||
if (comment.replyTo?.isInternal && params.isInternal === false) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'Cannot make a reply public when its parent comment is internal',
|
||||
})
|
||||
}
|
||||
|
||||
const existingAttachmentIds = comment.attachments.map(({ assetId }) => assetId)
|
||||
const existingSet = new Set(existingAttachmentIds)
|
||||
|
||||
let toAdd: string[] = []
|
||||
let toRemove: string[] = []
|
||||
let keptCount = existingAttachmentIds.length
|
||||
|
||||
if (params.attachmentIds !== undefined) {
|
||||
const desiredIds = Array.from(new Set(params.attachmentIds))
|
||||
const desiredSet = new Set(desiredIds)
|
||||
toAdd = desiredIds.filter((id) => !existingSet.has(id))
|
||||
toRemove = existingAttachmentIds.filter((id) => !desiredSet.has(id))
|
||||
keptCount = existingAttachmentIds.filter((id) => desiredSet.has(id)).length
|
||||
}
|
||||
|
||||
const idsToLock = Array.from(new Set([...toAdd, ...toRemove]))
|
||||
let claimedToAdd: string[] = []
|
||||
let lockedToRemove: string[] = []
|
||||
|
||||
if (idsToLock.length > 0) {
|
||||
const lockedRows = await tx.$queryRaw<
|
||||
{ id: string; projectId: string | null; creatorId: string | null }[]
|
||||
>`
|
||||
SELECT id, project_id AS "projectId", creator_id AS "creatorId" FROM assets
|
||||
WHERE id IN (${Prisma.join(idsToLock)}) AND type = 'attachment'
|
||||
ORDER BY id
|
||||
FOR NO KEY UPDATE
|
||||
`
|
||||
const toAddSet = new Set(toAdd)
|
||||
const toRemoveSet = new Set(toRemove)
|
||||
const ownedToAdd = lockedRows
|
||||
.filter(
|
||||
(row) =>
|
||||
toAddSet.has(row.id) &&
|
||||
row.projectId === comment.asset.projectId &&
|
||||
row.creatorId === params.userId,
|
||||
)
|
||||
.map((row) => row.id)
|
||||
|
||||
lockedToRemove = lockedRows.filter((row) => toRemoveSet.has(row.id)).map((row) => row.id)
|
||||
|
||||
if (ownedToAdd.length > 0) {
|
||||
const unclaimed = await tx.asset.findMany({
|
||||
where: { id: { in: ownedToAdd }, commentAttachments: { none: {} } },
|
||||
select: { id: true },
|
||||
})
|
||||
claimedToAdd = unclaimed.map(({ id }) => id)
|
||||
}
|
||||
}
|
||||
|
||||
const finalMessage = params.message !== undefined ? params.message : (comment.message ?? '')
|
||||
const hasAnnotations = Array.isArray(comment.annotation) && comment.annotation.length > 0
|
||||
const finalAttachmentCount = keptCount + claimedToAdd.length
|
||||
|
||||
if (!finalMessage.trim() && finalAttachmentCount === 0 && !hasAnnotations) {
|
||||
throw new HTTPException(400, { message: 'Comment cannot be empty' })
|
||||
}
|
||||
|
||||
if (toRemove.length > 0) {
|
||||
await tx.assetCommentAttachment.deleteMany({
|
||||
where: {
|
||||
commentId: params.commentId,
|
||||
assetId: { in: toRemove },
|
||||
},
|
||||
})
|
||||
if (lockedToRemove.length > 0) {
|
||||
await tx.asset.deleteMany({
|
||||
where: { id: { in: lockedToRemove }, commentAttachments: { none: {} } },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (claimedToAdd.length > 0) {
|
||||
await tx.assetCommentAttachment.createMany({
|
||||
data: claimedToAdd.map((assetId) => ({ assetId, commentId: params.commentId })),
|
||||
})
|
||||
}
|
||||
|
||||
const updateData: Prisma.AssetCommentUpdateInput = {}
|
||||
if (params.message !== undefined) {
|
||||
updateData.message = params.message
|
||||
}
|
||||
if (params.isInternal !== undefined) {
|
||||
updateData.isInternal = params.isInternal
|
||||
}
|
||||
if (params.second !== undefined) {
|
||||
updateData.second = params.second
|
||||
}
|
||||
|
||||
if (Object.keys(updateData).length > 0) {
|
||||
await tx.assetComment.update({
|
||||
where: { id: params.commentId },
|
||||
data: updateData,
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
return this.getComment(params.commentId, params.userId)
|
||||
}
|
||||
|
||||
async deleteComment({ commentId, userId }: { commentId: string; userId: string }): Promise<void> {
|
||||
const comment = await this.prismaClient.assetComment.findUnique({
|
||||
where: { id: commentId },
|
||||
include: {
|
||||
attachments: {
|
||||
include: {
|
||||
asset: {
|
||||
include: {
|
||||
storageKey: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
creatorId: true,
|
||||
attachments: { select: { assetId: true } },
|
||||
asset: {
|
||||
select: {
|
||||
project: { select: { id: true, teamId: true } },
|
||||
project: { select: { teamId: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -2241,75 +2439,70 @@ export class AssetService {
|
||||
throw new HTTPException(403, { message: 'You do not have permission to delete this comment' })
|
||||
}
|
||||
|
||||
// Clean up attachment files from S3/storage and delete their DB records
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
for (const att of comment.attachments) {
|
||||
const asset = att.asset
|
||||
if (asset.storageKey) {
|
||||
try {
|
||||
await s3Service.deleteObject(bucket, asset.storageKey.key)
|
||||
} catch (err) {
|
||||
logger.error({ err, assetId: asset.id }, 'Failed to delete attachment file from S3')
|
||||
}
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
const attachmentIds = await this.lockCommentAttachments(
|
||||
tx,
|
||||
comment.attachments.map(({ assetId }) => assetId),
|
||||
)
|
||||
await tx.assetComment.delete({ where: { id: commentId } })
|
||||
|
||||
if (attachmentIds.length > 0) {
|
||||
// The storage cleanup job removes objects once every asset using their storage key is gone.
|
||||
await tx.asset.deleteMany({
|
||||
where: { id: { in: attachmentIds }, commentAttachments: { none: {} } },
|
||||
})
|
||||
}
|
||||
|
||||
await this.prismaClient.asset.delete({
|
||||
where: { id: asset.id },
|
||||
})
|
||||
|
||||
if (asset.storageKey) {
|
||||
await this.prismaClient.storageKey
|
||||
.delete({
|
||||
where: { id: asset.storageKey.id },
|
||||
})
|
||||
.catch(() => {
|
||||
// Silently ignore if already deleted
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
await this.prismaClient.assetComment.delete({
|
||||
where: { id: commentId },
|
||||
})
|
||||
}
|
||||
|
||||
private getCommentInclude(options?: { excludeInternal?: boolean }) {
|
||||
return {
|
||||
creator: true,
|
||||
completionLastChangedBy: true,
|
||||
asset: { include: { storageKey: true } },
|
||||
attachments: { include: { asset: { include: { storageKey: true } } } },
|
||||
reactions: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' as const },
|
||||
},
|
||||
replies: {
|
||||
...(options?.excludeInternal ? { where: { isInternal: false } } : {}),
|
||||
include: {
|
||||
creator: true,
|
||||
completionLastChangedBy: true,
|
||||
attachments: { include: { asset: { include: { storageKey: true } } } },
|
||||
reactions: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' as const },
|
||||
},
|
||||
},
|
||||
orderBy: { id: 'asc' as const },
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async listComments(
|
||||
assetId: string,
|
||||
params: PaginationParams,
|
||||
requestingUserId?: string,
|
||||
options?: { excludeInternal?: boolean },
|
||||
): Promise<PaginatedData<CommentInfo[]>> {
|
||||
const resolvedAssetId = await this.resolveLatestVersionId(assetId)
|
||||
const where: Prisma.AssetCommentWhereInput = {
|
||||
assetId: resolvedAssetId,
|
||||
replyToId: null,
|
||||
...(options?.excludeInternal ? { isInternal: false } : {}),
|
||||
}
|
||||
|
||||
const { data: comments, pageInfo } = await paginateQuery(
|
||||
async (skip, take) => {
|
||||
return this.prismaClient.assetComment.findMany({
|
||||
where: { assetId: resolvedAssetId, replyToId: null },
|
||||
include: {
|
||||
creator: true,
|
||||
completionLastChangedBy: true,
|
||||
asset: { include: { storageKey: true } },
|
||||
attachments: { include: { asset: { include: { storageKey: true } } } },
|
||||
reactions: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
},
|
||||
replies: {
|
||||
include: {
|
||||
creator: true,
|
||||
completionLastChangedBy: true,
|
||||
attachments: { include: { asset: { include: { storageKey: true } } } },
|
||||
reactions: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
},
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
},
|
||||
},
|
||||
where,
|
||||
include: this.getCommentInclude(options),
|
||||
skip,
|
||||
take,
|
||||
orderBy: { id: 'asc' },
|
||||
@@ -2317,7 +2510,7 @@ export class AssetService {
|
||||
},
|
||||
async () =>
|
||||
this.prismaClient.assetComment.count({
|
||||
where: { assetId: resolvedAssetId, replyToId: null },
|
||||
where,
|
||||
}),
|
||||
params,
|
||||
)
|
||||
@@ -2327,6 +2520,36 @@ export class AssetService {
|
||||
return { data: infos, pageInfo }
|
||||
}
|
||||
|
||||
async listAllComments(
|
||||
assetId: string,
|
||||
requestingUserId?: string,
|
||||
options?: { excludeInternal?: boolean },
|
||||
): Promise<CommentInfo[]> {
|
||||
const resolvedAssetId = await this.resolveLatestVersionId(assetId)
|
||||
|
||||
const comments = await this.prismaClient.assetComment.findMany({
|
||||
where: {
|
||||
assetId: resolvedAssetId,
|
||||
replyToId: null,
|
||||
...(options?.excludeInternal ? { isInternal: false } : {}),
|
||||
},
|
||||
include: this.getCommentInclude(options),
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
|
||||
return Promise.all(comments.map((c) => this.toCommentInfo(c, requestingUserId)))
|
||||
}
|
||||
|
||||
async getProjectNameForAsset(assetId: string): Promise<string | null> {
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
select: {
|
||||
project: { select: { name: true } },
|
||||
},
|
||||
})
|
||||
return asset?.project?.name ?? null
|
||||
}
|
||||
|
||||
async exportComments(
|
||||
assetId: string,
|
||||
format: CommentExportFormat,
|
||||
@@ -2425,9 +2648,10 @@ export class AssetService {
|
||||
async toAssetInfos(
|
||||
assets: AssetWithIncludes[],
|
||||
previewFormat?: PreviewFormat,
|
||||
options?: { includeDeletedChildren?: boolean },
|
||||
options?: { includeDeletedChildren?: boolean; excludeInternalComments?: boolean },
|
||||
): Promise<AssetInfo[]> {
|
||||
const includeDeletedChildren = options?.includeDeletedChildren ?? false
|
||||
const excludeInternalComments = options?.excludeInternalComments ?? false
|
||||
const stackIds = new Set<string>()
|
||||
|
||||
for (const a of assets) {
|
||||
@@ -2517,6 +2741,12 @@ export class AssetService {
|
||||
by: ['assetId'],
|
||||
where: {
|
||||
assetId: { in: Array.from(commentTargetIds) },
|
||||
...(excludeInternalComments
|
||||
? {
|
||||
isInternal: false,
|
||||
OR: [{ replyToId: null }, { replyTo: { isInternal: false } }],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
_count: { _all: true },
|
||||
})
|
||||
@@ -2711,8 +2941,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,
|
||||
@@ -3073,6 +3303,10 @@ export class AssetService {
|
||||
* that belong to an asset they have access to.
|
||||
*/
|
||||
async getDownloadUrl(assetId: string, key: string): Promise<string> {
|
||||
return (await this.getDownloadUrlWithAsset(assetId, key)).url
|
||||
}
|
||||
|
||||
async getDownloadUrlWithAsset(assetId: string, key: string) {
|
||||
const targetAssetId = await this.resolveLatestVersionId(assetId)
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: targetAssetId },
|
||||
@@ -3093,6 +3327,7 @@ export class AssetService {
|
||||
throw new Error('Key does not belong to this asset')
|
||||
}
|
||||
|
||||
let signedAssetId = asset.id
|
||||
let storageKey = asset.storageKey.key
|
||||
let assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
|
||||
let targetName = asset.name
|
||||
@@ -3108,12 +3343,14 @@ export class AssetService {
|
||||
storageKey: { key: { startsWith: key.substring(0, key.lastIndexOf('/') + 1) } },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
status: true,
|
||||
storageKey: { select: { key: true, isArchived: true } },
|
||||
},
|
||||
})
|
||||
if (sibling?.storageKey?.key) {
|
||||
signedAssetId = sibling.id
|
||||
storageKey = sibling.storageKey.key
|
||||
assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
|
||||
targetStatus = sibling.status
|
||||
@@ -3169,7 +3406,14 @@ export class AssetService {
|
||||
}
|
||||
}
|
||||
|
||||
return s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET', true, downloadFilename)
|
||||
const url = await s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
key,
|
||||
'GET',
|
||||
true,
|
||||
downloadFilename,
|
||||
)
|
||||
return { url, assetId: signedAssetId }
|
||||
}
|
||||
|
||||
async archiveAssets(
|
||||
@@ -3379,6 +3623,7 @@ export class AssetService {
|
||||
updatedAt: c.updatedAt.toISOString(),
|
||||
sessionId: c.sessionId,
|
||||
isCompleted: c.isCompleted,
|
||||
isInternal: c.isInternal,
|
||||
completionLastChangedBy,
|
||||
reactionCounts,
|
||||
}
|
||||
|
||||
@@ -595,5 +595,70 @@ describe('AuthzService', () => {
|
||||
}),
|
||||
).rejects.toThrow('Permission denied')
|
||||
})
|
||||
|
||||
it('limits Kanban task reads for project-scoped members to their projects and their own tasks', async () => {
|
||||
const owner = await prisma.user.create({
|
||||
data: { name: 'Owner User', email: 'owner-kanban-read@example.com', password: 'pass' },
|
||||
})
|
||||
const client = await prisma.user.create({
|
||||
data: { name: 'Client User', email: 'client-kanban-read@example.com', password: 'pass' },
|
||||
})
|
||||
const teamReviewer = await prisma.user.create({
|
||||
data: { name: 'Team Reviewer', email: 'rev-kanban-read@example.com', password: 'pass' },
|
||||
})
|
||||
|
||||
const team = await prisma.team.create({ data: { name: 'Kanban Read Team' } })
|
||||
const ownProject = await prisma.project.create({
|
||||
data: { name: 'Client Project', teamId: team.id },
|
||||
})
|
||||
const otherProject = await prisma.project.create({
|
||||
data: { name: 'Internal Project', teamId: team.id },
|
||||
})
|
||||
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: owner.id, role: 'owner', scope: 'team' },
|
||||
})
|
||||
const clientMember = await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: client.id, role: 'reviewer', scope: 'project' },
|
||||
})
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: ownProject.id, teamMemberId: clientMember.id, role: 'reviewer' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: teamReviewer.id, role: 'reviewer', scope: 'team' },
|
||||
})
|
||||
|
||||
const createTask = (title: string, projectId?: string, assigneeId?: string) =>
|
||||
prisma.kanbanTask.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
title,
|
||||
projectId,
|
||||
creatorId: owner.id,
|
||||
reporterId: owner.id,
|
||||
assigneeId,
|
||||
},
|
||||
})
|
||||
const ownTask = await createTask('Client task', ownProject.id)
|
||||
const otherTask = await createTask('Internal task', otherProject.id)
|
||||
const teamTask = await createTask('Team task')
|
||||
const assignedTask = await createTask('Assigned task', otherProject.id, client.id)
|
||||
|
||||
const read = (user: { id: string }, id: string) =>
|
||||
authzService.hasPermission({
|
||||
type: ResourceType.KanbanTask,
|
||||
id,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
await expect(read(client, ownTask.id)).resolves.toBeUndefined()
|
||||
await expect(read(client, assignedTask.id)).resolves.toBeUndefined()
|
||||
await expect(read(client, otherTask.id)).rejects.toThrow('User has only project scope')
|
||||
await expect(read(client, teamTask.id)).rejects.toThrow('User has only project scope')
|
||||
|
||||
await expect(read(teamReviewer, otherTask.id)).resolves.toBeUndefined()
|
||||
await expect(read(teamReviewer, teamTask.id)).resolves.toBeUndefined()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -122,17 +122,16 @@ export class AuthzService {
|
||||
})
|
||||
if (!member) throw new HTTPException(403, { message: 'User is not a member of the team' })
|
||||
|
||||
// If this is a KanbanTask and user is a team member, check if they are the assignee, reporter, or creator
|
||||
// A project-scoped member can read or edit a KanbanTask outside their projects
|
||||
// only when they are its assignee, reporter, or creator.
|
||||
if (req.type === ResourceType.KanbanTask) {
|
||||
if (req.permission === Permission.Read) {
|
||||
return
|
||||
}
|
||||
if (req.permission === Permission.Edit) {
|
||||
if (req.permission === Permission.Read || req.permission === Permission.Edit) {
|
||||
const isParticipant = await this.isKanbanTaskParticipant(req.id, req.user.id)
|
||||
if (isParticipant) {
|
||||
return
|
||||
}
|
||||
}
|
||||
throw new HTTPException(403, { message: 'User has only project scope' })
|
||||
}
|
||||
|
||||
// Project-scoped member on a team-level resource (no project context):
|
||||
|
||||
+24
@@ -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
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,738 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { prisma, AssetType, AssetStatus } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import {
|
||||
CommentFrameService,
|
||||
FrameExtractionQueue,
|
||||
selectBestVideoProxyKey,
|
||||
type ExecFileFn,
|
||||
} from './comment-frame'
|
||||
import { execFileSync } from 'child_process'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
import sharp from 'sharp'
|
||||
|
||||
async function createSamplePngBuffer(): Promise<Buffer> {
|
||||
return sharp({
|
||||
create: {
|
||||
width: 32,
|
||||
height: 18,
|
||||
channels: 3,
|
||||
background: { r: 20, g: 120, b: 220 },
|
||||
},
|
||||
})
|
||||
.png()
|
||||
.toBuffer()
|
||||
}
|
||||
|
||||
async function createSampleWebpBuffer(): Promise<Buffer> {
|
||||
return sharp({
|
||||
create: {
|
||||
width: 32,
|
||||
height: 18,
|
||||
channels: 3,
|
||||
background: { r: 220, g: 80, b: 40 },
|
||||
},
|
||||
})
|
||||
.webp()
|
||||
.toBuffer()
|
||||
}
|
||||
|
||||
describe('FrameExtractionQueue', () => {
|
||||
it('enforces maxConcurrency and processes queued tasks in FIFO order', async () => {
|
||||
const queue = new FrameExtractionQueue(2)
|
||||
let active = 0
|
||||
let maxObserved = 0
|
||||
const order: number[] = []
|
||||
const resolvers: Array<() => void> = []
|
||||
|
||||
const makeTask = (id: number) =>
|
||||
queue.enqueue(async () => {
|
||||
active++
|
||||
maxObserved = Math.max(maxObserved, active)
|
||||
order.push(id)
|
||||
await new Promise<void>((resolve) => resolvers.push(resolve))
|
||||
active--
|
||||
return id
|
||||
})
|
||||
|
||||
const p1 = makeTask(1)
|
||||
const p2 = makeTask(2)
|
||||
const p3 = makeTask(3)
|
||||
const p4 = makeTask(4)
|
||||
|
||||
expect(queue.activeCount).toBe(2)
|
||||
expect(queue.queuedCount).toBe(2)
|
||||
expect(maxObserved).toBe(2)
|
||||
|
||||
resolvers.shift()?.()
|
||||
await p1
|
||||
expect(queue.activeCount).toBe(2)
|
||||
expect(queue.queuedCount).toBe(1)
|
||||
|
||||
resolvers.shift()?.()
|
||||
await p2
|
||||
expect(queue.activeCount).toBe(2)
|
||||
expect(queue.queuedCount).toBe(0)
|
||||
|
||||
resolvers.shift()?.()
|
||||
await p3
|
||||
resolvers.shift()?.()
|
||||
await p4
|
||||
|
||||
expect(order).toEqual([1, 2, 3, 4])
|
||||
expect(maxObserved).toBe(2)
|
||||
expect(queue.activeCount).toBe(0)
|
||||
expect(queue.queuedCount).toBe(0)
|
||||
})
|
||||
|
||||
it('cancels queued tasks when their AbortSignal fires before execution', async () => {
|
||||
const queue = new FrameExtractionQueue(1)
|
||||
let releaseFirst!: () => void
|
||||
const first = queue.enqueue(
|
||||
() =>
|
||||
new Promise<string>((resolve) => {
|
||||
releaseFirst = () => resolve('first')
|
||||
}),
|
||||
)
|
||||
|
||||
const controller = new AbortController()
|
||||
const runSecond = vi.fn().mockResolvedValue('second')
|
||||
const second = queue.enqueue(runSecond, controller.signal)
|
||||
|
||||
expect(queue.queuedCount).toBe(1)
|
||||
controller.abort()
|
||||
|
||||
await expect(second).rejects.toThrow('Frame extraction aborted')
|
||||
expect(queue.queuedCount).toBe(0)
|
||||
expect(runSecond).not.toHaveBeenCalled()
|
||||
|
||||
releaseFirst()
|
||||
await expect(first).resolves.toBe('first')
|
||||
})
|
||||
})
|
||||
|
||||
describe('selectBestVideoProxyKey', () => {
|
||||
it('prefers SDR proxies over HDR and chooses lowest adequate resolution >= 360p', () => {
|
||||
const key = selectBestVideoProxyKey([
|
||||
{ key: 'hdr-720.mp4', width: 1280, height: 720, hdr: true, resolution: '720p' },
|
||||
{ key: 'sdr-1080.mp4', width: 1920, height: 1080, hdr: false, resolution: '1080p' },
|
||||
{ key: 'sdr-540.mp4', width: 960, height: 540, hdr: false, resolution: '540p' },
|
||||
{ key: 'sdr-240.mp4', width: 426, height: 240, hdr: false, resolution: '240p' },
|
||||
])
|
||||
expect(key).toBe('sdr-540.mp4')
|
||||
})
|
||||
|
||||
it('falls back to highest available SDR proxy if all are below 360p', () => {
|
||||
const key = selectBestVideoProxyKey([
|
||||
{ key: 'sdr-180.mp4', width: 320, height: 180, hdr: false, resolution: '180p' },
|
||||
{ key: 'sdr-240.mp4', width: 426, height: 240, hdr: false, resolution: '240p' },
|
||||
])
|
||||
expect(key).toBe('sdr-240.mp4')
|
||||
})
|
||||
|
||||
it('falls back to HDR proxy if no SDR proxy exists', () => {
|
||||
const key = selectBestVideoProxyKey([
|
||||
{ key: 'hdr-1080.mp4', width: 1920, height: 1080, hdr: true, resolution: '1080p' },
|
||||
{ key: 'hdr-720.mp4', width: 1280, height: 720, hdr: true, resolution: '720p' },
|
||||
])
|
||||
expect(key).toBe('hdr-720.mp4')
|
||||
})
|
||||
|
||||
it('returns null when no valid keys exist', () => {
|
||||
expect(selectBestVideoProxyKey([])).toBeNull()
|
||||
expect(selectBestVideoProxyKey(null)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('CommentFrameService & AssetService print helpers', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let userId: string
|
||||
let teamId: string
|
||||
let projectId: string
|
||||
let rootFolderId: string
|
||||
let subFolderId: string
|
||||
|
||||
beforeEach(async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Alice',
|
||||
email: `alice-${Date.now()}-${Math.random()}@example.com`,
|
||||
},
|
||||
})
|
||||
userId = user.id
|
||||
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Studio Team',
|
||||
},
|
||||
})
|
||||
teamId = team.id
|
||||
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'root',
|
||||
type: AssetType.root,
|
||||
status: AssetStatus.processed,
|
||||
creatorId: userId,
|
||||
},
|
||||
})
|
||||
rootFolderId = rootFolder.id
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: {
|
||||
name: 'Commercial Cut',
|
||||
teamId,
|
||||
rootFolderId,
|
||||
},
|
||||
})
|
||||
projectId = project.id
|
||||
|
||||
await prisma.asset.update({
|
||||
where: { id: rootFolderId },
|
||||
data: { projectId },
|
||||
})
|
||||
|
||||
const subFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Dailies',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.processed,
|
||||
projectId,
|
||||
parentId: rootFolderId,
|
||||
creatorId: userId,
|
||||
},
|
||||
})
|
||||
subFolderId = subFolder.id
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('skips extraction when the request is aborted during asset lookup', async () => {
|
||||
const storageKey = await prisma.storageKey.create({ data: { key: 'files/clip.mp4' } })
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'clip.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
mediaType: 'video/mp4',
|
||||
projectId,
|
||||
parentId: subFolderId,
|
||||
creatorId: userId,
|
||||
storageKeyId: storageKey.id,
|
||||
},
|
||||
})
|
||||
const controller = new AbortController()
|
||||
const resolveLatestVersionId = assetService.resolveLatestVersionId.bind(assetService)
|
||||
vi.spyOn(assetService, 'resolveLatestVersionId').mockImplementationOnce(async (assetId) => {
|
||||
const resolvedId = await resolveLatestVersionId(assetId)
|
||||
controller.abort()
|
||||
return resolvedId
|
||||
})
|
||||
const resolveInput = vi.spyOn(s3Service, 'resolveInput').mockResolvedValue('/local/clip.mp4')
|
||||
const execFileFn = vi.fn<ExecFileFn>().mockResolvedValue({ stdout: '', stderr: '' })
|
||||
const service = new CommentFrameService({ execFileFn })
|
||||
|
||||
await expect(
|
||||
service.extractFrame({ assetId: asset.id, second: 0, signal: controller.signal }),
|
||||
).rejects.toMatchObject({ name: 'AbortError' })
|
||||
expect(resolveInput).not.toHaveBeenCalled()
|
||||
expect(execFileFn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('extracts a video frame using the lowest adequate SDR proxy and deduplicates concurrent requests', async () => {
|
||||
const webpBuffer = await createSampleWebpBuffer()
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/video-original.mp4' },
|
||||
})
|
||||
const videoAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'scene1.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
mediaType: 'video/mp4',
|
||||
projectId,
|
||||
parentId: subFolderId,
|
||||
creatorId: userId,
|
||||
storageKeyId: storageKey.id,
|
||||
media: {
|
||||
proxyType: 'video',
|
||||
duration: 10,
|
||||
filesize: 1000,
|
||||
frames: 240,
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [
|
||||
{ key: 'files/proxies/1080p.mp4', width: 1920, height: 1080, hdr: false },
|
||||
{ key: 'files/proxies/540p.mp4', width: 960, height: 540, hdr: false },
|
||||
{ key: 'files/proxies/720p-hdr.mp4', width: 1280, height: 720, hdr: true },
|
||||
],
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: null,
|
||||
original: null,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const resolveInputSpy = vi
|
||||
.spyOn(s3Service, 'resolveInput')
|
||||
.mockResolvedValue('/local/files/proxies/540p.mp4')
|
||||
|
||||
let releaseExec!: () => void
|
||||
const execFileMock = vi.fn<ExecFileFn>(async (_file, args) => {
|
||||
await new Promise<void>((resolve) => {
|
||||
releaseExec = resolve
|
||||
})
|
||||
const outPath = args[args.length - 1]
|
||||
fs.writeFileSync(outPath, webpBuffer)
|
||||
return { stdout: '', stderr: '' }
|
||||
})
|
||||
|
||||
const service = new CommentFrameService({ maxConcurrency: 2, execFileFn: execFileMock })
|
||||
|
||||
const p1 = service.extractFrame({ assetId: videoAsset.id, second: 2.5, width: 400 })
|
||||
const p2 = service.extractFrame({ assetId: videoAsset.id, second: 2.5, width: 400 })
|
||||
|
||||
// Let async DB lookup finish before releasing exec
|
||||
await vi.waitFor(() => expect(execFileMock).toHaveBeenCalledTimes(1))
|
||||
releaseExec()
|
||||
|
||||
const [r1, r2] = await Promise.all([p1, p2])
|
||||
expect(r1.mimeType).toBe('image/webp')
|
||||
expect(r1.buffer.equals(webpBuffer)).toBe(true)
|
||||
expect(r2.buffer.equals(webpBuffer)).toBe(true)
|
||||
expect(execFileMock).toHaveBeenCalledTimes(1)
|
||||
expect(resolveInputSpy).toHaveBeenCalledWith(expect.any(String), 'files/proxies/540p.mp4')
|
||||
})
|
||||
|
||||
it('extracts a 3D model turntable frame and enforces watermark-only proxies when watermarkConfigId is set', async () => {
|
||||
const webpBuffer = await createSampleWebpBuffer()
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/chair.glb' },
|
||||
})
|
||||
const modelAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'chair.glb',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
mediaType: 'model/gltf-binary',
|
||||
projectId,
|
||||
parentId: subFolderId,
|
||||
creatorId: userId,
|
||||
storageKeyId: storageKey.id,
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
duration: 24,
|
||||
filesize: 2000,
|
||||
frames: 24,
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [{ key: 'files/proxies/turntable.mp4', width: 1024, height: 1024 }],
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: null,
|
||||
original: null,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const watermarkSpy = vi
|
||||
.spyOn(watermarkService, 'getCompletedWatermarkMediaMap')
|
||||
.mockResolvedValueOnce(
|
||||
new Map([
|
||||
[
|
||||
modelAsset.id,
|
||||
{
|
||||
proxyType: '3d',
|
||||
duration: 24,
|
||||
filesize: 2000,
|
||||
frames: 24,
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [{ key: 'files/wm/turntable-wm.mp4', width: 1024, height: 1024 }],
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: null,
|
||||
original: null,
|
||||
},
|
||||
],
|
||||
]),
|
||||
)
|
||||
.mockResolvedValueOnce(new Map())
|
||||
|
||||
const resolveInputSpy = vi
|
||||
.spyOn(s3Service, 'resolveInput')
|
||||
.mockResolvedValue('/local/files/wm/turntable-wm.mp4')
|
||||
|
||||
const execFileMock = vi.fn<ExecFileFn>(async (_file, args) => {
|
||||
const outPath = args[args.length - 1]
|
||||
fs.writeFileSync(outPath, webpBuffer)
|
||||
return { stdout: '', stderr: '' }
|
||||
})
|
||||
|
||||
const service = new CommentFrameService({ execFileFn: execFileMock })
|
||||
|
||||
const res = await service.extractFrame({
|
||||
assetId: modelAsset.id,
|
||||
second: 3,
|
||||
width: 400,
|
||||
watermarkConfigId: 'wm-cfg-1',
|
||||
})
|
||||
expect(res.mimeType).toBe('image/webp')
|
||||
expect(watermarkSpy).toHaveBeenCalledWith([modelAsset.id], 'wm-cfg-1')
|
||||
expect(resolveInputSpy).toHaveBeenCalledWith(expect.any(String), 'files/wm/turntable-wm.mp4')
|
||||
|
||||
// Missing watermark proxy must reject with 422 rather than leaking unwatermarked media
|
||||
await expect(
|
||||
service.extractFrame({
|
||||
assetId: modelAsset.id,
|
||||
second: 3,
|
||||
width: 400,
|
||||
watermarkConfigId: 'wm-cfg-2',
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 422 })
|
||||
})
|
||||
|
||||
it('renders a PDF page frame via pdftoppm and sharp', async () => {
|
||||
const samplePng = await createSamplePngBuffer()
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/deck.pdf' },
|
||||
})
|
||||
const pdfAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'deck.pdf',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
mediaType: 'application/pdf',
|
||||
projectId,
|
||||
parentId: subFolderId,
|
||||
creatorId: userId,
|
||||
storageKeyId: storageKey.id,
|
||||
media: {
|
||||
proxyType: 'pdf',
|
||||
duration: 0,
|
||||
filesize: 5000,
|
||||
frames: 5,
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
pdfTranscode: { key: 'files/proxies/deck.pdf' },
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: null,
|
||||
original: null,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const downloadSpy = vi
|
||||
.spyOn(s3Service, 'downloadToFile')
|
||||
.mockImplementation(async (_bucket, _key, dest) => {
|
||||
fs.writeFileSync(dest, '%PDF-1.4 mock')
|
||||
})
|
||||
|
||||
const execFileMock = vi.fn<ExecFileFn>(async (file, args) => {
|
||||
expect(file).toBe('pdftoppm')
|
||||
expect(args[args.indexOf('-scale-to') + 1]).toBe('400')
|
||||
expect(args).toContain('-f')
|
||||
expect(args).toContain('3')
|
||||
const prefix = args[args.length - 1]
|
||||
fs.writeFileSync(`${prefix}-3.png`, samplePng)
|
||||
return { stdout: '', stderr: '' }
|
||||
})
|
||||
|
||||
const service = new CommentFrameService({ execFileFn: execFileMock })
|
||||
const res = await service.extractFrame({ assetId: pdfAsset.id, second: 3, width: 400 })
|
||||
expect(downloadSpy).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'files/proxies/deck.pdf',
|
||||
expect.stringContaining(path.sep),
|
||||
)
|
||||
expect(res.mimeType).toBe('image/webp')
|
||||
expect(res.buffer.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('rejects unsupported asset types with 400 and archived assets without proxy with 422', async () => {
|
||||
const imgKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/photo.png' },
|
||||
})
|
||||
const imageAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'photo.png',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
mediaType: 'image/png',
|
||||
projectId,
|
||||
parentId: subFolderId,
|
||||
creatorId: userId,
|
||||
storageKeyId: imgKey.id,
|
||||
media: {
|
||||
proxyType: 'image',
|
||||
duration: 0,
|
||||
filesize: 100,
|
||||
frames: 1,
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: null,
|
||||
original: null,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const archivedKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/archived.mp4', isArchived: true },
|
||||
})
|
||||
const archivedVideo = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'archived.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.archived,
|
||||
mediaType: 'video/mp4',
|
||||
projectId,
|
||||
parentId: subFolderId,
|
||||
creatorId: userId,
|
||||
storageKeyId: archivedKey.id,
|
||||
},
|
||||
})
|
||||
|
||||
const service = new CommentFrameService()
|
||||
await expect(service.extractFrame({ assetId: imageAsset.id, second: 0 })).rejects.toMatchObject(
|
||||
{ status: 400 },
|
||||
)
|
||||
await expect(
|
||||
service.extractFrame({ assetId: archivedVideo.id, second: 1 }),
|
||||
).rejects.toMatchObject({ status: 422 })
|
||||
await expect(
|
||||
service.extractFrame({ assetId: 'non-existent-id', second: 0 }),
|
||||
).rejects.toMatchObject({ status: 404 })
|
||||
})
|
||||
|
||||
it('lists all comments with replies, reactions, completion status, and fetches project name', async () => {
|
||||
vi.spyOn(s3Service, 'presign').mockResolvedValue('http://mock-s3/file')
|
||||
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/cut.mp4' },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'cut.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
mediaType: 'video/mp4',
|
||||
projectId,
|
||||
parentId: subFolderId,
|
||||
creatorId: userId,
|
||||
storageKeyId: storageKey.id,
|
||||
},
|
||||
})
|
||||
|
||||
const parent = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
creatorId: userId,
|
||||
message: 'Check lighting',
|
||||
second: 1.5,
|
||||
isCompleted: true,
|
||||
completionLastChangedById: userId,
|
||||
},
|
||||
})
|
||||
await prisma.assetCommentReaction.create({
|
||||
data: { commentId: parent.id, userId, code: '👍' },
|
||||
})
|
||||
await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
creatorId: userId,
|
||||
replyToId: parent.id,
|
||||
message: 'Fixed in v2',
|
||||
},
|
||||
})
|
||||
|
||||
const allComments = await assetService.listAllComments(asset.id, userId)
|
||||
expect(allComments).toHaveLength(1)
|
||||
expect(allComments[0].message).toBe('Check lighting')
|
||||
expect(allComments[0].isCompleted).toBe(true)
|
||||
expect(allComments[0].reactionCounts).toEqual([
|
||||
expect.objectContaining({ code: '👍', count: 1, requestingUserReacted: true }),
|
||||
])
|
||||
expect(allComments[0].replies).toHaveLength(1)
|
||||
expect(allComments[0].replies[0].message).toBe('Fixed in v2')
|
||||
|
||||
const projectName = await assetService.getProjectNameForAsset(asset.id)
|
||||
expect(projectName).toBe('Commercial Cut')
|
||||
})
|
||||
|
||||
it('extracts exact frames with real ffmpeg for 30fps video, 23.976fps video, and 6fps 3D turntable', async () => {
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shumai-frame-acc-'))
|
||||
const w = 64
|
||||
const h = 64
|
||||
|
||||
const createColorCodedVideo = (filename: string, rateArg: string, totalFrames: number) => {
|
||||
const raw = Buffer.alloc(w * h * 3 * totalFrames)
|
||||
for (let n = 0; n < totalFrames; n++) {
|
||||
const r = (n * 9) & 255
|
||||
const g = (n * 15) & 255
|
||||
const off = n * w * h * 3
|
||||
for (let i = 0; i < w * h; i++) {
|
||||
raw[off + i * 3] = r
|
||||
raw[off + i * 3 + 1] = g
|
||||
raw[off + i * 3 + 2] = 120
|
||||
}
|
||||
}
|
||||
const rawPath = path.join(tmpDir, `${filename}.rgb`)
|
||||
const mp4Path = path.join(tmpDir, `${filename}.mp4`)
|
||||
fs.writeFileSync(rawPath, raw)
|
||||
execFileSync('ffmpeg', [
|
||||
'-y',
|
||||
'-loglevel',
|
||||
'error',
|
||||
'-f',
|
||||
'rawvideo',
|
||||
'-pix_fmt',
|
||||
'rgb24',
|
||||
'-s',
|
||||
`${w}x${h}`,
|
||||
'-r',
|
||||
rateArg,
|
||||
'-i',
|
||||
rawPath,
|
||||
'-c:v',
|
||||
'libx264',
|
||||
'-pix_fmt',
|
||||
'yuv420p',
|
||||
'-g',
|
||||
'12',
|
||||
'-bf',
|
||||
'2',
|
||||
'-movflags',
|
||||
'+faststart',
|
||||
mp4Path,
|
||||
])
|
||||
return mp4Path
|
||||
}
|
||||
|
||||
const identifyExtractedFrame = async (webpBuffer: Buffer, totalFrames: number) => {
|
||||
const { data, info } = await sharp(webpBuffer).raw().toBuffer({ resolveWithObject: true })
|
||||
const cx = Math.floor(info.width / 2)
|
||||
const cy = Math.floor(info.height / 2)
|
||||
const idx = (cy * info.width + cx) * info.channels
|
||||
const r = data[idx]
|
||||
const g = data[idx + 1]
|
||||
let best = -1
|
||||
let bestDist = Infinity
|
||||
for (let n = 0; n < totalFrames; n++) {
|
||||
const dr = r - ((n * 9) & 255)
|
||||
const dg = g - ((n * 15) & 255)
|
||||
const dist = dr * dr + dg * dg
|
||||
if (dist < bestDist) {
|
||||
bestDist = dist
|
||||
best = n
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
try {
|
||||
const mp4Fps30 = createColorCodedVideo('v30', '30', 24)
|
||||
const mp4Fps23976 = createColorCodedVideo('v23976', '24000/1001', 24)
|
||||
const mp4Turntable = createColorCodedVideo('turntable', '6', 24)
|
||||
|
||||
const keyMap: Record<string, string> = {
|
||||
'files/proxies/v30.mp4': mp4Fps30,
|
||||
'files/proxies/v23976.mp4': mp4Fps23976,
|
||||
'files/proxies/turntable.mp4': mp4Turntable,
|
||||
}
|
||||
vi.spyOn(s3Service, 'resolveInput').mockImplementation(async (_bucket, key) => keyMap[key])
|
||||
|
||||
const createAsset = async (
|
||||
name: string,
|
||||
proxyType: 'video' | '3d',
|
||||
proxyKey: string,
|
||||
fps: number,
|
||||
totalFrames: number,
|
||||
) => {
|
||||
const sk = await prisma.storageKey.create({ data: { key: `files/${name}` } })
|
||||
return prisma.asset.create({
|
||||
data: {
|
||||
name,
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
mediaType: proxyType === '3d' ? 'model/gltf-binary' : 'video/mp4',
|
||||
projectId,
|
||||
parentId: subFolderId,
|
||||
creatorId: userId,
|
||||
storageKeyId: sk.id,
|
||||
media: {
|
||||
proxyType,
|
||||
duration: totalFrames / fps,
|
||||
filesize: 1000,
|
||||
frames: totalFrames,
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [{ key: proxyKey, width: 64, height: 64, hdr: false }],
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: {
|
||||
originalHeight: h,
|
||||
originalWidth: w,
|
||||
hasAudio: false,
|
||||
bitRate: 100000,
|
||||
frameRate: fps,
|
||||
totalFrames,
|
||||
duration: totalFrames / fps,
|
||||
startTimecode: '00:00:00:00',
|
||||
format: {},
|
||||
},
|
||||
original: null,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const asset30 = await createAsset('v30.mp4', 'video', 'files/proxies/v30.mp4', 30, 24)
|
||||
const asset23976 = await createAsset(
|
||||
'v23976.mp4',
|
||||
'video',
|
||||
'files/proxies/v23976.mp4',
|
||||
24000 / 1001,
|
||||
24,
|
||||
)
|
||||
const asset3d = await createAsset('chair.glb', '3d', 'files/proxies/turntable.mp4', 6, 24)
|
||||
|
||||
const realService = new CommentFrameService({ maxConcurrency: 2 })
|
||||
|
||||
// Frames where .toFixed(4) previously rounded UP and skipped to N+1:
|
||||
// 30fps: frame 2 (0.06666... -> 0.0667), frame 5 (0.16666... -> 0.1667), frame 23 (last frame)
|
||||
for (const frame of [0, 2, 5, 8, 17, 23]) {
|
||||
const res = await realService.extractFrame({
|
||||
assetId: asset30.id,
|
||||
second: frame / 30,
|
||||
width: 64,
|
||||
})
|
||||
expect(await identifyExtractedFrame(res.buffer, 24)).toBe(frame)
|
||||
}
|
||||
|
||||
// 23.976fps: frame 7 (0.291958 -> 0.2920), frame 8, frame 19, frame 23
|
||||
for (const frame of [0, 7, 8, 19, 23]) {
|
||||
const res = await realService.extractFrame({
|
||||
assetId: asset23976.id,
|
||||
second: frame / (24000 / 1001),
|
||||
width: 64,
|
||||
})
|
||||
expect(await identifyExtractedFrame(res.buffer, 24)).toBe(frame)
|
||||
}
|
||||
|
||||
// 3D 6fps turntable where model-viewer stores center times ((N + 0.5) / 6, last = (23 + 0.25) / 6)
|
||||
for (const frame of [0, 1, 6, 12, 23]) {
|
||||
const centerSec = frame === 23 ? (frame + 0.25) / 6 : (frame + 0.5) / 6
|
||||
const res = await realService.extractFrame({
|
||||
assetId: asset3d.id,
|
||||
second: centerSec,
|
||||
width: 64,
|
||||
})
|
||||
expect(await identifyExtractedFrame(res.buffer, 24)).toBe(frame)
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,557 @@
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { secondToTurntableFrame, TURNTABLE_FPS } from '@shumai/core/src/utils/model3d'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { prisma } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { execFile } from 'child_process'
|
||||
import * as fs from 'fs'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
import sharp from 'sharp'
|
||||
import { ulid } from 'ulid'
|
||||
import { promisify } from 'util'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const DEFAULT_CONCURRENCY = 4
|
||||
const DEFAULT_FRAME_TIMEOUT_MS = 30_000
|
||||
const MIN_PREFERRED_PROXY_HEIGHT = 360
|
||||
|
||||
export interface ExtractCommentFrameParams {
|
||||
assetId: string
|
||||
second: number
|
||||
width?: number
|
||||
watermarkConfigId?: string | null
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
export interface ExtractCommentFrameResult {
|
||||
buffer: Buffer
|
||||
mimeType: string
|
||||
}
|
||||
|
||||
export type ExecFileFn = (
|
||||
file: string,
|
||||
args: string[],
|
||||
options?: { signal?: AbortSignal; timeout?: number },
|
||||
) => Promise<{ stdout: string | Buffer; stderr: string | Buffer }>
|
||||
|
||||
interface QueuedTask<T> {
|
||||
run: () => Promise<T>
|
||||
resolve: (value: T) => void
|
||||
reject: (err: unknown) => void
|
||||
signal?: AbortSignal
|
||||
onAbort?: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounded FIFO concurrency queue dedicated to on-demand comment frame extraction,
|
||||
* isolated from background transcode workers so print requests stay fast without
|
||||
* overloading the main API server.
|
||||
*/
|
||||
export class FrameExtractionQueue {
|
||||
private running = 0
|
||||
private readonly pending: QueuedTask<unknown>[] = []
|
||||
|
||||
constructor(private readonly maxConcurrency: number) {}
|
||||
|
||||
get activeCount(): number {
|
||||
return this.running
|
||||
}
|
||||
|
||||
get queuedCount(): number {
|
||||
return this.pending.length
|
||||
}
|
||||
|
||||
enqueue<T>(run: () => Promise<T>, signal?: AbortSignal): Promise<T> {
|
||||
if (signal?.aborted) {
|
||||
return Promise.reject(new DOMException('Frame extraction aborted', 'AbortError'))
|
||||
}
|
||||
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const task: QueuedTask<T> = { run, resolve, reject, signal }
|
||||
|
||||
if (signal) {
|
||||
const onAbort = () => {
|
||||
const idx = this.pending.indexOf(task as QueuedTask<unknown>)
|
||||
if (idx !== -1) {
|
||||
this.pending.splice(idx, 1)
|
||||
signal.removeEventListener('abort', onAbort)
|
||||
reject(new DOMException('Frame extraction aborted', 'AbortError'))
|
||||
}
|
||||
}
|
||||
task.onAbort = onAbort
|
||||
signal.addEventListener('abort', onAbort, { once: true })
|
||||
}
|
||||
|
||||
this.pending.push(task as QueuedTask<unknown>)
|
||||
this.drain()
|
||||
})
|
||||
}
|
||||
|
||||
private drain(): void {
|
||||
while (this.running < this.maxConcurrency && this.pending.length > 0) {
|
||||
const task = this.pending.shift()
|
||||
if (!task) break
|
||||
|
||||
if (task.signal && task.onAbort) {
|
||||
task.signal.removeEventListener('abort', task.onAbort)
|
||||
}
|
||||
if (task.signal?.aborted) {
|
||||
task.reject(new DOMException('Frame extraction aborted', 'AbortError'))
|
||||
continue
|
||||
}
|
||||
|
||||
this.running++
|
||||
task.run().then(
|
||||
(result) => {
|
||||
this.running--
|
||||
this.drain()
|
||||
task.resolve(result)
|
||||
},
|
||||
(err) => {
|
||||
this.running--
|
||||
this.drain()
|
||||
task.reject(err)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the fastest video proxy suitable for thumbnail extraction:
|
||||
* 1. Prefer SDR proxies over HDR to avoid washed-out colors.
|
||||
* 2. Among SDR proxies, pick the lowest resolution that is still >= 360p (fast seek + decode
|
||||
* for a ~400px thumbnail). If none are >= 360p, pick the highest available SDR proxy.
|
||||
*/
|
||||
export function selectBestVideoProxyKey(
|
||||
videoTranscodes?: PrismaJson.VideoTranscode[] | null,
|
||||
): string | null {
|
||||
if (!videoTranscodes || videoTranscodes.length === 0) return null
|
||||
|
||||
const valid = videoTranscodes.filter((t) => Boolean(t.key))
|
||||
if (valid.length === 0) return null
|
||||
|
||||
const sdr = valid.filter((t) => !t.hdr)
|
||||
const pool = sdr.length > 0 ? sdr : valid
|
||||
|
||||
const adequate = pool
|
||||
.filter((t) => (t.height || 0) >= MIN_PREFERRED_PROXY_HEIGHT)
|
||||
.sort((a, b) => (a.height || 0) - (b.height || 0))
|
||||
if (adequate.length > 0) {
|
||||
return adequate[0].key ?? null
|
||||
}
|
||||
|
||||
const fallback = [...pool].sort((a, b) => (b.height || 0) - (a.height || 0))
|
||||
return fallback[0]?.key ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves an ffmpeg `-ss` input seek timestamp that lands squarely on the exact
|
||||
* target frame displayed by Shumai's video and 3D turntable players.
|
||||
*
|
||||
* `ffmpeg -ss T -i input -vframes 1` outputs the first frame with `PTS >= T`.
|
||||
* Passing `N / fps` directly (especially after decimal rounding) or a frame center
|
||||
* `(N + 0.5) / fps` causes ffmpeg to skip frame `N` and emit frame `N + 1` whenever
|
||||
* `T` exceeds `PTS(N)` by even 1µs.
|
||||
*
|
||||
* Instead, we recover integer frame `N` with the exact player formula
|
||||
* (`Math.floor(second * fps + 0.45)` for video, `secondToTurntableFrame` for 3D)
|
||||
* and seek to the midpoint between frame `N - 1` and frame `N`: `(N - 0.5) / fps`,
|
||||
* leaving a full ±0.5 frame tolerance margin on both sides.
|
||||
*/
|
||||
export function resolveFrameAccurateSeek(params: {
|
||||
second: number
|
||||
proxyType: 'video' | '3d'
|
||||
frameRate?: number | null
|
||||
totalFrames?: number | null
|
||||
duration?: number | null
|
||||
}): { seekTime: number; frameIndex: number | null } {
|
||||
const safeSecond = Math.max(0, params.second)
|
||||
|
||||
if (params.proxyType === '3d') {
|
||||
const frameIndex = secondToTurntableFrame(safeSecond)
|
||||
const seekTime = frameIndex <= 0 ? 0 : (frameIndex - 0.5) / TURNTABLE_FPS
|
||||
return { seekTime, frameIndex }
|
||||
}
|
||||
|
||||
const fps = params.frameRate && params.frameRate > 0 ? params.frameRate : null
|
||||
if (fps) {
|
||||
let frameIndex = Math.max(0, Math.floor(safeSecond * fps + 0.45))
|
||||
if (params.totalFrames && params.totalFrames > 0) {
|
||||
frameIndex = Math.min(frameIndex, params.totalFrames - 1)
|
||||
} else if (params.duration && params.duration > 0) {
|
||||
const maxFrame = Math.max(0, Math.round(params.duration * fps) - 1)
|
||||
frameIndex = Math.min(frameIndex, maxFrame)
|
||||
}
|
||||
const seekTime = frameIndex <= 0 ? 0 : (frameIndex - 0.5) / fps
|
||||
return { seekTime, frameIndex }
|
||||
}
|
||||
|
||||
const seekTime =
|
||||
params.duration && params.duration > 0 && safeSecond >= params.duration
|
||||
? Math.max(0, params.duration - 0.05)
|
||||
: safeSecond
|
||||
return { seekTime, frameIndex: null }
|
||||
}
|
||||
|
||||
export class CommentFrameService {
|
||||
private readonly queue: FrameExtractionQueue
|
||||
private readonly inFlight = new Map<
|
||||
string,
|
||||
{
|
||||
promise: Promise<ExtractCommentFrameResult>
|
||||
controller: AbortController
|
||||
waiters: number
|
||||
}
|
||||
>()
|
||||
private readonly execFileFn: ExecFileFn
|
||||
private readonly timeoutMs: number
|
||||
|
||||
constructor(options?: { maxConcurrency?: number; timeoutMs?: number; execFileFn?: ExecFileFn }) {
|
||||
const envConcurrency = Number(process.env.PRINT_FRAME_CONCURRENCY)
|
||||
const maxConcurrency =
|
||||
options?.maxConcurrency ??
|
||||
(Number.isInteger(envConcurrency) && envConcurrency > 0
|
||||
? envConcurrency
|
||||
: DEFAULT_CONCURRENCY)
|
||||
this.queue = new FrameExtractionQueue(maxConcurrency)
|
||||
this.timeoutMs = options?.timeoutMs ?? DEFAULT_FRAME_TIMEOUT_MS
|
||||
this.execFileFn =
|
||||
options?.execFileFn ??
|
||||
((file, args, opts) =>
|
||||
execFileAsync(file, args, {
|
||||
signal: opts?.signal,
|
||||
timeout: opts?.timeout,
|
||||
maxBuffer: 10 * 1024 * 1024,
|
||||
}))
|
||||
}
|
||||
|
||||
async extractFrame(params: ExtractCommentFrameParams): Promise<ExtractCommentFrameResult> {
|
||||
if (params.signal?.aborted) {
|
||||
throw new DOMException('Frame extraction aborted', 'AbortError')
|
||||
}
|
||||
|
||||
const width = Math.max(64, Math.min(1280, Math.round(params.width ?? 400)))
|
||||
const second = Math.max(0, params.second)
|
||||
|
||||
const targetAssetId = await assetService.resolveLatestVersionId(params.assetId)
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: targetAssetId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
params.signal?.throwIfAborted()
|
||||
|
||||
if (!asset || asset.isDeleted) {
|
||||
throw new HTTPException(404, { message: 'Asset not found' })
|
||||
}
|
||||
|
||||
const media = asset.media as PrismaJson.MediaInfo | null
|
||||
const proxyType = media?.proxyType ?? this.inferProxyType(asset.mediaType)
|
||||
|
||||
if (proxyType !== 'video' && proxyType !== '3d' && proxyType !== 'pdf') {
|
||||
throw new HTTPException(400, {
|
||||
message: 'Frame extraction is only supported for video, 3D model, and PDF assets',
|
||||
})
|
||||
}
|
||||
|
||||
const frameTarget =
|
||||
proxyType === 'pdf'
|
||||
? null
|
||||
: resolveFrameAccurateSeek({
|
||||
second,
|
||||
proxyType,
|
||||
frameRate: media?.metadata?.frameRate,
|
||||
totalFrames: media?.metadata?.totalFrames ?? media?.frames,
|
||||
duration: media?.duration ?? media?.metadata?.duration,
|
||||
})
|
||||
|
||||
const normalizedKeyTime =
|
||||
proxyType === 'pdf'
|
||||
? `p${Math.max(1, Math.round(second))}`
|
||||
: frameTarget!.frameIndex !== null
|
||||
? `f${frameTarget!.frameIndex}`
|
||||
: frameTarget!.seekTime.toFixed(6)
|
||||
const dedupeKey = `${targetAssetId}:${params.watermarkConfigId ?? ''}:${normalizedKeyTime}:${width}`
|
||||
|
||||
let entry = this.inFlight.get(dedupeKey)
|
||||
if (!entry) {
|
||||
const controller = new AbortController()
|
||||
const promise = this.queue
|
||||
.enqueue(async () => {
|
||||
if (proxyType === 'pdf') {
|
||||
return this.extractPdfPageFrame({
|
||||
asset,
|
||||
media,
|
||||
page: Math.max(1, Math.round(second)),
|
||||
width,
|
||||
signal: controller.signal,
|
||||
})
|
||||
}
|
||||
return this.extractVideoFrame({
|
||||
asset,
|
||||
media,
|
||||
second,
|
||||
seekTime: frameTarget!.seekTime,
|
||||
frameRate: proxyType === '3d' ? TURNTABLE_FPS : media?.metadata?.frameRate,
|
||||
width,
|
||||
watermarkConfigId: params.watermarkConfigId,
|
||||
signal: controller.signal,
|
||||
})
|
||||
}, controller.signal)
|
||||
.finally(() => {
|
||||
if (this.inFlight.get(dedupeKey)?.promise === promise) {
|
||||
this.inFlight.delete(dedupeKey)
|
||||
}
|
||||
})
|
||||
|
||||
entry = { promise, controller, waiters: 0 }
|
||||
this.inFlight.set(dedupeKey, entry)
|
||||
}
|
||||
|
||||
entry.waiters++
|
||||
const currentEntry = entry
|
||||
|
||||
if (!params.signal) {
|
||||
return currentEntry.promise.finally(() => {
|
||||
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
|
||||
})
|
||||
}
|
||||
|
||||
return new Promise<ExtractCommentFrameResult>((resolve, reject) => {
|
||||
let settled = false
|
||||
const cleanup = () => {
|
||||
params.signal?.removeEventListener('abort', onAbort)
|
||||
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
|
||||
if (currentEntry.waiters === 0) {
|
||||
currentEntry.controller.abort()
|
||||
}
|
||||
}
|
||||
const onAbort = () => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
cleanup()
|
||||
reject(new DOMException('Frame extraction aborted', 'AbortError'))
|
||||
}
|
||||
|
||||
params.signal!.addEventListener('abort', onAbort, { once: true })
|
||||
|
||||
currentEntry.promise.then(
|
||||
(res) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
params.signal?.removeEventListener('abort', onAbort)
|
||||
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
|
||||
resolve(res)
|
||||
},
|
||||
(err) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
params.signal?.removeEventListener('abort', onAbort)
|
||||
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
|
||||
reject(err)
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
private inferProxyType(mediaType: string | null): PrismaJson.MediaInfo['proxyType'] | undefined {
|
||||
const lower = (mediaType || '').toLowerCase()
|
||||
if (lower.startsWith('video/')) return 'video'
|
||||
if (lower === 'application/pdf') return 'pdf'
|
||||
if (lower.startsWith('image/')) return 'image'
|
||||
if (lower.startsWith('audio/')) return 'audio'
|
||||
return undefined
|
||||
}
|
||||
|
||||
private async extractVideoFrame(params: {
|
||||
asset: {
|
||||
id: string
|
||||
status: string
|
||||
storageKey: { key: string; isArchived: boolean } | null
|
||||
}
|
||||
media: PrismaJson.MediaInfo | null
|
||||
second: number
|
||||
seekTime: number
|
||||
frameRate?: number | null
|
||||
width: number
|
||||
watermarkConfigId?: string | null
|
||||
signal?: AbortSignal
|
||||
}): Promise<ExtractCommentFrameResult> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
let targetKey: string | null
|
||||
|
||||
if (params.watermarkConfigId) {
|
||||
const wfMap = await watermarkService.getCompletedWatermarkMediaMap(
|
||||
[params.asset.id],
|
||||
params.watermarkConfigId,
|
||||
)
|
||||
const watermarkMedia = wfMap.get(params.asset.id) ?? null
|
||||
targetKey = selectBestVideoProxyKey(watermarkMedia?.videoTranscodes)
|
||||
if (!targetKey) {
|
||||
throw new HTTPException(422, {
|
||||
message: 'Watermarked proxy is not ready for this asset',
|
||||
})
|
||||
}
|
||||
} else {
|
||||
targetKey = selectBestVideoProxyKey(params.media?.videoTranscodes)
|
||||
if (!targetKey) {
|
||||
const originalKey = params.asset.storageKey?.key
|
||||
const isArchived =
|
||||
Boolean(params.asset.storageKey?.isArchived) || params.asset.status === 'archived'
|
||||
if (!originalKey || isArchived) {
|
||||
throw new HTTPException(422, {
|
||||
message: 'Original video file is archived and no proxy is available',
|
||||
})
|
||||
}
|
||||
targetKey = originalKey
|
||||
}
|
||||
}
|
||||
|
||||
const inputSource = await s3Service.resolveInput(bucket, targetKey)
|
||||
const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://')
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shumai-print-frame-'))
|
||||
|
||||
try {
|
||||
const outPath = path.join(tmpDir, `frame-${ulid()}.webp`)
|
||||
const runFfmpeg = async (timestamp: number) => {
|
||||
const args = [
|
||||
'-y',
|
||||
'-loglevel',
|
||||
'warning',
|
||||
...(isRemote
|
||||
? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5']
|
||||
: []),
|
||||
'-ss',
|
||||
timestamp.toFixed(6),
|
||||
'-i',
|
||||
inputSource,
|
||||
'-map',
|
||||
'0:V:0',
|
||||
'-vframes',
|
||||
'1',
|
||||
'-vf',
|
||||
`scale=${params.width}:-2:force_original_aspect_ratio=decrease`,
|
||||
'-c:v',
|
||||
'libwebp',
|
||||
'-q:v',
|
||||
'80',
|
||||
outPath,
|
||||
]
|
||||
await this.execFileFn('ffmpeg', args, {
|
||||
signal: params.signal,
|
||||
timeout: this.timeoutMs,
|
||||
})
|
||||
}
|
||||
|
||||
await runFfmpeg(params.seekTime)
|
||||
|
||||
// If container metadata overestimated totalFrames at EOF, step back one frame and retry.
|
||||
if ((!fs.existsSync(outPath) || fs.statSync(outPath).size === 0) && params.seekTime > 0) {
|
||||
const stepBack = params.frameRate && params.frameRate > 0 ? 1 / params.frameRate : 0.1
|
||||
await runFfmpeg(Math.max(0, params.seekTime - stepBack))
|
||||
}
|
||||
|
||||
if (!fs.existsSync(outPath) || fs.statSync(outPath).size === 0) {
|
||||
throw new HTTPException(404, { message: 'Could not extract frame at requested timestamp' })
|
||||
}
|
||||
|
||||
const buffer = fs.readFileSync(outPath)
|
||||
return { buffer, mimeType: 'image/webp' }
|
||||
} catch (err) {
|
||||
if (err instanceof HTTPException) throw err
|
||||
if ((err as { name?: string })?.name === 'AbortError') throw err
|
||||
logger.error(
|
||||
{ assetId: params.asset.id, second: params.second, err },
|
||||
'Failed to extract video comment frame',
|
||||
)
|
||||
throw new HTTPException(500, { message: 'Failed to extract video frame' })
|
||||
} finally {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
private async extractPdfPageFrame(params: {
|
||||
asset: {
|
||||
id: string
|
||||
status: string
|
||||
storageKey: { key: string; isArchived: boolean } | null
|
||||
}
|
||||
media: PrismaJson.MediaInfo | null
|
||||
page: number
|
||||
width: number
|
||||
signal?: AbortSignal
|
||||
}): Promise<ExtractCommentFrameResult> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const proxyKey = params.media?.pdfTranscode?.key
|
||||
const originalKey = params.asset.storageKey?.key
|
||||
const isArchived =
|
||||
Boolean(params.asset.storageKey?.isArchived) || params.asset.status === 'archived'
|
||||
|
||||
let targetKey: string | null = proxyKey || null
|
||||
if (!targetKey) {
|
||||
if (!originalKey || isArchived) {
|
||||
throw new HTTPException(422, {
|
||||
message: 'Original PDF file is archived and no proxy is available',
|
||||
})
|
||||
}
|
||||
targetKey = originalKey
|
||||
}
|
||||
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shumai-print-pdf-'))
|
||||
try {
|
||||
const pdfPath = path.join(tmpDir, 'source.pdf')
|
||||
await s3Service.downloadToFile(bucket, targetKey, pdfPath)
|
||||
|
||||
const pagePrefix = path.join(tmpDir, 'page')
|
||||
await this.execFileFn(
|
||||
'pdftoppm',
|
||||
[
|
||||
'-png',
|
||||
'-scale-to',
|
||||
String(params.width),
|
||||
'-f',
|
||||
String(params.page),
|
||||
'-l',
|
||||
String(params.page),
|
||||
pdfPath,
|
||||
pagePrefix,
|
||||
],
|
||||
{
|
||||
signal: params.signal,
|
||||
timeout: this.timeoutMs,
|
||||
},
|
||||
)
|
||||
|
||||
const pngFile = fs.readdirSync(tmpDir).find((f) => f.endsWith('.png'))
|
||||
if (!pngFile) {
|
||||
throw new HTTPException(404, { message: `PDF page ${params.page} not found` })
|
||||
}
|
||||
|
||||
const buffer = await sharp(path.join(tmpDir, pngFile), {
|
||||
limitInputPixels: (params.width + 1) ** 2,
|
||||
})
|
||||
.toColorspace('srgb')
|
||||
.webp({ quality: 82 })
|
||||
.toBuffer()
|
||||
|
||||
return { buffer, mimeType: 'image/webp' }
|
||||
} catch (err) {
|
||||
if (err instanceof HTTPException) throw err
|
||||
if ((err as { name?: string })?.name === 'AbortError') throw err
|
||||
logger.error(
|
||||
{ assetId: params.asset.id, page: params.page, err },
|
||||
'Failed to render PDF comment page frame',
|
||||
)
|
||||
throw new HTTPException(500, { message: 'Failed to render PDF page' })
|
||||
} finally {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const commentFrameService = new CommentFrameService()
|
||||
@@ -12,6 +12,8 @@ export interface PostCommentParams {
|
||||
/** Timecode in seconds (or the encoded viewing angle for 3D models). */
|
||||
second?: number
|
||||
attachmentIds?: string[]
|
||||
/** Whether the comment is internal and hidden from public share links (default false). */
|
||||
isInternal?: boolean
|
||||
/** Whether mentions of agents start a chat with them (default true). */
|
||||
triggerAgents?: boolean
|
||||
}
|
||||
@@ -31,6 +33,7 @@ export class CommentService {
|
||||
annotations: params.annotations,
|
||||
second: params.second,
|
||||
attachmentIds: params.attachmentIds ?? [],
|
||||
isInternal: params.isInternal,
|
||||
},
|
||||
{ triggerAgents: params.triggerAgents },
|
||||
)
|
||||
|
||||
@@ -5,6 +5,7 @@ export * from './asset/auto-archive-job'
|
||||
export * from './auth/auth'
|
||||
export * from './authz/authz'
|
||||
export * from './collection/collection'
|
||||
export * from './comment/comment-frame'
|
||||
export * from './invite/invite'
|
||||
export * from './metadata/metadata'
|
||||
export * from './notification/index'
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { KanbanTaskStatus, KanbanTaskPriority } from '@shumai/db/enums'
|
||||
import { KanbanTaskStatus, KanbanTaskPriority, KanbanTaskEventType } from '@shumai/db/enums'
|
||||
import { UNASSIGNED_GOAL_ID } from '@shumai/dtos'
|
||||
import { kanbanService } from './kanban'
|
||||
|
||||
@@ -646,7 +646,7 @@ describe('KanbanService', () => {
|
||||
)
|
||||
|
||||
// Create attachment
|
||||
const att = await kanbanService.createAttachment(team.id, {
|
||||
const att = await kanbanService.createAttachment(team.id, editor.id, {
|
||||
fileName: 'design.png',
|
||||
size: 1024,
|
||||
contentType: 'image/png',
|
||||
@@ -688,6 +688,119 @@ describe('KanbanService', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Comment attachment keys', () => {
|
||||
function payload(key: string) {
|
||||
return [{ id: 'att-1', name: 'file.txt', key, sizeByte: 1, contentType: 'text/plain' }]
|
||||
}
|
||||
|
||||
it('rejects attachment keys that were not issued to the author for the task team', async () => {
|
||||
const { team, editor, reviewer } = await setupTeamAndUsers()
|
||||
const otherTeam = await prisma.team.create({ data: { name: 'Other Team' } })
|
||||
const task = await kanbanService.createTask(team.id, { title: 'Task' }, editor.id, 'editor')
|
||||
|
||||
const foreignTeam = await kanbanService.createAttachment(otherTeam.id, editor.id, {
|
||||
fileName: 'other.png',
|
||||
size: 1,
|
||||
})
|
||||
const otherUser = await kanbanService.createAttachment(team.id, reviewer.id, {
|
||||
fileName: 'theirs.png',
|
||||
size: 1,
|
||||
})
|
||||
const own = await kanbanService.createAttachment(team.id, editor.id, {
|
||||
fileName: 'own.png',
|
||||
size: 1,
|
||||
})
|
||||
const ownDir = own.key.slice(0, own.key.lastIndexOf('/'))
|
||||
|
||||
for (const key of [
|
||||
'files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov',
|
||||
'avatars/someone.png',
|
||||
'kanban/attachments/01JAAAAAAAAAAAAAAAAAAAAAAA/old.png',
|
||||
foreignTeam.key,
|
||||
otherUser.key,
|
||||
`${ownDir}/../../../../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov`,
|
||||
`kanban/attachments/${team.id}/${editor.id}/not-a-ulid/own.png`,
|
||||
]) {
|
||||
await expect(
|
||||
kanbanService.addComment(task.id, editor.id, 'see attached', payload(key)),
|
||||
).rejects.toThrow(/Invalid attachment/)
|
||||
}
|
||||
|
||||
const comments = await kanbanService.listComments(task.id)
|
||||
expect(comments).toHaveLength(0)
|
||||
|
||||
const accepted = await kanbanService.addComment(
|
||||
task.id,
|
||||
editor.id,
|
||||
'see attached',
|
||||
payload(own.key),
|
||||
)
|
||||
expect(accepted.attachments.map((a) => a.id)).toEqual(['att-1'])
|
||||
})
|
||||
|
||||
it('does not sign stored attachment keys outside kanban attachments', async () => {
|
||||
const { team, editor } = await setupTeamAndUsers()
|
||||
const task = await kanbanService.createTask(team.id, { title: 'Task' }, editor.id, 'editor')
|
||||
const legacyKey = 'kanban/attachments/01JAAAAAAAAAAAAAAAAAAAAAAA/notes.txt'
|
||||
|
||||
await prisma.kanbanTaskComment.create({
|
||||
data: {
|
||||
taskId: task.id,
|
||||
authorId: editor.id,
|
||||
body: 'stored before validation',
|
||||
attachments: [
|
||||
{
|
||||
id: 'a',
|
||||
name: 'secret',
|
||||
key: 'files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov',
|
||||
sizeByte: 1,
|
||||
},
|
||||
{
|
||||
id: 'b',
|
||||
name: 'escape',
|
||||
key: 'kanban/attachments/../files/x/master.mov',
|
||||
sizeByte: 1,
|
||||
},
|
||||
{ id: 'c', name: 'notes.txt', key: legacyKey, sizeByte: 1 },
|
||||
{
|
||||
id: 'd',
|
||||
name: 'other-team.txt',
|
||||
key: `kanban/attachments/other-team/${editor.id}/01JAAAAAAAAAAAAAAAAAAAAAAA/x.txt`,
|
||||
sizeByte: 1,
|
||||
},
|
||||
{
|
||||
id: 'e',
|
||||
name: 'current.txt',
|
||||
key: `kanban/attachments/${team.id}/${editor.id}/01JAAAAAAAAAAAAAAAAAAAAAAA/y.txt`,
|
||||
sizeByte: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
const [comment] = await kanbanService.listComments(task.id)
|
||||
expect(comment.attachments.map((a) => a.id)).toEqual(['c', 'e'])
|
||||
|
||||
const detail = await kanbanService.getTask(task.id)
|
||||
expect(detail.comments[0].attachments.map((a) => a.id)).toEqual(['c', 'e'])
|
||||
})
|
||||
|
||||
it('keeps attachment uploads inside the team attachment folder', async () => {
|
||||
const { team, editor } = await setupTeamAndUsers()
|
||||
|
||||
const att = await kanbanService.createAttachment(team.id, editor.id, {
|
||||
fileName: '../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov',
|
||||
size: 1,
|
||||
})
|
||||
|
||||
const parts = att.key.split('/')
|
||||
expect(parts.slice(0, 4)).toEqual(['kanban', 'attachments', team.id, editor.id])
|
||||
expect(parts).toHaveLength(6)
|
||||
expect(parts).not.toContain('..')
|
||||
expect(att.name).toBe('../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov')
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Task Ordering & Fractional Indexing
|
||||
// --------------------------------------------------------------------------
|
||||
@@ -1139,4 +1252,185 @@ describe('KanbanService', () => {
|
||||
expect(pdfDetail?.thumbnailUrl).toContain('posters/doc_poster.webp')
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Project membership
|
||||
// --------------------------------------------------------------------------
|
||||
describe('Project membership', () => {
|
||||
async function setupProjectScopedMember() {
|
||||
const { team, owner, reviewer } = await setupTeamAndUsers()
|
||||
const client = await prisma.user.create({
|
||||
data: { name: 'Client Reviewer', email: 'client@example.com' },
|
||||
})
|
||||
const ownProject = await prisma.project.create({
|
||||
data: { name: 'Client Project', teamId: team.id },
|
||||
})
|
||||
const otherProject = await prisma.project.create({
|
||||
data: { name: 'Internal Project', teamId: team.id },
|
||||
})
|
||||
const clientMember = await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: client.id, role: 'reviewer', scope: 'project' },
|
||||
})
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: ownProject.id, teamMemberId: clientMember.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
const ownTask = await kanbanService.createTask(
|
||||
team.id,
|
||||
{ title: 'Client task', projectId: ownProject.id },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
const otherTask = await kanbanService.createTask(
|
||||
team.id,
|
||||
{ title: 'Internal task', projectId: otherProject.id },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
const teamTask = await kanbanService.createTask(
|
||||
team.id,
|
||||
{ title: 'Team task' },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
const assignedTask = await kanbanService.createTask(
|
||||
team.id,
|
||||
{ title: 'Assigned internal task', projectId: otherProject.id, assigneeId: client.id },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
|
||||
return {
|
||||
team,
|
||||
owner,
|
||||
reviewer,
|
||||
client,
|
||||
otherProject,
|
||||
ownTask,
|
||||
otherTask,
|
||||
teamTask,
|
||||
assignedTask,
|
||||
}
|
||||
}
|
||||
|
||||
it('lists only tasks in their projects, or that they take part in, for project-scoped members', async () => {
|
||||
const { team, client, otherProject, ownTask, assignedTask } = await setupProjectScopedMember()
|
||||
|
||||
const list = await kanbanService.listTasks(team.id, {}, client.id)
|
||||
expect(list.data.map((t) => t.id).sort()).toEqual([ownTask.id, assignedTask.id].sort())
|
||||
expect(list.pageInfo.total).toBe(2)
|
||||
|
||||
const filtered = await kanbanService.listTasks(
|
||||
team.id,
|
||||
{ projectId: otherProject.id },
|
||||
client.id,
|
||||
)
|
||||
expect(filtered.data.map((t) => t.id)).toEqual([assignedTask.id])
|
||||
})
|
||||
|
||||
it('lists every team task for team-scoped members', async () => {
|
||||
const { team, reviewer, ownTask, otherTask, teamTask, assignedTask } =
|
||||
await setupProjectScopedMember()
|
||||
|
||||
const list = await kanbanService.listTasks(team.id, {}, reviewer.id)
|
||||
expect(list.data.map((t) => t.id).sort()).toEqual(
|
||||
[ownTask.id, otherTask.id, teamTask.id, assignedTask.id].sort(),
|
||||
)
|
||||
})
|
||||
|
||||
it('shows only readable dependencies, dependents, and dependency events', async () => {
|
||||
const { owner, team, client, reviewer, ownTask, otherTask, teamTask, assignedTask } =
|
||||
await setupProjectScopedMember()
|
||||
|
||||
await kanbanService.setDependencies(
|
||||
ownTask.id,
|
||||
[otherTask.id, assignedTask.id, teamTask.id],
|
||||
owner.id,
|
||||
)
|
||||
await kanbanService.setDependencies(ownTask.id, [otherTask.id, assignedTask.id], owner.id)
|
||||
await kanbanService.setDependencies(teamTask.id, [ownTask.id], owner.id)
|
||||
await kanbanService.setDependencies(assignedTask.id, [otherTask.id], owner.id)
|
||||
|
||||
const detail = await kanbanService.getTask(ownTask.id, client.id)
|
||||
expect(detail.dependencies.map((task) => task.id)).toEqual([assignedTask.id])
|
||||
expect(detail.dependents).toEqual([])
|
||||
expect(detail.dependencyCount).toBe(1)
|
||||
expect(detail.dependentCount).toBe(0)
|
||||
|
||||
const events = await kanbanService.listEvents(ownTask.id, client.id)
|
||||
for (const history of [detail.events, events]) {
|
||||
expect(
|
||||
history.filter((event) => event.type === KanbanTaskEventType.DEPENDENCY_ADDED),
|
||||
).toEqual([expect.objectContaining({ data: { parentId: assignedTask.id } })])
|
||||
expect(history).toContainEqual(
|
||||
expect.objectContaining({ type: KanbanTaskEventType.CREATED }),
|
||||
)
|
||||
expect(history).not.toContainEqual(
|
||||
expect.objectContaining({ type: KanbanTaskEventType.DEPENDENCY_REMOVED }),
|
||||
)
|
||||
}
|
||||
|
||||
const teamDetail = await kanbanService.getTask(ownTask.id, reviewer.id)
|
||||
expect(teamDetail.dependencies.map((task) => task.id).sort()).toEqual(
|
||||
[otherTask.id, assignedTask.id].sort(),
|
||||
)
|
||||
expect(teamDetail.dependents.map((task) => task.id)).toEqual([teamTask.id])
|
||||
expect(teamDetail.events).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: KanbanTaskEventType.DEPENDENCY_REMOVED,
|
||||
data: { parentId: teamTask.id },
|
||||
}),
|
||||
)
|
||||
|
||||
const summary = await kanbanService.listTasks(team.id, {}, client.id)
|
||||
expect(summary.data).toContainEqual(
|
||||
expect.objectContaining({ id: ownTask.id, dependencyCount: 1, dependentCount: 0 }),
|
||||
)
|
||||
|
||||
const updated = await kanbanService.updateTask(
|
||||
assignedTask.id,
|
||||
{ title: 'Updated assigned task' },
|
||||
client.id,
|
||||
null,
|
||||
)
|
||||
expect(updated).toMatchObject({ dependencyCount: 0, dependentCount: 1 })
|
||||
})
|
||||
|
||||
it('lists no tasks for users outside the team', async () => {
|
||||
const { team } = await setupProjectScopedMember()
|
||||
const outsider = await prisma.user.create({
|
||||
data: { name: 'Outsider', email: 'outsider@example.com' },
|
||||
})
|
||||
|
||||
const list = await kanbanService.listTasks(team.id, {}, outsider.id)
|
||||
expect(list.data).toEqual([])
|
||||
})
|
||||
|
||||
it('lists only readable tasks linked to an asset', async () => {
|
||||
const { team, owner, client, reviewer, otherProject, otherTask, assignedTask } =
|
||||
await setupProjectScopedMember()
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'internal.mp4',
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
projectId: otherProject.id,
|
||||
creatorId: owner.id,
|
||||
},
|
||||
})
|
||||
await kanbanService.linkAsset(team.id, otherTask.id, asset.id)
|
||||
await kanbanService.linkAsset(team.id, assignedTask.id, asset.id)
|
||||
await kanbanService.setDependencies(assignedTask.id, [otherTask.id], owner.id)
|
||||
|
||||
const forClient = await kanbanService.listTasksForAsset(team.id, asset.id, client.id)
|
||||
expect(forClient.map((t) => t.id)).toEqual([assignedTask.id])
|
||||
expect(forClient[0].dependencyCount).toBe(0)
|
||||
|
||||
const forReviewer = await kanbanService.listTasksForAsset(team.id, asset.id, reviewer.id)
|
||||
expect(forReviewer.map((t) => t.id).sort()).toEqual([otherTask.id, assignedTask.id].sort())
|
||||
expect(forReviewer).toContainEqual(
|
||||
expect.objectContaining({ id: assignedTask.id, dependencyCount: 1 }),
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -7,6 +7,7 @@ import { paginateQuery } from '../pagination'
|
||||
import { getAvatarUrl } from '../user/avatar'
|
||||
import { s3Service } from '../s3/s3'
|
||||
import { getProxyType } from '../utils/mime'
|
||||
import { sanitizeFilename } from '../utils/filename'
|
||||
import { assetService } from '../asset/asset'
|
||||
import type {
|
||||
CreateKanbanGoalRequest,
|
||||
@@ -28,6 +29,73 @@ import type {
|
||||
} from '@shumai/dtos'
|
||||
import { UNASSIGNED_GOAL_ID } from '@shumai/dtos'
|
||||
|
||||
type TaskEventWithActor = Prisma.KanbanTaskEventGetPayload<{ include: { actor: true } }>
|
||||
|
||||
function dependencyEventParentId(event: TaskEventWithActor): string | undefined {
|
||||
if (
|
||||
event.type === KanbanTaskEventType.DEPENDENCY_ADDED ||
|
||||
event.type === KanbanTaskEventType.DEPENDENCY_REMOVED
|
||||
) {
|
||||
const parentId = event.data?.parentId
|
||||
if (typeof parentId === 'string') return parentId
|
||||
}
|
||||
}
|
||||
|
||||
function taskRelationCountSelect(
|
||||
taskFilter: Prisma.KanbanTaskWhereInput | undefined,
|
||||
): Prisma.KanbanTaskCountOutputTypeSelect {
|
||||
return {
|
||||
comments: true,
|
||||
assets: true,
|
||||
dependencies: taskFilter ? { where: { parent: taskFilter } } : true,
|
||||
dependents: taskFilter ? { where: { child: taskFilter } } : true,
|
||||
}
|
||||
}
|
||||
|
||||
const ULID_PATTERN = /^[0-9A-HJKMNP-TV-Z]{26}$/
|
||||
|
||||
function isSafeKeySegment(segment: string): boolean {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
return segment !== '' && segment !== '.' && segment !== '..' && !/[\\\x00-\x1f\x7f]/.test(segment)
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a comment attachment key issued by `createAttachment`:
|
||||
* `kanban/attachments/<teamId>/<uploaderId>/<ulid>/<file name>`.
|
||||
*/
|
||||
function parseAttachmentKey(key: string): { teamId: string; uploaderId: string } | null {
|
||||
const parts = key.split('/')
|
||||
if (
|
||||
parts.length !== 6 ||
|
||||
parts[0] !== 'kanban' ||
|
||||
parts[1] !== 'attachments' ||
|
||||
!isSafeKeySegment(parts[2]) ||
|
||||
!isSafeKeySegment(parts[3]) ||
|
||||
!ULID_PATTERN.test(parts[4]) ||
|
||||
!isSafeKeySegment(parts[5])
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return { teamId: parts[2], uploaderId: parts[3] }
|
||||
}
|
||||
|
||||
/** Keys of comment attachments stored before keys carried the team and uploader. */
|
||||
function isLegacyAttachmentKey(key: string): boolean {
|
||||
const parts = key.split('/')
|
||||
return (
|
||||
parts.length === 4 &&
|
||||
parts[0] === 'kanban' &&
|
||||
parts[1] === 'attachments' &&
|
||||
ULID_PATTERN.test(parts[2]) &&
|
||||
isSafeKeySegment(parts[3])
|
||||
)
|
||||
}
|
||||
|
||||
/** Whether a stored attachment key may be signed for a comment on a task in `teamId`. */
|
||||
function isReadableAttachmentKey(key: string, teamId: string): boolean {
|
||||
return parseAttachmentKey(key)?.teamId === teamId || isLegacyAttachmentKey(key)
|
||||
}
|
||||
|
||||
export class KanbanService {
|
||||
// --------------------------------------------------------------------------
|
||||
// Goal CRUD
|
||||
@@ -314,7 +382,7 @@ export class KanbanService {
|
||||
})
|
||||
}
|
||||
|
||||
async getTask(taskId: string): Promise<KanbanTaskDetail> {
|
||||
async getTask(taskId: string, viewerId?: string): Promise<KanbanTaskDetail> {
|
||||
const task = await prisma.kanbanTask.findUnique({
|
||||
where: { id: taskId },
|
||||
include: {
|
||||
@@ -354,27 +422,38 @@ export class KanbanService {
|
||||
throw new HTTPException(404, { message: 'Task not found' })
|
||||
}
|
||||
|
||||
const readableIds = await this.readableRelatedTaskIds(task.teamId, viewerId, [
|
||||
...task.dependencies.map((link) => link.parentId),
|
||||
...task.dependents.map((link) => link.childId),
|
||||
...task.events.map(dependencyEventParentId).filter((id) => id !== undefined),
|
||||
])
|
||||
const dependencies = task.dependencies.filter(
|
||||
(link) => !readableIds || readableIds.has(link.parentId),
|
||||
)
|
||||
const dependents = task.dependents.filter(
|
||||
(link) => !readableIds || readableIds.has(link.childId),
|
||||
)
|
||||
const latestStatusEvent = await this.resolveLatestStatusEvent(taskId, task.status)
|
||||
const resolvedAssets = await this.resolveTaskAssetInfos(task.assets)
|
||||
|
||||
const baseInfo = await this.toTaskInfo(task, {
|
||||
latestStatusEvent,
|
||||
dependencyCount: task.dependencies.length,
|
||||
dependentCount: task.dependents.length,
|
||||
dependencyCount: dependencies.length,
|
||||
dependentCount: dependents.length,
|
||||
commentCount: task.comments.length,
|
||||
assetCount: task.assets.length,
|
||||
})
|
||||
|
||||
return {
|
||||
...baseInfo,
|
||||
dependencies: task.dependencies.map((d) => ({
|
||||
dependencies: dependencies.map((d) => ({
|
||||
id: d.parent.id,
|
||||
title: d.parent.title,
|
||||
isAgentTask: d.parent.isAgentTask,
|
||||
status: d.parent.status,
|
||||
priority: d.parent.priority,
|
||||
})),
|
||||
dependents: task.dependents.map((d) => ({
|
||||
dependents: dependents.map((d) => ({
|
||||
id: d.child.id,
|
||||
title: d.child.title,
|
||||
isAgentTask: d.child.isAgentTask,
|
||||
@@ -392,29 +471,12 @@ export class KanbanService {
|
||||
image: await getAvatarUrl(c.author.image),
|
||||
},
|
||||
body: c.body,
|
||||
attachments: await this.resolveCommentAttachments(c.attachments),
|
||||
attachments: await this.resolveCommentAttachments(c.attachments, task.teamId),
|
||||
createdAt: c.createdAt.toISOString(),
|
||||
updatedAt: c.updatedAt.toISOString(),
|
||||
})),
|
||||
),
|
||||
events: await Promise.all(
|
||||
task.events.map(async (e) => ({
|
||||
id: e.id,
|
||||
taskId: e.taskId,
|
||||
actor: e.actor
|
||||
? {
|
||||
id: e.actor.id,
|
||||
name: e.actor.name,
|
||||
image: await getAvatarUrl(e.actor.image),
|
||||
}
|
||||
: null,
|
||||
type: e.type,
|
||||
fromStatus: e.fromStatus,
|
||||
toStatus: e.toStatus,
|
||||
data: (e.data as Record<string, unknown>) ?? null,
|
||||
createdAt: e.createdAt.toISOString(),
|
||||
})),
|
||||
),
|
||||
events: await this.resolveTaskEvents(task.events, readableIds),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -659,7 +721,8 @@ export class KanbanService {
|
||||
}
|
||||
|
||||
const latestStatusEvent = await this.resolveLatestStatusEvent(taskId, updated.status)
|
||||
const counts = await this.getTaskCounts(taskId)
|
||||
const taskFilter = await this.readableTaskFilter(updated.teamId, actorId)
|
||||
const counts = await this.getTaskCounts(taskId, taskFilter)
|
||||
|
||||
return await this.toTaskInfo(updated, {
|
||||
latestStatusEvent,
|
||||
@@ -704,10 +767,54 @@ export class KanbanService {
|
||||
return taskInfo
|
||||
}
|
||||
|
||||
/**
|
||||
* Limits kanban tasks to those a user may read. Team-scoped members see every
|
||||
* task in the team; project-scoped members see tasks in the projects they
|
||||
* belong to and tasks they created, report, or are assigned to.
|
||||
*/
|
||||
private async readableTaskFilter(
|
||||
teamId: string,
|
||||
userId: string | undefined,
|
||||
): Promise<Prisma.KanbanTaskWhereInput | undefined> {
|
||||
if (!userId) return
|
||||
const member = await prisma.teamMember.findUnique({
|
||||
where: { teamIdUserId: { teamId, userId } },
|
||||
})
|
||||
if (!member) return { id: { in: [] } }
|
||||
if (member.scope === 'team') return
|
||||
return {
|
||||
teamId,
|
||||
OR: [
|
||||
{ project: { members: { some: { teamMemberId: member.id } } } },
|
||||
{ creatorId: userId },
|
||||
{ reporterId: userId },
|
||||
{ assigneeId: userId },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
private async readableRelatedTaskIds(
|
||||
teamId: string,
|
||||
viewerId: string | undefined,
|
||||
relatedIds: string[],
|
||||
): Promise<Set<string> | undefined> {
|
||||
if (relatedIds.length === 0) return
|
||||
const filter = await this.readableTaskFilter(teamId, viewerId)
|
||||
if (!filter) return
|
||||
|
||||
const tasks = await prisma.kanbanTask.findMany({
|
||||
where: { id: { in: [...new Set(relatedIds)] }, AND: [filter] },
|
||||
select: { id: true },
|
||||
})
|
||||
return new Set(tasks.map((task) => task.id))
|
||||
}
|
||||
|
||||
async listTasks(
|
||||
teamId: string,
|
||||
params: ListKanbanTasksRequest,
|
||||
viewerId?: string,
|
||||
): Promise<{ data: KanbanTaskInfo[]; pageInfo: { total?: number; cursor?: string } }> {
|
||||
const taskFilter = await this.readableTaskFilter(teamId, viewerId)
|
||||
const where: Prisma.KanbanTaskWhereInput = {
|
||||
teamId,
|
||||
...(params.status && { status: params.status }),
|
||||
@@ -721,6 +828,7 @@ export class KanbanService {
|
||||
...(params.priority && { priority: params.priority }),
|
||||
...(params.assigneeId && { assigneeId: params.assigneeId }),
|
||||
...(params.reporterId && { reporterId: params.reporterId }),
|
||||
...(taskFilter && { AND: [taskFilter] }),
|
||||
}
|
||||
|
||||
return await paginateQuery(
|
||||
@@ -732,14 +840,7 @@ export class KanbanService {
|
||||
reporter: true,
|
||||
assignee: true,
|
||||
goal: true,
|
||||
_count: {
|
||||
select: {
|
||||
comments: true,
|
||||
dependencies: true,
|
||||
dependents: true,
|
||||
assets: true,
|
||||
},
|
||||
},
|
||||
_count: { select: taskRelationCountSelect(taskFilter) },
|
||||
},
|
||||
orderBy: [{ sortIndex: 'asc' }, { id: 'asc' }],
|
||||
skip,
|
||||
@@ -869,9 +970,10 @@ export class KanbanService {
|
||||
|
||||
async createAttachment(
|
||||
teamId: string,
|
||||
uploaderId: string,
|
||||
req: { fileName: string; size: number; contentType?: string },
|
||||
): Promise<PostKanbanAttachmentResponse> {
|
||||
const key = `kanban/attachments/${ulid()}/${req.fileName}`
|
||||
const key = `kanban/attachments/${teamId}/${uploaderId}/${ulid()}/${sanitizeFilename(req.fileName)}`
|
||||
const uploadUrl = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'PUT')
|
||||
const proxyType = getProxyType(req.contentType, req.fileName)
|
||||
|
||||
@@ -895,6 +997,16 @@ export class KanbanService {
|
||||
const task = await prisma.kanbanTask.findUnique({ where: { id: taskId } })
|
||||
if (!task) throw new HTTPException(404, { message: 'Task not found' })
|
||||
|
||||
// Attachments are uploaded through createAttachment. Only keys it issued to the
|
||||
// comment author for this task's team may be stored and signed later.
|
||||
const isOwnUpload = (key: string) => {
|
||||
const parsed = parseAttachmentKey(key)
|
||||
return parsed?.teamId === task.teamId && parsed.uploaderId === authorId
|
||||
}
|
||||
if (attachments?.some((att) => !isOwnUpload(att.key))) {
|
||||
throw new HTTPException(400, { message: 'Invalid attachment' })
|
||||
}
|
||||
|
||||
const comment = await prisma.$transaction(async (tx) => {
|
||||
const c = await tx.kanbanTaskComment.create({
|
||||
data: {
|
||||
@@ -917,7 +1029,10 @@ export class KanbanService {
|
||||
return c
|
||||
})
|
||||
|
||||
const resolvedAttachments = await this.resolveCommentAttachments(comment.attachments)
|
||||
const resolvedAttachments = await this.resolveCommentAttachments(
|
||||
comment.attachments,
|
||||
task.teamId,
|
||||
)
|
||||
|
||||
return {
|
||||
id: comment.id,
|
||||
@@ -935,6 +1050,12 @@ export class KanbanService {
|
||||
}
|
||||
|
||||
async listComments(taskId: string): Promise<KanbanCommentInfo[]> {
|
||||
const task = await prisma.kanbanTask.findUnique({
|
||||
where: { id: taskId },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!task) throw new HTTPException(404, { message: 'Task not found' })
|
||||
|
||||
const comments = await prisma.kanbanTaskComment.findMany({
|
||||
where: { taskId },
|
||||
include: { author: true },
|
||||
@@ -951,7 +1072,7 @@ export class KanbanService {
|
||||
image: await getAvatarUrl(c.author.image),
|
||||
},
|
||||
body: c.body,
|
||||
attachments: await this.resolveCommentAttachments(c.attachments),
|
||||
attachments: await this.resolveCommentAttachments(c.attachments, task.teamId),
|
||||
createdAt: c.createdAt.toISOString(),
|
||||
updatedAt: c.updatedAt.toISOString(),
|
||||
})),
|
||||
@@ -981,7 +1102,8 @@ export class KanbanService {
|
||||
}
|
||||
|
||||
private async resolveCommentAttachments(
|
||||
attachments?: PrismaJson.KanbanCommentAttachmentList | null,
|
||||
attachments: PrismaJson.KanbanCommentAttachmentList | null | undefined,
|
||||
teamId: string,
|
||||
): Promise<KanbanAttachmentInfo[]> {
|
||||
if (!attachments || !Array.isArray(attachments) || attachments.length === 0) {
|
||||
return []
|
||||
@@ -989,29 +1111,50 @@ export class KanbanService {
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
return await Promise.all(
|
||||
attachments.map(async (att) => {
|
||||
const url = await s3Service.presign(bucket, att.key, 'GET')
|
||||
return {
|
||||
id: att.id,
|
||||
name: att.name,
|
||||
sizeByte: att.sizeByte,
|
||||
contentType: att.contentType,
|
||||
url,
|
||||
proxyType: att.proxyType,
|
||||
}
|
||||
}),
|
||||
attachments
|
||||
.filter((att) => typeof att.key === 'string' && isReadableAttachmentKey(att.key, teamId))
|
||||
.map(async (att) => {
|
||||
const url = await s3Service.presign(bucket, att.key, 'GET')
|
||||
return {
|
||||
id: att.id,
|
||||
name: att.name,
|
||||
sizeByte: att.sizeByte,
|
||||
contentType: att.contentType,
|
||||
url,
|
||||
proxyType: att.proxyType,
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
async listEvents(taskId: string): Promise<KanbanEventInfo[]> {
|
||||
const events = await prisma.kanbanTaskEvent.findMany({
|
||||
where: { taskId },
|
||||
include: { actor: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
async listEvents(taskId: string, viewerId?: string): Promise<KanbanEventInfo[]> {
|
||||
const task = await prisma.kanbanTask.findUnique({
|
||||
where: { id: taskId },
|
||||
select: {
|
||||
teamId: true,
|
||||
events: { include: { actor: true }, orderBy: { createdAt: 'desc' } },
|
||||
},
|
||||
})
|
||||
if (!task) return []
|
||||
const readableIds = await this.readableRelatedTaskIds(
|
||||
task.teamId,
|
||||
viewerId,
|
||||
task.events.map(dependencyEventParentId).filter((id) => id !== undefined),
|
||||
)
|
||||
return await this.resolveTaskEvents(task.events, readableIds)
|
||||
}
|
||||
|
||||
private async resolveTaskEvents(
|
||||
events: TaskEventWithActor[],
|
||||
readableIds: Set<string> | undefined,
|
||||
): Promise<KanbanEventInfo[]> {
|
||||
const visibleEvents = events.filter((event) => {
|
||||
const parentId = dependencyEventParentId(event)
|
||||
return !readableIds || parentId === undefined || readableIds.has(parentId)
|
||||
})
|
||||
|
||||
return await Promise.all(
|
||||
events.map(async (e) => ({
|
||||
visibleEvents.map(async (e) => ({
|
||||
id: e.id,
|
||||
taskId: e.taskId,
|
||||
actor: e.actor
|
||||
@@ -1024,7 +1167,7 @@ export class KanbanService {
|
||||
type: e.type,
|
||||
fromStatus: e.fromStatus,
|
||||
toStatus: e.toStatus,
|
||||
data: (e.data as Record<string, unknown>) ?? null,
|
||||
data: e.data ?? null,
|
||||
createdAt: e.createdAt.toISOString(),
|
||||
})),
|
||||
)
|
||||
@@ -1115,9 +1258,17 @@ export class KanbanService {
|
||||
return await this.resolveTaskAssetInfos(links)
|
||||
}
|
||||
|
||||
async listTasksForAsset(teamId: string, assetId: string): Promise<KanbanTaskInfo[]> {
|
||||
async listTasksForAsset(
|
||||
teamId: string,
|
||||
assetId: string,
|
||||
viewerId?: string,
|
||||
): Promise<KanbanTaskInfo[]> {
|
||||
const taskFilter = await this.readableTaskFilter(teamId, viewerId)
|
||||
const links = await prisma.kanbanTaskAsset.findMany({
|
||||
where: { assetId },
|
||||
where: {
|
||||
assetId,
|
||||
task: { teamId, ...taskFilter },
|
||||
},
|
||||
include: {
|
||||
task: {
|
||||
include: {
|
||||
@@ -1125,24 +1276,15 @@ export class KanbanService {
|
||||
reporter: true,
|
||||
assignee: true,
|
||||
goal: true,
|
||||
_count: {
|
||||
select: {
|
||||
comments: true,
|
||||
dependencies: true,
|
||||
dependents: true,
|
||||
assets: true,
|
||||
},
|
||||
},
|
||||
_count: { select: taskRelationCountSelect(taskFilter) },
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
})
|
||||
|
||||
const matchingLinks = links.filter((l) => l.task && l.task.teamId === teamId)
|
||||
|
||||
return await Promise.all(
|
||||
matchingLinks.map(async (l) => {
|
||||
links.map(async (l) => {
|
||||
const t = l.task
|
||||
const latestStatusEvent = await this.resolveLatestStatusEvent(t.id, t.status)
|
||||
return await this.toTaskInfo(t, {
|
||||
@@ -1195,19 +1337,25 @@ export class KanbanService {
|
||||
}
|
||||
}
|
||||
|
||||
private async getTaskCounts(taskId: string): Promise<{
|
||||
private async getTaskCounts(
|
||||
taskId: string,
|
||||
taskFilter?: Prisma.KanbanTaskWhereInput,
|
||||
): Promise<{
|
||||
commentCount: number
|
||||
dependencyCount: number
|
||||
dependentCount: number
|
||||
assetCount: number
|
||||
}> {
|
||||
const [commentCount, dependencyCount, dependentCount, assetCount] = await Promise.all([
|
||||
prisma.kanbanTaskComment.count({ where: { taskId } }),
|
||||
prisma.kanbanTaskLink.count({ where: { childId: taskId } }),
|
||||
prisma.kanbanTaskLink.count({ where: { parentId: taskId } }),
|
||||
prisma.kanbanTaskAsset.count({ where: { taskId } }),
|
||||
])
|
||||
return { commentCount, dependencyCount, dependentCount, assetCount }
|
||||
const task = await prisma.kanbanTask.findUnique({
|
||||
where: { id: taskId },
|
||||
select: { _count: { select: taskRelationCountSelect(taskFilter) } },
|
||||
})
|
||||
return {
|
||||
commentCount: task?._count.comments ?? 0,
|
||||
dependencyCount: task?._count.dependencies ?? 0,
|
||||
dependentCount: task?._count.dependents ?? 0,
|
||||
assetCount: task?._count.assets ?? 0,
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveTaskAssetInfos(
|
||||
|
||||
@@ -240,7 +240,12 @@ describe('collaboration Operations', () => {
|
||||
message: 'Too dark at the start',
|
||||
second: 2.5,
|
||||
})
|
||||
expect(comment).toEqual({ id: expect.any(String), assetId: file, replyToId: null })
|
||||
expect(comment).toEqual({
|
||||
id: expect.any(String),
|
||||
assetId: file,
|
||||
replyToId: null,
|
||||
isInternal: false,
|
||||
})
|
||||
|
||||
const reply = await runOperation(createCommentOp, as(owner, 'agent', undefined), {
|
||||
assetId: file,
|
||||
@@ -248,9 +253,17 @@ describe('collaboration Operations', () => {
|
||||
replyToId: comment.id,
|
||||
})
|
||||
expect(reply.replyToId).toBe(comment.id)
|
||||
expect(reply.isInternal).toBe(false)
|
||||
|
||||
const internalComment = await runOperation(createCommentOp, as(reviewer), {
|
||||
assetId: file,
|
||||
message: 'Internal budget note',
|
||||
isInternal: true,
|
||||
})
|
||||
expect(internalComment.isInternal).toBe(true)
|
||||
|
||||
const listed = await runOperation(listCommentsOp, as(reviewer), { assetId: file })
|
||||
expect(listed.total).toBe(1)
|
||||
expect(listed.total).toBe(2)
|
||||
expect(listed.data).toEqual([
|
||||
expect.objectContaining({
|
||||
id: comment.id,
|
||||
@@ -258,14 +271,21 @@ describe('collaboration Operations', () => {
|
||||
author: { id: reviewer.id, name: 'Reviewer' },
|
||||
second: 2.5,
|
||||
resolved: false,
|
||||
isInternal: false,
|
||||
replies: [
|
||||
expect.objectContaining({
|
||||
id: reply.id,
|
||||
message: 'Brightened in v2',
|
||||
author: { id: owner.id, name: 'Owner' },
|
||||
isInternal: false,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
expect.objectContaining({
|
||||
id: internalComment.id,
|
||||
message: 'Internal budget note',
|
||||
isInternal: true,
|
||||
}),
|
||||
])
|
||||
|
||||
await expect(
|
||||
@@ -276,7 +296,7 @@ describe('collaboration Operations', () => {
|
||||
).resolves.toEqual({ commentId: comment.id, resolved: false })
|
||||
|
||||
const created = await auditRows(AuditAction.comment_create)
|
||||
expect(created.map((r) => r.itemId)).toEqual([comment.id, reply.id])
|
||||
expect(created.map((r) => r.itemId)).toEqual([comment.id, reply.id, internalComment.id])
|
||||
expect(created.every((r) => r.teamId === teamId && r.projectId === projectId)).toBe(true)
|
||||
const completed = await auditRows(AuditAction.comment_complete)
|
||||
expect(completed).toHaveLength(2)
|
||||
|
||||
@@ -20,10 +20,16 @@ export const createCommentOp = implementOperation(createComment, {
|
||||
message: input.message,
|
||||
replyToId: input.replyToId,
|
||||
second: input.second,
|
||||
isInternal: input.isInternal,
|
||||
// Mentions in comments written by Shumai's own agent must not start more agent runs.
|
||||
triggerAgents: ctx.via !== 'agent',
|
||||
})
|
||||
return { id: comment.id, assetId: comment.assetId, replyToId: input.replyToId ?? null }
|
||||
return {
|
||||
id: comment.id,
|
||||
assetId: comment.assetId,
|
||||
replyToId: input.replyToId ?? null,
|
||||
isInternal: comment.isInternal,
|
||||
}
|
||||
},
|
||||
audit: (input, output) => [
|
||||
{ action: AuditAction.comment_create, itemId: output.id, contextAssetId: input.assetId },
|
||||
|
||||
@@ -15,6 +15,7 @@ function toCommentFields(comment: CommentInfo) {
|
||||
second: comment.second,
|
||||
hasMarkup: Array.isArray(comment.annotations) && comment.annotations.length > 0,
|
||||
attachmentCount: comment.attachments.length,
|
||||
isInternal: comment.isInternal,
|
||||
createdAt: comment.createdAt,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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')
|
||||
@@ -651,6 +752,18 @@ describe('S3Service implementations', () => {
|
||||
expect(size).toBe(11)
|
||||
})
|
||||
|
||||
it('rejects keys with parent directory segments', async () => {
|
||||
await localS3.putObject('test-bucket', 'files/a/master.mov', 'original', 8)
|
||||
|
||||
await expect(
|
||||
localS3.putObject('test-bucket', 'attachments/x/../../files/a/master.mov', 'evil', 4),
|
||||
).rejects.toThrow(/path traversal/)
|
||||
await expect(
|
||||
localS3.getObjectSize('test-bucket', 'attachments/x/..\\..\\files/a/master.mov'),
|
||||
).rejects.toThrow(/path traversal/)
|
||||
expect(await localS3.getObjectSize('test-bucket', 'files/a/master.mov')).toBe(8)
|
||||
})
|
||||
|
||||
it('removes empty embedding chunk directories after deleting the last chunk', async () => {
|
||||
const key = 'files/asset-1/tmp-embedding-chunks/chunk.mp4'
|
||||
await localS3.putObject('test-bucket', key, 'chunk', 5)
|
||||
@@ -807,6 +920,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 +972,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 +1227,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)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+68
-36
@@ -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
|
||||
|
||||
@@ -823,6 +850,11 @@ export class LocalStorageService implements S3Service {
|
||||
}
|
||||
|
||||
private getFilePath(bucket: string, key: string): string {
|
||||
// Object keys are flat names: a `..` segment must not be resolved into another
|
||||
// object's path (S3 keeps it literally).
|
||||
if (key.split(/[\\/]/).includes('..') || bucket.split(/[\\/]/).includes('..')) {
|
||||
throw new Error(`Invalid path: potential path traversal detected`)
|
||||
}
|
||||
const filePath = path.join(this.basePath, bucket, key)
|
||||
if (!filePath.startsWith(this.basePath)) {
|
||||
throw new Error(`Invalid path: potential path traversal detected`)
|
||||
@@ -1094,12 +1126,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)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -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
@@ -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()
|
||||
|
||||
@@ -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`)
|
||||
|
||||
@@ -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,158 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { shareActivityService } from './share-activity'
|
||||
import { shareService } from './share'
|
||||
|
||||
describe('Share activity', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let shareId: string
|
||||
let projectId: string
|
||||
let assetId: string
|
||||
let userId: string
|
||||
|
||||
beforeEach(async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Reviewer',
|
||||
email: 'reviewer@example.com',
|
||||
image: 'https://example.com/avatar',
|
||||
},
|
||||
})
|
||||
const team = await prisma.team.create({ data: { name: 'Team' } })
|
||||
const project = await prisma.project.create({ data: { name: 'Project', teamId: team.id } })
|
||||
const asset = await prisma.asset.create({
|
||||
data: { name: 'Review Cut', projectId: project.id, type: 'file', status: 'processed' },
|
||||
})
|
||||
const share = await shareService.createShareLink(project.id, { name: 'Review' }, user.id)
|
||||
shareId = share.id
|
||||
projectId = project.id
|
||||
assetId = asset.id
|
||||
userId = user.id
|
||||
})
|
||||
|
||||
it('sets the last view and counts every visit, including a duplicate deep-link visit', async () => {
|
||||
expect(await shareService.getShareLink(shareId)).toMatchObject({ views: 0, lastViewedAt: null })
|
||||
await shareActivityService.recordView(shareId, { assetId, isShareEntry: true })
|
||||
const first = await prisma.shareLink.findUniqueOrThrow({ where: { id: shareId } })
|
||||
expect(first).toMatchObject({ views: 1, lastViewedAt: expect.any(Date) })
|
||||
|
||||
const prior = new Date('2020-01-01T00:00:00Z')
|
||||
await prisma.shareLink.update({ where: { id: shareId }, data: { lastViewedAt: prior } })
|
||||
await shareActivityService.recordView(shareId, { assetId, isShareEntry: true })
|
||||
|
||||
const share = await prisma.shareLink.findUniqueOrThrow({ where: { id: shareId } })
|
||||
expect(share.views).toBe(2)
|
||||
expect(share.lastViewedAt!.getTime()).toBeGreaterThan(prior.getTime())
|
||||
expect(await prisma.shareActivity.findMany({ where: { shareLinkId: shareId } })).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ kind: 'share_viewed', userId: null, assetId: null }),
|
||||
expect.objectContaining({ kind: 'asset_viewed', userId: null, assetId }),
|
||||
]),
|
||||
)
|
||||
expect(await prisma.shareActivity.count({ where: { shareLinkId: shareId } })).toBe(2)
|
||||
})
|
||||
|
||||
it('uses a rolling window from the last recorded event and permits a match after 30 minutes', async () => {
|
||||
const event = { kind: 'asset_downloaded', userId, assetId } as const
|
||||
const record = await prisma.shareActivity.create({
|
||||
data: {
|
||||
...event,
|
||||
shareLinkId: shareId,
|
||||
createdAt: new Date(Date.now() - 29 * 60_000),
|
||||
},
|
||||
})
|
||||
await shareActivityService.recordEvent(shareId, event)
|
||||
expect(await prisma.shareActivity.count({ where: { shareLinkId: shareId } })).toBe(1)
|
||||
expect(await prisma.shareActivity.findUnique({ where: { id: record.id } })).toEqual(record)
|
||||
|
||||
await prisma.shareActivity.update({
|
||||
where: { id: record.id },
|
||||
data: { createdAt: new Date(Date.now() - 30 * 60_000) },
|
||||
})
|
||||
await shareActivityService.recordEvent(shareId, event)
|
||||
expect(await prisma.shareActivity.count({ where: { shareLinkId: shareId } })).toBe(2)
|
||||
})
|
||||
|
||||
it('scopes the deduplication identity to the share, event kind, user and asset', async () => {
|
||||
const otherShare = await shareService.createShareLink(projectId, { name: 'Other' })
|
||||
const otherAsset = await prisma.asset.create({
|
||||
data: { name: 'Other Cut', projectId, type: 'file', status: 'processed' },
|
||||
})
|
||||
await shareActivityService.recordView(shareId, { assetId })
|
||||
await shareActivityService.recordView(shareId, { assetId, userId })
|
||||
await shareActivityService.recordView(shareId, { assetId: otherAsset.id, userId })
|
||||
await shareActivityService.recordView(otherShare.id, { assetId, userId })
|
||||
await shareActivityService.recordEvent(shareId, { kind: 'asset_downloaded', assetId, userId })
|
||||
|
||||
expect(await prisma.shareActivity.count({ where: { shareLinkId: shareId } })).toBe(4)
|
||||
expect(await prisma.shareActivity.count({ where: { shareLinkId: otherShare.id } })).toBe(1)
|
||||
expect(await shareService.getShareLink(shareId)).toMatchObject({ views: 3 })
|
||||
})
|
||||
|
||||
it('records a share comment in its transaction while preserving every comment', async () => {
|
||||
const comment = { assetId, userId, message: 'Looks good', attachmentIds: [] }
|
||||
await assetService.createComment(comment, { shareLinkId: shareId })
|
||||
await assetService.createComment({ ...comment, message: 'Ready' }, { shareLinkId: shareId })
|
||||
await assetService.createComment({ ...comment, message: 'Workspace comment' })
|
||||
expect(await prisma.assetComment.count({ where: { assetId } })).toBe(3)
|
||||
const events = await prisma.shareActivity.findMany({ where: { shareLinkId: shareId } })
|
||||
expect(events).toMatchObject([{ kind: 'comment_created', assetId, userId }])
|
||||
|
||||
await expect(assetService.createComment(comment, { shareLinkId: 'missing' })).rejects.toThrow(
|
||||
'Share link not found',
|
||||
)
|
||||
expect(await prisma.assetComment.count({ where: { assetId } })).toBe(3)
|
||||
})
|
||||
|
||||
it('paginates the feed and resolves current names and missing assets', async () => {
|
||||
await shareActivityService.recordView(shareId, { assetId, userId, isShareEntry: true })
|
||||
await prisma.asset.update({ where: { id: assetId }, data: { name: 'Renamed Cut' } })
|
||||
const first = await shareActivityService.list(shareId, { first: 1 })
|
||||
expect(first.pageInfo).toMatchObject({ total: 2, cursor: expect.any(String) })
|
||||
const second = await shareActivityService.list(shareId, {
|
||||
first: 1,
|
||||
after: first.pageInfo.cursor,
|
||||
})
|
||||
expect(first.data).toHaveLength(1)
|
||||
expect(second.data).toHaveLength(1)
|
||||
expect(first.data[0].id > second.data[0].id).toBe(true)
|
||||
expect([...first.data, ...second.data]).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: 'asset_viewed',
|
||||
user: { name: 'Reviewer', image: 'https://example.com/avatar' },
|
||||
asset: { id: assetId, name: 'Renamed Cut' },
|
||||
}),
|
||||
expect.objectContaining({ kind: 'share_viewed', asset: null }),
|
||||
]),
|
||||
)
|
||||
|
||||
await prisma.asset.update({ where: { id: assetId }, data: { isDeleted: true } })
|
||||
const getAssetEvent = async () =>
|
||||
(await shareActivityService.list(shareId, {})).data.find(
|
||||
(event) => event.kind === 'asset_viewed',
|
||||
)
|
||||
expect((await getAssetEvent())?.asset).toEqual({ id: assetId, name: null })
|
||||
await prisma.asset.delete({ where: { id: assetId } })
|
||||
expect((await getAssetEvent())?.asset).toEqual({ id: assetId, name: null })
|
||||
await shareService.deleteShareLink(shareId)
|
||||
expect(await prisma.shareActivity.count({ where: { shareLinkId: shareId } })).toBe(0)
|
||||
})
|
||||
|
||||
it('checks that a share root is accessible before accepting a root view', async () => {
|
||||
const share = await shareService.getShareLink(shareId)
|
||||
await expect(shareService.verifyPublicAccess(shareId, undefined)).resolves.toMatchObject({
|
||||
id: shareId,
|
||||
})
|
||||
await prisma.asset.update({
|
||||
where: { id: share.rootFolderId },
|
||||
data: { isDeleted: true },
|
||||
})
|
||||
await expect(shareService.verifyPublicAccess(shareId, undefined)).rejects.toThrow(
|
||||
'Asset is not shared',
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,129 @@
|
||||
import { prisma, type Prisma } from '@shumai/db'
|
||||
import type { ShareActivityInfo, ShareActivityKind } from '@shumai/dtos'
|
||||
import { paginateQuery, type PaginationParams } from '@shumai/core/src/pagination'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { ShareLinkNotFoundError } from './errors'
|
||||
|
||||
const deduplicationWindowMs = 30 * 60 * 1000
|
||||
|
||||
type Activity = {
|
||||
kind: ShareActivityKind
|
||||
userId?: string
|
||||
assetId?: string
|
||||
}
|
||||
|
||||
class ShareActivityService {
|
||||
async recordView(
|
||||
shareLinkId: string,
|
||||
view: { userId?: string; assetId?: string; isShareEntry?: boolean },
|
||||
): Promise<void> {
|
||||
const events: Activity[] = []
|
||||
if (!view.assetId || view.isShareEntry) {
|
||||
events.push({ kind: 'share_viewed', userId: view.userId })
|
||||
}
|
||||
if (view.assetId) {
|
||||
events.push({ kind: 'asset_viewed', userId: view.userId, assetId: view.assetId })
|
||||
}
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const now = await this.lockShare(tx, shareLinkId)
|
||||
// A visit updates the counters independently of whether its events are duplicates.
|
||||
await tx.$executeRaw`
|
||||
UPDATE share_links
|
||||
SET views = views + 1,
|
||||
last_viewed_at = GREATEST(last_viewed_at, ${now.toISOString()}::timestamptz AT TIME ZONE 'UTC')
|
||||
WHERE id = ${shareLinkId}
|
||||
`
|
||||
for (const event of events) {
|
||||
await this.insertIfNew(tx, shareLinkId, event, now)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async recordEvent(
|
||||
shareLinkId: string,
|
||||
event: Activity,
|
||||
tx?: Prisma.TransactionClient,
|
||||
): Promise<void> {
|
||||
if (!tx) {
|
||||
await prisma.$transaction((client) => this.recordEvent(shareLinkId, event, client))
|
||||
return
|
||||
}
|
||||
|
||||
const now = await this.lockShare(tx, shareLinkId)
|
||||
await this.insertIfNew(tx, shareLinkId, event, now)
|
||||
}
|
||||
|
||||
async list(shareLinkId: string, params: PaginationParams) {
|
||||
const where = { shareLinkId }
|
||||
const page = await paginateQuery(
|
||||
(skip, take) => prisma.shareActivity.findMany({ where, orderBy: { id: 'desc' }, skip, take }),
|
||||
() => prisma.shareActivity.count({ where }),
|
||||
params,
|
||||
)
|
||||
const userIds = page.data.flatMap(({ userId }) => (userId ? [userId] : []))
|
||||
const assetIds = page.data.flatMap(({ assetId }) => (assetId ? [assetId] : []))
|
||||
const [users, assets] = await Promise.all([
|
||||
prisma.user.findMany({
|
||||
where: { id: { in: userIds } },
|
||||
select: { id: true, name: true, image: true },
|
||||
}),
|
||||
prisma.asset.findMany({
|
||||
where: { id: { in: assetIds }, isDeleted: false },
|
||||
select: { id: true, name: true },
|
||||
}),
|
||||
])
|
||||
const usersById = new Map(
|
||||
await Promise.all(
|
||||
users.map(
|
||||
async ({ id, name, image }) => [id, { name, image: await getAvatarUrl(image) }] as const,
|
||||
),
|
||||
),
|
||||
)
|
||||
const namesById = new Map(assets.map(({ id, name }) => [id, name]))
|
||||
const data: ShareActivityInfo[] = page.data.map((event) => ({
|
||||
id: event.id,
|
||||
kind: event.kind,
|
||||
createdAt: event.createdAt.toISOString(),
|
||||
user: event.userId ? (usersById.get(event.userId) ?? null) : null,
|
||||
asset: event.assetId
|
||||
? { id: event.assetId, name: namesById.get(event.assetId) ?? null }
|
||||
: null,
|
||||
}))
|
||||
return { data, pageInfo: page.pageInfo }
|
||||
}
|
||||
|
||||
private async lockShare(tx: Prisma.TransactionClient, shareLinkId: string) {
|
||||
const rows = await tx.$queryRaw<{ id: string }[]>`
|
||||
SELECT id FROM share_links WHERE id = ${shareLinkId} FOR UPDATE
|
||||
`
|
||||
if (rows.length === 0) throw new ShareLinkNotFoundError('Share link not found')
|
||||
// Read time after acquiring the lock so a queued request uses its actual write time.
|
||||
const [clock] = await tx.$queryRaw<{ now: Date }[]>`SELECT clock_timestamp() AS now`
|
||||
return clock.now
|
||||
}
|
||||
|
||||
private async insertIfNew(
|
||||
tx: Prisma.TransactionClient,
|
||||
shareLinkId: string,
|
||||
event: Activity,
|
||||
now: Date,
|
||||
) {
|
||||
const identity = {
|
||||
shareLinkId,
|
||||
kind: event.kind,
|
||||
userId: event.userId ?? null,
|
||||
assetId: event.assetId ?? null,
|
||||
}
|
||||
const recent = await tx.shareActivity.findFirst({
|
||||
where: {
|
||||
...identity,
|
||||
createdAt: { gt: new Date(now.getTime() - deduplicationWindowMs) },
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
if (!recent) await tx.shareActivity.create({ data: { ...identity, createdAt: now } })
|
||||
}
|
||||
}
|
||||
|
||||
export const shareActivityService = new ShareActivityService()
|
||||
@@ -6,6 +6,12 @@ import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { AssetType } from '@shumai/db'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { timingSafeEqual } from 'node:crypto'
|
||||
|
||||
vi.mock('node:crypto', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('node:crypto')>()
|
||||
return { ...actual, timingSafeEqual: vi.fn(actual.timingSafeEqual) }
|
||||
})
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
s3Service: {
|
||||
@@ -167,6 +173,69 @@ describe('ShareService', () => {
|
||||
).rejects.toThrow('expired')
|
||||
})
|
||||
|
||||
it('includes the saved password in share link settings', async () => {
|
||||
const created = await shareService.createShareLink(projectId, {
|
||||
name: 'Protected Share',
|
||||
password: 'secret-password',
|
||||
})
|
||||
expect(created.hasPassword).toBe(true)
|
||||
expect(created.password).toBe('secret-password')
|
||||
|
||||
const fetched = await shareService.getShareLink(created.id)
|
||||
expect(fetched.hasPassword).toBe(true)
|
||||
expect(fetched.password).toBe('secret-password')
|
||||
|
||||
const updated = await shareService.updateShareLink(created.id, { password: 'other' })
|
||||
expect(updated.hasPassword).toBe(true)
|
||||
expect(updated.password).toBe('other')
|
||||
|
||||
const list = await shareService.listProjectShareLinks({ projectId })
|
||||
expect(list.data).toContainEqual(expect.objectContaining({ id: created.id, password: 'other' }))
|
||||
|
||||
const cleared = await shareService.updateShareLink(created.id, { password: null })
|
||||
expect(cleared.hasPassword).toBe(false)
|
||||
expect(cleared.password).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects missing or different-length share passwords', async () => {
|
||||
const shareLink = await shareService.createShareLink(projectId, {
|
||||
name: 'Protected Share',
|
||||
password: 'secret-password',
|
||||
})
|
||||
|
||||
await expect(
|
||||
shareService.verifyPublicAccess(shareLink.id, shareLink.rootFolderId),
|
||||
).rejects.toThrow('Invalid password')
|
||||
await expect(
|
||||
shareService.verifyPublicAccess(shareLink.id, shareLink.rootFolderId, ''),
|
||||
).rejects.toThrow('Invalid password')
|
||||
await expect(
|
||||
shareService.verifyPublicAccess(shareLink.id, shareLink.rootFolderId, 'secret'),
|
||||
).rejects.toThrow('Invalid password')
|
||||
await expect(
|
||||
shareService.verifyPublicAccess(
|
||||
shareLink.id,
|
||||
shareLink.rootFolderId,
|
||||
'secret-password-and-more',
|
||||
),
|
||||
).rejects.toThrow('Invalid password')
|
||||
await expect(
|
||||
shareService.verifyPublicAccess(shareLink.id, shareLink.rootFolderId, 'secret-password'),
|
||||
).resolves.toBeDefined()
|
||||
})
|
||||
|
||||
it('compares share passwords in constant time', async () => {
|
||||
const shareLink = await shareService.createShareLink(projectId, {
|
||||
name: 'Protected Share',
|
||||
password: 'secret-password',
|
||||
})
|
||||
|
||||
await expect(
|
||||
shareService.verifyPublicAccess(shareLink.id, shareLink.rootFolderId, 'wrong'),
|
||||
).rejects.toThrow('Invalid password')
|
||||
expect(timingSafeEqual).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('traces deep ancestors for public access', async () => {
|
||||
const shareLink = await shareService.createShareLink(projectId, {
|
||||
name: 'Deep Share',
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createHash, timingSafeEqual } from 'node:crypto'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { AssetType, Prisma } from '@shumai/db'
|
||||
import {
|
||||
@@ -18,6 +19,17 @@ import {
|
||||
ShareLinkPasswordInvalidError,
|
||||
} from './errors'
|
||||
|
||||
/**
|
||||
* Compares a provided share password with the stored one in constant time.
|
||||
* Both values are hashed first so the comparison does not depend on their lengths.
|
||||
*/
|
||||
function sharePasswordMatches(stored: string, provided: string | undefined): boolean {
|
||||
if (provided === undefined) return false
|
||||
const a = createHash('sha256').update(stored).digest()
|
||||
const b = createHash('sha256').update(provided).digest()
|
||||
return timingSafeEqual(a, b)
|
||||
}
|
||||
|
||||
export class ShareService {
|
||||
async createShareLink(
|
||||
projectId: string,
|
||||
@@ -250,7 +262,7 @@ export class ShareService {
|
||||
|
||||
async verifyPublicAccess(
|
||||
shareLinkId: string,
|
||||
assetId: string,
|
||||
assetId: string | undefined,
|
||||
providedPassword?: string,
|
||||
): Promise<Prisma.ShareLinkGetPayload<true>> {
|
||||
const shareLink = await prisma.shareLink.findUnique({
|
||||
@@ -269,15 +281,17 @@ export class ShareService {
|
||||
throw new ShareLinkExpiredError('Share link has expired')
|
||||
}
|
||||
|
||||
if (shareLink.password && shareLink.password !== providedPassword) {
|
||||
if (shareLink.password && !sharePasswordMatches(shareLink.password, providedPassword)) {
|
||||
throw new ShareLinkPasswordInvalidError('Invalid password for share link')
|
||||
}
|
||||
|
||||
const targetId = assetId ?? shareLink.rootFolderId
|
||||
|
||||
const rows = await prisma.$queryRaw<{ id: string }[]>`
|
||||
WITH RECURSIVE
|
||||
-- Trace ancestors in the real asset tree
|
||||
real_ancestors AS (
|
||||
SELECT id, parent_id, type::text, target_id FROM assets WHERE id = ${assetId} AND is_deleted = false
|
||||
SELECT id, parent_id, type::text, target_id FROM assets WHERE id = ${targetId} AND is_deleted = false
|
||||
UNION ALL
|
||||
SELECT a.id, a.parent_id, a.type::text, a.target_id FROM assets a
|
||||
INNER JOIN real_ancestors ra ON ra.parent_id = a.id
|
||||
@@ -339,6 +353,8 @@ export class ShareService {
|
||||
rootFolderId: l.rootFolderId,
|
||||
projectId: l.projectId,
|
||||
isExpired,
|
||||
views: l.views,
|
||||
lastViewedAt: l.lastViewedAt?.toISOString() ?? null,
|
||||
watermarkConfigId: l.watermarkConfigId,
|
||||
watermarkStatus: l.watermarkStatus || 'disabled',
|
||||
watermarkConfig: watermarkConfig
|
||||
|
||||
@@ -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,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/db",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
+2
@@ -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;
|
||||
+5
@@ -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");
|
||||
@@ -0,0 +1,27 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "ShareActivityKind" AS ENUM ('share_viewed', 'asset_viewed', 'asset_downloaded', 'comment_created');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "share_links" ADD COLUMN "last_viewed_at" TIMESTAMP(3),
|
||||
ADD COLUMN "views" INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "share_activities" (
|
||||
"id" TEXT NOT NULL,
|
||||
"share_link_id" TEXT NOT NULL,
|
||||
"kind" "ShareActivityKind" NOT NULL,
|
||||
"user_id" TEXT,
|
||||
"asset_id" TEXT,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "share_activities_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "share_activities_dedup_idx" ON "share_activities"("share_link_id", "kind", "user_id", "asset_id", "created_at" DESC);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "share_activities_share_link_id_id_idx" ON "share_activities"("share_link_id", "id" DESC);
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "share_activities" ADD CONSTRAINT "share_activities_share_link_id_fkey" FOREIGN KEY ("share_link_id") REFERENCES "share_links"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "asset_comments" ADD COLUMN "is_internal" BOOLEAN NOT NULL DEFAULT false;
|
||||
@@ -125,6 +125,7 @@ enum WorkflowTaskType {
|
||||
transcode_image_annotation
|
||||
transcode_watermark
|
||||
transcode_3d
|
||||
transcode_video_chunks
|
||||
ai_metadata_autofill
|
||||
chat
|
||||
ai_embedding
|
||||
@@ -478,6 +479,8 @@ model ShareLink {
|
||||
viewMode String? @map("view_mode")
|
||||
/// [ShareLinkFieldVisibility]
|
||||
fieldVisibility Json? @map("field_visibility")
|
||||
views Int @default(0)
|
||||
lastViewedAt DateTime? @map("last_viewed_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@ -494,9 +497,33 @@ model ShareLink {
|
||||
watermarkStatus WatermarkStatus @default(disabled) @map("watermark_status")
|
||||
watermarkConfig WatermarkConfig? @relation(fields: [watermarkConfigId], references: [id], onDelete: SetNull)
|
||||
|
||||
activities ShareActivity[]
|
||||
|
||||
@@map("share_links")
|
||||
}
|
||||
|
||||
enum ShareActivityKind {
|
||||
share_viewed
|
||||
asset_viewed
|
||||
asset_downloaded
|
||||
comment_created
|
||||
}
|
||||
|
||||
model ShareActivity {
|
||||
id String @id @default(ulid())
|
||||
shareLinkId String @map("share_link_id")
|
||||
shareLink ShareLink @relation(fields: [shareLinkId], references: [id], onDelete: Cascade)
|
||||
kind ShareActivityKind
|
||||
// Historical references retained when the user or asset is deleted.
|
||||
userId String? @map("user_id")
|
||||
assetId String? @map("asset_id")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
@@index([shareLinkId, kind, userId, assetId, createdAt(sort: Desc)], map: "share_activities_dedup_idx")
|
||||
@@index([shareLinkId, id(sort: Desc)])
|
||||
@@map("share_activities")
|
||||
}
|
||||
|
||||
model WatermarkConfig {
|
||||
id String @id @default(ulid())
|
||||
/// [WatermarkConfigSpec]
|
||||
@@ -615,6 +642,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")
|
||||
}
|
||||
|
||||
@@ -681,6 +709,7 @@ model AssetComment {
|
||||
creator User? @relation("UserToAssetComment", fields: [creatorId], references: [id])
|
||||
|
||||
isCompleted Boolean @default(false) @map("is_completed")
|
||||
isInternal Boolean @default(false) @map("is_internal")
|
||||
completionLastChangedById String? @map("completion_last_changed_by_id")
|
||||
completionLastChangedBy User? @relation("UserToAssetCommentCompletionChanged", fields: [completionLastChangedById], references: [id])
|
||||
|
||||
@@ -732,12 +761,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")
|
||||
|
||||
+5
@@ -77,6 +77,11 @@ export type ProjectMember = Prisma.ProjectMemberModel
|
||||
*
|
||||
*/
|
||||
export type ShareLink = Prisma.ShareLinkModel
|
||||
/**
|
||||
* Model ShareActivity
|
||||
*
|
||||
*/
|
||||
export type ShareActivity = Prisma.ShareActivityModel
|
||||
/**
|
||||
* Model WatermarkConfig
|
||||
*
|
||||
|
||||
+5
@@ -101,6 +101,11 @@ export type ProjectMember = Prisma.ProjectMemberModel
|
||||
*
|
||||
*/
|
||||
export type ShareLink = Prisma.ShareLinkModel
|
||||
/**
|
||||
* Model ShareActivity
|
||||
*
|
||||
*/
|
||||
export type ShareActivity = Prisma.ShareActivityModel
|
||||
/**
|
||||
* Model WatermarkConfig
|
||||
*
|
||||
|
||||
+88
-54
@@ -267,6 +267,17 @@ export type EnumProjectMemberRoleWithAggregatesFilter<$PrismaModel = never> = {
|
||||
_max?: Prisma.NestedEnumProjectMemberRoleFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type IntFilter<$PrismaModel = never> = {
|
||||
equals?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedIntFilter<$PrismaModel> | number
|
||||
}
|
||||
|
||||
export type EnumWatermarkStatusFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.WatermarkStatus | Prisma.EnumWatermarkStatusFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.WatermarkStatus[] | Prisma.ListEnumWatermarkStatusFieldRefInput<$PrismaModel>
|
||||
@@ -274,6 +285,22 @@ export type EnumWatermarkStatusFilter<$PrismaModel = never> = {
|
||||
not?: Prisma.NestedEnumWatermarkStatusFilter<$PrismaModel> | $Enums.WatermarkStatus
|
||||
}
|
||||
|
||||
export type IntWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedIntWithAggregatesFilter<$PrismaModel> | number
|
||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_avg?: Prisma.NestedFloatFilter<$PrismaModel>
|
||||
_sum?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_min?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_max?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type EnumWatermarkStatusWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.WatermarkStatus | Prisma.EnumWatermarkStatusFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.WatermarkStatus[] | Prisma.ListEnumWatermarkStatusFieldRefInput<$PrismaModel>
|
||||
@@ -284,6 +311,23 @@ export type EnumWatermarkStatusWithAggregatesFilter<$PrismaModel = never> = {
|
||||
_max?: Prisma.NestedEnumWatermarkStatusFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type EnumShareActivityKindFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.ShareActivityKind | Prisma.EnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.ShareActivityKind[] | Prisma.ListEnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||
notIn?: $Enums.ShareActivityKind[] | Prisma.ListEnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedEnumShareActivityKindFilter<$PrismaModel> | $Enums.ShareActivityKind
|
||||
}
|
||||
|
||||
export type EnumShareActivityKindWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.ShareActivityKind | Prisma.EnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.ShareActivityKind[] | Prisma.ListEnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||
notIn?: $Enums.ShareActivityKind[] | Prisma.ListEnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedEnumShareActivityKindWithAggregatesFilter<$PrismaModel> | $Enums.ShareActivityKind
|
||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_min?: Prisma.NestedEnumShareActivityKindFilter<$PrismaModel>
|
||||
_max?: Prisma.NestedEnumShareActivityKindFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type JsonFilter<$PrismaModel = never> =
|
||||
| Prisma.PatchUndefined<
|
||||
Prisma.Either<Required<JsonFilterBase<$PrismaModel>>, Exclude<keyof Required<JsonFilterBase<$PrismaModel>>, 'path'>>,
|
||||
@@ -359,17 +403,6 @@ export type EnumAssetTypeFilter<$PrismaModel = never> = {
|
||||
not?: Prisma.NestedEnumAssetTypeFilter<$PrismaModel> | $Enums.AssetType
|
||||
}
|
||||
|
||||
export type IntFilter<$PrismaModel = never> = {
|
||||
equals?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedIntFilter<$PrismaModel> | number
|
||||
}
|
||||
|
||||
export type BigIntFilter<$PrismaModel = never> = {
|
||||
equals?: bigint | number | Prisma.BigIntFieldRefInput<$PrismaModel>
|
||||
in?: bigint[] | number[] | Prisma.ListBigIntFieldRefInput<$PrismaModel>
|
||||
@@ -398,22 +431,6 @@ export type EnumAssetTypeWithAggregatesFilter<$PrismaModel = never> = {
|
||||
_max?: Prisma.NestedEnumAssetTypeFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type IntWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedIntWithAggregatesFilter<$PrismaModel> | number
|
||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_avg?: Prisma.NestedFloatFilter<$PrismaModel>
|
||||
_sum?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_min?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_max?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type BigIntWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: bigint | number | Prisma.BigIntFieldRefInput<$PrismaModel>
|
||||
in?: bigint[] | number[] | Prisma.ListBigIntFieldRefInput<$PrismaModel>
|
||||
@@ -1147,6 +1164,33 @@ export type NestedEnumWatermarkStatusFilter<$PrismaModel = never> = {
|
||||
not?: Prisma.NestedEnumWatermarkStatusFilter<$PrismaModel> | $Enums.WatermarkStatus
|
||||
}
|
||||
|
||||
export type NestedIntWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedIntWithAggregatesFilter<$PrismaModel> | number
|
||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_avg?: Prisma.NestedFloatFilter<$PrismaModel>
|
||||
_sum?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_min?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_max?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type NestedFloatFilter<$PrismaModel = never> = {
|
||||
equals?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
||||
in?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
|
||||
notIn?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
|
||||
lt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
||||
lte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
||||
gt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
||||
gte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedFloatFilter<$PrismaModel> | number
|
||||
}
|
||||
|
||||
export type NestedEnumWatermarkStatusWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.WatermarkStatus | Prisma.EnumWatermarkStatusFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.WatermarkStatus[] | Prisma.ListEnumWatermarkStatusFieldRefInput<$PrismaModel>
|
||||
@@ -1157,6 +1201,23 @@ export type NestedEnumWatermarkStatusWithAggregatesFilter<$PrismaModel = never>
|
||||
_max?: Prisma.NestedEnumWatermarkStatusFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type NestedEnumShareActivityKindFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.ShareActivityKind | Prisma.EnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.ShareActivityKind[] | Prisma.ListEnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||
notIn?: $Enums.ShareActivityKind[] | Prisma.ListEnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedEnumShareActivityKindFilter<$PrismaModel> | $Enums.ShareActivityKind
|
||||
}
|
||||
|
||||
export type NestedEnumShareActivityKindWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.ShareActivityKind | Prisma.EnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.ShareActivityKind[] | Prisma.ListEnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||
notIn?: $Enums.ShareActivityKind[] | Prisma.ListEnumShareActivityKindFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedEnumShareActivityKindWithAggregatesFilter<$PrismaModel> | $Enums.ShareActivityKind
|
||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_min?: Prisma.NestedEnumShareActivityKindFilter<$PrismaModel>
|
||||
_max?: Prisma.NestedEnumShareActivityKindFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type NestedJsonFilter<$PrismaModel = never> =
|
||||
| Prisma.PatchUndefined<
|
||||
Prisma.Either<Required<NestedJsonFilterBase<$PrismaModel>>, Exclude<keyof Required<NestedJsonFilterBase<$PrismaModel>>, 'path'>>,
|
||||
@@ -1233,33 +1294,6 @@ export type NestedEnumAssetTypeWithAggregatesFilter<$PrismaModel = never> = {
|
||||
_max?: Prisma.NestedEnumAssetTypeFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type NestedIntWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
|
||||
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedIntWithAggregatesFilter<$PrismaModel> | number
|
||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_avg?: Prisma.NestedFloatFilter<$PrismaModel>
|
||||
_sum?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_min?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_max?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type NestedFloatFilter<$PrismaModel = never> = {
|
||||
equals?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
||||
in?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
|
||||
notIn?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
|
||||
lt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
||||
lte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
||||
gt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
||||
gte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedFloatFilter<$PrismaModel> | number
|
||||
}
|
||||
|
||||
export type NestedBigIntWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: bigint | number | Prisma.BigIntFieldRefInput<$PrismaModel>
|
||||
in?: bigint[] | number[] | Prisma.ListBigIntFieldRefInput<$PrismaModel>
|
||||
|
||||
+11
@@ -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',
|
||||
@@ -267,6 +268,16 @@ export const KanbanTaskEventType = {
|
||||
export type KanbanTaskEventType = (typeof KanbanTaskEventType)[keyof typeof KanbanTaskEventType]
|
||||
|
||||
|
||||
export const ShareActivityKind = {
|
||||
share_viewed: 'share_viewed',
|
||||
asset_viewed: 'asset_viewed',
|
||||
asset_downloaded: 'asset_downloaded',
|
||||
comment_created: 'comment_created'
|
||||
} as const
|
||||
|
||||
export type ShareActivityKind = (typeof ShareActivityKind)[keyof typeof ShareActivityKind]
|
||||
|
||||
|
||||
export const AgentType = {
|
||||
chat: 'chat',
|
||||
autofill: 'autofill',
|
||||
|
||||
+14
-4
File diff suppressed because one or more lines are too long
+121
-15
@@ -409,6 +409,7 @@ export const ModelName = {
|
||||
Project: 'Project',
|
||||
ProjectMember: 'ProjectMember',
|
||||
ShareLink: 'ShareLink',
|
||||
ShareActivity: 'ShareActivity',
|
||||
WatermarkConfig: 'WatermarkConfig',
|
||||
WatermarkTemplate: 'WatermarkTemplate',
|
||||
WatermarkFile: 'WatermarkFile',
|
||||
@@ -473,7 +474,7 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
|
||||
omit: GlobalOmitOptions
|
||||
}
|
||||
meta: {
|
||||
modelProps: "user" | "session" | "account" | "verification" | "authToken" | "team" | "runner" | "skill" | "teamMember" | "project" | "projectMember" | "shareLink" | "watermarkConfig" | "watermarkTemplate" | "watermarkFile" | "asset" | "storageKey" | "assetMetadataValue" | "assetAgentMd" | "assetComment" | "assetCommentAttachment" | "assetCommentReaction" | "assetEmbedding" | "invite" | "metadataField" | "notification" | "systemSettings" | "task" | "workflowTask" | "agent" | "agentSkill" | "mcpServer" | "agentMcpServer" | "mcpServerCredential" | "agentSession" | "agentSessionCommit" | "agentSessionEntry" | "userMetadata" | "model" | "provider" | "collection" | "apiToken" | "aiUsage" | "auditLog" | "quotaRule" | "quotaRecord" | "kanbanGoal" | "kanbanTask" | "kanbanTaskLink" | "kanbanTaskAsset" | "kanbanTaskComment" | "kanbanTaskEvent" | "recentFileItem" | "jwks" | "oauthClient" | "oauthResource" | "oauthClientResource" | "oauthRefreshToken" | "oauthAccessToken" | "oauthConsent" | "oauthClientAssertion"
|
||||
modelProps: "user" | "session" | "account" | "verification" | "authToken" | "team" | "runner" | "skill" | "teamMember" | "project" | "projectMember" | "shareLink" | "shareActivity" | "watermarkConfig" | "watermarkTemplate" | "watermarkFile" | "asset" | "storageKey" | "assetMetadataValue" | "assetAgentMd" | "assetComment" | "assetCommentAttachment" | "assetCommentReaction" | "assetEmbedding" | "invite" | "metadataField" | "notification" | "systemSettings" | "task" | "workflowTask" | "agent" | "agentSkill" | "mcpServer" | "agentMcpServer" | "mcpServerCredential" | "agentSession" | "agentSessionCommit" | "agentSessionEntry" | "userMetadata" | "model" | "provider" | "collection" | "apiToken" | "aiUsage" | "auditLog" | "quotaRule" | "quotaRecord" | "kanbanGoal" | "kanbanTask" | "kanbanTaskLink" | "kanbanTaskAsset" | "kanbanTaskComment" | "kanbanTaskEvent" | "recentFileItem" | "jwks" | "oauthClient" | "oauthResource" | "oauthClientResource" | "oauthRefreshToken" | "oauthAccessToken" | "oauthConsent" | "oauthClientAssertion"
|
||||
txIsolationLevel: TransactionIsolationLevel
|
||||
}
|
||||
model: {
|
||||
@@ -1365,6 +1366,80 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
|
||||
}
|
||||
}
|
||||
}
|
||||
ShareActivity: {
|
||||
payload: Prisma.$ShareActivityPayload<ExtArgs>
|
||||
fields: Prisma.ShareActivityFieldRefs
|
||||
operations: {
|
||||
findUnique: {
|
||||
args: Prisma.ShareActivityFindUniqueArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload> | null
|
||||
}
|
||||
findUniqueOrThrow: {
|
||||
args: Prisma.ShareActivityFindUniqueOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>
|
||||
}
|
||||
findFirst: {
|
||||
args: Prisma.ShareActivityFindFirstArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload> | null
|
||||
}
|
||||
findFirstOrThrow: {
|
||||
args: Prisma.ShareActivityFindFirstOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>
|
||||
}
|
||||
findMany: {
|
||||
args: Prisma.ShareActivityFindManyArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>[]
|
||||
}
|
||||
create: {
|
||||
args: Prisma.ShareActivityCreateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>
|
||||
}
|
||||
createMany: {
|
||||
args: Prisma.ShareActivityCreateManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
createManyAndReturn: {
|
||||
args: Prisma.ShareActivityCreateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>[]
|
||||
}
|
||||
delete: {
|
||||
args: Prisma.ShareActivityDeleteArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>
|
||||
}
|
||||
update: {
|
||||
args: Prisma.ShareActivityUpdateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>
|
||||
}
|
||||
deleteMany: {
|
||||
args: Prisma.ShareActivityDeleteManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
updateMany: {
|
||||
args: Prisma.ShareActivityUpdateManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
updateManyAndReturn: {
|
||||
args: Prisma.ShareActivityUpdateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>[]
|
||||
}
|
||||
upsert: {
|
||||
args: Prisma.ShareActivityUpsertArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ShareActivityPayload>
|
||||
}
|
||||
aggregate: {
|
||||
args: Prisma.ShareActivityAggregateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.AggregateShareActivity>
|
||||
}
|
||||
groupBy: {
|
||||
args: Prisma.ShareActivityGroupByArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.ShareActivityGroupByOutputType>[]
|
||||
}
|
||||
count: {
|
||||
args: Prisma.ShareActivityCountArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.ShareActivityCountAggregateOutputType> | number
|
||||
}
|
||||
}
|
||||
}
|
||||
WatermarkConfig: {
|
||||
payload: Prisma.$WatermarkConfigPayload<ExtArgs>
|
||||
fields: Prisma.WatermarkConfigFieldRefs
|
||||
@@ -5198,6 +5273,8 @@ export const ShareLinkScalarFieldEnum = {
|
||||
defaultSortOrder: 'defaultSortOrder',
|
||||
viewMode: 'viewMode',
|
||||
fieldVisibility: 'fieldVisibility',
|
||||
views: 'views',
|
||||
lastViewedAt: 'lastViewedAt',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt',
|
||||
projectId: 'projectId',
|
||||
@@ -5210,6 +5287,18 @@ export const ShareLinkScalarFieldEnum = {
|
||||
export type ShareLinkScalarFieldEnum = (typeof ShareLinkScalarFieldEnum)[keyof typeof ShareLinkScalarFieldEnum]
|
||||
|
||||
|
||||
export const ShareActivityScalarFieldEnum = {
|
||||
id: 'id',
|
||||
shareLinkId: 'shareLinkId',
|
||||
kind: 'kind',
|
||||
userId: 'userId',
|
||||
assetId: 'assetId',
|
||||
createdAt: 'createdAt'
|
||||
} as const
|
||||
|
||||
export type ShareActivityScalarFieldEnum = (typeof ShareActivityScalarFieldEnum)[keyof typeof ShareActivityScalarFieldEnum]
|
||||
|
||||
|
||||
export const WatermarkConfigScalarFieldEnum = {
|
||||
id: 'id',
|
||||
config: 'config',
|
||||
@@ -5323,6 +5412,7 @@ export const AssetCommentScalarFieldEnum = {
|
||||
assetId: 'assetId',
|
||||
creatorId: 'creatorId',
|
||||
isCompleted: 'isCompleted',
|
||||
isInternal: 'isInternal',
|
||||
completionLastChangedById: 'completionLastChangedById',
|
||||
replyToId: 'replyToId'
|
||||
} as const
|
||||
@@ -5356,6 +5446,7 @@ export const AssetEmbeddingScalarFieldEnum = {
|
||||
id: 'id',
|
||||
startTime: 'startTime',
|
||||
endTime: 'endTime',
|
||||
sprite: 'sprite',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt',
|
||||
assetId: 'assetId'
|
||||
@@ -6118,6 +6209,20 @@ export type ListEnumProjectMemberRoleFieldRefInput<$PrismaModel> = FieldRefInput
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'Int'
|
||||
*/
|
||||
export type IntFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Int'>
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'Int[]'
|
||||
*/
|
||||
export type ListIntFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Int[]'>
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'WatermarkStatus'
|
||||
*/
|
||||
@@ -6132,6 +6237,20 @@ export type ListEnumWatermarkStatusFieldRefInput<$PrismaModel> = FieldRefInputTy
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'ShareActivityKind'
|
||||
*/
|
||||
export type EnumShareActivityKindFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'ShareActivityKind'>
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'ShareActivityKind[]'
|
||||
*/
|
||||
export type ListEnumShareActivityKindFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'ShareActivityKind[]'>
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'WatermarkFileStatus'
|
||||
*/
|
||||
@@ -6160,20 +6279,6 @@ export type ListEnumAssetTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$Pr
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'Int'
|
||||
*/
|
||||
export type IntFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Int'>
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'Int[]'
|
||||
*/
|
||||
export type ListIntFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Int[]'>
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'BigInt'
|
||||
*/
|
||||
@@ -6630,6 +6735,7 @@ export type GlobalOmitConfig = {
|
||||
project?: Prisma.ProjectOmit
|
||||
projectMember?: Prisma.ProjectMemberOmit
|
||||
shareLink?: Prisma.ShareLinkOmit
|
||||
shareActivity?: Prisma.ShareActivityOmit
|
||||
watermarkConfig?: Prisma.WatermarkConfigOmit
|
||||
watermarkTemplate?: Prisma.WatermarkTemplateOmit
|
||||
watermarkFile?: Prisma.WatermarkFileOmit
|
||||
|
||||
@@ -63,6 +63,7 @@ export const ModelName = {
|
||||
Project: 'Project',
|
||||
ProjectMember: 'ProjectMember',
|
||||
ShareLink: 'ShareLink',
|
||||
ShareActivity: 'ShareActivity',
|
||||
WatermarkConfig: 'WatermarkConfig',
|
||||
WatermarkTemplate: 'WatermarkTemplate',
|
||||
WatermarkFile: 'WatermarkFile',
|
||||
@@ -298,6 +299,8 @@ export const ShareLinkScalarFieldEnum = {
|
||||
defaultSortOrder: 'defaultSortOrder',
|
||||
viewMode: 'viewMode',
|
||||
fieldVisibility: 'fieldVisibility',
|
||||
views: 'views',
|
||||
lastViewedAt: 'lastViewedAt',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt',
|
||||
projectId: 'projectId',
|
||||
@@ -310,6 +313,18 @@ export const ShareLinkScalarFieldEnum = {
|
||||
export type ShareLinkScalarFieldEnum = (typeof ShareLinkScalarFieldEnum)[keyof typeof ShareLinkScalarFieldEnum]
|
||||
|
||||
|
||||
export const ShareActivityScalarFieldEnum = {
|
||||
id: 'id',
|
||||
shareLinkId: 'shareLinkId',
|
||||
kind: 'kind',
|
||||
userId: 'userId',
|
||||
assetId: 'assetId',
|
||||
createdAt: 'createdAt'
|
||||
} as const
|
||||
|
||||
export type ShareActivityScalarFieldEnum = (typeof ShareActivityScalarFieldEnum)[keyof typeof ShareActivityScalarFieldEnum]
|
||||
|
||||
|
||||
export const WatermarkConfigScalarFieldEnum = {
|
||||
id: 'id',
|
||||
config: 'config',
|
||||
@@ -423,6 +438,7 @@ export const AssetCommentScalarFieldEnum = {
|
||||
assetId: 'assetId',
|
||||
creatorId: 'creatorId',
|
||||
isCompleted: 'isCompleted',
|
||||
isInternal: 'isInternal',
|
||||
completionLastChangedById: 'completionLastChangedById',
|
||||
replyToId: 'replyToId'
|
||||
} as const
|
||||
@@ -456,6 +472,7 @@ export const AssetEmbeddingScalarFieldEnum = {
|
||||
id: 'id',
|
||||
startTime: 'startTime',
|
||||
endTime: 'endTime',
|
||||
sprite: 'sprite',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt',
|
||||
assetId: 'assetId'
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user