Compare commits

..
Author SHA1 Message Date
yiling 3e81550a81 docs: consolidate embedding and transcript changelog entry 2026-12-04 21:14:31 +08:00
yiling 46bfb86c74 fix(agents): require a configured embedding server URL 2026-12-04 20:25:25 +08:00
yiling 01c471f292 fix(agents): guide Transcript Agent setup 2026-12-04 19:15:58 +08:00
yiling 553269012c feat: configure embedding servers and transcript agents 2026-12-04 18:54:29 +08:00
Yiling-J 72a7f68c92 fix(video): transcribe archived videos and show progress (#560) 2026-12-04 15:37:58 +08:00
Yiling-J d3899d1257 feat(video): add video transcripts (#559)
* feat(video): generate transcripts with the local embedding server

* feat(video): show saved transcripts in the player

* fix(video): preserve transcript seek timestamps

* fix(video): refine transcript viewing and generation

* feat(video): resize transcripts and follow playback earlier

* fix(video): animate transcript playback scrolling

* fix(video): transcribe from the smallest full proxy

* fix(video): refine the sync to playback button

* feat(video): edit transcript segment text inline

* fix(video): keep transcript segment highlighted over edit button

* docs(video): note embedding server version for transcripts
2026-12-04 13:49:25 +08:00
Yiling-J e420f03b35 Merge commit from fork 2026-12-03 10:44:12 +08:00
Yiling-J 17ba2631c5 feat(webui): open projects and assets in new tabs (#558) 2026-12-02 10:27:59 +08:00
yiling 2505612dd8 fix(ci): re-enable Bun caching on Windows ARM64 2026-12-01 21:06:49 +08:00
Yiling-J bfeabb8244 feat(sessions): show token usage and estimated cost in logs (#557)
* feat(sessions): show token usage and estimated cost in logs

* fix(sessions): compact the usage footer

* fix(ci): bypass Bun cache for Windows ARM64
2026-12-01 20:49:07 +08:00
Yiling-J e3fe5792b9 Refresh provider models from the public Pi catalog (#555)
* feat(provider): refresh models from the public Pi catalog

* fix(provider): simplify provider card actions
2026-11-30 10:59:51 +08:00
yiling d315253450 Release v0.7.2 2026-11-27 20:02:39 +08:00
Yiling-J a049f50c3e Add WeChat group link to README_CN.md 2026-11-27 13:10:12 +08:00
Yiling-J 6b2648fe28 Add WeChat badge to README
Added WeChat badge link to README.
2026-11-27 13:06:40 +08:00
Yiling-J c654a4fe03 fix(webui): scrub video using the 180p preview (#553) 2026-11-27 12:00:21 +08:00
90f076f3ba fix(webui): stop duplicate seeks on the video progress bar (#532)
* fix(webui): avoid duplicate seek on progress bar tap

A single tap/click fired onSeek twice: once on pointer-down and again
on pointer-up at the same position. The second seek restarted the
native seek right as data began arriving, which stalled playback for
several seconds on slow connections. Track pointer movement and only
re-seek on release after an actual drag.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(webui): suppress synthetic mouse seek after touch on progress bar

Mobile browsers dispatch synthetic mousedown/mouseup after touch
interactions. The mouse path re-queued a seek to the same position,
which restarted the native seek ~500ms later and stalled playback on
slow connections. Ignore mouse-down within 700ms of a touch end.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(webui): reset progress bar drag state on touchcancel

OS gestures (app switch, palm rejection, notification pull) cancel
touches without a touchend. The drag/hover state then stayed stuck
until the next interaction. Reset state without seeking.

Co-Authored-By: Claude <noreply@anthropic.com>

* perf(webui): load seek preview video metadata only

The hidden 180p preview video used preload="auto", downloading the
whole file alongside main playback. On constrained connections it
competed for bandwidth exactly when a seek needed data, lengthening
rebuffering. Metadata is enough until the user actually scrubs.

Co-Authored-By: Claude <noreply@anthropic.com>

* test(webui): cover progress bar seeking on click, tap and touch cancel

Check that a plain click or tap seeks once, a real drag seeks again on release, synthetic mouse events right after a touch are ignored, a cancelled touch resets without seeking, and the hidden preview video preloads metadata only.

Co-Authored-By: Claude <noreply@anthropic.com>

* docs(changelog): note the progress bar seek fixes

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: phj1081 <5908832+phj1081@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-27 10:12:53 +08:00
Yiling-J fee6f39828 feat(comments): add internal comments and author comment editing (#552)
* feat(comments): add internal comments and author comment editing

* chore(i18n): add Korean comment translations and update AGENTS.md i18n rule

* style(comments): refine visibility selector corner radius and align send button height

* fix(webui): avoid ResizeObserver loop when resizing file browser
2026-11-26 14:54:45 +08:00
Yiling-Jandphj1081 1066900c78 Merge commit from fork
* fix(share): only return share-visible field values on public share links

The public share children and file detail endpoints returned every custom
field value on an asset, while the share's field settings only hid them in
the share UI. Filter fieldValues server-side to the fields turned on for the
share, matching what GET /shares/:shareId/fields already returns.

* fix(share): stop returning share passwords and compare them in constant time

Share link responses included the saved password in plain text. Remove it
from ShareLinkInfo; clients already get hasPassword. Check the password a
guest enters with a constant-time comparison of SHA-256 digests instead of
a string comparison.

The share settings panel no longer pre-fills the saved password. When a
password is set, the field starts empty with a hint, Save stays disabled
until a new password is typed, and the field clears after saving. Turning
the password off still removes it.

* fix(kanban): limit task lists and task reads to the caller's projects

Kanban checked only team membership for task reads, so a member invited to
one project could list every task in the team and open any task, its linked
files, comments and activity.

- Task lists and the tasks linked to a file now include, for project-scoped
  members, only tasks in projects they belong to plus tasks they created,
  report, or are assigned to. Team-scoped members see every task as before.
- Reading a task, its files, comments and activity follows the same rule:
  a project-scoped member outside the task's project needs to be its
  creator, reporter or assignee.
- Linking a file to a task (create, update, or the link endpoints) now
  requires Read on that file, since linked files are shown to everyone who
  can read the task.

* fix(security): sign only issued comment attachments and keep files on comment delete

Kanban comment attachments:
- Upload keys now include the team and the uploader:
  kanban/attachments/<teamId>/<userId>/<ulid>/<file name>.
- addComment rejects any attachment key that was not issued to the comment
  author for the task's team, so a client can no longer store an arbitrary
  storage key in a comment.
- When comments are read, only keys of kanban comment attachments for the
  task's team (or the previous kanban/attachments/<ulid>/<name> form) are
  presigned. Keys stored earlier that point anywhere else are dropped.

Asset comment attachments:
- createComment only links attachment uploads made by the commenter in the
  same project that are not linked to another comment. Project files can no
  longer be linked as comment attachments.
- deleteComment deletes the stored object and asset only for attachment
  uploads not linked elsewhere; anything else linked to the comment is only
  unlinked.

Upload keys:
- Sanitize the file name in kanban and project attachment upload keys, as
  regular uploads already do, so a name cannot add path segments.
- The local storage backend rejects keys with a '..' segment instead of
  resolving them into another object's path.

* fix(security): enforce visibility and protect comment attachments

---------

Co-authored-by: phj1081 <5908832+phj1081@users.noreply.github.com>
2026-11-26 10:43:08 +08:00
Yiling-J f2febaf652 fix(comments): size printable comment thumbnails to match media aspect ratio (#551) 2026-11-25 21:07:45 +08:00
Yiling-J 5a1655e4ef feat(comments): add printable comments page with frame thumbnails and markup overlays (#550)
* feat(comments): add printable comments page with frame thumbnails and markup overlays

* fix(comments): guarantee frame-accurate ffmpeg seeking for printable comment thumbnails

* fix(comments): address printable comments review findings
2026-11-25 19:53:39 +08:00
Yiling-J e32445684f feat(share): record and display share activity (#549)
* feat(share): record and display share activity

* style(share): remove activity entry borders

* docs(share): explain share link activity
2026-11-25 12:23:11 +08:00
Yiling-J 9c8eb16259 feat(share): allow creating share links from media view with quick share dialog (#548)
* feat(share): allow creating share links from media view with quick share dialog

* fix(share): prevent horizontal overflow in quick share dialog
2026-11-24 19:39:06 +08:00
272 changed files with 25262 additions and 6221 deletions
+1 -1
View File
@@ -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). - **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. - **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`). - **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`) ## Database & Prisma (`packages/db`)
+37
View File
@@ -8,8 +8,44 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added ### Added
- **sessions**: See total tokens and estimated cost in the session logs footer, with a breakdown of input, output, and cached tokens.
- **projects**: Middle-click or Command/Ctrl-click a project to open it in a new tab. Use **Open in new tab** in a file or folder's context menu to keep your current view open.
- **video**: Update your local embedding server to v0.1.3 to generate video transcripts. Choose a language or detect it automatically, then open the transcript in the video player to switch languages, follow playback, search the text, jump to a segment, or edit its text.
- **integrations**: Set and test an embedding server URL under **Team Settings → Integrations**. A URL set through environment variables appears read-only. Once the server is configured, enable the Transcript Agent to generate video transcripts and receive an internal comment if a job fails. The updated embedding and full Docker Compose files create and enable the agent automatically with a distinct avatar.
For an existing deployment, create and enable the Transcript Agent under **Team Settings → Agents**, or add this line to the Shumai service’s `environment` block in your Compose file.
```yaml
ENABLE_TRANSCRIPTION_AGENT: 'true'
```
### Fixed ### Fixed
- **storage**: Download HTML, SVG, and other unsupported preview formats when opened from local storage.
### Changed
- **provider**: Open a provider card to edit its settings, or use its refresh button to choose new models to add. Use Add Provider to set up a new provider.
## [0.7.2] - 2026-11-27
### 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 ### Changed
## [0.7.1] - 2026-11-23 ## [0.7.1] - 2026-11-23
@@ -36,6 +72,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Fixed ### 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. - **cli**: Fix release publication failing to find staged standalone downloads.
### Changed ### Changed
+1
View File
@@ -13,6 +13,7 @@
<a href="https://github.com/shumaiOne/shumai/releases"><img alt="GitHub latest release" src="https://img.shields.io/github/v/release/shumaiOne/shumai" /></a> <a href="https://github.com/shumaiOne/shumai/releases"><img alt="GitHub latest release" src="https://img.shields.io/github/v/release/shumaiOne/shumai" /></a>
<a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-blue" /></a> <a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-blue" /></a>
<a target="_blank" href="https://deepwiki.com/shumaiOne/shumai"><img alt="Ask DeepWiki" src="https://img.shields.io/badge/Ask-DeepWiki-6E56CF" /></a> <a target="_blank" href="https://deepwiki.com/shumaiOne/shumai"><img alt="Ask DeepWiki" src="https://img.shields.io/badge/Ask-DeepWiki-6E56CF" /></a>
<a target="_blank" href="https://docs.qq.com/doc/DUmJRWndFVWJPQVRI"><img alt="微信群" src="https://img.shields.io/badge/WeChat-%E5%BE%AE%E4%BF%A1%E7%BE%A4-07C160" /></a>
</p> </p>
<p align="center"> <p align="center">
+1
View File
@@ -13,6 +13,7 @@
<a href="https://github.com/shumaiOne/shumai/releases"><img alt="GitHub latest release" src="https://img.shields.io/github/v/release/shumaiOne/shumai" /></a> <a href="https://github.com/shumaiOne/shumai/releases"><img alt="GitHub latest release" src="https://img.shields.io/github/v/release/shumaiOne/shumai" /></a>
<a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-blue" /></a> <a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-blue" /></a>
<a target="_blank" href="https://deepwiki.com/shumaiOne/shumai"><img alt="Ask DeepWiki" src="https://img.shields.io/badge/Ask-DeepWiki-6E56CF" /></a> <a target="_blank" href="https://deepwiki.com/shumaiOne/shumai"><img alt="Ask DeepWiki" src="https://img.shields.io/badge/Ask-DeepWiki-6E56CF" /></a>
<a target="_blank" href="https://docs.qq.com/doc/DUmJRWndFVWJPQVRI"><img alt="微信群" src="https://img.shields.io/badge/WeChat-%E5%BE%AE%E4%BF%A1%E7%BE%A4-07C160" /></a>
</p> </p>
<p align="center"> <p align="center">
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/cli", "name": "@shumai/cli",
"version": "0.7.1", "version": "0.7.2",
"private": true, "private": true,
"type": "module", "type": "module",
"bin": { "bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/premiere-uxp", "name": "@shumai/premiere-uxp",
"version": "0.7.1", "version": "0.7.2",
"private": true, "private": true,
"type": "commonjs", "type": "commonjs",
"scripts": { "scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/transcode-app", "name": "@shumai/transcode-app",
"version": "0.7.1", "version": "0.7.2",
"private": true, "private": true,
"type": "module", "type": "module",
"bin": { "bin": {
+15 -2
View File
@@ -67,18 +67,27 @@ apps/web/e2e/
| Owner changes a team member role in the members dialog and permissions update | `tests/team/change-member-role.spec.ts` | | Owner changes a team member role in the members dialog and permissions update | `tests/team/change-member-role.spec.ts` |
| Owner manages resource quotas in settings and resets usage from the dashboard | `tests/team/quotas-settings.spec.ts` | | Owner manages resource quotas in settings and resets usage from the dashboard | `tests/team/quotas-settings.spec.ts` |
| Owner creates an API token that is shown once, listed by hint, and authenticates API calls | `tests/team/api-tokens.spec.ts` | | Owner creates an API token that is shown once, listed by hint, and authenticates API calls | `tests/team/api-tokens.spec.ts` |
| Session logs stay within the dialog and scroll through long messages and expanded records on desktop and narrow screens | `tests/team/agent-session-logs.spec.ts` | | Session logs scroll through long messages and expanded records with the usage footer pinned and the token breakdown available on desktop and narrow screens | `tests/team/agent-session-logs.spec.ts` |
| Provider cards open the editor by click and keyboard, keep menu actions independent, and show a scrollable model preview on desktop and mobile | `tests/team/provider-model-refresh.spec.ts` |
### project ### project
| Test | File | | Test | File |
|---|---| |---|---|
| Owner creates a project with a cover image | `tests/project/create-project.spec.ts` | | Owner creates a project with a cover image | `tests/project/create-project.spec.ts` |
| Owner opens project cards in new tabs with middle-click and modifier-click | `tests/project/open-in-new-tab.spec.ts` |
| Owner opens a folder card and a file row in new tabs from the context menu | `tests/project/open-in-new-tab.spec.ts` |
| Owner sees the transcript action only when available, generates a transcript from an archived video's context menu, sees progress in card and list metadata across a refresh, and reuses the project status across folders | `tests/project/generate-transcripts.spec.ts` |
| Owner uploads a file or an unsupported file via the "Upload File" context menu action | `tests/project/upload-file.spec.ts` | | Owner uploads a file or an unsupported file via the "Upload File" context menu action | `tests/project/upload-file.spec.ts` |
| Owner deletes a file, finds it in recently deleted, and restores it | `tests/project/delete-restore.spec.ts` | | 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 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 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` | | 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 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 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` | | Owner changes a project member role in the members dialog and permissions update | `tests/project/change-member-role.spec.ts` |
@@ -112,7 +121,11 @@ apps/web/e2e/
| Upload a txt file, wait for transcode, and create a comment with draw | `tests/file/txt-draw-comment.spec.ts` | | Upload a txt file, wait for transcode, and create a comment with draw | `tests/file/txt-draw-comment.spec.ts` |
| Upload an image file, wait for transcode, and create a comment with draw | `tests/file/image-draw-comment.spec.ts` | | 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 a video file, wait for transcode, and create a comment with draw at a non-zero timestamp | `tests/file/video-draw-comment.spec.ts` |
| Read and search saved video transcripts, resize the desktop panel, jump to a segment, verify smooth playback following and interruption, and check mobile and version-stack behavior | `tests/file/view-transcript.spec.ts` |
| Edit video transcript text inline, verify playback pauses and timestamps survive a blank edit, retry a failed save, and check reviewer permissions | `tests/file/view-transcript.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` | | 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 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` | | Show a preparing circle before the poster is generated | `tests/file/processing-preview.spec.ts` |
+1
View File
@@ -23,6 +23,7 @@ async function start() {
process.env.NODE_ENV = 'development' process.env.NODE_ENV = 'development'
process.env.SHUMAI_E2E = 'true' process.env.SHUMAI_E2E = 'true'
process.env.ENABLE_EMBEDDING_AGENT = 'false' process.env.ENABLE_EMBEDDING_AGENT = 'false'
process.env.ENABLE_TRANSCRIPTION_AGENT = 'false'
// Write variables to .env.e2e file so the teardown can load them // Write variables to .env.e2e file so the teardown can load them
const envContent = [ const envContent = [
@@ -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'])
})
})
@@ -0,0 +1,472 @@
import type { Locator } from '@playwright/test'
import { expect, test } from '../../fixtures'
import { seedProjectMember } from '../../helpers/team'
test.use({ fileOptions: { mediaType: 'video' } })
test('reads, searches and follows a saved transcript in the video player', async ({
file,
prisma,
}) => {
const { page, projectId, fileId } = file
await page.setViewportSize({ width: 1280, height: 720 })
await page.emulateMedia({ colorScheme: 'dark' })
await expect
.poll(() =>
prisma.asset.findUnique({
where: { id: fileId },
select: { status: true, media: true },
}),
)
.toMatchObject({ status: 'processed', media: { proxyType: 'video' } })
await prisma.assetTranscript.create({
data: {
assetId: fileId,
language: 'en',
model: 'whisper-tiny',
workflowTaskId: 'english-test',
segments: {
create: [
{ position: 0, startMs: 0, endMs: 180, text: 'Signal. signal.' },
...Array.from({ length: 28 }, (_, index) => ({
position: index + 1,
startMs: 300 + index * 12,
endMs: 312 + index * 12,
text: `Intervening segment ${index + 1}`,
})),
{ position: 29, startMs: 720, endMs: 980, text: 'Final signal.' },
{ position: 30, startMs: 995, endMs: 1000, text: 'Closing word.' },
],
},
},
})
await prisma.assetTranscript.create({
data: {
assetId: fileId,
language: 'zh',
model: 'whisper-tiny',
workflowTaskId: 'chinese-test',
segments: { create: { position: 0, startMs: 0, endMs: 700, text: '你好。' } },
},
})
await page.goto(`/projects/${projectId}/files/${fileId}`)
const toggle = page.getByRole('button', { name: 'Show transcript' })
const navigator = page.getByRole('link', { name: 'Preview', exact: true })
await expect(navigator).toBeVisible()
await toggle.click()
const panel = page.getByRole('complementary', { name: 'Transcript' })
const divider = page.getByRole('separator', { name: 'Resize transcript' })
const first = panel.getByRole('button', { name: /Signal\. signal\./ })
const last = panel.getByRole('button', { name: /Final signal\./ })
const video = page.locator('video').first()
const sync = panel.getByRole('button', { name: 'Sync to playback' })
await expect(navigator).toBeHidden()
await expect(panel).toHaveCSS('width', '384px')
await expect(toggle).toHaveAttribute('aria-expanded', 'true')
await expect(toggle).toHaveCSS('cursor', 'pointer')
await expect(first).toHaveAttribute('aria-current', 'true')
await expect(first.getByText('Signal. signal.', { exact: true })).toHaveCSS('font-weight', '700')
await expect(first).toHaveCSS('background-color', 'rgba(0, 0, 0, 0)')
await expect(first).toContainText('00:00.000 – 00:00.180')
const dragDivider = async (handle: Locator, delta: number) => {
const box = await handle.boundingBox()
if (!box) throw new Error('Expected the divider to be visible')
const x = box.x + box.width / 2
const y = box.y + box.height / 2
await page.mouse.move(x, y)
await page.mouse.down()
await page.mouse.move(x + delta, y, { steps: 8 })
await page.mouse.up()
}
await dragDivider(divider, 256)
await expect(panel).toHaveCSS('width', '576px')
await dragDivider(divider, -384)
await expect(panel).toHaveCSS('width', '256px')
await divider.press('ArrowRight')
await expect(divider).toHaveAttribute('aria-valuenow', '21')
await divider.press('Home')
await expect(panel).toHaveCSS('width', '256px')
await dragDivider(divider, 128)
await expect(panel).toHaveCSS('width', '384px')
const viewport = panel.locator('[data-slot=scroll-area-viewport]')
const nearBottomId = await viewport.evaluate((element) => {
const view = element.getBoundingClientRect()
const nearBottom = Array.from(element.querySelectorAll('li[data-segment-id]')).find((row) => {
const { top, bottom } = row.getBoundingClientRect()
return top > view.top + view.height * 0.75 && bottom < view.bottom
})
return nearBottom?.getAttribute('data-segment-id')
})
if (!nearBottomId) throw new Error('Expected a visible segment in the bottom quarter')
const nearBottom = panel
.locator(`[data-segment-id="${nearBottomId}"]`)
.getByRole('button', { name: /Intervening segment/ })
await viewport.evaluate((element) => {
let scrollSteps = 0
const record = () => {
element.setAttribute('data-test-scroll-steps', String(++scrollSteps))
if (scrollSteps === 2) element.removeEventListener('scroll', record)
}
element.addEventListener('scroll', record)
})
await nearBottom.click()
await expect(nearBottom).toHaveAttribute('aria-current', 'true')
await expect
.poll(() =>
nearBottom.evaluate((element) => {
const view = element.closest('[data-slot=scroll-area-viewport]')!.getBoundingClientRect()
const row = element.getBoundingClientRect()
return (row.top + row.height / 2 - view.top) / view.height
}),
)
.toBeCloseTo(0.5, 1)
await expect(viewport).toHaveAttribute('data-test-scroll-steps', '2')
await expect(sync).toBeHidden()
await page.emulateMedia({ reducedMotion: 'reduce' })
await viewport.evaluate((element) => {
let previousTop = element.scrollTop
const record = () => {
const top = element.scrollTop
if (top < previousTop) {
element.setAttribute('data-test-first-reverse-scroll-top', String(top))
element.removeEventListener('scroll', record)
}
previousTop = top
}
element.addEventListener('scroll', record)
})
await video.evaluate((element) => {
const media = element as HTMLVideoElement
media.currentTime = 0
})
await expect(first).toHaveAttribute('aria-current', 'true')
await expect(first).toBeInViewport()
await expect(viewport).toHaveAttribute('data-test-first-reverse-scroll-top', '0')
await page.emulateMedia({ reducedMotion: 'no-preference' })
await panel.getByRole('button', { name: 'Search transcript' }).click()
const search = panel.getByRole('searchbox', { name: 'Search transcript' })
await expect(search).toBeFocused()
await search.fill('SIGNAL.')
await expect(panel.getByText('1 / 3')).toBeVisible()
const match = panel.locator('[data-current-match]')
await expect(match).toHaveCSS('padding-left', '1px')
await expect(match).toHaveCSS('padding-right', '1px')
await panel.getByRole('button', { name: 'Next match' }).click()
await expect(panel.getByText('2 / 3')).toBeVisible()
await search.press('Enter')
await expect(panel.getByText('3 / 3')).toBeVisible()
await expect(last).toBeInViewport()
await expect(first).toHaveAttribute('aria-current', 'true')
await last.click()
await expect(last).toHaveAttribute('aria-current', 'true')
await expect
.poll(() => video.evaluate((element) => (element as HTMLVideoElement).currentTime))
.toBeCloseTo(0.72, 1)
await expect(video).toHaveJSProperty('paused', true)
await panel.getByRole('button', { name: 'Next match' }).click()
await expect(panel.getByText('1 / 3')).toBeVisible()
await panel.getByRole('button', { name: 'Previous match' }).click()
await expect(panel.getByText('3 / 3')).toBeVisible()
await search.fill('unmatched')
await expect(panel.getByText('0 / 0')).toBeVisible()
await search.press('Escape')
await expect(search).toBeHidden()
await sync.click()
await expect(sync).toBeHidden()
await viewport.hover()
await page.mouse.wheel(0, -2500)
await expect(sync).toBeVisible()
await expect(page.locator('html')).toHaveClass('dark')
const background = await panel.evaluate((element) => getComputedStyle(element).backgroundColor)
await expect(sync).toHaveCSS('background-color', background)
await expect(sync.locator('svg')).toHaveCount(0)
expect(
await sync.evaluate(
(element) =>
parseFloat(getComputedStyle(element).borderTopLeftRadius) >= element.clientHeight / 2,
),
).toBe(true)
await sync.hover()
await expect(sync).not.toHaveCSS('background-color', background)
await expect(sync).toHaveCSS('background-color', /^oklch\([^/]+\)$/)
await expect(last).not.toBeInViewport()
await expect(last).toHaveAttribute('aria-current', 'true')
await viewport.evaluate((element) => {
element.addEventListener(
'scroll',
() => {
element.dispatchEvent(new WheelEvent('wheel', { bubbles: true, deltaY: -120 }))
element.setAttribute('data-test-follow-interrupted', 'true')
},
{ once: true },
)
})
await sync.click()
await expect(viewport).toHaveAttribute('data-test-follow-interrupted', 'true')
await expect(sync).toBeVisible()
await expect(last).not.toBeInViewport()
await sync.click()
await expect(last).toBeInViewport()
await expect(sync).toBeHidden()
await video.evaluate((element) => {
const media = element as HTMLVideoElement
media.currentTime = 0.22
})
await expect(panel.locator('[aria-current=true]')).toHaveCount(0)
await video.evaluate((element) => {
const media = element as HTMLVideoElement
media.currentTime = 0
})
await expect(first).toHaveAttribute('aria-current', 'true')
await expect(first).toBeInViewport()
await video.evaluate(async (element) => {
const media = element as HTMLVideoElement
media.playbackRate = 0.5
await media.play()
})
await expect(last).toBeInViewport()
await expect(sync).toBeHidden()
await expect(video).toHaveJSProperty('ended', true)
await last.press('Enter')
await expect(last).toHaveAttribute('aria-current', 'true')
await expect(video).toHaveJSProperty('paused', true)
const closingWord = panel.getByRole('button', { name: /Closing word\./ })
await closingWord.click()
await expect
.poll(() =>
video.evaluate((element) => {
const media = element as HTMLVideoElement
return { seeking: media.seeking, timeMs: Math.round(media.currentTime * 1000) }
}),
)
.toEqual({ seeking: false, timeMs: 995 })
await expect(closingWord).toHaveAttribute('aria-current', 'true')
await expect(video).toHaveJSProperty('paused', true)
await panel.getByRole('combobox', { name: 'Language' }).selectOption('zh')
await expect(panel.getByText('你好。')).toBeVisible()
await expect(last).toHaveCount(0)
await dragDivider(divider, 64)
await expect(panel).toHaveCSS('width', '448px')
await panel.getByRole('button', { name: 'Close transcript' }).click()
await expect(panel).toBeHidden()
await expect(navigator).toBeVisible()
await expect(toggle).toBeFocused()
await toggle.click()
await expect(panel).toHaveCSS('width', '448px')
const commentsDivider = page.locator('main [data-slot="resize-handle"]:not([role="separator"])')
await dragDivider(commentsDivider, -200)
await page.setViewportSize({ width: 840, height: 720 })
await expect
.poll(async () => Number(await divider.getAttribute('aria-valuemax')))
.toBeLessThan(20)
await divider.press('End')
await page.setViewportSize({ width: 1280, height: 720 })
await dragDivider(commentsDivider, 200)
await expect(panel).toHaveCSS('width', '448px')
await panel.getByRole('button', { name: 'Close transcript' }).click()
await page.setViewportSize({ width: 390, height: 844 })
const comments = page.getByTestId('mobile-bottom-sheet')
await expect(comments).toBeVisible()
await toggle.click()
await expect(panel).toBeVisible()
await expect(video).toBeVisible()
await expect(comments).toBeHidden()
await panel.getByRole('button', { name: 'Close transcript' }).click()
await expect(comments).toBeVisible()
})
test('edits segment text inline while preserving timestamps and reviewer access', async ({
file,
browser,
prisma,
}) => {
const { page, context, teamId, projectId, fileId } = file
await expect
.poll(async () => (await prisma.asset.findUnique({ where: { id: fileId } }))?.status)
.toBe('processed')
const transcript = await prisma.assetTranscript.create({
data: {
assetId: fileId,
language: 'en',
model: 'whisper-tiny',
workflowTaskId: 'edit-transcript-test',
segments: { create: { position: 0, startMs: 125, endMs: 950, text: 'Original text' } },
},
include: { segments: true },
})
const [segment] = transcript.segments
const url = `/projects/${projectId}/files/${fileId}`
const editPath = `/api/files/${fileId}/transcripts/en/segments/${segment.id}`
const timestamps = '00:00.125 – 00:00.950'
await page.goto(url)
const toggle = page.getByRole('button', { name: 'Show transcript' })
await toggle.click()
const panel = page.getByRole('complementary', { name: 'Transcript' })
const row = panel.getByRole('listitem')
const seek = row.getByRole('button', { name: /Original text/ })
const edit = row.getByRole('button', { name: 'Edit segment text' })
const draft = row.getByRole('textbox', { name: 'Edit segment text' })
const video = page.locator('video').first()
await expect(edit).toHaveCSS('opacity', '0')
await seek.hover()
await expect(edit).toHaveCSS('opacity', '1')
const highlight = await seek.evaluate((element) => getComputedStyle(element).backgroundColor)
expect(highlight).not.toBe('rgba(0, 0, 0, 0)')
await edit.hover()
await expect(seek).toHaveCSS('background-color', highlight)
await video.evaluate(async (element) => {
const media = element as HTMLVideoElement
media.loop = true
await media.play()
})
await expect(video).toHaveJSProperty('paused', false)
await edit.click()
await expect(video).toHaveJSProperty('paused', true)
await expect(draft).toBeFocused()
await expect(draft).toHaveValue('Original text')
await expect(row.getByText(timestamps)).toBeVisible()
await draft.fill('Discard this draft')
await draft.press('Escape')
await expect(edit).toBeFocused()
await expect(row.getByText('Original text')).toBeVisible()
await panel.getByRole('button', { name: 'Search transcript' }).click()
await panel.getByRole('searchbox').fill('corrected')
await expect(panel.getByText('0 / 0')).toBeVisible()
await edit.click()
await draft.fill('Corrected text')
await page.route(`**${editPath}`, (route) => route.fulfill({ status: 503 }), { times: 1 })
await row.getByRole('button', { name: 'Save', exact: true }).click()
await expect(row.getByRole('alert')).toHaveText('Could not save this segment.')
await expect(draft).toHaveValue('Corrected text')
await row.getByRole('button', { name: 'Save', exact: true }).click()
await expect(row.getByRole('button', { name: /Corrected text/ })).toBeVisible()
await expect(panel.getByText('1 / 1')).toBeVisible()
await expect(video).toHaveJSProperty('paused', true)
const reviewer = await seedProjectMember(
prisma,
teamId,
projectId,
'reviewer',
'project',
browser,
context,
)
const reviewerContext = reviewer.context!
try {
const reviewerPage = await reviewerContext.newPage()
await reviewerPage.goto(url)
await reviewerPage.getByRole('button', { name: 'Show transcript' }).click()
const reviewerPanel = reviewerPage.getByRole('complementary', { name: 'Transcript' })
await expect(reviewerPanel.getByText('Corrected text')).toBeVisible()
await expect(reviewerPanel.getByRole('button', { name: 'Edit segment text' })).toHaveCount(0)
const response = await reviewerContext.request.patch(editPath, { data: { text: 'Denied' } })
expect(response.status()).toBe(403)
} finally {
await reviewerContext.close()
}
await edit.click()
await expect(draft).toHaveValue('Corrected text')
await draft.fill('')
await row.getByRole('button', { name: 'Save', exact: true }).click()
await expect(panel.getByText('0 / 0')).toBeVisible()
await page.reload()
await toggle.click()
await expect(row.getByRole('button', { name: timestamps })).toBeVisible()
await edit.click()
await expect(draft).toHaveValue('')
await row.getByRole('button', { name: 'Cancel' }).click()
await expect(row.getByRole('button', { name: timestamps })).toBeVisible()
expect(await prisma.assetTranscriptSegment.findUnique({ where: { id: segment.id } })).toEqual({
...segment,
text: '',
})
})
test('uses the displayed video version and hides the toggle for versions without a transcript', async ({
file,
prisma,
}) => {
const { page, projectId, fileId, rootFolderId } = file
await expect
.poll(() =>
prisma.asset.findUnique({
where: { id: fileId },
select: { status: true, media: true },
}),
)
.toMatchObject({ status: 'processed', media: { proxyType: 'video' } })
const latest = await prisma.asset.findUniqueOrThrow({ where: { id: fileId } })
if (!latest.media) throw new Error('Expected processed video media')
const stack = await prisma.asset.create({
data: {
projectId,
parentId: rootFolderId,
name: latest.name,
type: 'version_stack',
status: 'processed',
fileCount: 2,
},
})
await prisma.asset.update({
where: { id: fileId },
data: { parentId: stack.id, sortIndex: 'a0' },
})
const old = await prisma.asset.create({
data: {
projectId,
parentId: stack.id,
name: 'Earlier video.mp4',
type: 'file',
status: 'processed',
mediaType: latest.mediaType,
storageKeyId: latest.storageKeyId,
media: latest.media,
sizeByte: latest.sizeByte,
sortIndex: 'a1',
},
})
await prisma.assetTranscript.create({
data: {
assetId: fileId,
language: 'en',
model: 'whisper-tiny',
workflowTaskId: 'latest-version-test',
segments: {
create: { position: 0, startMs: 0, endMs: 950, text: 'Latest version text' },
},
},
})
const stackUrl = `/projects/${projectId}/files/${stack.id}`
await page.goto(stackUrl)
const toggle = page.getByRole('button', { name: 'Show transcript' })
await toggle.click()
const panel = page.getByRole('complementary', { name: 'Transcript' })
await expect(panel.getByText('Latest version text')).toBeVisible()
const [languages] = await Promise.all([
page.waitForResponse(`**/api/files/${old.id}/transcripts`),
page.goto(`${stackUrl}?version=${old.id}`),
])
expect(await languages.json()).toEqual({ languages: [] })
await expect(panel).toBeHidden()
await expect(toggle).toBeHidden()
})
@@ -1,7 +1,7 @@
import { expect, test } from '../../fixtures' 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, file,
prisma, 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 fileCard(page, fileName).click({ button: 'right' })
await page.getByRole('menuitem', { name: 'Create Share Link' }).click() await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
// The toast offers a "View" action that navigates to the share page // Quick share dialog opens with share name, URL, security controls, and footer actions
const toast = page.locator('[data-sonner-toast]').filter({ hasText: 'Share link created' }) const dialog = page.getByRole('dialog')
await expect(toast).toBeVisible() await expect(dialog).toBeVisible()
await toast.getByRole('button', { name: 'View' }).click() 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\/[^/]+/) await expect(page).toHaveURL(/\/projects\/[^/]+\/shares\/[^/]+/)
// The shared file is listed in the share contents // The shared file is listed in the share contents
await expect(fileCard(page, fileName)).toBeVisible() 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 } }) const share = await prisma.shareLink.findFirst({ where: { projectId } })
expect(share).not.toBeNull() expect(share).not.toBeNull()
expect(share?.name).toBe('Client Review Cut')
expect(share?.allowDownload).toBe(false)
const symlink = await prisma.asset.findFirst({ const symlink = await prisma.asset.findFirst({
where: { parentId: share?.rootFolderId, targetId: fileId }, 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).not.toBeNull()
expect(symlink?.type).toBe('symlink') 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')
})
@@ -0,0 +1,131 @@
import { expect, test } from '../../fixtures'
import { seedFolder } from '../../helpers/assets'
import { fileCard } from '../../helpers/files'
test.use({ fileOptions: { mediaType: 'video' } })
test('starts a transcript for an archived video and tracks it in the file metadata', async ({
file,
prisma,
}) => {
const { page, projectId, rootFolderId, fileId, fileName } = file
const projectPath = `/projects/${projectId}`
const statusPath = `/api${projectPath}/transcription-status`
const folder = await seedFolder(prisma, projectId, rootFolderId, 'Other folder')
const expectedLanguages = ['zh', 'en']
let submissions = 0
let rejectSubmission = true
let statusRequests = 0
let transcriptionEnabled = false
page.on('request', (request) => {
if (new URL(request.url()).pathname === statusPath) {
expect(request.method()).toBe('GET')
expect(request.postData()).toBeNull()
statusRequests++
}
})
await page.route('**/api/signup-info', async (route) => {
const response = await route.fetch()
await route.fulfill({ json: { ...(await response.json()), transcriptionEnabled } })
})
await page.route('**/api/transcription/languages', (route) =>
route.fulfill({
json: {
model: 'whisper-tiny',
languages: [
{ code: 'en', name: 'English' },
{ code: 'zh', name: 'Chinese' },
],
},
}),
)
await page.route(`**/api/files/${fileId}/transcripts`, async (route) => {
expect(route.request().postDataJSON()).toEqual({ language: expectedLanguages[submissions] })
if (rejectSubmission) {
rejectSubmission = false
await route.fulfill({ status: 503 })
return
}
const task = await prisma.workflowTask.create({
data: { projectId, assetId: fileId, type: 'ai_transcription', status: 'processing' },
})
submissions++
await route.fulfill({ status: 202, json: { kind: 'queued', taskId: task.id } })
})
await expect
.poll(() =>
prisma.asset.findUnique({
where: { id: fileId },
select: { status: true, media: true },
}),
)
.toMatchObject({ status: 'processed', media: { proxyType: 'video' } })
await prisma.asset.update({ where: { id: fileId }, data: { status: 'processing' } })
await page.goto(projectPath)
const action = page.getByRole('menuitem', { name: 'Generate Transcripts' })
await fileCard(page, fileName).click({ button: 'right' })
await expect(page.getByRole('menu')).toBeVisible()
await expect(action).toHaveCount(0)
transcriptionEnabled = true
const [signupInfo] = await Promise.all([
page.waitForResponse('**/api/signup-info'),
page.goto(projectPath),
])
expect(await signupInfo.json()).toMatchObject({ transcriptionEnabled: true })
await fileCard(page, fileName).click({ button: 'right' })
await expect(action).toBeDisabled()
await prisma.asset.update({ where: { id: fileId }, data: { status: 'archived' } })
const [idleStatus] = await Promise.all([page.waitForResponse(`**${statusPath}`), page.reload()])
expect(await idleStatus.json()).toEqual({ assetIds: [] })
const idleRequests = statusRequests
await fileCard(page, folder.name).dblclick()
await expect(page).toHaveURL(`${projectPath}/folders/${folder.id}`)
await page.goBack()
await expect(fileCard(page, fileName)).toBeVisible()
expect(statusRequests).toBe(idleRequests)
const openDialog = async () => {
await fileCard(page, fileName).click({ button: 'right' })
await action.click()
}
await openDialog()
const dialog = page.getByRole('dialog', { name: 'Generate Transcripts' })
const language = dialog.getByRole('combobox', { name: 'Language' })
const generate = dialog.getByRole('button', { name: 'Generate', exact: true })
const metadata = fileCard(page, fileName).getByTestId('file-card-metadata')
await expect(language).toHaveValue('Auto')
await language.fill('Chi')
await dialog.getByRole('option', { name: 'Chinese' }).click()
await expect(language).toHaveValue('Chinese')
await generate.click()
await expect(dialog.getByRole('alert')).toBeVisible()
await expect(language).toHaveValue('Chinese')
await generate.click()
await expect(dialog).toBeHidden()
await expect(metadata).toHaveText('Transcribing…')
await page.reload()
await expect(metadata).toHaveText('Transcribing…')
await page.getByRole('button', { name: 'List View' }).click()
const dateCell = fileCard(page, fileName).getByTestId('file-list-item-date')
await expect(dateCell).toHaveText('Transcribing…')
const activeTranscript = {
assetId: fileId,
type: 'ai_transcription',
status: 'processing',
} as const
await prisma.workflowTask.updateMany({ where: activeTranscript, data: { status: 'completed' } })
await expect(dateCell).toHaveText(/\d/)
const modifiedDate = await dateCell.innerText()
await openDialog()
await expect(generate).toBeEnabled()
await language.fill('Eng')
await dialog.getByRole('option', { name: 'English' }).click()
await generate.click()
await expect(dialog).toBeHidden()
await expect(dateCell).toHaveText('Transcribing…')
await prisma.workflowTask.updateMany({ where: activeTranscript, data: { status: 'failed' } })
await expect(dateCell).toHaveText(modifiedDate)
await expect(page.getByText('Transcript generation failed.', { exact: true })).toHaveCount(0)
})
@@ -0,0 +1,68 @@
import { expect, test } from '../../fixtures'
import { seedFolder } from '../../helpers/assets'
import { fileCard } from '../../helpers/files'
test('project cards open in a new tab with middle-click and modifier-click', async ({
project,
}) => {
const { page, context, teamId, projectId, projectName } = project
await page.reload()
const projectLink = page.getByRole('link', { name: projectName, exact: true })
const [middleClickTab] = await Promise.all([
context.waitForEvent('page'),
projectLink.click({ button: 'middle' }),
])
await expect(middleClickTab).toHaveURL(`/projects/${projectId}`)
await expect(page).toHaveURL(`/teams/${teamId}`)
await middleClickTab.close()
const [modifierClickTab] = await Promise.all([
context.waitForEvent('page'),
projectLink.click({ modifiers: ['ControlOrMeta'] }),
])
await expect(modifierClickTab).toHaveURL(`/projects/${projectId}`)
await expect(page).toHaveURL(`/teams/${teamId}`)
await modifierClickTab.close()
await page.getByRole('button', { name: 'More options' }).click()
await expect(page.getByRole('menuitem', { name: 'Project Settings' })).toBeVisible()
await expect(page).toHaveURL(`/teams/${teamId}`)
await page.keyboard.press('Escape')
await projectLink.click()
await expect(page).toHaveURL(`/projects/${projectId}`)
})
test('the context menu opens a folder card and a file row in new tabs', async ({
file,
prisma,
}) => {
const { page, context, projectId, rootFolderId, fileId, fileName } = file
const projectPath = `/projects/${projectId}`
const folder = await seedFolder(prisma, projectId, rootFolderId, 'Test folder')
await page.goto(projectPath)
const openInNewTab = page.getByRole('menuitem', { name: 'Open in new tab' })
await fileCard(page, folder.name).click({ button: 'right' })
await expect(openInNewTab).toBeVisible()
expect(context.pages()).toHaveLength(1)
const [folderTab] = await Promise.all([context.waitForEvent('page'), openInNewTab.click()])
await expect(folderTab).toHaveURL(`${projectPath}/folders/${folder.id}`)
await expect(page).toHaveURL(projectPath)
await folderTab.close()
await page.getByRole('button', { name: 'List View' }).click()
const fileRow = fileCard(page, fileName)
const fileLabel = fileRow.getByText(fileName, { exact: true })
const selected = fileRow.getByRole('checkbox')
await fileLabel.click()
await expect(selected).toBeChecked()
await expect(page).toHaveURL(projectPath)
await fileLabel.click({ button: 'right' })
const [fileTab] = await Promise.all([context.waitForEvent('page'), openInNewTab.press('Enter')])
await expect(fileTab).toHaveURL(`${projectPath}/files/${fileId}`)
await expect(page).toHaveURL(projectPath)
await expect(selected).toBeChecked()
})
@@ -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() 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 // Share the version stack
await fileCard(page, fileB.name).click({ button: 'right' }) await fileCard(page, fileB.name).click({ button: 'right' })
await page.getByRole('menuitem', { name: 'Create Share Link' }).click() await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
const toast = page.locator('[data-sonner-toast]').filter({ hasText: 'Share link created' }) const shareDialog = page.getByRole('dialog')
await expect(toast).toBeVisible() await expect(shareDialog).toBeVisible()
await shareDialog.getByRole('button', { name: 'Done' }).click()
await expect(shareDialog).toBeHidden()
const share = await prisma.shareLink.findFirstOrThrow({ const share = await prisma.shareLink.findFirstOrThrow({
where: { projectId }, where: { projectId },
@@ -1,6 +1,6 @@
import { expect, test } from '../../fixtures' import { expect, test } from '../../fixtures'
test('session logs stay within the dialog and scroll through long messages and expanded records', async ({ test('session logs scroll with usage pinned below long messages and expanded records', async ({
owner, owner,
prisma, prisma,
}) => { }) => {
@@ -25,6 +25,13 @@ test('session logs stay within the dialog and scroll through long messages and e
type: 'chat', type: 'chat',
name: 'Scrollable Session Logs', name: 'Scrollable Session Logs',
cwd: '/test', cwd: '/test',
accountedUsage: {
inputTokens: 12800,
outputTokens: 1580,
cacheReadTokens: 10000,
totalTokens: 24380,
cost: 0.014,
},
}, },
}) })
await prisma.agentSessionCommit.create({ await prisma.agentSessionCommit.create({
@@ -64,6 +71,10 @@ test('session logs stay within the dialog and scroll through long messages and e
await expect(dialog.getByText(/^(Entry ID|条目 ID):/)).toHaveCount(0) await expect(dialog.getByText(/^(Entry ID|条目 ID):/)).toHaveCount(0)
const viewport = dialog.locator('[data-slot="scroll-area-viewport"]') const viewport = dialog.locator('[data-slot="scroll-area-viewport"]')
const heading = dialog.getByRole('heading') const heading = dialog.getByRole('heading')
const footer = dialog.locator('footer')
const breakdown = footer.getByRole('button', { name: /^(Breakdown|明细|상세 내역)$/ })
await expect(footer).toContainText('24,380')
await expect(footer).toContainText('$0.014')
for (const size of [ for (const size of [
{ width: 1280, height: 800 }, { width: 1280, height: 800 },
@@ -97,6 +108,7 @@ test('session logs stay within the dialog and scroll through long messages and e
) )
.toBe(true) .toBe(true)
const headerTop = (await heading.boundingBox())!.y const headerTop = (await heading.boundingBox())!.y
const footerTop = (await footer.boundingBox())!.y
await viewport.evaluate((element) => { await viewport.evaluate((element) => {
element.scrollTop = 0 element.scrollTop = 0
}) })
@@ -110,6 +122,26 @@ test('session logs stay within the dialog and scroll through long messages and e
}) })
await expect(record.locator('summary')).toBeInViewport() await expect(record.locator('summary')).toBeInViewport()
expect((await heading.boundingBox())!.y).toBeCloseTo(headerTop, 0) expect((await heading.boundingBox())!.y).toBeCloseTo(headerTop, 0)
expect((await footer.boundingBox())!.y).toBeCloseTo(footerTop, 0)
await expect(footer).toBeInViewport()
await breakdown.click()
const popover = page.getByRole('dialog', {
name: /Token breakdown|Token 用量明细|토큰 사용량 상세 내역/,
})
await expect(popover).toBeVisible()
for (const count of ['12,800', '1,580', '10,000']) {
await expect(popover.getByText(count, { exact: true })).toBeVisible()
}
await expect
.poll(async () => {
const bounds = await popover.boundingBox()
return bounds ? bounds.y + bounds.height : Infinity
})
.toBeLessThan(footerTop + 1)
await page.keyboard.press('Escape')
await expect(popover).toBeHidden()
await expect(breakdown).toBeFocused()
await record.locator('summary').click() await record.locator('summary').click()
await viewport.evaluate((element) => { await viewport.evaluate((element) => {
@@ -0,0 +1,134 @@
import type { RefreshedProviderModel } from '@shumai/dtos'
import { expect, test } from '../../fixtures'
test('provider cards open the edit dialog and keep their refresh and menu actions independent', async ({
owner,
prisma,
}) => {
const { page, teamId } = owner
const provider = await prisma.provider.create({
data: {
teamId,
name: 'OpenAI production',
config: {
api: 'openai-responses',
baseUrl: 'https://api.openai.com/v1',
apiKey: 'saved-test-key',
},
},
})
const missing = await prisma.provider.create({
data: {
teamId,
name: 'Anthropic staging',
config: {
api: 'anthropic-messages',
baseUrl: 'https://api.anthropic.com',
apiKey: 'UNSET_E2E_ANTHROPIC_KEY',
},
},
})
const models = Array.from({ length: 48 }, (_, index): RefreshedProviderModel => ({
modelId: `test-model-${index + 1}`,
name: `Test Model ${index + 1}`,
config: {
reasoning: false,
input: ['text'],
contextWindow: 128000,
maxTokens: 4096,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
},
}))
const releasePreview = Promise.withResolvers<void>()
await page.route(
`**/api/teams/${teamId}/providers/${provider.id}/models/refresh`,
async (route) => {
await releasePreview.promise
await route.fulfill({
json: { status: 'ready', providerUpdatedAt: provider.updatedAt.toISOString(), models },
})
},
)
await page.goto(`/teams/${teamId}/settings#providers`)
const cards = page.locator('main [data-slot="card"]')
const openai = cards.filter({ hasText: provider.name })
const anthropic = cards.filter({ hasText: missing.name })
const refresh = openai.getByRole('button', { name: /Refresh models for OpenAI production/ })
const edit = openai.getByRole('button', { name: `Edit ${provider.name}` })
const editDialog = page.getByRole('dialog', { name: `Edit ${provider.name}` })
const options = openai.getByRole('button', { name: `Options for ${provider.name}` })
await expect(cards.first()).toContainText(provider.name)
await expect(openai.getByText('Configured', { exact: true })).toBeVisible()
await expect(anthropic.getByText('Configured', { exact: true })).toHaveCount(0)
await expect(anthropic.getByRole('button', { name: /Refresh models/ })).toBeEnabled()
await expect(refresh).toHaveText('')
await openai.click({ position: { x: 8, y: 30 } })
await expect(editDialog).toBeVisible()
await page.keyboard.press('Escape')
await expect(editDialog).toBeHidden()
await expect(edit).toBeFocused()
await edit.press('Enter')
await expect(editDialog).toBeVisible()
await page.keyboard.press('Escape')
await expect(editDialog).toBeHidden()
await options.click()
await expect(editDialog).toBeHidden()
await page.getByRole('menuitem', { name: 'Edit', exact: true }).click()
await expect(editDialog).toBeVisible()
await page.keyboard.press('Escape')
await expect(editDialog).toBeHidden()
await expect(options).toBeFocused()
await options.click()
await page.getByRole('menuitem', { name: 'Delete', exact: true }).click()
const confirmDelete = page.getByRole('alertdialog')
await expect(confirmDelete).toContainText(provider.name)
await expect(editDialog).toBeHidden()
await confirmDelete.getByRole('button', { name: 'Cancel' }).click()
await refresh.click()
await expect(refresh).toHaveAttribute('aria-busy', 'true')
await expect(editDialog).toBeHidden()
await expect(anthropic.getByRole('button', { name: /Refresh models/ })).toHaveAttribute(
'aria-busy',
'false',
)
releasePreview.resolve()
const dialog = page.getByRole('dialog', { name: 'New models for OpenAI production' })
await expect(dialog).toBeVisible()
await expect(dialog.getByRole('checkbox', { name: 'Test Model 1 test-model-1' })).toBeVisible()
for (const viewport of [
{ width: 1280, height: 800 },
{ width: 390, height: 640 },
]) {
await page.setViewportSize(viewport)
await expect
.poll(() =>
dialog.locator('[data-slot="scroll-area-viewport"]').evaluate((element) => {
const scrollAreaBounds = element.getBoundingClientRect()
const dialogBounds = element.closest('[role="dialog"]')?.getBoundingClientRect()
return (
dialogBounds !== undefined &&
dialogBounds.left >= 0 &&
dialogBounds.right <= window.innerWidth &&
dialogBounds.top >= 0 &&
dialogBounds.bottom <= window.innerHeight &&
scrollAreaBounds.bottom < dialogBounds.bottom &&
element.scrollHeight > element.clientHeight
)
}),
)
.toBe(true)
}
await dialog.getByRole('button', { name: 'Cancel' }).click()
await expect(dialog).toBeHidden()
await expect(refresh).toBeFocused()
})
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/web-app", "name": "@shumai/web-app",
"version": "0.7.1", "version": "0.7.2",
"private": true, "private": true,
"type": "module", "type": "module",
"dependencies": { "dependencies": {
+1 -1
View File
@@ -99,7 +99,7 @@ async function run() {
// Start services // Start services
await metadataService.syncSystemFields().catch(console.error) await metadataService.syncSystemFields().catch(console.error)
await migrateLegacyAgentAvatars().catch(console.error) await migrateLegacyAgentAvatars().catch(console.error)
await agentService.ensureSystemEmbeddingAgents().catch(console.error) await agentService.ensureSystemAgents().catch(console.error)
assetService.startCleanupJob() assetService.startCleanupJob()
notificationJobService.start() notificationJobService.start()
autoArchiveJobService.start() autoArchiveJobService.start()
+200 -136
View File
@@ -32,7 +32,7 @@
}, },
"apps/cli": { "apps/cli": {
"name": "@shumai/cli", "name": "@shumai/cli",
"version": "0.7.1", "version": "0.7.2",
"bin": { "bin": {
"shumai-cli": "./src/index.ts", "shumai-cli": "./src/index.ts",
}, },
@@ -59,7 +59,7 @@
}, },
"apps/premiere-uxp": { "apps/premiere-uxp": {
"name": "@shumai/premiere-uxp", "name": "@shumai/premiere-uxp",
"version": "0.7.1", "version": "0.7.2",
"dependencies": { "dependencies": {
"@shumai/api": "workspace:*", "@shumai/api": "workspace:*",
"@shumai/dtos": "workspace:*", "@shumai/dtos": "workspace:*",
@@ -113,7 +113,7 @@
}, },
"apps/transcode": { "apps/transcode": {
"name": "@shumai/transcode-app", "name": "@shumai/transcode-app",
"version": "0.7.1", "version": "0.7.2",
"bin": { "bin": {
"shumai-transcode": "./src/index.ts", "shumai-transcode": "./src/index.ts",
}, },
@@ -125,7 +125,7 @@
}, },
"apps/web": { "apps/web": {
"name": "@shumai/web-app", "name": "@shumai/web-app",
"version": "0.7.1", "version": "0.7.2",
"dependencies": { "dependencies": {
"@shumai/agent": "workspace:*", "@shumai/agent": "workspace:*",
"@shumai/api": "workspace:*", "@shumai/api": "workspace:*",
@@ -145,11 +145,11 @@
}, },
"packages/agent": { "packages/agent": {
"name": "@shumai/agent", "name": "@shumai/agent",
"version": "0.7.1", "version": "0.7.2",
"dependencies": { "dependencies": {
"@earendil-works/chord": "1.5.0", "@earendil-works/chord": "1.7.0",
"@earendil-works/pi-ai": "1.5.0", "@earendil-works/pi-ai": "1.7.0",
"@earendil-works/pi-durable": "1.5.0", "@earendil-works/pi-durable": "1.7.0",
"@google/genai": "2.28.0", "@google/genai": "2.28.0",
"@shumai/core": "workspace:*", "@shumai/core": "workspace:*",
"@shumai/db": "workspace:*", "@shumai/db": "workspace:*",
@@ -169,10 +169,10 @@
}, },
"packages/api": { "packages/api": {
"name": "@shumai/api", "name": "@shumai/api",
"version": "0.7.1", "version": "0.7.2",
"dependencies": { "dependencies": {
"@better-auth/mcp": "1.7.12", "@better-auth/mcp": "1.7.12",
"@earendil-works/pi-durable": "1.5.0", "@earendil-works/pi-durable": "1.7.0",
"@hono/zod-validator": "0.7.6", "@hono/zod-validator": "0.7.6",
"@modelcontextprotocol/server": "2.0.0", "@modelcontextprotocol/server": "2.0.0",
"@shumai/core": "workspace:*", "@shumai/core": "workspace:*",
@@ -190,7 +190,7 @@
}, },
"packages/core": { "packages/core": {
"name": "@shumai/core", "name": "@shumai/core",
"version": "0.7.1", "version": "0.7.2",
"dependencies": { "dependencies": {
"@ai-sdk/alibaba": "2.0.38", "@ai-sdk/alibaba": "2.0.38",
"@ai-sdk/amazon-bedrock": "5.0.67", "@ai-sdk/amazon-bedrock": "5.0.67",
@@ -214,9 +214,9 @@
"@aws-sdk/s3-request-presigner": "3.1121.0", "@aws-sdk/s3-request-presigner": "3.1121.0",
"@better-auth/mcp": "1.7.12", "@better-auth/mcp": "1.7.12",
"@better-auth/oauth-provider": "1.7.12", "@better-auth/oauth-provider": "1.7.12",
"@earendil-works/chord": "1.5.0", "@earendil-works/chord": "1.7.0",
"@earendil-works/pi-ai": "1.5.0", "@earendil-works/pi-ai": "1.7.0",
"@earendil-works/pi-durable": "1.5.0", "@earendil-works/pi-durable": "1.7.0",
"@google/genai": "2.28.0", "@google/genai": "2.28.0",
"@modelcontextprotocol/client": "2.0.0", "@modelcontextprotocol/client": "2.0.0",
"@shumai/db": "workspace:*", "@shumai/db": "workspace:*",
@@ -254,7 +254,7 @@
}, },
"packages/db": { "packages/db": {
"name": "@shumai/db", "name": "@shumai/db",
"version": "0.7.1", "version": "0.7.2",
"dependencies": { "dependencies": {
"@prisma/adapter-pg": "7.10.0", "@prisma/adapter-pg": "7.10.0",
"@prisma/client": "7.10.0", "@prisma/client": "7.10.0",
@@ -269,19 +269,19 @@
}, },
"packages/dtos": { "packages/dtos": {
"name": "@shumai/dtos", "name": "@shumai/dtos",
"version": "0.7.1", "version": "0.7.2",
"dependencies": { "dependencies": {
"@earendil-works/pi-ai": "1.5.0", "@earendil-works/pi-ai": "1.7.0",
"@earendil-works/pi-durable": "1.5.0", "@earendil-works/pi-durable": "1.7.0",
"zod": "4.5.4", "zod": "4.5.4",
}, },
}, },
"packages/e2e": { "packages/e2e": {
"name": "@shumai/e2e", "name": "@shumai/e2e",
"version": "0.7.1", "version": "0.7.2",
"dependencies": { "dependencies": {
"@earendil-works/pi-ai": "1.5.0", "@earendil-works/pi-ai": "1.7.0",
"@earendil-works/pi-durable": "1.5.0", "@earendil-works/pi-durable": "1.7.0",
"@google/genai": "2.28.0", "@google/genai": "2.28.0",
"@shumai/agent": "workspace:*", "@shumai/agent": "workspace:*",
"@shumai/core": "workspace:*", "@shumai/core": "workspace:*",
@@ -294,18 +294,18 @@
}, },
"packages/operations": { "packages/operations": {
"name": "@shumai/operations", "name": "@shumai/operations",
"version": "0.7.1", "version": "0.7.2",
"dependencies": { "dependencies": {
"zod": "4.5.4", "zod": "4.5.4",
}, },
}, },
"packages/tableprinter": { "packages/tableprinter": {
"name": "@shumai/tableprinter", "name": "@shumai/tableprinter",
"version": "0.7.1", "version": "0.7.2",
}, },
"packages/transcode": { "packages/transcode": {
"name": "@shumai/transcode", "name": "@shumai/transcode",
"version": "0.7.1", "version": "0.7.2",
"dependencies": { "dependencies": {
"@shumai/core": "workspace:*", "@shumai/core": "workspace:*",
"@shumai/db": "workspace:*", "@shumai/db": "workspace:*",
@@ -316,15 +316,15 @@
}, },
"packages/webui": { "packages/webui": {
"name": "@shumai/webui", "name": "@shumai/webui",
"version": "0.7.1", "version": "0.7.2",
"dependencies": { "dependencies": {
"@base-ui/react": "1.7.0", "@base-ui/react": "1.7.0",
"@better-auth/oauth-provider": "1.7.12", "@better-auth/oauth-provider": "1.7.12",
"@dnd-kit/abstract": "0.5.0", "@dnd-kit/abstract": "0.5.0",
"@dnd-kit/dom": "0.5.0", "@dnd-kit/dom": "0.5.0",
"@dnd-kit/react": "0.5.0", "@dnd-kit/react": "0.5.0",
"@earendil-works/pi-ai": "1.5.0", "@earendil-works/pi-ai": "1.7.0",
"@earendil-works/pi-durable": "1.5.0", "@earendil-works/pi-durable": "1.7.0",
"@ferrucc-io/emoji-picker": "0.1.2", "@ferrucc-io/emoji-picker": "0.1.2",
"@hookform/resolvers": "5.9.1", "@hookform/resolvers": "5.9.1",
"@lexical/code": "0.49.0", "@lexical/code": "0.49.0",
@@ -421,7 +421,7 @@
}, },
"packages/workflow-core": { "packages/workflow-core": {
"name": "@shumai/workflow-core", "name": "@shumai/workflow-core",
"version": "0.7.1", "version": "0.7.2",
"dependencies": { "dependencies": {
"@dbos-inc/dbos-sdk": "5.2.11", "@dbos-inc/dbos-sdk": "5.2.11",
"@shumai/core": "workspace:*", "@shumai/core": "workspace:*",
@@ -496,21 +496,21 @@
"@aws-sdk/core": ["@aws-sdk/core@3.977.9", "", { "dependencies": { "@aws-sdk/types": "^3.974.5", "@aws-sdk/xml-builder": "^3.972.40", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.33.3", "@smithy/signature-v4": "^5.6.12", "@smithy/types": "^4.17.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-reqPFEQrZxDZpeGj4PFMepBeR5LGYHRqq/L0motTzgFkCRBA4rFdaVXDSLYyGHhxVz7sT2PDnPN9CluGSfgyJA=="], "@aws-sdk/core": ["@aws-sdk/core@3.977.9", "", { "dependencies": { "@aws-sdk/types": "^3.974.5", "@aws-sdk/xml-builder": "^3.972.40", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.33.3", "@smithy/signature-v4": "^5.6.12", "@smithy/types": "^4.17.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-reqPFEQrZxDZpeGj4PFMepBeR5LGYHRqq/L0motTzgFkCRBA4rFdaVXDSLYyGHhxVz7sT2PDnPN9CluGSfgyJA=="],
"@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.70", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-H404B7dJl2mCrBqahDEYsanB0xhdDp6tXnXcTUnXmmpy2Q3J0Ho0bUajZ2jr/RdwzCyS59Gi8xXIFwPLGBl6Uw=="], "@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.80", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-uO5TiSvb6j1w9RTe5z28OaOmsrOxVQUPaC5+wZl50RfOXcrYD/KgnS8I9lfyGXc7sGbkCopK6VnhNIAoLqfewQ=="],
"@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.72", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/fetch-http-handler": "^5.7.2", "@smithy/node-http-handler": "^4.11.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-X98zYOrVOeuosCX+6ktf29FC2N2GHPLia7qv6mzPzTc+RPAuHWCDS++Z6JK7eGYqb/v6uaW7bAXaOvDBfol+0w=="], "@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.82", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.14.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-vQzlDHlC24Yz42p+rT4NBoP/5VdetkBoujbOLq9h6QYWC8THuZSPYnXIR9OP3XcOrdMgPBBipOrdssfxnIiWUg=="],
"@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.973.15", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/credential-provider-env": "^3.972.70", "@aws-sdk/credential-provider-http": "^3.972.72", "@aws-sdk/credential-provider-login": "^3.972.77", "@aws-sdk/credential-provider-process": "^3.972.70", "@aws-sdk/credential-provider-sso": "^3.973.14", "@aws-sdk/credential-provider-web-identity": "^3.972.76", "@aws-sdk/nested-clients": "^3.997.44", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/credential-provider-imds": "^4.4.16", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-Rykg6s5ceBuynMOGWgoowO4N+27JfnqXAnVaSunZl0hOO1XodSrxGNz6sCEbnmS0lAfQZDKyb3fbr46gSuv6Sg=="], "@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.973.25", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/credential-provider-env": "^3.972.80", "@aws-sdk/credential-provider-http": "^3.972.82", "@aws-sdk/credential-provider-login": "^3.972.87", "@aws-sdk/credential-provider-process": "^3.972.80", "@aws-sdk/credential-provider-sso": "^3.973.24", "@aws-sdk/credential-provider-web-identity": "^3.972.86", "@aws-sdk/nested-clients": "^3.997.54", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-b5xl71uCRdWsu7P1VeGpiGuCf6zfYETsSNOv8AmYVTrsgbvTJRXdmmOPVfxkvGGVNsiKkGctClQW3jAn0SZLug=="],
"@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.77", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/nested-clients": "^3.997.44", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-Jb59xfEISoN5mmbnA+HYqdtrSX3CgCtJoof+V5D8/TgUI56W63GEEd5Y58WijU3Ou6+WEgaLD1feVzaRXV5IDQ=="], "@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.87", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/nested-clients": "^3.997.54", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-C4ZFmcwM+Zj14Z8huVUk54Gv4uzT1ZdzG9cY3Gdh8FePakq7Bss1OFsgZjAhWFOkFOGpBvFBeu0OWjWf8HNKRQ=="],
"@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.81", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.70", "@aws-sdk/credential-provider-http": "^3.972.72", "@aws-sdk/credential-provider-ini": "^3.973.15", "@aws-sdk/credential-provider-process": "^3.972.70", "@aws-sdk/credential-provider-sso": "^3.973.14", "@aws-sdk/credential-provider-web-identity": "^3.972.76", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/credential-provider-imds": "^4.4.16", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-Rml+WitoFvXmv6JZ18U/xGdGDGGvB/mOin0ya0lTnTrdC0Z1lrVxTYh7iNklZBcvcRMrs4DoEf6xy1KWyrLQQw=="], "@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.82", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.70", "@aws-sdk/credential-provider-http": "^3.972.72", "@aws-sdk/credential-provider-ini": "^3.973.15", "@aws-sdk/credential-provider-process": "^3.972.70", "@aws-sdk/credential-provider-sso": "^3.973.14", "@aws-sdk/credential-provider-web-identity": "^3.972.76", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/credential-provider-imds": "^4.4.16", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-znDkEOGXB8W3kG1LJUKP3foBZY/9qLM0eil/DxWXSp37XsdsRLQHE/d/OaCGGVgKpA6znR38h/+INk8do1FjiA=="],
"@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.70", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-2ry03fGRJr4sV3jI+ocjj5JqALnFD6ymM5KiNCDZMvq8bX2GSbE0vji4aM43TVCl2nXqqLRZaUxdq/KeWRAY4Q=="], "@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.80", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-xqfixO5aclje7tbQJDias+iNND5wp/3QZixCdZcVQpgWPTZ0V5DfTW9A804A5Z7ezu7sH3WRO+vzUjtiJBA8yg=="],
"@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.973.14", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/nested-clients": "^3.997.44", "@aws-sdk/token-providers": "3.1116.0", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-jkhg/8ocAAoc0RFyLMhCw+/zZh7gystQgd4F4hznNa8P4Cc501PQmxd+jGLiMHodPJ+7Zv/3znM62gZojyasmA=="], "@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.973.24", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/nested-clients": "^3.997.54", "@aws-sdk/token-providers": "3.1161.0", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-nlg3BKG03Cgzvv/dMnhxvDJPhAhQSpaN0RUdwgU7ziwkasoev7iI8el8Xy4Rd5sqzgaDUbV269fOXck5SargqA=="],
"@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.76", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/nested-clients": "^3.997.44", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-d3AGyVu759PGr35mEB2s22xxlNEA5rpdxtSPJthfPFJvoQ8dt357iVPECqWfUxXp1toJAvKmbtcIYVGigaGsCA=="], "@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.86", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/nested-clients": "^3.997.54", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-zKTyLJBEyfQBVlYqT6Jt+mYV4r8kGbWM7dn6v4Y4MRARizhYafjDXP/iMu76UMRhToSPNmIKX1XAb24gtpBFIA=="],
"@aws-sdk/eventstream-handler-node": ["@aws-sdk/eventstream-handler-node@3.972.34", "", { "dependencies": { "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-cTeVzpu1xEAkryTZBYhGwnQ6gOGyp8ZYZvmn0Sg/nI/ABmy/CRHHxPDJDUi9PxwxUtGGaatvfRUB3FCgT/rSWw=="], "@aws-sdk/eventstream-handler-node": ["@aws-sdk/eventstream-handler-node@3.972.34", "", { "dependencies": { "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-cTeVzpu1xEAkryTZBYhGwnQ6gOGyp8ZYZvmn0Sg/nI/ABmy/CRHHxPDJDUi9PxwxUtGGaatvfRUB3FCgT/rSWw=="],
@@ -618,17 +618,17 @@
"@dnd-kit/state": ["@dnd-kit/state@0.5.0", "", { "dependencies": { "@preact/signals-core": "^1.10.0", "tslib": "^2.6.2" } }, "sha512-y7XbabQqjF58Lk8YmDQuR8l6QjN+Kh4qlGEjUvHuIeasLk1QP+9L5diXS98VMxQIivyMmUtX2//f+3N7qPJX4w=="], "@dnd-kit/state": ["@dnd-kit/state@0.5.0", "", { "dependencies": { "@preact/signals-core": "^1.10.0", "tslib": "^2.6.2" } }, "sha512-y7XbabQqjF58Lk8YmDQuR8l6QjN+Kh4qlGEjUvHuIeasLk1QP+9L5diXS98VMxQIivyMmUtX2//f+3N7qPJX4w=="],
"@earendil-works/chord": ["@earendil-works/chord@1.5.0", "", { "dependencies": { "@earendil-works/pi-schema": "1.5.0", "@earendil-works/pi-telemetry": "1.5.0" }, "peerDependencies": { "esbuild": "0.28.2", "ws": "8.21.0" }, "optionalPeers": ["esbuild", "ws"] }, "sha512-jf555zbCM21E03DVBDPD/Tuae0lz64YjaHx/athUxNZ/H7phVVb0dWfZsaYnxaXPQ1odW8iHEoVLOlE/prvUPg=="], "@earendil-works/chord": ["@earendil-works/chord@1.7.0", "", { "dependencies": { "@earendil-works/pi-schema": "1.7.0", "@earendil-works/pi-telemetry": "1.7.0" }, "peerDependencies": { "esbuild": "^0.28.2", "react": "^19.3.0", "ws": "^8.21.0" }, "optionalPeers": ["esbuild", "react", "ws"] }, "sha512-/zBlRrJkNbw0dJ4OrUzk08PC48mzOIFZQKTUE1qxQUWoPlf/xms95lEigzC30MllS+k5qqih7Clg0cTzYgPs1w=="],
"@earendil-works/pi-ai": ["@earendil-works/pi-ai@1.5.0", "", { "dependencies": { "@anthropic-ai/sdk": "0.129.0", "@aws-sdk/client-bedrock-runtime": "3.1127.0", "@earendil-works/pi-schema": "1.5.0", "@earendil-works/pi-telemetry": "1.5.0", "@google/genai": "2.21.0", "@smithy/node-http-handler": "4.12.1", "http-proxy-agent": "9.1.0", "https-proxy-agent": "9.1.0", "openai": "7.19.0", "partial-json": "0.1.7" }, "bin": { "pi-ai": "dist/cli.js" } }, "sha512-VeWxNqTHSqRCf8AcY/6kvNwh+neRL6MPxZPePVztIQy6qqK9MR/YoCSN/ZgDnIyCD3pqEXgRyQbzk4KV4uvjbg=="], "@earendil-works/pi-ai": ["@earendil-works/pi-ai@1.7.0", "", { "dependencies": { "@anthropic-ai/sdk": "0.129.0", "@aws-sdk/client-bedrock-runtime": "3.1127.0", "@aws-sdk/credential-provider-node": "3.972.82", "@earendil-works/pi-schema": "1.7.0", "@earendil-works/pi-telemetry": "1.7.0", "@google/genai": "3.6.1", "@smithy/node-http-handler": "4.12.1", "http-proxy-agent": "9.1.0", "https-proxy-agent": "9.1.0", "openai": "7.59.0", "partial-json": "0.1.7" }, "bin": { "pi-ai": "dist/cli.js" } }, "sha512-iKryMlUYniwWbU7YU0uS7W0+cGd9c6oJ6PzRLOn8j4+1njG4c+BQq1cNawctx/npDqGeOx8ME7Gkgl6K6arPuw=="],
"@earendil-works/pi-codemode": ["@earendil-works/pi-codemode@1.5.0", "", { "dependencies": { "quickjs-wasi": "3.6.2" } }, "sha512-PLBJZ17AEWGzOlAAcFuOkw3PxkOti0JlFuZQyeF2GRTqbpuYo4k9t8YqUV2uOQVzrUnKdxahwaFUqc1eNS1WAg=="], "@earendil-works/pi-codemode": ["@earendil-works/pi-codemode@1.7.0", "", { "dependencies": { "quickjs-wasi": "3.6.2" } }, "sha512-fhCoh8TLxhdRTOWSEplwp39Uv+JTsu9pCqtgu9gorO8zcaw92vsbVI/G89yFs92csTo2+yB7EsJq/+725Vj+eA=="],
"@earendil-works/pi-durable": ["@earendil-works/pi-durable@1.5.0", "", { "dependencies": { "@earendil-works/chord": "1.5.0", "@earendil-works/pi-ai": "1.5.0", "@earendil-works/pi-codemode": "1.5.0", "@earendil-works/pi-schema": "1.5.0", "@earendil-works/pi-telemetry": "1.5.0", "@silvia-odwyer/photon": "0.3.3", "diff": "8.0.4" } }, "sha512-xeBP2vIo5NvsCMQ4Y/V+Z164xQEi9JWiBWHdjn4Z15EnFqV3c0FxJAX26FqyyyintrYyk+Enre94GNcvRlBA5g=="], "@earendil-works/pi-durable": ["@earendil-works/pi-durable@1.7.0", "", { "dependencies": { "@earendil-works/chord": "1.7.0", "@earendil-works/pi-ai": "1.7.0", "@earendil-works/pi-codemode": "1.7.0", "@earendil-works/pi-schema": "1.7.0", "@earendil-works/pi-telemetry": "1.7.0", "@silvia-odwyer/photon": "0.3.3", "diff": "8.0.4" } }, "sha512-qL9PlFfXrirBNt7QR2bjZfviN6ZVcsGTHEqaj6U4Lxqqx9Vtth7LyIuGNlG2chDKMr3/ABamH8qZ9ggMgTGDOQ=="],
"@earendil-works/pi-schema": ["@earendil-works/pi-schema@1.5.0", "", {}, "sha512-RW0MbT2tR65OY6xMsgB/yVBb7m/RTNwA+9hurSN1vVXfHZRVmVnXbruBPrx/PzbrQnW5yLVlMRWxErGDQtF1Hg=="], "@earendil-works/pi-schema": ["@earendil-works/pi-schema@1.7.0", "", {}, "sha512-skji4McLg9jum3NFWzFa/4QRGEZhMGnSi3QL8b9VljJkc/QopH2/BFuGKI+VcEwYzKGwsd0I8RzvXGnZGfGltQ=="],
"@earendil-works/pi-telemetry": ["@earendil-works/pi-telemetry@1.5.0", "", {}, "sha512-VW3tcVdnNfl/Vk8wHPTzZdKkxcsCOM12ppiO4DXnd9wMxUCmOfLt/wvUnWeKWbTVlVSRg0uqKtnnhE2UCsG2Bw=="], "@earendil-works/pi-telemetry": ["@earendil-works/pi-telemetry@1.7.0", "", {}, "sha512-QZkngqktohuFZ2TZuJSXDuUntld4sCMW1tkUPaD4moMEX/z1lwcjycXnd9ChO9HNxm/Jfo+UTiC+N2hkAF9b0w=="],
"@electric-sql/pglite": ["@electric-sql/pglite@0.4.3", "", {}, "sha512-ichuWTgtd4mOM1G4SpyGJa5trT03lWbMypDV0fUXUCXg5hiHqVAz/bZyV68NqmkLB7WcYmj1RMJVSp8HV/v/ZQ=="], "@electric-sql/pglite": ["@electric-sql/pglite@0.4.3", "", {}, "sha512-ichuWTgtd4mOM1G4SpyGJa5trT03lWbMypDV0fUXUCXg5hiHqVAz/bZyV68NqmkLB7WcYmj1RMJVSp8HV/v/ZQ=="],
@@ -2498,7 +2498,7 @@
"once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="], "once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
"openai": ["openai@7.19.0", "", { "peerDependencies": { "@aws-sdk/credential-provider-node": ">=3.972.0 <4", "@smithy/hash-node": ">=4.3.0 <5", "@smithy/signature-v4": ">=5.4.0 <6", "undici": ">=5 <9", "ws": "^8.21.0", "zod": "^3.25 || ^4.0" }, "optionalPeers": ["@aws-sdk/credential-provider-node", "@smithy/hash-node", "@smithy/signature-v4", "undici", "ws", "zod"] }, "sha512-MX2s3u2L5racTO0CC/SWpCOasJQBCJrqLKXK+l82cAhdeF8mPMBEe/gxMm0ZFa2xpKpOFLRjxv5afYEZbBXmbQ=="], "openai": ["openai@7.59.0", "", { "peerDependencies": { "@aws-sdk/credential-provider-node": ">=3.972.0 <4", "@smithy/hash-node": ">=4.3.0 <5", "@smithy/signature-v4": ">=5.4.0 <6", "google-auth-library": ">=9.15.1 <12", "undici": ">=5 <9", "ws": "^8.21.0", "zod": "^3.25 || ^4.0" }, "optionalPeers": ["@aws-sdk/credential-provider-node", "@smithy/hash-node", "@smithy/signature-v4", "google-auth-library", "undici", "ws", "zod"] }, "sha512-wPYKJkLPFEdNJ2tThSg4jE1Ptsv4X3u8g8LIvu0Qz/UIhsKeCzl73rl48PtQsDVrJL/ku0liXOsbyd2TsRsPJw=="],
"optionator": ["optionator@0.9.4", "", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="], "optionator": ["optionator@0.9.4", "", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="],
@@ -3046,11 +3046,85 @@
"@aws-sdk/client-bedrock-runtime/@smithy/node-http-handler": ["@smithy/node-http-handler@4.11.3", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-2jY1tSpERfPfWqyBV2pH+iGFaghVsIJszJNsT7hxtQYhVJpWDyc0LqOWI+nXOxOAHaEfZ4PXXtp1wW1TGpHhkA=="], "@aws-sdk/client-bedrock-runtime/@smithy/node-http-handler": ["@smithy/node-http-handler@4.11.3", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-2jY1tSpERfPfWqyBV2pH+iGFaghVsIJszJNsT7hxtQYhVJpWDyc0LqOWI+nXOxOAHaEfZ4PXXtp1wW1TGpHhkA=="],
"@aws-sdk/client-s3/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.81", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.70", "@aws-sdk/credential-provider-http": "^3.972.72", "@aws-sdk/credential-provider-ini": "^3.973.15", "@aws-sdk/credential-provider-process": "^3.972.70", "@aws-sdk/credential-provider-sso": "^3.973.14", "@aws-sdk/credential-provider-web-identity": "^3.972.76", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/credential-provider-imds": "^4.4.16", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-Rml+WitoFvXmv6JZ18U/xGdGDGGvB/mOin0ya0lTnTrdC0Z1lrVxTYh7iNklZBcvcRMrs4DoEf6xy1KWyrLQQw=="],
"@aws-sdk/client-s3/@smithy/node-http-handler": ["@smithy/node-http-handler@4.11.3", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-2jY1tSpERfPfWqyBV2pH+iGFaghVsIJszJNsT7hxtQYhVJpWDyc0LqOWI+nXOxOAHaEfZ4PXXtp1wW1TGpHhkA=="], "@aws-sdk/client-s3/@smithy/node-http-handler": ["@smithy/node-http-handler@4.11.3", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-2jY1tSpERfPfWqyBV2pH+iGFaghVsIJszJNsT7hxtQYhVJpWDyc0LqOWI+nXOxOAHaEfZ4PXXtp1wW1TGpHhkA=="],
"@aws-sdk/credential-provider-http/@smithy/node-http-handler": ["@smithy/node-http-handler@4.11.3", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-2jY1tSpERfPfWqyBV2pH+iGFaghVsIJszJNsT7hxtQYhVJpWDyc0LqOWI+nXOxOAHaEfZ4PXXtp1wW1TGpHhkA=="], "@aws-sdk/credential-provider-env/@aws-sdk/core": ["@aws-sdk/core@3.979.1", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@aws-sdk/xml-builder": "^3.972.42", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.38.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-ayOlV1VhLNMiq8PW9ZkVobG4gkldnUoHjG69yy2b8j+VYFlhz/uAL7ZdYQAoQ+eShtGUdNDnnG5rxDg6yUJrOg=="],
"@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1116.0", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/nested-clients": "^3.997.44", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-ygIivKqh8aHzNkucOCXHyIBgBpLPfrSI0mCqXF+vLBsPTUKqj0VSqAY0GFPe7lQl4HntjOcQ+KSyS7oUV2C54Q=="], "@aws-sdk/credential-provider-env/@aws-sdk/types": ["@aws-sdk/types@3.975.0", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WQlhs6juByzWOzj5fwxOx0mPJaEqMcG/sDpl3Id61B3XhKE63xY+0QWcnG+sWR/sCfprmreyUo1lM7IKZmHMzw=="],
"@aws-sdk/credential-provider-env/@smithy/core": ["@smithy/core@3.38.1", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-U/mB2XiwTLaf+NSgLSWwJfptsMT/H8aBi0aTAA/E5e2/TagFeGCqAyhKGG0w0A9IWTkm4qYEmLoD/HB6aYfnRA=="],
"@aws-sdk/credential-provider-env/@smithy/types": ["@smithy/types@4.19.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q=="],
"@aws-sdk/credential-provider-http/@aws-sdk/core": ["@aws-sdk/core@3.979.1", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@aws-sdk/xml-builder": "^3.972.42", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.38.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-ayOlV1VhLNMiq8PW9ZkVobG4gkldnUoHjG69yy2b8j+VYFlhz/uAL7ZdYQAoQ+eShtGUdNDnnG5rxDg6yUJrOg=="],
"@aws-sdk/credential-provider-http/@aws-sdk/types": ["@aws-sdk/types@3.975.0", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WQlhs6juByzWOzj5fwxOx0mPJaEqMcG/sDpl3Id61B3XhKE63xY+0QWcnG+sWR/sCfprmreyUo1lM7IKZmHMzw=="],
"@aws-sdk/credential-provider-http/@smithy/core": ["@smithy/core@3.38.1", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-U/mB2XiwTLaf+NSgLSWwJfptsMT/H8aBi0aTAA/E5e2/TagFeGCqAyhKGG0w0A9IWTkm4qYEmLoD/HB6aYfnRA=="],
"@aws-sdk/credential-provider-http/@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.8.0", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.18.0", "tslib": "^2.6.2" } }, "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA=="],
"@aws-sdk/credential-provider-http/@smithy/node-http-handler": ["@smithy/node-http-handler@4.14.1", "", { "dependencies": { "@smithy/core": "^3.38.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/T6E1jzCL0fErS9uq8JqES/5yYQQ4ppVmmYHwXw2nlov8KFzLb+3QqHR5iAun1BsuAB50IPxZliV8YMgghLwhA=="],
"@aws-sdk/credential-provider-http/@smithy/types": ["@smithy/types@4.19.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q=="],
"@aws-sdk/credential-provider-ini/@aws-sdk/core": ["@aws-sdk/core@3.979.1", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@aws-sdk/xml-builder": "^3.972.42", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.38.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-ayOlV1VhLNMiq8PW9ZkVobG4gkldnUoHjG69yy2b8j+VYFlhz/uAL7ZdYQAoQ+eShtGUdNDnnG5rxDg6yUJrOg=="],
"@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.54", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/signature-v4-multi-region": "^3.996.51", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.14.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/OczlavsS7U5sOodRO10Ug4R/AKFVZiXTstKipWe68EfjPkmdDFNXNl9FCJyXWkg1DG6RBm3qAuVB8FNW9O8KQ=="],
"@aws-sdk/credential-provider-ini/@aws-sdk/types": ["@aws-sdk/types@3.975.0", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WQlhs6juByzWOzj5fwxOx0mPJaEqMcG/sDpl3Id61B3XhKE63xY+0QWcnG+sWR/sCfprmreyUo1lM7IKZmHMzw=="],
"@aws-sdk/credential-provider-ini/@smithy/core": ["@smithy/core@3.38.1", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-U/mB2XiwTLaf+NSgLSWwJfptsMT/H8aBi0aTAA/E5e2/TagFeGCqAyhKGG0w0A9IWTkm4qYEmLoD/HB6aYfnRA=="],
"@aws-sdk/credential-provider-ini/@smithy/types": ["@smithy/types@4.19.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q=="],
"@aws-sdk/credential-provider-login/@aws-sdk/core": ["@aws-sdk/core@3.979.1", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@aws-sdk/xml-builder": "^3.972.42", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.38.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-ayOlV1VhLNMiq8PW9ZkVobG4gkldnUoHjG69yy2b8j+VYFlhz/uAL7ZdYQAoQ+eShtGUdNDnnG5rxDg6yUJrOg=="],
"@aws-sdk/credential-provider-login/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.54", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/signature-v4-multi-region": "^3.996.51", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.14.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/OczlavsS7U5sOodRO10Ug4R/AKFVZiXTstKipWe68EfjPkmdDFNXNl9FCJyXWkg1DG6RBm3qAuVB8FNW9O8KQ=="],
"@aws-sdk/credential-provider-login/@aws-sdk/types": ["@aws-sdk/types@3.975.0", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WQlhs6juByzWOzj5fwxOx0mPJaEqMcG/sDpl3Id61B3XhKE63xY+0QWcnG+sWR/sCfprmreyUo1lM7IKZmHMzw=="],
"@aws-sdk/credential-provider-login/@smithy/core": ["@smithy/core@3.38.1", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-U/mB2XiwTLaf+NSgLSWwJfptsMT/H8aBi0aTAA/E5e2/TagFeGCqAyhKGG0w0A9IWTkm4qYEmLoD/HB6aYfnRA=="],
"@aws-sdk/credential-provider-login/@smithy/types": ["@smithy/types@4.19.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q=="],
"@aws-sdk/credential-provider-node/@aws-sdk/types": ["@aws-sdk/types@3.975.0", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WQlhs6juByzWOzj5fwxOx0mPJaEqMcG/sDpl3Id61B3XhKE63xY+0QWcnG+sWR/sCfprmreyUo1lM7IKZmHMzw=="],
"@aws-sdk/credential-provider-node/@smithy/core": ["@smithy/core@3.38.1", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-U/mB2XiwTLaf+NSgLSWwJfptsMT/H8aBi0aTAA/E5e2/TagFeGCqAyhKGG0w0A9IWTkm4qYEmLoD/HB6aYfnRA=="],
"@aws-sdk/credential-provider-node/@smithy/types": ["@smithy/types@4.19.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q=="],
"@aws-sdk/credential-provider-process/@aws-sdk/core": ["@aws-sdk/core@3.979.1", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@aws-sdk/xml-builder": "^3.972.42", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.38.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-ayOlV1VhLNMiq8PW9ZkVobG4gkldnUoHjG69yy2b8j+VYFlhz/uAL7ZdYQAoQ+eShtGUdNDnnG5rxDg6yUJrOg=="],
"@aws-sdk/credential-provider-process/@aws-sdk/types": ["@aws-sdk/types@3.975.0", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WQlhs6juByzWOzj5fwxOx0mPJaEqMcG/sDpl3Id61B3XhKE63xY+0QWcnG+sWR/sCfprmreyUo1lM7IKZmHMzw=="],
"@aws-sdk/credential-provider-process/@smithy/core": ["@smithy/core@3.38.1", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-U/mB2XiwTLaf+NSgLSWwJfptsMT/H8aBi0aTAA/E5e2/TagFeGCqAyhKGG0w0A9IWTkm4qYEmLoD/HB6aYfnRA=="],
"@aws-sdk/credential-provider-process/@smithy/types": ["@smithy/types@4.19.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q=="],
"@aws-sdk/credential-provider-sso/@aws-sdk/core": ["@aws-sdk/core@3.979.1", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@aws-sdk/xml-builder": "^3.972.42", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.38.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-ayOlV1VhLNMiq8PW9ZkVobG4gkldnUoHjG69yy2b8j+VYFlhz/uAL7ZdYQAoQ+eShtGUdNDnnG5rxDg6yUJrOg=="],
"@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.54", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/signature-v4-multi-region": "^3.996.51", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.14.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/OczlavsS7U5sOodRO10Ug4R/AKFVZiXTstKipWe68EfjPkmdDFNXNl9FCJyXWkg1DG6RBm3qAuVB8FNW9O8KQ=="],
"@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1161.0", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/nested-clients": "^3.997.54", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-ypbXSofNcSHwf/KA40bFCXJb0MLaAKrfT7sot4dFaA+2lsuXNah4zLRJIAU7Qmvs9PFJ6rnY0bZFEC+mE7attA=="],
"@aws-sdk/credential-provider-sso/@aws-sdk/types": ["@aws-sdk/types@3.975.0", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WQlhs6juByzWOzj5fwxOx0mPJaEqMcG/sDpl3Id61B3XhKE63xY+0QWcnG+sWR/sCfprmreyUo1lM7IKZmHMzw=="],
"@aws-sdk/credential-provider-sso/@smithy/core": ["@smithy/core@3.38.1", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-U/mB2XiwTLaf+NSgLSWwJfptsMT/H8aBi0aTAA/E5e2/TagFeGCqAyhKGG0w0A9IWTkm4qYEmLoD/HB6aYfnRA=="],
"@aws-sdk/credential-provider-sso/@smithy/types": ["@smithy/types@4.19.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q=="],
"@aws-sdk/credential-provider-web-identity/@aws-sdk/core": ["@aws-sdk/core@3.979.1", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@aws-sdk/xml-builder": "^3.972.42", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.38.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-ayOlV1VhLNMiq8PW9ZkVobG4gkldnUoHjG69yy2b8j+VYFlhz/uAL7ZdYQAoQ+eShtGUdNDnnG5rxDg6yUJrOg=="],
"@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.54", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/signature-v4-multi-region": "^3.996.51", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.14.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/OczlavsS7U5sOodRO10Ug4R/AKFVZiXTstKipWe68EfjPkmdDFNXNl9FCJyXWkg1DG6RBm3qAuVB8FNW9O8KQ=="],
"@aws-sdk/credential-provider-web-identity/@aws-sdk/types": ["@aws-sdk/types@3.975.0", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WQlhs6juByzWOzj5fwxOx0mPJaEqMcG/sDpl3Id61B3XhKE63xY+0QWcnG+sWR/sCfprmreyUo1lM7IKZmHMzw=="],
"@aws-sdk/credential-provider-web-identity/@smithy/core": ["@smithy/core@3.38.1", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-U/mB2XiwTLaf+NSgLSWwJfptsMT/H8aBi0aTAA/E5e2/TagFeGCqAyhKGG0w0A9IWTkm4qYEmLoD/HB6aYfnRA=="],
"@aws-sdk/credential-provider-web-identity/@smithy/types": ["@smithy/types@4.19.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q=="],
"@aws-sdk/nested-clients/@smithy/node-http-handler": ["@smithy/node-http-handler@4.11.3", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-2jY1tSpERfPfWqyBV2pH+iGFaghVsIJszJNsT7hxtQYhVJpWDyc0LqOWI+nXOxOAHaEfZ4PXXtp1wW1TGpHhkA=="], "@aws-sdk/nested-clients/@smithy/node-http-handler": ["@smithy/node-http-handler@4.11.3", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-2jY1tSpERfPfWqyBV2pH+iGFaghVsIJszJNsT7hxtQYhVJpWDyc0LqOWI+nXOxOAHaEfZ4PXXtp1wW1TGpHhkA=="],
@@ -3060,9 +3134,7 @@
"@dbos-inc/dbos-sdk/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="], "@dbos-inc/dbos-sdk/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
"@earendil-works/chord/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="], "@earendil-works/pi-ai/@google/genai": ["@google/genai@3.6.1", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.6.5", "ws": "^8.21.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"] }, "sha512-DQIkZkl+VoZc+RUSaJ41vRuywjQDpP0t/oUf5/ddQhNW6JsPjVULW2EgHmuJ1mrr6ACtrmUdPlqtNXF1yfKySg=="],
"@earendil-works/pi-ai/@google/genai": ["@google/genai@2.21.0", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"], "hasInstallScript": true }, "sha512-+PDtco2/Z0ONdzCGekCoCT+O1VJS9xJQNN4XzQpXG/t3El/SWWMkCWlFRO1KmivOHPa4Q0VjUYu1HBKCZ/v33Q=="],
"@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="], "@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],
@@ -3320,25 +3392,77 @@
"wrap-ansi-cjs/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], "wrap-ansi-cjs/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.80", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-uO5TiSvb6j1w9RTe5z28OaOmsrOxVQUPaC5+wZl50RfOXcrYD/KgnS8I9lfyGXc7sGbkCopK6VnhNIAoLqfewQ=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.82", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.14.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-vQzlDHlC24Yz42p+rT4NBoP/5VdetkBoujbOLq9h6QYWC8THuZSPYnXIR9OP3XcOrdMgPBBipOrdssfxnIiWUg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.973.25", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/credential-provider-env": "^3.972.80", "@aws-sdk/credential-provider-http": "^3.972.82", "@aws-sdk/credential-provider-login": "^3.972.87", "@aws-sdk/credential-provider-process": "^3.972.80", "@aws-sdk/credential-provider-sso": "^3.973.24", "@aws-sdk/credential-provider-web-identity": "^3.972.86", "@aws-sdk/nested-clients": "^3.997.54", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-b5xl71uCRdWsu7P1VeGpiGuCf6zfYETsSNOv8AmYVTrsgbvTJRXdmmOPVfxkvGGVNsiKkGctClQW3jAn0SZLug=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.80", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-xqfixO5aclje7tbQJDias+iNND5wp/3QZixCdZcVQpgWPTZ0V5DfTW9A804A5Z7ezu7sH3WRO+vzUjtiJBA8yg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.973.24", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/nested-clients": "^3.997.54", "@aws-sdk/token-providers": "3.1161.0", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-nlg3BKG03Cgzvv/dMnhxvDJPhAhQSpaN0RUdwgU7ziwkasoev7iI8el8Xy4Rd5sqzgaDUbV269fOXck5SargqA=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.86", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/nested-clients": "^3.997.54", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-zKTyLJBEyfQBVlYqT6Jt+mYV4r8kGbWM7dn6v4Y4MRARizhYafjDXP/iMu76UMRhToSPNmIKX1XAb24gtpBFIA=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/types": ["@aws-sdk/types@3.975.0", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WQlhs6juByzWOzj5fwxOx0mPJaEqMcG/sDpl3Id61B3XhKE63xY+0QWcnG+sWR/sCfprmreyUo1lM7IKZmHMzw=="], "@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/types": ["@aws-sdk/types@3.975.0", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WQlhs6juByzWOzj5fwxOx0mPJaEqMcG/sDpl3Id61B3XhKE63xY+0QWcnG+sWR/sCfprmreyUo1lM7IKZmHMzw=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@smithy/core": ["@smithy/core@3.38.1", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-U/mB2XiwTLaf+NSgLSWwJfptsMT/H8aBi0aTAA/E5e2/TagFeGCqAyhKGG0w0A9IWTkm4qYEmLoD/HB6aYfnRA=="], "@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@smithy/core": ["@smithy/core@3.38.1", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-U/mB2XiwTLaf+NSgLSWwJfptsMT/H8aBi0aTAA/E5e2/TagFeGCqAyhKGG0w0A9IWTkm4qYEmLoD/HB6aYfnRA=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@smithy/types": ["@smithy/types@4.19.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q=="], "@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@smithy/types": ["@smithy/types@4.19.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q=="],
"@earendil-works/pi-ai/@google/genai/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="], "@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.70", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-H404B7dJl2mCrBqahDEYsanB0xhdDp6tXnXcTUnXmmpy2Q3J0Ho0bUajZ2jr/RdwzCyS59Gi8xXIFwPLGBl6Uw=="],
"@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.72", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/fetch-http-handler": "^5.7.2", "@smithy/node-http-handler": "^4.11.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-X98zYOrVOeuosCX+6ktf29FC2N2GHPLia7qv6mzPzTc+RPAuHWCDS++Z6JK7eGYqb/v6uaW7bAXaOvDBfol+0w=="],
"@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.973.15", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/credential-provider-env": "^3.972.70", "@aws-sdk/credential-provider-http": "^3.972.72", "@aws-sdk/credential-provider-login": "^3.972.77", "@aws-sdk/credential-provider-process": "^3.972.70", "@aws-sdk/credential-provider-sso": "^3.973.14", "@aws-sdk/credential-provider-web-identity": "^3.972.76", "@aws-sdk/nested-clients": "^3.997.44", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/credential-provider-imds": "^4.4.16", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-Rykg6s5ceBuynMOGWgoowO4N+27JfnqXAnVaSunZl0hOO1XodSrxGNz6sCEbnmS0lAfQZDKyb3fbr46gSuv6Sg=="],
"@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.70", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-2ry03fGRJr4sV3jI+ocjj5JqALnFD6ymM5KiNCDZMvq8bX2GSbE0vji4aM43TVCl2nXqqLRZaUxdq/KeWRAY4Q=="],
"@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.973.14", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/nested-clients": "^3.997.44", "@aws-sdk/token-providers": "3.1116.0", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-jkhg/8ocAAoc0RFyLMhCw+/zZh7gystQgd4F4hznNa8P4Cc501PQmxd+jGLiMHodPJ+7Zv/3znM62gZojyasmA=="],
"@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.76", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/nested-clients": "^3.997.44", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-d3AGyVu759PGr35mEB2s22xxlNEA5rpdxtSPJthfPFJvoQ8dt357iVPECqWfUxXp1toJAvKmbtcIYVGigaGsCA=="],
"@aws-sdk/credential-provider-env/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.42", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-smX8/gNP8Kjq+CWTBMZQLQ912vOQjiWExzwzvMO+eujPB5RY8IbtF0AGdUUXHKN7KoDWK9dIcuW0WG269kiP6w=="],
"@aws-sdk/credential-provider-env/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/credential-provider-http/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.42", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-smX8/gNP8Kjq+CWTBMZQLQ912vOQjiWExzwzvMO+eujPB5RY8IbtF0AGdUUXHKN7KoDWK9dIcuW0WG269kiP6w=="],
"@aws-sdk/credential-provider-http/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/credential-provider-http/@smithy/fetch-http-handler/@smithy/core": ["@smithy/core@3.33.3", "", { "dependencies": { "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-CsOeKq/9kA3y6VJHt+/+VTCtBaxJ4OTFpgrjIUhPpDIKxBci1k2bJaQASF2h/ELWrulGp+t97DZ0mevfAD8idg=="],
"@aws-sdk/credential-provider-ini/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.42", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-smX8/gNP8Kjq+CWTBMZQLQ912vOQjiWExzwzvMO+eujPB5RY8IbtF0AGdUUXHKN7KoDWK9dIcuW0WG269kiP6w=="],
"@aws-sdk/credential-provider-ini/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.51", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-+aHvUugVBuMPXxgkPfWnTMyGdE/yWS8GHi5+qQ37HowS0YqzrbuaDLznj+Dtmtu5jgCdqz36gXmujOToUhNNWw=="],
"@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.8.0", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.18.0", "tslib": "^2.6.2" } }, "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA=="],
"@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@smithy/node-http-handler": ["@smithy/node-http-handler@4.14.1", "", { "dependencies": { "@smithy/core": "^3.38.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/T6E1jzCL0fErS9uq8JqES/5yYQQ4ppVmmYHwXw2nlov8KFzLb+3QqHR5iAun1BsuAB50IPxZliV8YMgghLwhA=="],
"@aws-sdk/credential-provider-login/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.42", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-smX8/gNP8Kjq+CWTBMZQLQ912vOQjiWExzwzvMO+eujPB5RY8IbtF0AGdUUXHKN7KoDWK9dIcuW0WG269kiP6w=="],
"@aws-sdk/credential-provider-login/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/credential-provider-login/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.51", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-+aHvUugVBuMPXxgkPfWnTMyGdE/yWS8GHi5+qQ37HowS0YqzrbuaDLznj+Dtmtu5jgCdqz36gXmujOToUhNNWw=="],
"@aws-sdk/credential-provider-login/@aws-sdk/nested-clients/@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.8.0", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.18.0", "tslib": "^2.6.2" } }, "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA=="],
"@aws-sdk/credential-provider-login/@aws-sdk/nested-clients/@smithy/node-http-handler": ["@smithy/node-http-handler@4.14.1", "", { "dependencies": { "@smithy/core": "^3.38.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/T6E1jzCL0fErS9uq8JqES/5yYQQ4ppVmmYHwXw2nlov8KFzLb+3QqHR5iAun1BsuAB50IPxZliV8YMgghLwhA=="],
"@aws-sdk/credential-provider-process/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.42", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-smX8/gNP8Kjq+CWTBMZQLQ912vOQjiWExzwzvMO+eujPB5RY8IbtF0AGdUUXHKN7KoDWK9dIcuW0WG269kiP6w=="],
"@aws-sdk/credential-provider-process/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/credential-provider-sso/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.42", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-smX8/gNP8Kjq+CWTBMZQLQ912vOQjiWExzwzvMO+eujPB5RY8IbtF0AGdUUXHKN7KoDWK9dIcuW0WG269kiP6w=="],
"@aws-sdk/credential-provider-sso/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.51", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-+aHvUugVBuMPXxgkPfWnTMyGdE/yWS8GHi5+qQ37HowS0YqzrbuaDLznj+Dtmtu5jgCdqz36gXmujOToUhNNWw=="],
"@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.8.0", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.18.0", "tslib": "^2.6.2" } }, "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA=="],
"@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@smithy/node-http-handler": ["@smithy/node-http-handler@4.14.1", "", { "dependencies": { "@smithy/core": "^3.38.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/T6E1jzCL0fErS9uq8JqES/5yYQQ4ppVmmYHwXw2nlov8KFzLb+3QqHR5iAun1BsuAB50IPxZliV8YMgghLwhA=="],
"@aws-sdk/credential-provider-web-identity/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.42", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-smX8/gNP8Kjq+CWTBMZQLQ912vOQjiWExzwzvMO+eujPB5RY8IbtF0AGdUUXHKN7KoDWK9dIcuW0WG269kiP6w=="],
"@aws-sdk/credential-provider-web-identity/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.51", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-+aHvUugVBuMPXxgkPfWnTMyGdE/yWS8GHi5+qQ37HowS0YqzrbuaDLznj+Dtmtu5jgCdqz36gXmujOToUhNNWw=="],
"@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.8.0", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.18.0", "tslib": "^2.6.2" } }, "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA=="],
"@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@smithy/node-http-handler": ["@smithy/node-http-handler@4.14.1", "", { "dependencies": { "@smithy/core": "^3.38.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/T6E1jzCL0fErS9uq8JqES/5yYQQ4ppVmmYHwXw2nlov8KFzLb+3QqHR5iAun1BsuAB50IPxZliV8YMgghLwhA=="],
"@isaacs/cliui/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="], "@isaacs/cliui/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="],
@@ -3456,31 +3580,27 @@
"readdir-glob/minimatch/brace-expansion": ["brace-expansion@2.1.4", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg=="], "readdir-glob/minimatch/brace-expansion": ["brace-expansion@2.1.4", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env/@aws-sdk/core": ["@aws-sdk/core@3.979.1", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@aws-sdk/xml-builder": "^3.972.42", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.38.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-ayOlV1VhLNMiq8PW9ZkVobG4gkldnUoHjG69yy2b8j+VYFlhz/uAL7ZdYQAoQ+eShtGUdNDnnG5rxDg6yUJrOg=="], "@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.77", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/nested-clients": "^3.997.44", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-Jb59xfEISoN5mmbnA+HYqdtrSX3CgCtJoof+V5D8/TgUI56W63GEEd5Y58WijU3Ou6+WEgaLD1feVzaRXV5IDQ=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http/@aws-sdk/core": ["@aws-sdk/core@3.979.1", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@aws-sdk/xml-builder": "^3.972.42", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.38.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-ayOlV1VhLNMiq8PW9ZkVobG4gkldnUoHjG69yy2b8j+VYFlhz/uAL7ZdYQAoQ+eShtGUdNDnnG5rxDg6yUJrOg=="], "@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1116.0", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/nested-clients": "^3.997.44", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-ygIivKqh8aHzNkucOCXHyIBgBpLPfrSI0mCqXF+vLBsPTUKqj0VSqAY0GFPe7lQl4HntjOcQ+KSyS7oUV2C54Q=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http/@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.8.0", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.18.0", "tslib": "^2.6.2" } }, "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA=="], "@aws-sdk/credential-provider-http/@smithy/fetch-http-handler/@smithy/core/@smithy/types": ["@smithy/types@4.17.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-FOKpVZob9MPTn2znRzGrnsMHv7BOsKVw3XiP/cOyYLDVZ9qKp4nifIiSCuUU/fIj5Vu0UOAxCFr+qRAtG0NUkA=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http/@smithy/node-http-handler": ["@smithy/node-http-handler@4.14.1", "", { "dependencies": { "@smithy/core": "^3.38.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/T6E1jzCL0fErS9uq8JqES/5yYQQ4ppVmmYHwXw2nlov8KFzLb+3QqHR5iAun1BsuAB50IPxZliV8YMgghLwhA=="], "@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/core": ["@aws-sdk/core@3.979.1", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@aws-sdk/xml-builder": "^3.972.42", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.38.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-ayOlV1VhLNMiq8PW9ZkVobG4gkldnUoHjG69yy2b8j+VYFlhz/uAL7ZdYQAoQ+eShtGUdNDnnG5rxDg6yUJrOg=="], "@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@smithy/fetch-http-handler/@smithy/core": ["@smithy/core@3.33.3", "", { "dependencies": { "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-CsOeKq/9kA3y6VJHt+/+VTCtBaxJ4OTFpgrjIUhPpDIKxBci1k2bJaQASF2h/ELWrulGp+t97DZ0mevfAD8idg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.87", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/nested-clients": "^3.997.54", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-C4ZFmcwM+Zj14Z8huVUk54Gv4uzT1ZdzG9cY3Gdh8FePakq7Bss1OFsgZjAhWFOkFOGpBvFBeu0OWjWf8HNKRQ=="], "@aws-sdk/credential-provider-login/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.54", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/signature-v4-multi-region": "^3.996.51", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.14.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/OczlavsS7U5sOodRO10Ug4R/AKFVZiXTstKipWe68EfjPkmdDFNXNl9FCJyXWkg1DG6RBm3qAuVB8FNW9O8KQ=="], "@aws-sdk/credential-provider-login/@aws-sdk/nested-clients/@smithy/fetch-http-handler/@smithy/core": ["@smithy/core@3.33.3", "", { "dependencies": { "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-CsOeKq/9kA3y6VJHt+/+VTCtBaxJ4OTFpgrjIUhPpDIKxBci1k2bJaQASF2h/ELWrulGp+t97DZ0mevfAD8idg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-process/@aws-sdk/core": ["@aws-sdk/core@3.979.1", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@aws-sdk/xml-builder": "^3.972.42", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.38.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-ayOlV1VhLNMiq8PW9ZkVobG4gkldnUoHjG69yy2b8j+VYFlhz/uAL7ZdYQAoQ+eShtGUdNDnnG5rxDg6yUJrOg=="], "@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/core": ["@aws-sdk/core@3.979.1", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@aws-sdk/xml-builder": "^3.972.42", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.38.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-ayOlV1VhLNMiq8PW9ZkVobG4gkldnUoHjG69yy2b8j+VYFlhz/uAL7ZdYQAoQ+eShtGUdNDnnG5rxDg6yUJrOg=="], "@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@smithy/fetch-http-handler/@smithy/core": ["@smithy/core@3.33.3", "", { "dependencies": { "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-CsOeKq/9kA3y6VJHt+/+VTCtBaxJ4OTFpgrjIUhPpDIKxBci1k2bJaQASF2h/ELWrulGp+t97DZ0mevfAD8idg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.54", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/signature-v4-multi-region": "^3.996.51", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.14.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/OczlavsS7U5sOodRO10Ug4R/AKFVZiXTstKipWe68EfjPkmdDFNXNl9FCJyXWkg1DG6RBm3qAuVB8FNW9O8KQ=="], "@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1161.0", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/nested-clients": "^3.997.54", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-ypbXSofNcSHwf/KA40bFCXJb0MLaAKrfT7sot4dFaA+2lsuXNah4zLRJIAU7Qmvs9PFJ6rnY0bZFEC+mE7attA=="], "@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@smithy/fetch-http-handler/@smithy/core": ["@smithy/core@3.33.3", "", { "dependencies": { "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-CsOeKq/9kA3y6VJHt+/+VTCtBaxJ4OTFpgrjIUhPpDIKxBci1k2bJaQASF2h/ELWrulGp+t97DZ0mevfAD8idg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/core": ["@aws-sdk/core@3.979.1", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@aws-sdk/xml-builder": "^3.972.42", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.38.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-ayOlV1VhLNMiq8PW9ZkVobG4gkldnUoHjG69yy2b8j+VYFlhz/uAL7ZdYQAoQ+eShtGUdNDnnG5rxDg6yUJrOg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.54", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/signature-v4-multi-region": "^3.996.51", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.14.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/OczlavsS7U5sOodRO10Ug4R/AKFVZiXTstKipWe68EfjPkmdDFNXNl9FCJyXWkg1DG6RBm3qAuVB8FNW9O8KQ=="],
"@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
@@ -3508,70 +3628,14 @@
"readdir-glob/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], "readdir-glob/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.42", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-smX8/gNP8Kjq+CWTBMZQLQ912vOQjiWExzwzvMO+eujPB5RY8IbtF0AGdUUXHKN7KoDWK9dIcuW0WG269kiP6w=="], "@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@smithy/fetch-http-handler/@smithy/core/@smithy/types": ["@smithy/types@4.17.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-FOKpVZob9MPTn2znRzGrnsMHv7BOsKVw3XiP/cOyYLDVZ9qKp4nifIiSCuUU/fIj5Vu0UOAxCFr+qRAtG0NUkA=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="], "@aws-sdk/credential-provider-login/@aws-sdk/nested-clients/@smithy/fetch-http-handler/@smithy/core/@smithy/types": ["@smithy/types@4.17.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-FOKpVZob9MPTn2znRzGrnsMHv7BOsKVw3XiP/cOyYLDVZ9qKp4nifIiSCuUU/fIj5Vu0UOAxCFr+qRAtG0NUkA=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.42", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-smX8/gNP8Kjq+CWTBMZQLQ912vOQjiWExzwzvMO+eujPB5RY8IbtF0AGdUUXHKN7KoDWK9dIcuW0WG269kiP6w=="], "@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@smithy/fetch-http-handler/@smithy/core/@smithy/types": ["@smithy/types@4.17.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-FOKpVZob9MPTn2znRzGrnsMHv7BOsKVw3XiP/cOyYLDVZ9qKp4nifIiSCuUU/fIj5Vu0UOAxCFr+qRAtG0NUkA=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="], "@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@smithy/fetch-http-handler/@smithy/core/@smithy/types": ["@smithy/types@4.17.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-FOKpVZob9MPTn2znRzGrnsMHv7BOsKVw3XiP/cOyYLDVZ9qKp4nifIiSCuUU/fIj5Vu0UOAxCFr+qRAtG0NUkA=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http/@smithy/fetch-http-handler/@smithy/core": ["@smithy/core@3.33.3", "", { "dependencies": { "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-CsOeKq/9kA3y6VJHt+/+VTCtBaxJ4OTFpgrjIUhPpDIKxBci1k2bJaQASF2h/ELWrulGp+t97DZ0mevfAD8idg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.42", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-smX8/gNP8Kjq+CWTBMZQLQ912vOQjiWExzwzvMO+eujPB5RY8IbtF0AGdUUXHKN7KoDWK9dIcuW0WG269kiP6w=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.51", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-+aHvUugVBuMPXxgkPfWnTMyGdE/yWS8GHi5+qQ37HowS0YqzrbuaDLznj+Dtmtu5jgCdqz36gXmujOToUhNNWw=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.8.0", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.18.0", "tslib": "^2.6.2" } }, "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@smithy/node-http-handler": ["@smithy/node-http-handler@4.14.1", "", { "dependencies": { "@smithy/core": "^3.38.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/T6E1jzCL0fErS9uq8JqES/5yYQQ4ppVmmYHwXw2nlov8KFzLb+3QqHR5iAun1BsuAB50IPxZliV8YMgghLwhA=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-process/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.42", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-smX8/gNP8Kjq+CWTBMZQLQ912vOQjiWExzwzvMO+eujPB5RY8IbtF0AGdUUXHKN7KoDWK9dIcuW0WG269kiP6w=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-process/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.42", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-smX8/gNP8Kjq+CWTBMZQLQ912vOQjiWExzwzvMO+eujPB5RY8IbtF0AGdUUXHKN7KoDWK9dIcuW0WG269kiP6w=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.51", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-+aHvUugVBuMPXxgkPfWnTMyGdE/yWS8GHi5+qQ37HowS0YqzrbuaDLznj+Dtmtu5jgCdqz36gXmujOToUhNNWw=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.8.0", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.18.0", "tslib": "^2.6.2" } }, "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@smithy/node-http-handler": ["@smithy/node-http-handler@4.14.1", "", { "dependencies": { "@smithy/core": "^3.38.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/T6E1jzCL0fErS9uq8JqES/5yYQQ4ppVmmYHwXw2nlov8KFzLb+3QqHR5iAun1BsuAB50IPxZliV8YMgghLwhA=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.42", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-smX8/gNP8Kjq+CWTBMZQLQ912vOQjiWExzwzvMO+eujPB5RY8IbtF0AGdUUXHKN7KoDWK9dIcuW0WG269kiP6w=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.51", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-+aHvUugVBuMPXxgkPfWnTMyGdE/yWS8GHi5+qQ37HowS0YqzrbuaDLznj+Dtmtu5jgCdqz36gXmujOToUhNNWw=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.8.0", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.18.0", "tslib": "^2.6.2" } }, "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@smithy/node-http-handler": ["@smithy/node-http-handler@4.14.1", "", { "dependencies": { "@smithy/core": "^3.38.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/T6E1jzCL0fErS9uq8JqES/5yYQQ4ppVmmYHwXw2nlov8KFzLb+3QqHR5iAun1BsuAB50IPxZliV8YMgghLwhA=="],
"@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/react-primitive/@radix-ui/react-slot/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], "@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/react-primitive/@radix-ui/react-slot/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http/@smithy/fetch-http-handler/@smithy/core/@smithy/types": ["@smithy/types@4.17.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-FOKpVZob9MPTn2znRzGrnsMHv7BOsKVw3XiP/cOyYLDVZ9qKp4nifIiSCuUU/fIj5Vu0UOAxCFr+qRAtG0NUkA=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@smithy/fetch-http-handler/@smithy/core": ["@smithy/core@3.33.3", "", { "dependencies": { "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-CsOeKq/9kA3y6VJHt+/+VTCtBaxJ4OTFpgrjIUhPpDIKxBci1k2bJaQASF2h/ELWrulGp+t97DZ0mevfAD8idg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@smithy/fetch-http-handler/@smithy/core": ["@smithy/core@3.33.3", "", { "dependencies": { "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-CsOeKq/9kA3y6VJHt+/+VTCtBaxJ4OTFpgrjIUhPpDIKxBci1k2bJaQASF2h/ELWrulGp+t97DZ0mevfAD8idg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@smithy/fetch-http-handler/@smithy/core": ["@smithy/core@3.33.3", "", { "dependencies": { "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-CsOeKq/9kA3y6VJHt+/+VTCtBaxJ4OTFpgrjIUhPpDIKxBci1k2bJaQASF2h/ELWrulGp+t97DZ0mevfAD8idg=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@smithy/fetch-http-handler/@smithy/core/@smithy/types": ["@smithy/types@4.17.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-FOKpVZob9MPTn2znRzGrnsMHv7BOsKVw3XiP/cOyYLDVZ9qKp4nifIiSCuUU/fIj5Vu0UOAxCFr+qRAtG0NUkA=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@smithy/fetch-http-handler/@smithy/core/@smithy/types": ["@smithy/types@4.17.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-FOKpVZob9MPTn2znRzGrnsMHv7BOsKVw3XiP/cOyYLDVZ9qKp4nifIiSCuUU/fIj5Vu0UOAxCFr+qRAtG0NUkA=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@smithy/fetch-http-handler/@smithy/core/@smithy/types": ["@smithy/types@4.17.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-FOKpVZob9MPTn2znRzGrnsMHv7BOsKVw3XiP/cOyYLDVZ9qKp4nifIiSCuUU/fIj5Vu0UOAxCFr+qRAtG0NUkA=="],
} }
} }
@@ -50,6 +50,7 @@ services:
EMBEDDING_PROVIDER: gemma-embedding-2-openai EMBEDDING_PROVIDER: gemma-embedding-2-openai
GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1 GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1
ENABLE_EMBEDDING_AGENT: 'true' ENABLE_EMBEDDING_AGENT: 'true'
ENABLE_TRANSCRIPTION_AGENT: 'true'
CONCURRENCY_AGENT: 1 CONCURRENCY_AGENT: 1
depends_on: depends_on:
@@ -60,6 +60,7 @@ services:
EMBEDDING_PROVIDER: gemma-embedding-2-openai EMBEDDING_PROVIDER: gemma-embedding-2-openai
GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1 GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1
ENABLE_EMBEDDING_AGENT: 'true' ENABLE_EMBEDDING_AGENT: 'true'
ENABLE_TRANSCRIPTION_AGENT: 'true'
CONCURRENCY_AGENT: 1 CONCURRENCY_AGENT: 1
# 3D Turntable Renderer Configuration # 3D Turntable Renderer Configuration
@@ -50,6 +50,7 @@ services:
EMBEDDING_PROVIDER: gemma-embedding-2-openai EMBEDDING_PROVIDER: gemma-embedding-2-openai
GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1 GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1
ENABLE_EMBEDDING_AGENT: 'true' ENABLE_EMBEDDING_AGENT: 'true'
ENABLE_TRANSCRIPTION_AGENT: 'true'
CONCURRENCY_AGENT: 1 CONCURRENCY_AGENT: 1
depends_on: depends_on:
@@ -60,6 +60,7 @@ services:
EMBEDDING_PROVIDER: gemma-embedding-2-openai EMBEDDING_PROVIDER: gemma-embedding-2-openai
GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1 GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1
ENABLE_EMBEDDING_AGENT: 'true' ENABLE_EMBEDDING_AGENT: 'true'
ENABLE_TRANSCRIPTION_AGENT: 'true'
CONCURRENCY_AGENT: 1 CONCURRENCY_AGENT: 1
# 3D Turntable Renderer Configuration # 3D Turntable Renderer Configuration
+24
View File
@@ -3,6 +3,29 @@ title: "Changelog"
description: "Recent updates, new features, and improvements in Shumai" description: "Recent updates, new features, and improvements in Shumai"
--- ---
<Update label="v0.7.2" description="November 27, 2026">
### 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
</Update>
<Update label="v0.7.1" description="November 23, 2026"> <Update label="v0.7.1" description="November 23, 2026">
### Added ### Added
@@ -29,6 +52,7 @@ description: "Recent updates, new features, and improvements in Shumai"
### Fixed ### 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. - **cli**: Fix release publication failing to find staged standalone downloads.
### Changed ### Changed
+2 -1
View File
@@ -100,10 +100,11 @@ Configures background worker execution, concurrency limits, and worker identity
## Embedding Config ## Embedding Config
| Variable | Description | Example / Default | | Variable | Description | Example / Default |
| :-------------------------------- | :------------------------------------------------------------------------------------------------------------ | :-------------------------------- | | :-------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------- |
| `EMBEDDING_PROVIDER` | Multimodal embedding provider. Options: `gemini-embedding-2`, `gemma-embedding-2-openai`. | `gemini-embedding-2` (default) | | `EMBEDDING_PROVIDER` | Multimodal embedding provider. Options: `gemini-embedding-2`, `gemma-embedding-2-openai`. | `gemini-embedding-2` (default) |
| `GEMMA_EMBEDDING_OPENAI_BASE_URL` | Base URL of the OpenAI-compatible LiteRT-LM embedding server. | `http://embedding-server:9379/v1` | | `GEMMA_EMBEDDING_OPENAI_BASE_URL` | Base URL of the OpenAI-compatible LiteRT-LM embedding server. | `http://embedding-server:9379/v1` |
| `ENABLE_EMBEDDING_AGENT` | When set to `true`, automatically provisions and enables the system embedding agent for all teams on startup. | `false` (default) | | `ENABLE_EMBEDDING_AGENT` | When set to `true`, automatically provisions and enables the system embedding agent for all teams on startup. | `false` (default) |
| `ENABLE_TRANSCRIPTION_AGENT` | Set to `true` to provision and enable the Transcript Agent, or `false` to disable it. Either value makes it read-only in team settings. | Unset. Manage the agent in team settings. |
| `EMBEDDING_CHUNK_DURATION` | The duration in seconds for each video chunk when generating video embeddings. | `60.0` (default) | | `EMBEDDING_CHUNK_DURATION` | The duration in seconds for each video chunk when generating video embeddings. | `60.0` (default) |
| `EMBEDDING_CHUNK_OVERLAP` | The duration in seconds to overlap video chunks when generating video embeddings. | `5.0` (default) | | `EMBEDDING_CHUNK_OVERLAP` | The duration in seconds to overlap video chunks when generating video embeddings. | `5.0` (default) |
+1 -1
View File
@@ -11,7 +11,7 @@ When creating agents for chat or metadata autofill, you must select an underlyin
## Built-In Providers ## Built-In Providers
Shumai ships with pre-configured configurations for major LLM providers. Because Shumai uses [Pi](https://github.com/earendil-works/pi) as its core agent framework, the supported provider and model configurations are automatically synchronized with Pi's capabilities. Shumai seeds new teams with provider and model configurations bundled with [Pi](https://github.com/earendil-works/pi). In **Settings → Providers**, choose **Refresh models** on a provider card, select compatible models, then choose **Add selected**. Refresh looks up the public catalog and preserves your saved settings and models. Use **Add Provider** to set up another provider.
Team Owner can freely edit, delete, or add new providers. All configured provider and model settings are injected directly into the Pi framework at runtime. Team Owner can freely edit, delete, or add new providers. All configured provider and model settings are injected directly into the Pi framework at runtime.
+14 -4
View File
@@ -41,7 +41,7 @@ For video assets, Shumai breaks videos into standardized segments and extracts k
> >
> If you change your embedding provider (for example, switching from Google Gemini's 1536-dimensional embeddings to EmbeddingGemma's 768-dimensional embeddings, or vice versa), **all existing vector embeddings in your database become invalid**. > If you change your embedding provider (for example, switching from Google Gemini's 1536-dimensional embeddings to EmbeddingGemma's 768-dimensional embeddings, or vice versa), **all existing vector embeddings in your database become invalid**.
> >
> To protect production databases from accidental corruption and search failures, **Shumai intentionally does not provide a WebUI toggle to change the embedding provider**. The provider can only be configured by an administrator via environment variables (`EMBEDDING_PROVIDER` and `GEMMA_EMBEDDING_OPENAI_BASE_URL`). > Saving an embedding server URL in Integrations selects EmbeddingGemma when `EMBEDDING_PROVIDER` is unset. Regenerate your embeddings after switching providers.
--- ---
@@ -103,6 +103,7 @@ services:
EMBEDDING_PROVIDER: gemma-embedding-2-openai EMBEDDING_PROVIDER: gemma-embedding-2-openai
GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1 GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1
ENABLE_EMBEDDING_AGENT: 'true' ENABLE_EMBEDDING_AGENT: 'true'
ENABLE_TRANSCRIPTION_AGENT: 'true'
CONCURRENCY_AGENT: 1 CONCURRENCY_AGENT: 1
depends_on: depends_on:
- embedding-server - embedding-server
@@ -111,13 +112,22 @@ services:
> [!NOTE] > [!NOTE]
> Since Shumai communicates with `embedding-server` over Docker's internal network, `embedding-server` does not need to expose any ports to the host machine. > Since Shumai communicates with `embedding-server` over Docker's internal network, `embedding-server` does not need to expose any ports to the host machine.
### Configure in Shumai
Open **Team Settings → Integrations → Embedding Server**. Enter the URL as reached from Shumai, select **Test Connection**, and save. For Docker Compose, use the internal service address, such as `http://embedding-server:9379/v1`. Clear the field and save to remove the setting.
`EMBEDDING_PROVIDER` takes precedence over automatic provider selection. When `GEMMA_EMBEDDING_OPENAI_BASE_URL` is set, that URL takes precedence and the field is read-only. The embedding server accepts unauthenticated requests. [Embedding server source](https://github.com/shumaiOne/embedding-server/blob/main/serve.py)
Enable the **Embedding Agent** for semantic search. Enable the **Transcript Agent** for video transcription and internal comments on failed jobs. Both agents are available in **Team Settings → Agents**.
### Environment Variables ### Environment Variables
| Variable | Required | Description | Default | | Variable | Required | Description | Default |
| :-------------------------------- | :---------- | :---------------------------------------------------------------------------------------------------------------------------- | :------------------------- | | :-------------------------------- | :------------ | :----------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------- |
| `EMBEDDING_PROVIDER` | Yes | Set to `gemma-embedding-2-openai` to use the local LiteRT-LM server. | `gemini-embedding-2` | | `EMBEDDING_PROVIDER` | For env setup | Set to `gemma-embedding-2-openai` to use the local LiteRT-LM server. | `gemini-embedding-2` when no integration URL is saved |
| `GEMMA_EMBEDDING_OPENAI_BASE_URL` | Yes | HTTP base URL of the embedding server (e.g. `http://embedding-server:9379/v1`). | `http://localhost:9379/v1` | | `GEMMA_EMBEDDING_OPENAI_BASE_URL` | No | Overrides the saved embedding server URL and makes the integration read-only. | `http://localhost:9379/v1` when the local provider is selected without a URL |
| `ENABLE_EMBEDDING_AGENT` | No | Automatically provisions and enables the system embedding agent for all teams on startup. | `false` | | `ENABLE_EMBEDDING_AGENT` | No | Automatically provisions and enables the system embedding agent for all teams on startup. | `false` |
| `ENABLE_TRANSCRIPTION_AGENT` | No | Set to `true` to create or enable the Transcript Agent, or `false` to disable it. Either value makes it read-only in Settings. | Unset. Manage the agent in Settings. |
| `CONCURRENCY_AGENT` | Recommended | Maximum concurrent AI tasks executed by workers. **Set to `1`** when running `embedding-server` to prevent high memory usage. | `5` | | `CONCURRENCY_AGENT` | Recommended | Maximum concurrent AI tasks executed by workers. **Set to `1`** when running `embedding-server` to prevent high memory usage. | `5` |
--- ---
+11 -1
View File
@@ -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**. 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. 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 - Add password protection
- Set an expiration date - Set an expiration date
- Allow or disallow downloads - 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 ## Security and Settings
### Expiration Date ### Expiration Date
+2 -1
View File
@@ -100,9 +100,10 @@ Shumai 支持配置可选的**归档存储**(冷存储)层级(`local` NAS/
## 向量模型配置 ## 向量模型配置
| 变量 | 说明 | 示例 / 默认值 | | 变量 | 说明 | 示例 / 默认值 |
| :-------------------------------- | :------------------------------------------------------------------------------- | :-------------------------------- | | :-------------------------------- | :-------------------------------------------------------------------------------------------- | :-------------------------------- |
| `EMBEDDING_PROVIDER` | 多模态向量模型服务商。可选值:`gemini-embedding-2`、`gemma-embedding-2-openai`。 | `gemini-embedding-2`(默认) | | `EMBEDDING_PROVIDER` | 多模态向量模型服务商。可选值:`gemini-embedding-2`、`gemma-embedding-2-openai`。 | `gemini-embedding-2`(默认) |
| `GEMMA_EMBEDDING_OPENAI_BASE_URL` | 兼容 OpenAI 协议的 LiteRT-LM 向量模型服务 Base URL。 | `http://embedding-server:9379/v1` | | `GEMMA_EMBEDDING_OPENAI_BASE_URL` | 兼容 OpenAI 协议的 LiteRT-LM 向量模型服务 Base URL。 | `http://embedding-server:9379/v1` |
| `ENABLE_TRANSCRIPTION_AGENT` | 设置为 `true` 时自动创建并启用转录智能体,设置为 `false` 时停用。两种情况下团队设置均为只读。 | 未设置时可在团队设置中管理。 |
| `ENABLE_EMBEDDING_AGENT` | 设为 `true` 时,在启动时自动为所有团队置备并启用系统向量智能体。 | `false`(默认) | | `ENABLE_EMBEDDING_AGENT` | 设为 `true` 时,在启动时自动为所有团队置备并启用系统向量智能体。 | `false`(默认) |
| `EMBEDDING_CHUNK_DURATION` | 生成视频向量时每个视频切片的时长(单位:秒)。 | `60.0`(默认) | | `EMBEDDING_CHUNK_DURATION` | 生成视频向量时每个视频切片的时长(单位:秒)。 | `60.0`(默认) |
| `EMBEDDING_CHUNK_OVERLAP` | 生成视频向量时各个视频切片的重叠时长(单位:秒)。 | `5.0`(默认) | | `EMBEDDING_CHUNK_OVERLAP` | 生成视频向量时各个视频切片的重叠时长(单位:秒)。 | `5.0`(默认) |
+1 -1
View File
@@ -11,7 +11,7 @@ description: 将 Shumai 连接至 OpenAI、Anthropic、Gemini 或自定义 LLM
## 内置模型服务商 ## 内置模型服务商
Shumai 预置了主流 LLM 服务商的配置。由于 Shumai 采用 [Pi](https://github.com/earendil-works/pi) 作为底层核心智能体框架,系统支持的服务商与模型配置会自动与 Pi 的功能生态保持同步。 Shumai 使用 [Pi](https://github.com/earendil-works/pi) 随附的服务商与模型配置初始化新团队。在**设置 → 服务商**中,点击服务商卡片上的**刷新模型**,选择兼容的模型,然后点击**添加所选**。刷新会查询公开模型目录,并保留现有设置和模型。若要设置其他服务商,请点击**添加服务商**。
团队所有者可自由编辑、删除或添加新服务商。所有已配置的服务商与模型参数均会在运行时直接注入 Pi 框架。 团队所有者可自由编辑、删除或添加新服务商。所有已配置的服务商与模型参数均会在运行时直接注入 Pi 框架。
+14 -4
View File
@@ -41,7 +41,7 @@ Shumai 支持通过 [shumaiOne/embedding-server](https://github.com/shumaiOne/em
> >
> 若更换向量服务提供商(例如从 Google Gemini 的 1536 维向量切换到 EmbeddingGemma 的 768 维向量,反之亦然),**数据库中现存的所有向量嵌入数据将全部失效**。 > 若更换向量服务提供商(例如从 Google Gemini 的 1536 维向量切换到 EmbeddingGemma 的 768 维向量,反之亦然),**数据库中现存的所有向量嵌入数据将全部失效**。
> >
> 为保护生产数据库免受误操作损坏及搜索失效,**Shumai 刻意未在 Web 界面中提供切换 Embedding 提供商的开关**。该配置仅能由管理员通过环境变量(`EMBEDDING_PROVIDER` 和 `GEMMA_EMBEDDING_OPENAI_BASE_URL`)进行配置。 > 未设置 `EMBEDDING_PROVIDER` 时,在集成页面保存向量模型服务地址会启用 EmbeddingGemma。切换向量模型服务后,请重新生成向量。
--- ---
@@ -103,6 +103,7 @@ services:
EMBEDDING_PROVIDER: gemma-embedding-2-openai EMBEDDING_PROVIDER: gemma-embedding-2-openai
GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1 GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1
ENABLE_EMBEDDING_AGENT: 'true' ENABLE_EMBEDDING_AGENT: 'true'
ENABLE_TRANSCRIPTION_AGENT: 'true'
CONCURRENCY_AGENT: 1 CONCURRENCY_AGENT: 1
depends_on: depends_on:
- embedding-server - embedding-server
@@ -111,13 +112,22 @@ services:
> [!NOTE] > [!NOTE]
> 由于 Shumai 与 `embedding-server` 在 Docker 内部网络中通信,`embedding-server` 无需向宿主机映射暴露端口。 > 由于 Shumai 与 `embedding-server` 在 Docker 内部网络中通信,`embedding-server` 无需向宿主机映射暴露端口。
### 在 Shumai 中配置
打开 **团队设置 → 集成 → 向量模型服务**。输入 Shumai 可以访问的服务地址,选择 **测试连接**,然后保存。使用 Docker Compose 时,可填写内部服务地址,例如 `http://embedding-server:9379/v1`。清空地址并保存即可移除配置。
已设置的 `EMBEDDING_PROVIDER` 优先于自动选择。设置 `GEMMA_EMBEDDING_OPENAI_BASE_URL` 后,环境变量中的地址优先生效,集成页面的地址字段为只读。向量模型服务接受未经身份验证的请求。[向量模型服务源码](https://github.com/shumaiOne/embedding-server/blob/main/serve.py)
在 **团队设置 → 智能体** 中启用 **嵌入智能体** 后可使用语义搜索。启用 **转录智能体** 后可生成视频转录,转录失败时会在视频中发布内部评论。
### 环境变量 ### 环境变量
| 变量 | 必填 | 说明 | 默认值 | | 变量 | 必填 | 说明 | 默认值 |
| :-------------------------------- | :------- | :------------------------------------------------------------------------------------------------ | :------------------------- | | :-------------------------------- | :----------------- | :------------------------------------------------------------------------------------------------ | :---------------------------------------------------------- |
| `EMBEDDING_PROVIDER` | 是 | 设置为 `gemma-embedding-2-openai` 以使用本地 LiteRT-LM 服务。 | `gemini-embedding-2` | | `EMBEDDING_PROVIDER` | 环境变量配置时需要 | 设置为 `gemma-embedding-2-openai` 以使用本地 LiteRT-LM 服务。 | 未保存服务地址时为 `gemini-embedding-2` |
| `GEMMA_EMBEDDING_OPENAI_BASE_URL` | 是 | 向量模型服务的 HTTP 基础地址(例如 `http://embedding-server:9379/v1`)。 | `http://localhost:9379/v1` | | `GEMMA_EMBEDDING_OPENAI_BASE_URL` | 否 | 覆盖集成页面保存的服务地址,并将地址字段设为只读。 | 选择本地模型服务且未配置地址时为 `http://localhost:9379/v1` |
| `ENABLE_EMBEDDING_AGENT` | 否 | 启动时自动为所有团队初始化并启用系统级向量嵌入智能体。 | `false` | | `ENABLE_EMBEDDING_AGENT` | 否 | 启动时自动为所有团队初始化并启用系统级向量嵌入智能体。 | `false` |
| `ENABLE_TRANSCRIPTION_AGENT` | 否 | `true` 会创建或启用转录智能体,`false` 会停用它。两种情况下设置页面均为只读。 | 未设置时可在设置页面管理。 |
| `CONCURRENCY_AGENT` | 推荐配置 | Worker 执行 AI 任务的最大并发数。运行 `embedding-server` 时**务必设为 `1`**,以防止内存开销过大。 | `5` | | `CONCURRENCY_AGENT` | 推荐配置 | Worker 执行 AI 任务的最大并发数。运行 `embedding-server` 时**务必设为 `1`**,以防止内存开销过大。 | `5` |
--- ---
+11 -1
View File
@@ -11,7 +11,7 @@ Shumai 支持与未注册工作区账号的外部利益相关者协作。借助*
1. 选中要分享的文件或文件夹,右键单击并选择**创建新分享链接**。 1. 选中要分享的文件或文件夹,右键单击并选择**创建新分享链接**。
2. 在项目侧边栏中点击刚创建的**分享链接**,进入其配置页面。 2. 在项目侧边栏中点击刚创建的**分享链接**,进入其配置页面。
3. 在右侧边栏中配置分享链接参数: 3. 在右侧边栏的**设置**选项卡中配置分享链接。
- 添加密码保护 - 添加密码保护
- 设置过期时间 - 设置过期时间
- 开启或禁止文件下载 - 开启或禁止文件下载
@@ -33,6 +33,16 @@ Shumai 支持与未注册工作区账号的外部利益相关者协作。借助*
--- ---
## 查看分享活动
在项目侧边栏打开**所有分享链接**,即可看到每条链接的**浏览次数**和**最近浏览**时间。点击对应行的**查看活动**,或在该链接的配置页面切换到**活动**选项卡,即可查看活动记录。
活动按天分组,包括打开分享链接、浏览文件和文件夹、下载以及发表评论。可以识别访客时显示其姓名,匿名活动显示为**有人**。访客开始下载且通过权限验证后,系统会记录下载活动。
每次成功打开分享页面、共享文件夹或共享文件(包括刷新页面)都会增加一次**浏览次数**,并更新**最近浏览**时间。系统根据分享链接、操作、访客和相关资产(如有)判断活动是否重复,30 分钟内的重复活动只显示一次。判断时,所有匿名访客视为同一位访客。例如,同一位访客在十分钟内两次打开同一文件,**浏览次数**会增加两次,活动列表显示一条**浏览了素材**的记录。
---
## 安全与权限配置 ## 安全与权限配置
### 有效期 ### 有效期
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "shumai", "name": "shumai",
"version": "0.7.1", "version": "0.7.2",
"private": true, "private": true,
"type": "module", "type": "module",
"repository": { "repository": {
+4 -4
View File
@@ -1,14 +1,14 @@
{ {
"name": "@shumai/agent", "name": "@shumai/agent",
"version": "0.7.1", "version": "0.7.2",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./src/index.ts", "main": "./src/index.ts",
"types": "./src/index.ts", "types": "./src/index.ts",
"dependencies": { "dependencies": {
"@earendil-works/chord": "1.5.0", "@earendil-works/chord": "1.7.0",
"@earendil-works/pi-ai": "1.5.0", "@earendil-works/pi-ai": "1.7.0",
"@earendil-works/pi-durable": "1.5.0", "@earendil-works/pi-durable": "1.7.0",
"@google/genai": "2.28.0", "@google/genai": "2.28.0",
"@shumai/core": "workspace:*", "@shumai/core": "workspace:*",
"@shumai/db": "workspace:*", "@shumai/db": "workspace:*",
+2
View File
@@ -601,6 +601,7 @@ export const createCommentActivity = defineStep(
sessionId?: string | null sessionId?: string | null
agentId?: string | null agentId?: string | null
replyToId?: string | null replyToId?: string | null
isInternal?: boolean
}) { }) {
if (params.sessionId) { if (params.sessionId) {
const agentId = params.agentId && params.agentId !== 'default' ? params.agentId : 'default' const agentId = params.agentId && params.agentId !== 'default' ? params.agentId : 'default'
@@ -669,6 +670,7 @@ export const createCommentActivity = defineStep(
sessionId: params.sessionId ?? null, sessionId: params.sessionId ?? null,
creatorId: params.agentId && params.agentId !== 'default' ? params.agentId : null, creatorId: params.agentId && params.agentId !== 'default' ? params.agentId : null,
replyToId: params.replyToId, replyToId: params.replyToId,
isInternal: params.isInternal ?? false,
}, },
}) })
}, },
+35 -22
View File
@@ -1,5 +1,9 @@
import { GoogleGenAI } from '@google/genai' import { GoogleGenAI } from '@google/genai'
import { s3Service } from '@shumai/core/src/s3/s3' import { s3Service } from '@shumai/core/src/s3/s3'
import {
embeddingServerService,
LOCAL_EMBEDDING_PROVIDER,
} from '@shumai/core/src/search/embedding-server'
import { textEmbeddingService } from '@shumai/core/src/search/text-embedding' import { textEmbeddingService } from '@shumai/core/src/search/text-embedding'
import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db' import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import { import {
@@ -59,19 +63,13 @@ interface OpenAiEmbeddingItem {
} }
} }
async function callGemmaEmbeddingServer(input: string | OpenAiEmbeddingItem[]): Promise<{ async function callGemmaEmbeddingServer(
endpoint: string,
input: OpenAiEmbeddingItem[],
): Promise<{
embedding: number[] embedding: number[]
usage: Usage usage: Usage
}> { }> {
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(endpoint, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
@@ -89,8 +87,12 @@ async function callGemmaEmbeddingServer(input: string | OpenAiEmbeddingItem[]):
}) })
} }
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- response json shape is dynamic from external endpoint const json = (await response.json()) as {
const json: any = await response.json() model?: string
data?: Array<{ embedding?: number[] }>
// eslint-disable-next-line @typescript-eslint/naming-convention -- OpenAI response field
usage?: { prompt_tokens?: number }
}
const embedding = json.data?.[0]?.embedding const embedding = json.data?.[0]?.embedding
if (!embedding || !Array.isArray(embedding)) { if (!embedding || !Array.isArray(embedding)) {
throw ApplicationFailure.create({ throw ApplicationFailure.create({
@@ -102,7 +104,7 @@ async function callGemmaEmbeddingServer(input: string | OpenAiEmbeddingItem[]):
return { return {
embedding, embedding,
usage: { usage: {
model: json.model || 'gemma-embedding-2-openai', model: json.model || LOCAL_EMBEDDING_PROVIDER,
inputTokens: json.usage?.prompt_tokens ?? 0, inputTokens: json.usage?.prompt_tokens ?? 0,
outputTokens: 0, outputTokens: 0,
}, },
@@ -119,8 +121,8 @@ export const generateTextEmbeddingActivity = defineStep(
embedding: number[] embedding: number[]
usage: Usage usage: Usage
}> { }> {
const provider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2' const { provider } = await embeddingServerService.resolveRuntimeConfig(params.teamId)
if (provider !== 'gemma-embedding-2-openai' && !process.env.GEMINI_API_KEY) { if (provider !== LOCAL_EMBEDDING_PROVIDER && !process.env.GEMINI_API_KEY) {
throw ApplicationFailure.create({ throw ApplicationFailure.create({
message: 'GEMINI_API_KEY environment variable is not configured', message: 'GEMINI_API_KEY environment variable is not configured',
nonRetryable: true, nonRetryable: true,
@@ -129,6 +131,7 @@ export const generateTextEmbeddingActivity = defineStep(
try { try {
const result = await textEmbeddingService.generateEmbedding(params.text, { const result = await textEmbeddingService.generateEmbedding(params.text, {
provider,
teamId: params.teamId, teamId: params.teamId,
skipCache: true, skipCache: true,
}) })
@@ -193,7 +196,9 @@ export const getEmbeddingContextActivity = defineStep(
const parsedOverlap = parseFloat(process.env.EMBEDDING_CHUNK_OVERLAP || '') const parsedOverlap = parseFloat(process.env.EMBEDDING_CHUNK_OVERLAP || '')
const chunkOverlap = Number.isFinite(parsedOverlap) && parsedOverlap >= 0 ? parsedOverlap : 5.0 const chunkOverlap = Number.isFinite(parsedOverlap) && parsedOverlap >= 0 ? parsedOverlap : 5.0
const embeddingProvider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2' const { provider: embeddingProvider } = await embeddingServerService.resolveRuntimeConfig(
params.teamId,
)
const existingEmbeddings = await prisma.$queryRaw<ExistingAssetEmbeddingInfo[]>` const existingEmbeddings = await prisma.$queryRaw<ExistingAssetEmbeddingInfo[]>`
SELECT SELECT
@@ -290,6 +295,7 @@ export const saveAssetEmbeddingsActivity = defineStep(
export interface GenerateImageEmbeddingParams { export interface GenerateImageEmbeddingParams {
teamId: string teamId: string
provider?: string
assetKey: string assetKey: string
mediaType: string mediaType: string
} }
@@ -299,20 +305,23 @@ export const generateImageEmbeddingActivity = defineStep(
embedding: number[] embedding: number[]
usage: Usage usage: Usage
}> { }> {
const provider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2' const { provider, embeddingEndpoint } = await embeddingServerService.resolveRuntimeConfig(
params.teamId,
params.provider,
)
const { buffer: data } = await s3Service.getObject( const { buffer: data } = await s3Service.getObject(
process.env.S3_BUCKET || 'shumai', process.env.S3_BUCKET || 'shumai',
params.assetKey, params.assetKey,
) )
if (provider === 'gemma-embedding-2-openai') { if (provider === LOCAL_EMBEDDING_PROVIDER) {
let imgData = data let imgData = data
let mimeType = params.mediaType || 'image/jpeg' let mimeType = params.mediaType || 'image/jpeg'
if (mimeType !== 'image/jpeg' && mimeType !== 'image/png') { if (mimeType !== 'image/jpeg' && mimeType !== 'image/png') {
imgData = await sharp(data).jpeg().toBuffer() imgData = await sharp(data).jpeg().toBuffer()
mimeType = 'image/jpeg' mimeType = 'image/jpeg'
} }
return callGemmaEmbeddingServer([ return callGemmaEmbeddingServer(embeddingEndpoint, [
{ {
type: 'image_url', type: 'image_url',
// eslint-disable-next-line @typescript-eslint/naming-convention // eslint-disable-next-line @typescript-eslint/naming-convention
@@ -383,6 +392,7 @@ export function getGemmaEmbeddingTargetFrameCount(width?: number, height?: numbe
export interface GenerateVideoChunkEmbeddingParams { export interface GenerateVideoChunkEmbeddingParams {
teamId: string teamId: string
provider?: string
chunkKey: string chunkKey: string
} }
@@ -393,8 +403,11 @@ export const generateVideoChunkEmbeddingActivity = defineStep(
embedding: number[] embedding: number[]
usage: Usage usage: Usage
}> { }> {
const provider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2' const { provider, embeddingEndpoint } = await embeddingServerService.resolveRuntimeConfig(
const isGemma = provider === 'gemma-embedding-2-openai' || params.chunkKey.endsWith('.tar') params.teamId,
params.provider,
)
const isGemma = provider === LOCAL_EMBEDDING_PROVIDER || params.chunkKey.endsWith('.tar')
if (isGemma) { if (isGemma) {
const { buffer: data } = await s3Service.getObject( const { buffer: data } = await s3Service.getObject(
@@ -467,7 +480,7 @@ export const generateVideoChunkEmbeddingActivity = defineStep(
}), }),
) )
return await callGemmaEmbeddingServer(input) return await callGemmaEmbeddingServer(embeddingEndpoint, input)
} }
const apiKey = process.env.GEMINI_API_KEY const apiKey = process.env.GEMINI_API_KEY
@@ -0,0 +1,222 @@
import { execFile } from 'node:child_process'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { promisify } from 'node:util'
import { logger } from '@shumai/core/src/logger'
import { s3Service } from '@shumai/core/src/s3/s3'
import {
isLocalTranscriptionEnabled,
LocalTranscriptionError,
transcribeLocalAudio,
} from '@shumai/core/src/transcript/local-transcription'
import { transcriptService } from '@shumai/core/src/transcript/transcript'
import { selectPrimaryAudioStream } from '@shumai/core/src/transcode/transcode'
import { prisma } from '@shumai/db'
import {
selectTranscriptVideoProxyKey,
transcriptionErrors,
transcriptVideoStatuses,
} from '@shumai/dtos'
import {
ApplicationFailure,
defineStep,
ensureLocalMediaFile,
getLocalTaskAbortSignal,
} from '@shumai/workflow-core'
import { z } from 'zod'
const execFileAsync = promisify(execFile)
const audioProbeSchema = z.object({
streams: z.array(
z.object({
index: z.number().int().nonnegative(),
// eslint-disable-next-line @typescript-eslint/naming-convention -- ffprobe field
codec_type: z.string(),
// eslint-disable-next-line @typescript-eslint/naming-convention -- ffprobe field
bit_rate: z.string().optional(),
disposition: z.record(z.string(), z.number()).optional(),
}),
),
})
async function removeTempDirectory(directory: string): Promise<void> {
try {
await rm(directory, { recursive: true, force: true })
} catch (error) {
logger.warn({ err: error, directory }, 'Failed to remove local transcription files')
}
}
export const extractTranscriptAudioActivity = defineStep(
async function extractTranscriptAudioActivity({
assetId,
taskId,
audioKey,
teamId,
}: {
assetId: string
taskId: string
audioKey: string
teamId?: string
}): Promise<void> {
if (!(await isLocalTranscriptionEnabled(teamId))) {
throw ApplicationFailure.create({
message: 'Local transcription is disabled',
nonRetryable: true,
})
}
const asset = await prisma.asset.findFirst({
where: {
id: assetId,
type: 'file',
status: { in: [...transcriptVideoStatuses] },
isDeleted: false,
mediaType: { startsWith: 'video/' },
},
select: { media: true },
})
const proxyKey = selectTranscriptVideoProxyKey(asset?.media)
if (!proxyKey) {
throw ApplicationFailure.create({ message: transcriptionErrors.noProxy, nonRetryable: true })
}
const signal = getLocalTaskAbortSignal(taskId)
const directory = await mkdtemp(join(tmpdir(), 'shumai-transcript-'))
try {
const video = await ensureLocalMediaFile(proxyKey, join(directory, 'video.mp4'))
const { stdout } = await execFileAsync(
'ffprobe',
['-v', 'error', '-select_streams', 'a', '-show_streams', '-of', 'json', video],
{ signal },
)
const stream = selectPrimaryAudioStream(audioProbeSchema.parse(JSON.parse(stdout)).streams)
if (!stream) {
throw ApplicationFailure.create({
message: transcriptionErrors.noAudio,
nonRetryable: true,
})
}
const wav = join(directory, 'audio.wav')
// Keep the container timeline and fill any leading gap before the primary audio starts.
await execFileAsync(
'ffmpeg',
[
'-nostdin',
'-v',
'error',
'-copyts',
'-start_at_zero',
'-i',
video,
'-map',
`0:${stream.index}`,
'-af',
'aresample=16000:async=1:first_pts=0',
'-ac',
'1',
'-c:a',
'pcm_s16le',
wav,
],
{ signal },
)
signal?.throwIfAborted()
await s3Service.uploadFileToKey(wav, audioKey, 'audio/wav')
} finally {
await removeTempDirectory(directory)
}
},
)
export const transcribeAudioActivity = defineStep(async function transcribeAudioActivity({
teamId,
taskId,
audioKey,
language,
model,
}: {
teamId?: string
taskId: string
audioKey: string
language: string | null
model: string
}) {
const directory = await mkdtemp(join(tmpdir(), 'shumai-transcript-'))
try {
const path = await ensureLocalMediaFile(audioKey, join(directory, 'audio.wav'))
return await transcribeLocalAudio({
teamId,
audio: Bun.file(path),
language,
model,
signal: getLocalTaskAbortSignal(taskId),
})
} catch (error) {
if (error instanceof LocalTranscriptionError) {
const { status } = error
if (status >= 400 && status < 500 && status !== 408 && status !== 429) {
throw ApplicationFailure.create({
message: status === 413 ? transcriptionErrors.tooLarge : error.message,
nonRetryable: true,
})
}
}
if (error instanceof z.ZodError || error instanceof SyntaxError) {
throw ApplicationFailure.create({
message: 'Invalid transcription response',
nonRetryable: true,
})
}
throw error
} finally {
await removeTempDirectory(directory)
}
})
export const saveTranscriptActivity = defineStep(async function saveTranscriptActivity(
params: Parameters<typeof transcriptService.saveResult>[0],
): Promise<void> {
if (!(await transcriptService.saveResult(params))) {
throw ApplicationFailure.create({ message: 'Video is no longer available', nonRetryable: true })
}
})
export const reportTranscriptionFailureActivity = defineStep(
async function reportTranscriptionFailureActivity(taskId: string, reason: string | undefined) {
if (getLocalTaskAbortSignal(taskId)?.aborted) return
const task = await prisma.workflowTask.findUnique({
where: { id: taskId, type: 'ai_transcription', status: 'processing' },
select: { assetId: true, teamId: true },
})
if (!task?.teamId) return
const asset = await prisma.asset.findFirst({
where: { id: task.assetId, isDeleted: false, project: { teamId: task.teamId } },
select: { id: true },
})
if (!asset) return
const agent = await transcriptService.findEnabledAgent(task.teamId)
if (!agent || getLocalTaskAbortSignal(taskId)?.aborted) return
const detail = Object.values(transcriptionErrors).find((message) => message === reason)
await prisma.assetComment.upsert({
where: { transcriptionTaskId: taskId },
update: {},
create: {
assetId: asset.id,
creatorId: agent.id,
transcriptionTaskId: taskId,
isInternal: true,
message: detail
? `Transcription failed. ${detail}.`
: 'Transcription failed. Try generating the transcript again.',
},
})
},
)
+2
View File
@@ -3,9 +3,11 @@ import { registerWorkflow } from '@shumai/workflow-core'
import { agentAutofillMedia } from './workflows/agent-autofill' import { agentAutofillMedia } from './workflows/agent-autofill'
import { agentChat } from './workflows/agent-chat' import { agentChat } from './workflows/agent-chat'
import { agentEmbeddingMedia } from './workflows/agent-embedding' import { agentEmbeddingMedia } from './workflows/agent-embedding'
import { transcribeVideoWorkflow } from './workflows/transcribe-video'
export function initAgentWorkflows() { export function initAgentWorkflows() {
registerWorkflow(WorkflowTaskType.ai_embedding, agentEmbeddingMedia) registerWorkflow(WorkflowTaskType.ai_embedding, agentEmbeddingMedia)
registerWorkflow(WorkflowTaskType.ai_transcription, transcribeVideoWorkflow)
registerWorkflow(WorkflowTaskType.ai_metadata_autofill, agentAutofillMedia) registerWorkflow(WorkflowTaskType.ai_metadata_autofill, agentAutofillMedia)
registerWorkflow(WorkflowTaskType.chat, agentChat) registerWorkflow(WorkflowTaskType.chat, agentChat)
} }
@@ -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 () => { it('should skip session initialization if sessionId is already provided', async () => {
const task = await prisma.workflowTask.create({ const task = await prisma.workflowTask.create({
data: { data: {
@@ -85,6 +85,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
sessionId: sessionId || 'pending', sessionId: sessionId || 'pending',
agentId: agentId, agentId: agentId,
replyToId: userComment.replyToId ?? userComment.id, replyToId: userComment.replyToId ?? userComment.id,
...(userComment.isInternal ? { isInternal: true } : {}),
}) })
placeholderCommentId = placeholder.id placeholderCommentId = placeholder.id
@@ -1,4 +1,5 @@
import { logger } from '@shumai/core/src/logger' import { logger } from '@shumai/core/src/logger'
import { LOCAL_EMBEDDING_PROVIDER } from '@shumai/core/src/search/embedding-server'
import type { WorkflowTask } from '@shumai/db' import type { WorkflowTask } from '@shumai/db'
import { import {
ApplicationFailure, ApplicationFailure,
@@ -56,7 +57,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
} }
const { asset, chunkDuration, chunkOverlap, embeddingProvider, existingEmbeddings } = context const { asset, chunkDuration, chunkOverlap, embeddingProvider, existingEmbeddings } = context
const isGemmaProvider = embeddingProvider === 'gemma-embedding-2-openai' const isGemmaProvider = embeddingProvider === LOCAL_EMBEDDING_PROVIDER
const existing = existingEmbeddings || [] const existing = existingEmbeddings || []
@@ -130,6 +131,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
if (!alreadyEmbedded) { if (!alreadyEmbedded) {
const result = await generateImageEmbeddingActivity({ const result = await generateImageEmbeddingActivity({
teamId: task.teamId, teamId: task.teamId,
provider: embeddingProvider,
assetKey: embeddingKey, assetKey: embeddingKey,
mediaType: embeddingMediaType || 'image/jpeg', mediaType: embeddingMediaType || 'image/jpeg',
}) })
@@ -195,6 +197,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
// Step B: Generate embedding on agent worker // Step B: Generate embedding on agent worker
const chunkResult = await generateVideoChunkEmbeddingActivity({ const chunkResult = await generateVideoChunkEmbeddingActivity({
teamId: task.teamId, teamId: task.teamId,
provider: embeddingProvider,
chunkKey: chunk.chunkKey, chunkKey: chunk.chunkKey,
}) })
@@ -0,0 +1,64 @@
import { logger } from '@shumai/core/src/logger'
import type { WorkflowTask } from '@shumai/db'
import { ApplicationFailure, isDbosWorkflowCancelledError } from '@shumai/workflow-core'
import { deleteS3ObjectActivity } from '../activities/ai'
import {
extractTranscriptAudioActivity,
saveTranscriptActivity,
transcribeAudioActivity,
reportTranscriptionFailureActivity,
} from '../activities/transcription'
export async function transcribeVideoWorkflow(task: WorkflowTask): Promise<void> {
const request = task.payload?.transcription
if (!request) {
throw ApplicationFailure.create({
message: 'Missing transcription request',
nonRetryable: true,
})
}
const taskId = task.id
const assetId = task.assetId
const teamId = task.teamId ?? undefined
const audioKey = `temp/transcripts/${taskId}.wav`
try {
await extractTranscriptAudioActivity({ assetId, taskId, audioKey, teamId })
const transcript = await transcribeAudioActivity({ taskId, audioKey, teamId, ...request })
if (request.language && transcript.language && request.language !== transcript.language) {
throw ApplicationFailure.create({
message: 'Transcription returned an unexpected language',
nonRetryable: true,
})
}
await saveTranscriptActivity({
taskId,
assetId,
model: request.model,
language: transcript.language,
segments: transcript.segments.map((segment) => ({
startMs: Math.round(segment.start * 1000),
endMs: Math.round(segment.end * 1000),
text: segment.text,
})),
})
} catch (error) {
if (!isDbosWorkflowCancelledError(error)) {
try {
await reportTranscriptionFailureActivity(
taskId,
error instanceof Error ? error.message : undefined,
)
} catch (commentError) {
logger.error({ err: commentError, taskId }, 'Failed to post transcript failure comment')
}
}
throw error
} finally {
try {
await deleteS3ObjectActivity({ key: audioKey })
} catch (error) {
logger.error({ err: error, taskId, audioKey }, 'Failed to delete staged transcript audio')
}
}
}
+2 -2
View File
@@ -1,13 +1,13 @@
{ {
"name": "@shumai/api", "name": "@shumai/api",
"version": "0.7.1", "version": "0.7.2",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./src/index.ts", "main": "./src/index.ts",
"types": "./src/index.ts", "types": "./src/index.ts",
"dependencies": { "dependencies": {
"@better-auth/mcp": "1.7.12", "@better-auth/mcp": "1.7.12",
"@earendil-works/pi-durable": "1.5.0", "@earendil-works/pi-durable": "1.7.0",
"@hono/zod-validator": "0.7.6", "@hono/zod-validator": "0.7.6",
"@modelcontextprotocol/server": "2.0.0", "@modelcontextprotocol/server": "2.0.0",
"@shumai/core": "workspace:*", "@shumai/core": "workspace:*",
+6 -5
View File
@@ -1,11 +1,12 @@
import type { EntryRecord } from '@earendil-works/pi-durable' import type { EntryRecord } from '@earendil-works/pi-durable'
import type { AgentSessionLogs } from '@shumai/dtos'
import type { TypedResponse } from 'hono' import type { TypedResponse } from 'hono'
/** Pi records are already JSON; retain their public types without recursively remapping SDK schemas. */ /** Pi records are already JSON; retain their public types without recursively remapping SDK schemas. */
export function agentEntriesResponse( export function agentEntriesResponse<T extends EntryRecord[] | AgentSessionLogs>(
entries: EntryRecord[], body: T,
): Response & TypedResponse<EntryRecord[], 200, 'json'> { ): Response & TypedResponse<T, 200, 'json'> {
return new Response(JSON.stringify(entries), { return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json; charset=UTF-8' }, headers: { 'Content-Type': 'application/json; charset=UTF-8' },
}) as Response & TypedResponse<EntryRecord[], 200, 'json'> }) as Response & TypedResponse<T, 200, 'json'>
} }
+80 -1
View File
@@ -2,12 +2,14 @@ import { ROOT_CONVERSATION_ID, type EntryId, type EntryRecord } from '@earendil-
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { HTTPException } from 'hono/http-exception' import { HTTPException } from 'hono/http-exception'
import { agentService } from '@shumai/core/src/agent/agent' import { agentService } from '@shumai/core/src/agent/agent'
import { agentSessionService } from '@shumai/core/src/agent/session-service'
import { authzService } from '@shumai/core/src/authz/authz' import { authzService } from '@shumai/core/src/authz/authz'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog' import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import type { AgentInfo } from '@shumai/dtos' import type { AgentInfo } from '@shumai/dtos'
import app from './agent' import app from './agent'
vi.mock('@shumai/core/src/agent/agent') vi.mock('@shumai/core/src/agent/agent')
vi.mock('@shumai/core/src/agent/session-service')
vi.mock('@shumai/core/src/authz/authz') vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({ vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: { auditLogService: {
@@ -69,6 +71,36 @@ describe('Agent API', () => {
}) })
}) })
it.each(['true', 'false'])(
'protects the Transcript Agent when ENABLE_TRANSCRIPTION_AGENT=%s',
async (value) => {
vi.stubEnv('ENABLE_TRANSCRIPTION_AGENT', value)
try {
vi.mocked(agentService.getAgent).mockResolvedValue({
id: 'transcript1',
teamId: 'team1',
type: 'transcription',
} as Awaited<ReturnType<typeof agentService.getAgent>>)
const payload = JSON.stringify({ type: 'transcription', name: 'Transcript Agent' })
const headers = { 'Content-Type': 'application/json' }
for (const [path, method, body] of [
['/teams/team1/agents', 'POST', payload],
['/agents/transcript1', 'PUT', payload],
['/agents/transcript1/permission', 'PATCH', JSON.stringify({ permission: 'editor' })],
['/agents/transcript1', 'DELETE', undefined],
] as const) {
expect((await app.request(path, { method, headers, body })).status).toBe(403)
}
expect(agentService.createAgent).not.toHaveBeenCalled()
expect(agentService.updateAgent).not.toHaveBeenCalled()
expect(agentService.updateAgentPermission).not.toHaveBeenCalled()
expect(agentService.deleteAgent).not.toHaveBeenCalled()
} finally {
vi.unstubAllEnvs()
}
},
)
describe('GET /teams/:teamId/agents', () => { describe('GET /teams/:teamId/agents', () => {
it('returns list of agents', async () => { it('returns list of agents', async () => {
const mockAgents = [ const mockAgents = [
@@ -352,7 +384,6 @@ describe('Agent API', () => {
}) })
describe('GET /agent-sessions/:sessionId/entries', () => { describe('GET /agent-sessions/:sessionId/entries', () => {
it('returns entries of agent session if user is admin', async () => {
const mockEntries: EntryRecord[] = [ const mockEntries: EntryRecord[] = [
{ {
id: 7 as EntryId, id: 7 as EntryId,
@@ -361,6 +392,8 @@ describe('Agent API', () => {
model: [{ role: 'user', content: 'Step 1', timestamp: 1 }], model: [{ role: 'user', content: 'Step 1', timestamp: 1 }],
}, },
] ]
it('returns entries of agent session if user is admin', async () => {
vi.mocked(agentService.getSessionEntries).mockResolvedValue(mockEntries) vi.mocked(agentService.getSessionEntries).mockResolvedValue(mockEntries)
const res = await app.request('/agent-sessions/session1/entries', { const res = await app.request('/agent-sessions/session1/entries', {
@@ -373,6 +406,7 @@ describe('Agent API', () => {
expect(data[0].id).toBe(7) expect(data[0].id).toBe(7)
expect(data[0].kind).toBe('pi.user') expect(data[0].kind).toBe('pi.user')
expect(data[0].model[0].content).toBe('Step 1') expect(data[0].model[0].content).toBe('Step 1')
expect(agentSessionService.getLogs).not.toHaveBeenCalled()
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
user: undefined, user: undefined,
permission: 'Admin', permission: 'Admin',
@@ -381,6 +415,51 @@ describe('Agent API', () => {
}) })
}) })
it.each([
{
inputTokens: 12800,
outputTokens: 1580,
cacheReadTokens: 10000,
totalTokens: 24380,
cost: 0.014,
},
null,
])('includes requested usage with the session entries (%j)', async (usage) => {
vi.mocked(agentSessionService.getLogs).mockResolvedValue({ entries: mockEntries, usage })
const res = await app.request('/agent-sessions/session1/entries?includeUsage=true')
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ entries: mockEntries, usage })
expect(agentSessionService.getLogs).toHaveBeenCalledWith('session1')
expect(agentService.getSessionEntries).not.toHaveBeenCalled()
})
it('checks session admin permission before loading requested usage', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValue(
new HTTPException(403, { message: 'Forbidden' }),
)
const res = await app.request('/agent-sessions/session1/entries?includeUsage=true')
expect(res.status).toBe(403)
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: undefined,
permission: 'Admin',
type: 'agentSession',
id: 'session1',
})
expect(agentSessionService.getLogs).not.toHaveBeenCalled()
})
it('rejects invalid includeUsage values', async () => {
const res = await app.request('/agent-sessions/session1/entries?includeUsage=invalid')
expect(res.status).toBe(400)
expect(agentSessionService.getLogs).not.toHaveBeenCalled()
expect(agentService.getSessionEntries).not.toHaveBeenCalled()
})
it('denies access if user is not admin', async () => { it('denies access if user is not admin', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValue(new Error('Forbidden')) vi.mocked(authzService.hasPermission).mockRejectedValue(new Error('Forbidden'))
+29 -28
View File
@@ -1,5 +1,7 @@
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { agentService } from '@shumai/core/src/agent/agent' import { agentService } from '@shumai/core/src/agent/agent'
import { getSystemAgentSetting } from '@shumai/core/src/agent/system-agents'
import { agentSessionService } from '@shumai/core/src/agent/session-service'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { import {
AgentInfo, AgentInfo,
@@ -11,6 +13,7 @@ import {
} from '@shumai/dtos' } from '@shumai/dtos'
import { Hono } from 'hono' import { Hono } from 'hono'
import { HTTPException } from 'hono/http-exception' import { HTTPException } from 'hono/http-exception'
import { z } from 'zod'
import { agentEntriesResponse } from './agent-entries' import { agentEntriesResponse } from './agent-entries'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog' import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
@@ -18,6 +21,8 @@ import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>> type User = Prisma.UserGetPayload<Record<string, never>>
const sessionEntriesQuerySchema = z.object({ includeUsage: z.enum(['true', 'false']).optional() })
const route = new Hono<{ Variables: { user: User } }>() const route = new Hono<{ Variables: { user: User } }>()
.get('/teams/:teamId/agents', async (c) => { .get('/teams/:teamId/agents', async (c) => {
const teamId = c.req.param('teamId') const teamId = c.req.param('teamId')
@@ -64,13 +69,10 @@ const route = new Hono<{ Variables: { user: User } }>()
id: teamId, id: teamId,
}) })
const isEmbeddingManagedByEnv = const managedSetting = getSystemAgentSetting(req.type)
process.env.ENABLE_EMBEDDING_AGENT === 'true' || if (managedSetting) {
process.env.ENABLE_EMBEDDING_AGENT === 'false'
if (req.type === 'embedding' && isEmbeddingManagedByEnv) {
throw new HTTPException(403, { throw new HTTPException(403, {
message: 'Embedding agent is managed by environment configuration and cannot be created', message: `${managedSetting.name} is managed by environment configuration and cannot be created`,
}) })
} }
@@ -104,14 +106,13 @@ const route = new Hono<{ Variables: { user: User } }>()
id: agentId, id: agentId,
}) })
const isEmbeddingManagedByEnv =
process.env.ENABLE_EMBEDDING_AGENT === 'true' ||
process.env.ENABLE_EMBEDDING_AGENT === 'false'
const existingAgent = await agentService.getAgent({ agentId }) const existingAgent = await agentService.getAgent({ agentId })
if (existingAgent?.type === 'embedding' && isEmbeddingManagedByEnv) { const managedSetting =
(existingAgent && getSystemAgentSetting(existingAgent.type)) ??
getSystemAgentSetting(req.type)
if (managedSetting) {
throw new HTTPException(403, { throw new HTTPException(403, {
message: 'Embedding agent is managed by environment configuration and cannot be modified', message: `${managedSetting.name} is managed by environment configuration and cannot be modified`,
}) })
} }
@@ -146,14 +147,11 @@ const route = new Hono<{ Variables: { user: User } }>()
id: agentId, id: agentId,
}) })
const isEmbeddingManagedByEnv =
process.env.ENABLE_EMBEDDING_AGENT === 'true' ||
process.env.ENABLE_EMBEDDING_AGENT === 'false'
const existingAgent = await agentService.getAgent({ agentId }) const existingAgent = await agentService.getAgent({ agentId })
if (existingAgent?.type === 'embedding' && isEmbeddingManagedByEnv) { const managedSetting = existingAgent && getSystemAgentSetting(existingAgent.type)
if (managedSetting) {
throw new HTTPException(403, { throw new HTTPException(403, {
message: 'Embedding agent is managed by environment configuration and cannot be modified', message: `${managedSetting.name} is managed by environment configuration and cannot be modified`,
}) })
} }
@@ -182,14 +180,11 @@ const route = new Hono<{ Variables: { user: User } }>()
id: agentId, id: agentId,
}) })
const isEmbeddingManagedByEnv =
process.env.ENABLE_EMBEDDING_AGENT === 'true' ||
process.env.ENABLE_EMBEDDING_AGENT === 'false'
const existingAgent = await agentService.getAgent({ agentId }) const existingAgent = await agentService.getAgent({ agentId })
if (existingAgent?.type === 'embedding' && isEmbeddingManagedByEnv) { const managedSetting = existingAgent && getSystemAgentSetting(existingAgent.type)
if (managedSetting) {
throw new HTTPException(403, { throw new HTTPException(403, {
message: 'Embedding agent is managed by environment configuration and cannot be deleted', message: `${managedSetting.name} is managed by environment configuration and cannot be deleted`,
}) })
} }
@@ -208,7 +203,10 @@ const route = new Hono<{ Variables: { user: User } }>()
return new Response(null, { status: 204 }) return new Response(null, { status: 204 })
}) })
.get('/agent-sessions/:sessionId/entries', async (c) => { .get(
'/agent-sessions/:sessionId/entries',
zValidator('query', sessionEntriesQuerySchema),
async (c) => {
const sessionId = c.req.param('sessionId') const sessionId = c.req.param('sessionId')
const userReq = c.get('user') const userReq = c.get('user')
@@ -219,9 +217,12 @@ const route = new Hono<{ Variables: { user: User } }>()
id: sessionId, id: sessionId,
}) })
const entries = await agentService.getSessionEntries({ sessionId }) if (c.req.valid('query').includeUsage === 'true') {
return agentEntriesResponse(entries) return agentEntriesResponse(await agentSessionService.getLogs(sessionId))
}) }
return agentEntriesResponse(await agentService.getSessionEntries({ sessionId }))
},
)
.get('/teams/:teamId/agent-sessions', zValidator('query', paginationParamsSchema), async (c) => { .get('/teams/:teamId/agent-sessions', zValidator('query', paginationParamsSchema), async (c) => {
const teamId = c.req.param('teamId') const teamId = c.req.param('teamId')
const userReq = c.get('user') const userReq = c.get('user')
+25
View File
@@ -6,6 +6,7 @@ import { AssetType } from '@shumai/db'
import { authMiddleware } from './middleware/auth' import { authMiddleware } from './middleware/auth'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog' import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { s3Service } from '@shumai/core/src/s3/s3'
vi.mock('./middleware/auth', () => ({ vi.mock('./middleware/auth', () => ({
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock // 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', 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 }),
)
})
}) })
+2 -1
View File
@@ -7,6 +7,7 @@ import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { projectService } from '@shumai/core/src/project/project' import { projectService } from '@shumai/core/src/project/project'
import { AssetType } from '@shumai/db' import { AssetType } from '@shumai/db'
import { ulid } from 'ulid' import { ulid } from 'ulid'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import type { Prisma } from '@shumai/db' import type { Prisma } from '@shumai/db'
@@ -27,7 +28,7 @@ const route = new Hono<{ Variables: { user: User } }>().post(
id: projectId, id: projectId,
}) })
const key = `attachments/${ulid()}/${req.fileName}` const key = `attachments/${ulid()}/${sanitizeFilename(req.fileName)}`
const assetInfo = await assetService.createAsset({ const assetInfo = await assetService.createAsset({
name: req.fileName, name: req.fileName,
+13
View File
@@ -2,6 +2,7 @@ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono' import { Hono } from 'hono'
import authnRoute from './authn' import authnRoute from './authn'
import { teamService } from '@shumai/core/src/team/team' import { teamService } from '@shumai/core/src/team/team'
import { transcriptService } from '@shumai/core/src/transcript/transcript'
describe('authn api', () => { describe('authn api', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -13,9 +14,11 @@ describe('authn api', () => {
afterEach(() => { afterEach(() => {
vi.restoreAllMocks() vi.restoreAllMocks()
vi.unstubAllEnvs()
}) })
it('GET /signup-info', async () => { it('GET /signup-info', async () => {
vi.spyOn(transcriptService, 'isGenerationEnabled').mockResolvedValue(false)
mockGetSignupInfo.mockResolvedValue({ mockGetSignupInfo.mockResolvedValue({
initialized: true, initialized: true,
demoMode: false, demoMode: false,
@@ -29,6 +32,16 @@ describe('authn api', () => {
initialized: true, initialized: true,
demoMode: false, demoMode: false,
archiveStorageEnabled: false, archiveStorageEnabled: false,
transcriptionEnabled: false,
}) })
}) })
it('advertises transcription when generation is enabled', async () => {
vi.spyOn(transcriptService, 'isGenerationEnabled').mockResolvedValue(true)
mockGetSignupInfo.mockResolvedValue({ initialized: true, demoMode: false })
const res = await new Hono().route('/', authnRoute).request('/signup-info')
expect(await res.json()).toMatchObject({ transcriptionEnabled: true })
})
}) })
+2
View File
@@ -4,6 +4,7 @@ import { userService } from '@shumai/core/src/user/user'
import { auth } from '@shumai/core/src/auth/auth' import { auth } from '@shumai/core/src/auth/auth'
import { createGuestToken } from '@shumai/core/src/auth/guest-token' import { createGuestToken } from '@shumai/core/src/auth/guest-token'
import { isArchiveStorageEnabled } from '@shumai/core/src/s3/archive-storage' import { isArchiveStorageEnabled } from '@shumai/core/src/s3/archive-storage'
import { transcriptService } from '@shumai/core/src/transcript/transcript'
import { z } from 'zod' import { z } from 'zod'
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { ulid } from 'ulid' import { ulid } from 'ulid'
@@ -24,6 +25,7 @@ const route = app
initialized: info.initialized, initialized: info.initialized,
demoMode: info.demoMode, demoMode: info.demoMode,
archiveStorageEnabled: isArchiveStorageEnabled(), archiveStorageEnabled: isArchiveStorageEnabled(),
transcriptionEnabled: await transcriptService.isGenerationEnabled(),
}) })
}) })
.get('/me', async (c) => { .get('/me', async (c) => {
+199
View File
@@ -3,6 +3,7 @@ import { Hono, type Context, type Next } from 'hono'
import { HTTPException } from 'hono/http-exception' import { HTTPException } from 'hono/http-exception'
import fileRoute from './file' import fileRoute from './file'
import { assetService } from '@shumai/core/src/asset/asset' 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 { projectService } from '@shumai/core/src/project/project'
import { metadataService } from '@shumai/core/src/metadata/metadata' import { metadataService } from '@shumai/core/src/metadata/metadata'
import { notificationService } from '@shumai/core/src/notification/notification' 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, 'updateAssetName').mockImplementation(vi.fn())
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn()) vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
vi.spyOn(assetService, 'createComment').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, 'completeComment').mockImplementation(vi.fn())
vi.spyOn(assetService, 'deleteComment').mockImplementation(vi.fn()) vi.spyOn(assetService, 'deleteComment').mockImplementation(vi.fn())
vi.spyOn(assetService, 'addCommentReaction').mockImplementation(vi.fn()) vi.spyOn(assetService, 'addCommentReaction').mockImplementation(vi.fn())
@@ -90,7 +92,10 @@ describe('file api', () => {
assetId: 'file1', assetId: 'file1',
} as unknown as Awaited<ReturnType<typeof assetService.getComment>>) } as unknown as Awaited<ReturnType<typeof assetService.getComment>>)
vi.spyOn(assetService, 'listComments').mockImplementation(vi.fn()) 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(assetService, 'exportComments').mockImplementation(vi.fn())
vi.spyOn(commentFrameService, 'extractFrame').mockImplementation(vi.fn())
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn()) vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn()) vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn())
vi.spyOn(notificationService, 'create').mockImplementation(vi.fn()) vi.spyOn(notificationService, 'create').mockImplementation(vi.fn())
@@ -287,6 +292,7 @@ describe('file api', () => {
updatedAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
sessionId: null, sessionId: null,
isCompleted: false, isCompleted: false,
isInternal: false,
completionLastChangedBy: null, completionLastChangedBy: null,
reactionCounts: [], reactionCounts: [],
}) })
@@ -347,6 +353,7 @@ describe('file api', () => {
updatedAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
sessionId: null, sessionId: null,
isCompleted: false, isCompleted: false,
isInternal: false,
completionLastChangedBy: null, completionLastChangedBy: null,
reactionCounts: [], reactionCounts: [],
}) })
@@ -404,6 +411,7 @@ describe('file api', () => {
updatedAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
sessionId: null, sessionId: null,
isCompleted: false, isCompleted: false,
isInternal: false,
completionLastChangedBy: null, completionLastChangedBy: null,
reactionCounts: [], reactionCounts: [],
}, },
@@ -549,6 +557,7 @@ describe('file api', () => {
updatedAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
sessionId: null, sessionId: null,
isCompleted: true, isCompleted: true,
isInternal: false,
completionLastChangedBy: { id: 'user1', name: 'Test User' }, completionLastChangedBy: { id: 'user1', name: 'Test User' },
reactionCounts: [], reactionCounts: [],
}) })
@@ -575,6 +584,110 @@ describe('file api', () => {
expect(assetService.getComment).toHaveBeenCalledWith('comment-id', 'user1') 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 () => { it('POST /comments/:commentId/complete reopens with isCompleted false', async () => {
vi.mocked(runOperation).mockResolvedValue({ commentId: 'comment-id', resolved: false }) vi.mocked(runOperation).mockResolvedValue({ commentId: 'comment-id', resolved: false })
vi.mocked(assetService.getComment).mockResolvedValue({ 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()
})
})
}) })
+90
View File
@@ -3,6 +3,7 @@ import { assetService } from '@shumai/core/src/asset/asset'
import { projectService } from '@shumai/core/src/project/project' import { projectService } from '@shumai/core/src/project/project'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { commentService } from '@shumai/core/src/comment/comment' 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 { s3Service } from '@shumai/core/src/s3/s3'
import type { Prisma } from '@shumai/db' import type { Prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog' import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
@@ -17,6 +18,7 @@ import {
import { import {
archiveAssetsRequestSchema, archiveAssetsRequestSchema,
createCommentRequestSchema, createCommentRequestSchema,
updateCommentRequestSchema,
deleteFilesRequestSchema, deleteFilesRequestSchema,
batchGetFilesRequestSchema, batchGetFilesRequestSchema,
paginationParamsSchema, paginationParamsSchema,
@@ -29,6 +31,7 @@ import {
getDownloadLinksRequestSchema, getDownloadLinksRequestSchema,
getStoragePathsRequestSchema, getStoragePathsRequestSchema,
completeCommentRequestSchema, completeCommentRequestSchema,
commentFrameQuerySchema,
exportCommentsRequestSchema, exportCommentsRequestSchema,
addCommentReactionRequestSchema, addCommentReactionRequestSchema,
removeCommentReactionRequestSchema, removeCommentReactionRequestSchema,
@@ -197,6 +200,7 @@ const route = new Hono<{ Variables: { user: User } }>()
annotations: req.annotations, annotations: req.annotations,
second: req.second, second: req.second,
attachmentIds: req.attachmentIds, attachmentIds: req.attachmentIds,
isInternal: req.isInternal,
}) })
const context = await assetService.getAssetContext(fileId) const context = await assetService.getAssetContext(fileId)
@@ -248,6 +252,60 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.body(result.content) 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( .post(
'/comments/:commentId/reactions', '/comments/:commentId/reactions',
zValidator('json', addCommentReactionRequestSchema), zValidator('json', addCommentReactionRequestSchema),
@@ -305,6 +363,38 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(await assetService.getComment(commentId, user.id)) 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) => { .delete('/comments/:commentId', async (c) => {
const commentId = c.req.param('commentId') const commentId = c.req.param('commentId')
const user = c.get('user') const user = c.get('user')
+2
View File
@@ -31,6 +31,7 @@ import versionStackRoute from './versionStack'
import kanbanRoute from './kanban' import kanbanRoute from './kanban'
import mediaGenerationRoute from './media-generation' import mediaGenerationRoute from './media-generation'
import runnerWsRoute, { runnerWebsocket } from './runner-ws' import runnerWsRoute, { runnerWebsocket } from './runner-ws'
import transcriptRoute from './transcript'
export { runnerWebsocket } export { runnerWebsocket }
@@ -72,6 +73,7 @@ const apiRoute = new Hono<{ Variables: { user: User } }>()
.route('/', teamRoute) .route('/', teamRoute)
.route('/', versionStackRoute) .route('/', versionStackRoute)
.route('/', fileRoute) .route('/', fileRoute)
.route('/', transcriptRoute)
.route('/', folderRoute) .route('/', folderRoute)
.route('/', agentRoute) .route('/', agentRoute)
.route('/', chatRoute) .route('/', chatRoute)
+2 -2
View File
@@ -30,7 +30,7 @@ const route = new Hono<{ Variables: { user: User } }>()
id: teamId, id: teamId,
}) })
const attachment = await kanbanService.createAttachment(teamId, req) const attachment = await kanbanService.createAttachment(teamId, user.id, req)
return c.json(attachment) return c.json(attachment)
}, },
) )
@@ -123,7 +123,7 @@ const route = new Hono<{ Variables: { user: User } }>()
id: taskId, id: taskId,
}) })
const events = await kanbanService.listEvents(taskId) const events = await kanbanService.listEvents(taskId, user.id)
return c.json({ data: events }) return c.json({ data: events })
}) })
+77 -4
View File
@@ -4,6 +4,8 @@ import { kanbanService } from '@shumai/core/src/kanban/kanban'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog' import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { notificationService } from '@shumai/core/src/notification/notification' import { notificationService } from '@shumai/core/src/notification/notification'
import { KanbanTaskStatus, KanbanTaskPriority } from '@shumai/db/enums' 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' import kanbanRoute from './index'
vi.mock('@shumai/core/src/authz/authz', () => ({ vi.mock('@shumai/core/src/authz/authz', () => ({
@@ -19,6 +21,7 @@ vi.mock('@shumai/core/src/authz/authz', () => ({
ResourceType: { ResourceType: {
Team: 'team', Team: 'team',
Project: 'project', Project: 'project',
Asset: 'asset',
KanbanGoal: 'kanbanGoal', KanbanGoal: 'kanbanGoal',
KanbanTask: 'kanbanTask', KanbanTask: 'kanbanTask',
}, },
@@ -51,6 +54,7 @@ describe('Kanban API Routes', () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks() 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(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 vi.mocked(notificationService.notifyKanbanTaskEvent).mockResolvedValue(undefined as any) // eslint-disable-line @typescript-eslint/no-explicit-any
app = new Hono() app = new Hono()
@@ -218,6 +222,7 @@ describe('Kanban API Routes', () => {
status: 'READY', status: 'READY',
goalId: 'goal-1', goalId: 'goal-1',
}), }),
'user-1',
) )
}) })
@@ -248,7 +253,7 @@ describe('Kanban API Routes', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const json = await res.json() const json = await res.json()
expect(json.id).toBe(taskId) expect(json.id).toBe(taskId)
expect(mockGet).toHaveBeenCalledWith(taskId) expect(mockGet).toHaveBeenCalledWith(taskId, 'user-1')
}) })
it('PATCH /teams/:teamId/kanban/tasks/:taskId', async () => { 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']) 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 () => { it('DELETE /teams/:teamId/kanban/tasks/:taskId/assets/:assetId', async () => {
const mockUnlinkAsset = vi.spyOn(kanbanService, 'unlinkAsset').mockResolvedValue(undefined) const mockUnlinkAsset = vi.spyOn(kanbanService, 'unlinkAsset').mockResolvedValue(undefined)
@@ -530,7 +603,7 @@ describe('Kanban API Routes', () => {
const json = await res.json() const json = await res.json()
expect(json.total).toBe(1) expect(json.total).toBe(1)
expect(json.data).toHaveLength(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 () => { it('POST /teams/:teamId/kanban/assets/:assetId/tasks', async () => {
@@ -585,7 +658,7 @@ describe('Kanban API Routes', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const json = await res.json() const json = await res.json()
expect(json.id).toBe('att-1') expect(json.id).toBe('att-1')
expect(mockAttachment).toHaveBeenCalledWith(teamId, { expect(mockAttachment).toHaveBeenCalledWith(teamId, 'user-1', {
fileName: 'test.png', fileName: 'test.png',
size: 1024, size: 1024,
contentType: 'image/png', contentType: 'image/png',
@@ -683,7 +756,7 @@ describe('Kanban API Routes', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const json = await res.json() const json = await res.json()
expect(json.data).toHaveLength(1) expect(json.data).toHaveLength(1)
expect(mockEvents).toHaveBeenCalledWith(taskId) expect(mockEvents).toHaveBeenCalledWith(taskId, 'user-1')
}) })
}) })
}) })
+26 -3
View File
@@ -22,6 +22,21 @@ import { HTTPException } from 'hono/http-exception'
type User = Prisma.UserGetPayload<Record<string, never>> 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 } }>() const route = new Hono<{ Variables: { user: User } }>()
.post('/teams/:teamId/kanban/tasks', zValidator('json', createKanbanTaskSchema), async (c) => { .post('/teams/:teamId/kanban/tasks', zValidator('json', createKanbanTaskSchema), async (c) => {
const { teamId } = c.req.param() 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' }) 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) const task = await kanbanService.createTask(teamId, req, user.id, role)
await auditLogService.logAction({ await auditLogService.logAction({
@@ -89,7 +106,7 @@ const route = new Hono<{ Variables: { user: User } }>()
id: teamId, id: teamId,
}) })
const result = await kanbanService.listTasks(teamId, req) const result = await kanbanService.listTasks(teamId, req, user.id)
return c.json(result) return c.json(result)
}, },
) )
@@ -104,7 +121,7 @@ const route = new Hono<{ Variables: { user: User } }>()
id: taskId, id: taskId,
}) })
const task = await kanbanService.getTask(taskId) const task = await kanbanService.getTask(taskId, user.id)
return c.json(task) return c.json(task)
}) })
.patch( .patch(
@@ -122,6 +139,8 @@ const route = new Hono<{ Variables: { user: User } }>()
id: taskId, id: taskId,
}) })
await assertCanReadAssets(user, req.assetIds)
const existing = await kanbanService.getTask(taskId) const existing = await kanbanService.getTask(taskId)
const role = await resolveEffectiveRole(teamId, existing.projectId ?? undefined, user.id) const role = await resolveEffectiveRole(teamId, existing.projectId ?? undefined, user.id)
const task = await kanbanService.updateTask(taskId, req, user.id, role) const task = await kanbanService.updateTask(taskId, req, user.id, role)
@@ -262,6 +281,8 @@ const route = new Hono<{ Variables: { user: User } }>()
id: taskId, id: taskId,
}) })
await assertCanReadAssets(user, req.assetIds)
await kanbanService.linkAssets(teamId, taskId, req.assetIds) await kanbanService.linkAssets(teamId, taskId, req.assetIds)
return c.json({ success: true }) return c.json({ success: true })
}, },
@@ -291,7 +312,7 @@ const route = new Hono<{ Variables: { user: User } }>()
id: teamId, 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 }) return c.json({ data: tasks, total: tasks.length })
}) })
.post( .post(
@@ -309,6 +330,8 @@ const route = new Hono<{ Variables: { user: User } }>()
id: req.taskId, id: req.taskId,
}) })
await assertCanReadAssets(user, [assetId])
await kanbanService.linkAsset(teamId, req.taskId, assetId) await kanbanService.linkAsset(teamId, req.taskId, assetId)
return c.json({ success: true }) return c.json({ success: true })
}, },
+68 -57
View File
@@ -1,5 +1,6 @@
import { describe, expect, it, vi, beforeEach } from 'vitest' import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono, type Context, type Next } from 'hono' import { Hono, type Context, type Next } from 'hono'
import { HTTPException } from 'hono/http-exception'
import providerRoute from './provider' import providerRoute from './provider'
import { providerService } from '@shumai/core/src/provider/provider' import { providerService } from '@shumai/core/src/provider/provider'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
@@ -34,6 +35,7 @@ describe('provider api', () => {
beforeEach(() => { beforeEach(() => {
vi.restoreAllMocks() vi.restoreAllMocks()
vi.clearAllMocks()
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined) vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
}) })
@@ -320,78 +322,57 @@ describe('provider api', () => {
}) })
}) })
it('POST /teams/:teamId/providers/sync-check checks for updates', async () => { const modelsPath = '/teams/t1/providers/p1/models'
vi.mocked(providerService.checkUpdates).mockResolvedValue({ const providerUpdatedAt = '2026-11-29T09:15:00.000Z'
providers: [ const selection = {
{ providerUpdatedAt,
name: 'deepseek', modelIds: ['test-model'],
isNewProvider: true, }
config: { api: 'openai-responses', apiKey: 'DEEPSEEK_API_KEY' }, const importRequest = {
models: [],
},
],
totalNewProviders: 1,
totalNewModels: 0,
})
const res = await app.request('/teams/t1/providers/sync-check', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(selection),
}
it('previews refresh results for the requested provider as a team admin', async () => {
vi.mocked(providerService.refreshModels).mockResolvedValue({
status: 'ready',
providerUpdatedAt,
models: [],
}) })
const res = await app.request(modelsPath + '/refresh', { method: 'POST' })
expect(res.status).toBe(200) expect(res.status).toBe(200)
const data = await res.json() expect(res.headers.get('Cache-Control')).toBe('no-store')
expect(data.totalNewProviders).toBe(1) expect(await res.json()).toEqual({ status: 'ready', providerUpdatedAt, models: [] })
expect(data.providers).toHaveLength(1) expect(providerService.refreshModels).toHaveBeenCalledWith('t1', 'p1')
expect(providerService.checkUpdates).toHaveBeenCalledWith('t1')
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(), user: expect.anything(),
permission: Permission.Admin, permission: Permission.Admin,
type: ResourceType.Team, type: ResourceType.Team,
id: 't1', id: 't1',
}) })
expect(auditLogService.logAction).not.toHaveBeenCalled()
}) })
it('POST /teams/:teamId/providers/sync-apply applies sync selection', async () => { it('returns the server reason for an unavailable refresh', async () => {
vi.mocked(providerService.applySync).mockResolvedValue({ vi.mocked(providerService.refreshModels).mockResolvedValue({
addedProviders: 1, status: 'unavailable',
addedModels: 3, reason: 'catalog_unavailable',
})
const payload = {
providers: [
{
name: 'deepseek',
isNewProvider: true,
config: { api: 'openai-responses', apiKey: 'KEY' },
models: [
{
modelId: 'deepseek-v4-flash',
name: 'DeepSeek V4 Flash',
config: {
api: 'openai-responses',
reasoning: true,
input: ['text'],
contextWindow: 128000,
maxTokens: 4096,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
},
},
],
},
],
}
const res = await app.request('/teams/t1/providers/sync-apply', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
}) })
const res = await app.request(modelsPath + '/refresh', { method: 'POST' })
expect(res.status).toBe(200) expect(res.status).toBe(200)
const data = await res.json() expect(await res.json()).toEqual({ status: 'unavailable', reason: 'catalog_unavailable' })
expect(data.addedProviders).toBe(1) })
expect(data.addedModels).toBe(3)
expect(providerService.applySync).toHaveBeenCalledWith('t1', payload) it('imports the selection into the scoped provider and records its audit entry', async () => {
vi.mocked(providerService.importModels).mockResolvedValue({ addedModels: 1 })
const res = await app.request(modelsPath + '/import', importRequest)
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ addedModels: 1 })
expect(providerService.importModels).toHaveBeenCalledWith('t1', 'p1', selection)
expect(authzService.hasPermission).toHaveBeenCalledWith({ expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(), user: expect.anything(),
permission: Permission.Admin, permission: Permission.Admin,
@@ -402,6 +383,36 @@ describe('provider api', () => {
action: 'provider_update', action: 'provider_update',
teamId: 't1', teamId: 't1',
userId: 'user1', userId: 'user1',
itemId: 'p1',
}) })
}) })
it('skips the audit entry when the selected models already exist', async () => {
vi.mocked(providerService.importModels).mockResolvedValue({ addedModels: 0 })
const res = await app.request(modelsPath + '/import', importRequest)
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ addedModels: 0 })
expect(auditLogService.logAction).not.toHaveBeenCalled()
})
it('rejects requests without team-admin permission before looking up the provider', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValue(new HTTPException(403))
const refresh = await app.request(modelsPath + '/refresh', { method: 'POST' })
const apply = await app.request(modelsPath + '/import', importRequest)
expect(refresh.status).toBe(403)
expect(apply.status).toBe(403)
expect(providerService.refreshModels).not.toHaveBeenCalled()
expect(providerService.importModels).not.toHaveBeenCalled()
expect(auditLogService.logAction).not.toHaveBeenCalled()
})
it('rejects an empty import selection before performing a write', async () => {
const res = await app.request(modelsPath + '/import', {
...importRequest,
body: JSON.stringify({ providerUpdatedAt, modelIds: [] }),
})
expect(res.status).toBe(400)
expect(providerService.importModels).not.toHaveBeenCalled()
})
}) })
+12 -8
View File
@@ -5,7 +5,7 @@ import { providerService } from '@shumai/core/src/provider/provider'
import { import {
createModelRequestSchema, createModelRequestSchema,
createProviderRequestSchema, createProviderRequestSchema,
syncApplyRequestSchema, importProviderModelsRequestSchema,
updateModelRequestSchema, updateModelRequestSchema,
updateProviderRequestSchema, updateProviderRequestSchema,
AuditAction, AuditAction,
@@ -31,8 +31,8 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(providers) return c.json(providers)
}) })
.post('/teams/:teamId/providers/sync-check', async (c) => { .post('/teams/:teamId/providers/:providerId/models/refresh', async (c) => {
const teamId = c.req.param('teamId') const { teamId, providerId } = c.req.param()
const user = c.get('user') const user = c.get('user')
await authzService.hasPermission({ await authzService.hasPermission({
@@ -42,15 +42,16 @@ const route = new Hono<{ Variables: { user: User } }>()
id: teamId, id: teamId,
}) })
const result = await providerService.checkUpdates(teamId) const result = await providerService.refreshModels(teamId, providerId)
c.header('Cache-Control', 'no-store')
return c.json(result) return c.json(result)
}) })
.post( .post(
'/teams/:teamId/providers/sync-apply', '/teams/:teamId/providers/:providerId/models/import',
zValidator('json', syncApplyRequestSchema), zValidator('json', importProviderModelsRequestSchema),
async (c) => { async (c) => {
const teamId = c.req.param('teamId') const { teamId, providerId } = c.req.param()
const user = c.get('user') const user = c.get('user')
const body = c.req.valid('json') const body = c.req.valid('json')
@@ -61,12 +62,15 @@ const route = new Hono<{ Variables: { user: User } }>()
id: teamId, id: teamId,
}) })
const result = await providerService.applySync(teamId, body) const result = await providerService.importModels(teamId, providerId, body)
if (result.addedModels > 0) {
await auditLogService.logAction({ await auditLogService.logAction({
action: AuditAction.provider_update, action: AuditAction.provider_update,
teamId, teamId,
userId: user?.id, userId: user?.id,
itemId: providerId,
}) })
}
return c.json(result) return c.json(result)
}, },
) )
+166
View File
@@ -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)
})
})
+192 -53
View File
@@ -1,11 +1,19 @@
import { Hono } from 'hono' import { Hono } from 'hono'
import type { Context } from 'hono' import type { Context } from 'hono'
import { HTTPException } from 'hono/http-exception'
import { getCookie } from 'hono/cookie' import { getCookie } from 'hono/cookie'
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { shareService } from '@shumai/core/src/share/share' 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 { 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 { 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 { z } from 'zod'
import { metadataService } from '@shumai/core/src/metadata/metadata' import { metadataService } from '@shumai/core/src/metadata/metadata'
import { FieldInfo } from '@shumai/dtos' 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() const app = new Hono()
function toFieldInfo( function toFieldInfo(
@@ -133,6 +155,9 @@ function toFieldInfo(
} }
export function handlePublicShareError(c: Context, err: unknown) { export function handlePublicShareError(c: Context, err: unknown) {
if (err instanceof HTTPException) {
throw err
}
if (err instanceof ShareLinkPasswordInvalidError) { if (err instanceof ShareLinkPasswordInvalidError) {
return c.json({ error: 'Unauthorized' }, 401) return c.json({ error: 'Unauthorized' }, 401)
} }
@@ -156,7 +181,36 @@ const sharedChildrenRequestSchema = paginationParamsSchema.extend({
assetType: assetTypeFilterSchema.optional().default('file'), 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 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) => { .get('/shares/:shareId/info', async (c) => {
const shareId = c.req.param('shareId') const shareId = c.req.param('shareId')
const password = c.req.header('x-share-password') const password = c.req.header('x-share-password')
@@ -222,13 +276,16 @@ const route = app
order = parts[1] order = parts[1]
} }
const res = await assetService.listChildren({ const res = await assetService.listChildren(
{
...req, ...req,
assetId: folderId, assetId: folderId,
assetType: req.assetType || 'file', assetType: req.assetType || 'file',
sort, sort,
order, order,
}) },
{ excludeInternalComments: true },
)
if (shareLink.watermarkConfigId && res.data.length > 0) { if (shareLink.watermarkConfigId && res.data.length > 0) {
// Resolve symlink targets once and reuse for the media lookup, so each // 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) return c.json(res)
} catch (err) { } catch (err) {
return handlePublicShareError(c, err) return handlePublicShareError(c, err)
@@ -274,7 +333,10 @@ const route = app
try { try {
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password) 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 // Only video/image/3d assets are subject to watermark protection; skip the
// watermark lookup entirely for other media types (pdf, audio, ...). // 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}` 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) { } catch (err) {
return handlePublicShareError(c, err) return handlePublicShareError(c, err)
} }
}) })
.post( .post(
'/shares/:shareId/files/:fileId/download-url', '/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) => { async (c) => {
const shareId = c.req.param('shareId') const shareId = c.req.param('shareId')
const fileId = c.req.param('fileId') const fileId = c.req.param('fileId')
const password = c.req.header('x-share-password') const password = c.req.header('x-share-password')
const { key } = c.req.valid('json') const { key, purpose } = c.req.valid('json')
try { try {
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password) const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
@@ -323,7 +391,16 @@ const route = app
return c.json({ error: 'Invalid key' }, 400) 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 }) return c.json({ url })
} catch (err) { } catch (err) {
return handlePublicShareError(c, err) return handlePublicShareError(c, err)
@@ -343,32 +420,107 @@ const route = app
await shareService.verifyPublicAccess(shareId, fileId, password) await shareService.verifyPublicAccess(shareId, fileId, password)
const targetFileId = await assetService.resolveTargetAssetId(fileId) const targetFileId = await assetService.resolveTargetAssetId(fileId)
let userId: string | undefined const userId = await getPublicShareUserId(c, shareId)
const session = await auth.api.getSession({ const res = await assetService.listComments(targetFileId, req, userId, {
headers: c.req.raw.headers, 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) return c.json(res)
} catch (err) { } catch (err) {
return handlePublicShareError(c, 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( .post(
'/shares/:shareId/files/:fileId/comments', '/shares/:shareId/files/:fileId/comments',
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })), 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) 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 { try {
const shareLink = await shareService.getShareLink(shareId) const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
await shareService.verifyPublicAccess(shareId, fileId, password)
const targetFileId = await assetService.resolveTargetAssetId(fileId) const targetFileId = await assetService.resolveTargetAssetId(fileId)
const teamId = await projectService.getProjectTeam(shareLink.projectId) const teamId = await projectService.getProjectTeam(shareLink.projectId)
// Identify user const userId = await getPublicShareUserId(c, shareId)
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
}
}
}
}
if (!userId) { if (!userId) {
return c.json({ error: 'Unauthorized' }, 401) return c.json({ error: 'Unauthorized' }, 401)
} }
const comment = await assetService.createComment({ const comment = await assetService.createComment(
{
assetId: targetFileId, assetId: targetFileId,
userId: userId, userId,
replyToId: req.replyToId, replyToId: req.replyToId,
message: req.message, message: req.message,
annotations: req.annotations, annotations: req.annotations,
second: req.second, second: req.second,
attachmentIds: req.attachmentIds, attachmentIds: req.attachmentIds,
}) isInternal: false,
},
{ shareLinkId: shareId },
)
const notifType = req.replyToId ? 'reply_created' : 'comment_created' const notifType = req.replyToId ? 'reply_created' : 'comment_created'
+125 -145
View File
@@ -1,168 +1,148 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { basename, dirname, join } from 'node:path'
import { Hono } from 'hono' import { Hono } from 'hono'
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
const { mockServeStatic } = vi.hoisted(() => ({ import { signLocalGetUrl } from '@shumai/core/src/s3/s3'
// eslint-disable-next-line @typescript-eslint/no-explicit-any import route from './s3'
mockServeStatic: vi.fn<(args: any) => any>(() => (c: any) => c.text('static-file')),
}))
vi.mock('hono/bun', () => ({
serveStatic: mockServeStatic,
}))
describe('S3 API', () => { describe('S3 API', () => {
beforeEach(() => { const app = new Hono().route('/files', route)
vi.clearAllMocks() const bucket = 'test-bucket'
vi.resetModules() const body = 'inert file contents'
let originalDir: string
let storageDir: string
beforeAll(async () => {
originalDir = process.cwd()
storageDir = await mkdtemp(join(tmpdir(), 'shumai-local-file-test-'))
process.chdir(storageDir)
}) })
it('GET /files/* calls serveStatic with correct options when valid signature is provided', async () => { afterAll(async () => {
const { signLocalGetUrl } = await import('@shumai/core/src/s3/s3') process.chdir(originalDir)
const { signature, expires } = signLocalGetUrl('b1', 'test.webp') await rm(storageDir, { recursive: true, force: true })
})
const { default: route } = await import('./s3') beforeEach(() => {
const app = new Hono().route('/files', route) vi.stubEnv('STORAGE_BACKEND', 'local')
})
const res = await app.request(`/files/b1/test.webp?Signature=${signature}&Expires=${expires}`) afterEach(() => {
vi.unstubAllEnvs()
})
function signedPath(key: string, query: Record<string, string> = {}, lifetime?: number) {
const { signature, expires } = signLocalGetUrl(bucket, key, lifetime)
const params = new URLSearchParams({ Signature: signature, Expires: String(expires), ...query })
return `/files/${bucket}/${key}?${params}`
}
async function writeStoredFile(key: string) {
const path = join(storageDir, 'data', bucket, key)
await mkdir(dirname(path), { recursive: true })
await writeFile(path, body)
}
it.each([
['files/a/poster.WEBP', 'image/webp'],
['files/a/proxy.pdf', 'application/pdf'],
['files/a/video.mp4', 'video/mp4'],
['files/a/stream.m3u8', 'application/vnd.apple.mpegurl'],
['files/a/segment.m4s', 'video/iso.segment'],
['files/a/model.glb', 'model/gltf-binary'],
])('serves %s inline with its media type', async (key, mimeType) => {
await writeStoredFile(key)
const res = await app.request(signedPath(key))
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(await res.text()).toBe('static-file') expect(res.headers.get('Content-Type')).toBe(mimeType)
expect(mockServeStatic).toHaveBeenCalledWith( expect(res.headers.get('Content-Disposition')).toBeNull()
expect.objectContaining({ expect(res.headers.get('X-Content-Type-Options')).toBe('nosniff')
root: './data', expect(await res.text()).toBe(body)
rewriteRequestPath: expect.any(Function),
}),
)
// Verify rewriteRequestPath logic
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const options = vi.mocked(mockServeStatic).mock.calls[0][0] as any
if (options && options.rewriteRequestPath) {
expect(options.rewriteRequestPath('/files/b1/test.webp')).toBe('b1/test.webp')
}
}) })
it('GET /files/* returns 403 Forbidden when signature is missing', async () => { it.each([
const { default: route } = await import('./s3') 'files/a/original.html',
const app = new Hono().route('/files', route) 'attachments/a/notes.HTML',
'attachments/a/diagram.svg',
'kanban/attachments/team/user/a/notes.html',
'kanban/attachments/team/user/a/diagram.svg',
'files/a/document.xhtml',
'files/a/source.js',
'files/a/unknown.ext',
'files/a/extensionless',
])('serves %s as a download even without a download request', async (key) => {
await writeStoredFile(key)
const res = await app.request(signedPath(key))
const res = await app.request('/files/b1/test.webp') expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('application/octet-stream')
const filename = basename(key)
expect(res.headers.get('Content-Disposition')).toBe(
`attachment; filename="${filename}"; filename*=UTF-8''${filename}`,
)
expect(res.headers.get('X-Content-Type-Options')).toBe('nosniff')
expect(res.headers.get('Content-Security-Policy')).toBe('sandbox')
expect(await res.text()).toBe(body)
})
it('uses the stored file type when an explicit download has a different filename', async () => {
const key = 'attachments/a/diagram.svg'
await writeStoredFile(key)
const res = await app.request(signedPath(key, { download: '1', filename: '図.png' }))
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('application/octet-stream')
expect(res.headers.get('Content-Disposition')).toBe(
"attachment; filename*=UTF-8''%E5%9B%B3.png",
)
expect(res.headers.get('Content-Security-Policy')).toBe('sandbox')
})
it('honors explicit downloads of inline formats with and without a filename', async () => {
const key = 'files/a/preview.webp'
await writeStoredFile(key)
const withName = await app.request(signedPath(key, { download: '1', filename: 'image.webp' }))
expect(withName.status).toBe(200)
expect(withName.headers.get('Content-Disposition')).toBe(
'attachment; filename="image.webp"; filename*=UTF-8\'\'image.webp',
)
expect(withName.headers.get('Content-Type')).toBe('image/webp')
const withoutName = await app.request(signedPath(key, { download: '1' }))
expect(withoutName.status).toBe(200)
expect(withoutName.headers.get('Content-Disposition')).toBe('attachment')
})
it('returns 403 when a signature is missing, invalid, or expired', async () => {
const key = 'files/a/preview.webp'
const responses = await Promise.all([
app.request(`/files/${bucket}/${key}`),
app.request(signedPath(key, { Signature: 'invalid' })),
app.request(signedPath(key, {}, -10)),
])
for (const res of responses) {
expect(res.status).toBe(403) expect(res.status).toBe(403)
const json = await res.json() expect(await res.json()).toMatchObject({ error: expect.stringContaining('Forbidden') })
expect(json.error).toContain('Forbidden')
})
it('GET /files/* returns 403 Forbidden when signature is invalid', async () => {
const { default: route } = await import('./s3')
const app = new Hono().route('/files', route)
const res = await app.request('/files/b1/test.webp?Signature=invalidsig&Expires=9999999999')
expect(res.status).toBe(403)
})
it('GET /files/* returns 403 Forbidden when signature is expired', async () => {
const { signLocalGetUrl } = await import('@shumai/core/src/s3/s3')
// Signed with -10 seconds (expired)
const { signature, expires } = signLocalGetUrl('b1', 'test.webp', -10)
const { default: route } = await import('./s3')
const app = new Hono().route('/files', route)
const res = await app.request(`/files/b1/test.webp?Signature=${signature}&Expires=${expires}`)
expect(res.status).toBe(403)
})
it('GET /files/* sets Content-Disposition with filename when download=1 & filename query params are present', async () => {
const { signLocalGetUrl } = await import('@shumai/core/src/s3/s3')
const { signature, expires } = signLocalGetUrl('b1', 'test.webp')
// We need to capture the onFound callback from serveStatic options
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let onFoundCallback: ((path: string, c: any) => void) | undefined
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mockServeStatic.mockImplementationOnce((options: any) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onFoundCallback = (options as any).onFound
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (c: any) => c.text('static-file')
})
const { default: route } = await import('./s3')
const app = new Hono().route('/files', route)
await app.request(
`/files/b1/test.webp?Signature=${signature}&Expires=${expires}&download=1&filename=foo.png`,
)
expect(onFoundCallback).toBeDefined()
// Test with download=1 and filename
const mockContextWithDownload = {
req: {
query: (key: string) =>
key === 'download' ? '1' : key === 'filename' ? 'foo.png' : undefined,
},
header: vi.fn(),
}
if (onFoundCallback) {
onFoundCallback('/files/b1/test.webp', mockContextWithDownload)
expect(mockContextWithDownload.header).toHaveBeenCalledWith(
'Content-Disposition',
'attachment; filename="foo.png"; filename*=UTF-8\'\'foo.png',
)
}
// Test with download=1 but no filename
const mockContextDownloadNoFilename = {
req: { query: (key: string) => (key === 'download' ? '1' : undefined) },
header: vi.fn(),
}
if (onFoundCallback) {
onFoundCallback('/files/b1/test.webp', mockContextDownloadNoFilename)
expect(mockContextDownloadNoFilename.header).toHaveBeenCalledWith(
'Content-Disposition',
'attachment',
)
}
// Test without download param
const mockContextWithout = {
req: { query: () => undefined },
header: vi.fn(),
}
if (onFoundCallback) {
onFoundCallback('/files/b1/test.webp', mockContextWithout)
expect(mockContextWithout.header).not.toHaveBeenCalled()
} }
}) })
it('PUT /files/:bucket/:key returns 404', async () => { it('returns 404 for a validly signed missing file', async () => {
const { default: route } = await import('./s3') const res = await app.request(signedPath('files/a/missing.webp'))
const app = new Hono().route('/files', route)
const body = new TextEncoder().encode('test-data')
const res = await app.request('/files/b1/test.webp', {
method: 'PUT',
headers: {
'content-length': body.byteLength.toString(),
},
body,
})
expect(res.status).toBe(404) expect(res.status).toBe(404)
}) })
it('GET /files/* returns 404 when STORAGE_BACKEND is not local', async () => { it('returns 404 for PUT /files/:bucket/:key', async () => {
const s3Module = await import('@shumai/core/src/s3/s3') const res = await app.request(signedPath('files/a/preview.webp'), { method: 'PUT', body })
vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('s3') expect(res.status).toBe(404)
})
const { default: route } = await import('./s3') it('returns 404 for local URLs when the storage backend is S3', async () => {
const app = new Hono().route('/files', route) vi.stubEnv('STORAGE_BACKEND', 's3')
const res = await app.request(signedPath('files/a/preview.webp'))
const res = await app.request('/files/b1/test.webp')
expect(res.status).toBe(404) expect(res.status).toBe(404)
}) })
}) })
+39 -3
View File
@@ -1,3 +1,4 @@
import { basename, extname } from 'node:path'
import { Hono } from 'hono' import { Hono } from 'hono'
import { import {
buildContentDisposition, buildContentDisposition,
@@ -6,6 +7,32 @@ import {
} from '@shumai/core/src/s3/s3' } from '@shumai/core/src/s3/s3'
import { serveStatic } from 'hono/bun' import { serveStatic } from 'hono/bun'
// Only serve formats used by preview and media clients inline on the app origin.
const inlineFileTypes = new Map([
['.aac', 'audio/aac'],
['.avif', 'image/avif'],
['.bmp', 'image/bmp'],
['.gif', 'image/gif'],
['.glb', 'model/gltf-binary'],
['.gltf', 'model/gltf+json'],
['.ico', 'image/x-icon'],
['.jpeg', 'image/jpeg'],
['.jpg', 'image/jpeg'],
['.m3u8', 'application/vnd.apple.mpegurl'],
['.m4a', 'audio/mp4'],
['.m4s', 'video/iso.segment'],
['.mp3', 'audio/mpeg'],
['.mp4', 'video/mp4'],
['.ogg', 'audio/ogg'],
['.opus', 'audio/opus'],
['.pdf', 'application/pdf'],
['.png', 'image/png'],
['.ts', 'video/mp2t'],
['.wav', 'audio/wav'],
['.webm', 'video/webm'],
['.webp', 'image/webp'],
])
const route = new Hono() const route = new Hono()
.use('*', async (c, next) => { .use('*', async (c, next) => {
if (getStorageBackend() !== 'local') { if (getStorageBackend() !== 'local') {
@@ -36,9 +63,18 @@ const route = new Hono()
serveStatic({ serveStatic({
root: './data', root: './data',
rewriteRequestPath: (path) => path.replace(/^\/files\//, ''), rewriteRequestPath: (path) => path.replace(/^\/files\//, ''),
onFound: (_path, c) => { onFound: (path, c) => {
if (c.req.query('download') === '1') { const inlineType = inlineFileTypes.get(extname(path).toLowerCase())
c.header('Content-Disposition', buildContentDisposition(c.req.query('filename'))) c.header('Content-Type', inlineType ?? 'application/octet-stream')
c.header('X-Content-Type-Options', 'nosniff')
if (!inlineType) {
c.header('Content-Security-Policy', 'sandbox')
}
if (!inlineType || c.req.query('download') === '1') {
const filename = c.req.query('filename') ?? (inlineType ? undefined : basename(path))
c.header('Content-Disposition', buildContentDisposition(filename))
} }
}, },
}), }),
+274 -5
View File
@@ -4,9 +4,15 @@ import shareRoute from './share'
import publicShareRoute from './public-share' import publicShareRoute from './public-share'
import { authMiddleware } from './middleware/auth' import { authMiddleware } from './middleware/auth'
import { shareService } from '@shumai/core/src/share/share' 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 { assetService } from '@shumai/core/src/asset/asset'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' 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 { createGuestToken } from '@shumai/core/src/auth/guest-token'
import { userService } from '@shumai/core/src/user/user' import { userService } from '@shumai/core/src/user/user'
import { notificationService } from '@shumai/core/src/notification/notification' import { notificationService } from '@shumai/core/src/notification/notification'
@@ -93,6 +99,82 @@ describe('Share API', () => {
}) })
// Public Routes // 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', () => { describe('GET /shares/:shareId/info', () => {
test('Success', async () => { test('Success', async () => {
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({ vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
@@ -101,6 +183,8 @@ describe('Share API', () => {
isDisabled: false, isDisabled: false,
allowDownload: false, allowDownload: false,
isExpired: false, isExpired: false,
views: 0,
lastViewedAt: null,
hasPassword: true, hasPassword: true,
rootFolderId: 'folder1', rootFolderId: 'folder1',
projectId: 'project1', projectId: 'project1',
@@ -134,6 +218,8 @@ describe('Share API', () => {
isDisabled: false, isDisabled: false,
allowDownload: false, allowDownload: false,
isExpired: false, isExpired: false,
views: 0,
lastViewedAt: null,
hasPassword: true, hasPassword: true,
rootFolderId: 'folder1', rootFolderId: 'folder1',
projectId: 'project1', projectId: 'project1',
@@ -161,6 +247,8 @@ describe('Share API', () => {
isDisabled: false, isDisabled: false,
allowDownload: false, allowDownload: false,
isExpired: false, isExpired: false,
views: 0,
lastViewedAt: null,
hasPassword: true, hasPassword: true,
rootFolderId: 'folder1', rootFolderId: 'folder1',
projectId: 'project1', projectId: 'project1',
@@ -217,6 +305,7 @@ describe('Share API', () => {
sort: 'name', sort: 'name',
order: 'asc', 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', () => { describe('GET /shares/:shareId/files/:fileId', () => {
const shareLinkWithWatermark = { const shareLinkWithWatermark = {
id: 'share1', id: 'share1',
@@ -712,6 +914,8 @@ describe('Share API', () => {
rootFolderId: 'root1', rootFolderId: 'root1',
projectId: 'project1', projectId: 'project1',
isExpired: false, isExpired: false,
views: 0,
lastViewedAt: null,
hasPassword: false, hasPassword: false,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
@@ -756,6 +960,8 @@ describe('Share API', () => {
rootFolderId: 'root1', rootFolderId: 'root1',
projectId: 'project1', projectId: 'project1',
isExpired: false, isExpired: false,
views: 0,
lastViewedAt: null,
hasPassword: false, hasPassword: false,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
@@ -813,6 +1019,8 @@ describe('Share API', () => {
rootFolderId: 'root1', rootFolderId: 'root1',
projectId: 'project1', projectId: 'project1',
isExpired: false, isExpired: false,
views: 0,
lastViewedAt: null,
hasPassword: false, hasPassword: false,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
@@ -844,6 +1052,8 @@ describe('Share API', () => {
rootFolderId: 'root1', rootFolderId: 'root1',
projectId: 'project1', projectId: 'project1',
isExpired: false, isExpired: false,
views: 0,
lastViewedAt: null,
hasPassword: false, hasPassword: false,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
@@ -888,6 +1098,8 @@ describe('Share API', () => {
rootFolderId: 'root1', rootFolderId: 'root1',
projectId: 'project1', projectId: 'project1',
isExpired: false, isExpired: false,
views: 0,
lastViewedAt: null,
hasPassword: false, hasPassword: false,
watermarkStatus: 'processing', watermarkStatus: 'processing',
watermarkConfigId: 'cfg1', watermarkConfigId: 'cfg1',
@@ -976,12 +1188,60 @@ describe('Share API', () => {
}) })
describe('POST /shares/:shareId/files/:fileId/download-url', () => { 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 () => { test('Success for symlink asset in share', async () => {
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
allowDownload: true, allowDownload: true,
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
} as 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', { const res = await app.request('/shares/share1/files/symlink1/download-url', {
method: 'POST', method: 'POST',
@@ -993,7 +1253,15 @@ describe('Share API', () => {
const body = await res.json() const body = await res.json()
expect(body.url).toBe('https://s3.example.com/download') expect(body.url).toBe('https://s3.example.com/download')
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'symlink1', undefined) 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 () => { test('Rejects when allowDownload is disabled', async () => {
@@ -1004,8 +1272,8 @@ describe('Share API', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any) } as any)
const getDownloadUrlSpy = vi const getDownloadUrlSpy = vi
.spyOn(assetService, 'getDownloadUrl') .spyOn(assetService, 'getDownloadUrlWithAsset')
.mockResolvedValue('https://s3.example.com/download') .mockResolvedValue({ url: 'https://s3.example.com/download', assetId: 'target1' })
const res = await app.request('/shares/share1/files/symlink1/download-url', { const res = await app.request('/shares/share1/files/symlink1/download-url', {
method: 'POST', method: 'POST',
@@ -1173,6 +1441,7 @@ describe('Share API', () => {
userId: 'guest1', userId: 'guest1',
message: 'hello from alice', message: 'hello from alice',
}), }),
{ shareLinkId: 'share1' },
) )
}) })
+12
View File
@@ -2,11 +2,13 @@ import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { shareService } from '@shumai/core/src/share/share' 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 { projectService } from '@shumai/core/src/project/project'
import { import {
createShareLinkRequestSchema, createShareLinkRequestSchema,
updateShareLinkRequestSchema, updateShareLinkRequestSchema,
listShareLinksRequestSchema, listShareLinksRequestSchema,
paginationParamsSchema,
addAssetToShareRequestSchema, addAssetToShareRequestSchema,
updateShareLinkWatermarkRequestSchema, updateShareLinkWatermarkRequestSchema,
AuditAction, AuditAction,
@@ -90,6 +92,16 @@ const route = new Hono<{ Variables: { user: User } }>()
const shareLink = await shareService.getShareLink(shareId) const shareLink = await shareService.getShareLink(shareId)
return c.json(shareLink) 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) => { .put('/shares/:shareId', zValidator('json', updateShareLinkRequestSchema), async (c) => {
const shareId = c.req.param('shareId') const shareId = c.req.param('shareId')
const user = c.get('user') const user = c.get('user')
+69
View File
@@ -6,6 +6,8 @@ import { authMiddleware } from './middleware/auth'
import { teamService } from '@shumai/core/src/team/team' import { teamService } from '@shumai/core/src/team/team'
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata' import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz' import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
import { embeddingServerService } from '@shumai/core/src/search/embedding-server'
import { HTTPException } from 'hono/http-exception'
vi.mock('@shumai/core/src/authz/authz', () => ({ vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: { authzService: {
@@ -112,6 +114,73 @@ describe('team api', () => {
vi.restoreAllMocks() vi.restoreAllMocks()
}) })
it('lets team members view the effective embedding server settings', async () => {
vi.spyOn(embeddingServerService, 'getSettings').mockResolvedValue({
url: 'http://embedding:9379/v1',
isEnvConfigured: true,
})
const response = await app.request('/teams/t1/embedding-server-settings')
expect(await response.json()).toEqual({
url: 'http://embedding:9379/v1',
isEnvConfigured: true,
})
expect(authzService.hasPermission).toHaveBeenLastCalledWith(
expect.objectContaining({ id: 't1', permission: Permission.Read }),
)
})
it('lets admins save and test embedding server settings', async () => {
vi.mocked(authzService.hasPermission).mockClear()
const url = 'http://embedding:9379/v1'
const settings = { url, isEnvConfigured: false }
const save = vi.spyOn(embeddingServerService, 'updateSettings').mockResolvedValue(settings)
const test = vi.spyOn(embeddingServerService, 'testConnection').mockResolvedValue({ ok: true })
const body = JSON.stringify({ url })
const headers = { 'Content-Type': 'application/json' }
const saved = await app.request('/teams/t1/embedding-server-settings', {
method: 'PUT',
headers,
body,
})
expect(await saved.json()).toEqual(settings)
const tested = await app.request('/teams/t1/embedding-server-settings/test', {
method: 'POST',
headers,
body,
})
expect(await tested.json()).toEqual({ ok: true })
expect(save).toHaveBeenCalledWith('t1', url)
expect(test).toHaveBeenCalledWith('t1', url)
expect(authzService.hasPermission).toHaveBeenNthCalledWith(
1,
expect.objectContaining({ permission: Permission.Admin }),
)
expect(authzService.hasPermission).toHaveBeenNthCalledWith(
2,
expect.objectContaining({ permission: Permission.Admin }),
)
})
it('rejects embedding settings writes and connection tests without admin permission', async () => {
const save = vi.spyOn(embeddingServerService, 'updateSettings')
const test = vi.spyOn(embeddingServerService, 'testConnection')
vi.mocked(authzService.hasPermission).mockRejectedValue(new HTTPException(403))
for (const [method, suffix] of [
['PUT', ''],
['POST', '/test'],
]) {
const denied = await app.request(`/teams/t1/embedding-server-settings${suffix}`, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: 'http://embedding:9379/v1' }),
})
expect(denied.status).toBe(403)
}
expect(save).not.toHaveBeenCalled()
expect(test).not.toHaveBeenCalled()
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
})
it('POST /teams returns 404 without creating a team or writing an audit entry', async () => { it('POST /teams returns 404 without creating a team or writing an audit entry', async () => {
const createTeam = vi.spyOn(teamService, 'createTeam').mockResolvedValue({ const createTeam = vi.spyOn(teamService, 'createTeam').mockResolvedValue({
id: 't1', id: 't1',
+42
View File
@@ -12,6 +12,7 @@ import {
updateRunnerRequestSchema, updateRunnerRequestSchema,
updateTurntableSettingsRequestSchema, updateTurntableSettingsRequestSchema,
updateGotenbergSettingsRequestSchema, updateGotenbergSettingsRequestSchema,
updateEmbeddingServerSettingsRequestSchema,
updateMeRequestSchema, updateMeRequestSchema,
updateTeamMemberRoleRequestSchema, updateTeamMemberRoleRequestSchema,
createApiTokenRequestSchema, createApiTokenRequestSchema,
@@ -31,6 +32,7 @@ import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { workflowTaskService } from '@shumai/core/src/workflowTask/workflowTask' import { workflowTaskService } from '@shumai/core/src/workflowTask/workflowTask'
import { turntableService } from '@shumai/core/src/turntable/turntable' import { turntableService } from '@shumai/core/src/turntable/turntable'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg' import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { embeddingServerService } from '@shumai/core/src/search/embedding-server'
import type { Prisma } from '@shumai/db' import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>> type User = Prisma.UserGetPayload<Record<string, never>>
@@ -405,6 +407,46 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(res) return c.json(res)
}, },
) )
.get('/teams/:teamId/embedding-server-settings', async (c) => {
const teamId = c.req.param('teamId')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
})
return c.json(await embeddingServerService.getSettings(teamId))
})
.put(
'/teams/:teamId/embedding-server-settings',
zValidator('json', updateEmbeddingServerSettingsRequestSchema),
async (c) => {
const teamId = c.req.param('teamId')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
const { url } = c.req.valid('json')
return c.json(await embeddingServerService.updateSettings(teamId, url))
},
)
.post(
'/teams/:teamId/embedding-server-settings/test',
zValidator('json', updateEmbeddingServerSettingsRequestSchema.partial()),
async (c) => {
const teamId = c.req.param('teamId')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
const { url } = c.req.valid('json')
return c.json(await embeddingServerService.testConnection(teamId, url))
},
)
.get('/teams/:teamId/user-metadata', async (c) => { .get('/teams/:teamId/user-metadata', async (c) => {
const user = c.get('user') const user = c.get('user')
const teamId = c.req.param('teamId') const teamId = c.req.param('teamId')
+196
View File
@@ -0,0 +1,196 @@
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { transcriptService } from '@shumai/core/src/transcript/transcript'
import { Hono } from 'hono'
import { HTTPException } from 'hono/http-exception'
import { afterEach, describe, expect, it, vi } from 'vitest'
import transcriptRoute from './transcript'
describe('Transcript API', () => {
const app = new Hono().route('/', transcriptRoute)
const submit = (body: { language?: string }) =>
app.request('/files/file-id/transcripts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
const edit = (body: object, language = 'en') =>
app.request(`/files/file-id/transcripts/${language}/segments/segment-id`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
afterEach(() => vi.restoreAllMocks())
it('proxies the server language list', async () => {
const list = { model: 'whisper-tiny', languages: [{ code: 'en', name: 'English' }] }
vi.spyOn(transcriptService, 'listLanguages').mockResolvedValue(list)
const response = await app.request('/transcription/languages')
expect(await response.json()).toEqual(list)
})
it('requires project edit access to list file IDs with active transcription', async () => {
const request = () => app.request('/projects/project-id/transcription-status')
const permission = vi
.spyOn(authzService, 'hasPermission')
.mockRejectedValue(new HTTPException(403))
const list = vi.spyOn(transcriptService, 'listActiveAssetIds').mockResolvedValue(['file-id'])
expect((await request()).status).toBe(403)
expect(list).not.toHaveBeenCalled()
permission.mockResolvedValue(undefined)
const response = await request()
expect(response.status).toBe(200)
expect(await response.json()).toEqual({ assetIds: ['file-id'] })
expect(permission).toHaveBeenLastCalledWith(
expect.objectContaining({
type: ResourceType.Project,
permission: Permission.Edit,
id: 'project-id',
}),
)
expect(list).toHaveBeenCalledWith('project-id')
})
it('returns saved languages and segments with asset read access', async () => {
const permission = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
const list = vi
.spyOn(transcriptService, 'listSavedLanguages')
.mockResolvedValue({ languages: ['en'] })
const saved = {
id: 'transcript-id',
language: 'en',
segments: [{ id: 'segment-id', startMs: 0, endMs: 1400, text: 'Hello' }],
}
const get = vi.spyOn(transcriptService, 'getSavedTranscript').mockResolvedValue(saved)
const languages = await app.request('/files/file-id/transcripts')
expect(languages.status).toBe(200)
expect(await languages.json()).toEqual({ languages: ['en'] })
expect(list).toHaveBeenCalledWith('file-id')
const transcript = await app.request('/files/file-id/transcripts/en')
expect(transcript.status).toBe(200)
expect(await transcript.json()).toEqual(saved)
expect(get).toHaveBeenCalledWith('file-id', 'en')
expect(permission).toHaveBeenCalledTimes(2)
for (const [request] of permission.mock.calls) {
expect(request).toMatchObject({
type: ResourceType.Asset,
permission: Permission.Read,
id: 'file-id',
})
}
})
it('validates the saved language path and authorizes before reading saved data', async () => {
const permission = vi
.spyOn(authzService, 'hasPermission')
.mockRejectedValue(new HTTPException(403))
const list = vi.spyOn(transcriptService, 'listSavedLanguages')
const get = vi.spyOn(transcriptService, 'getSavedTranscript')
expect((await app.request('/files/file-id/transcripts/auto')).status).toBe(400)
expect((await app.request('/files/file-id/transcripts')).status).toBe(403)
expect((await app.request('/files/file-id/transcripts/en')).status).toBe(403)
expect(list).not.toHaveBeenCalled()
expect(get).not.toHaveBeenCalled()
permission.mockResolvedValue(undefined)
get.mockRejectedValue(new HTTPException(404))
expect((await app.request('/files/file-id/transcripts/zh')).status).toBe(404)
})
it('requires asset edit permission and accepts an empty segment', async () => {
const permission = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
const segment = { id: 'segment-id', startMs: 0, endMs: 1400, text: '' }
const update = vi.spyOn(transcriptService, 'updateSegmentText').mockResolvedValue(segment)
const response = await edit({ text: '' })
expect(response.status).toBe(200)
expect(await response.json()).toEqual(segment)
expect(update).toHaveBeenCalledWith('file-id', 'en', 'segment-id', '')
expect(permission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Asset,
permission: Permission.Edit,
id: 'file-id',
}),
)
})
it('rejects invalid text and timing fields before handling segment edits', async () => {
const permission = vi.spyOn(authzService, 'hasPermission')
const update = vi.spyOn(transcriptService, 'updateSegmentText')
for (const body of [
{},
{ text: null },
{ text: 'invalid\0text' },
{ text: 'Hello', startMs: 1 },
{ text: 'Hello', endMs: 1 },
]) {
expect((await edit(body)).status).toBe(400)
}
expect((await edit({ text: 'Hello' }, 'auto')).status).toBe(400)
expect(permission).not.toHaveBeenCalled()
expect(update).not.toHaveBeenCalled()
})
it('does not edit for a read-only user and forwards missing segment errors', async () => {
const permission = vi
.spyOn(authzService, 'hasPermission')
.mockRejectedValue(new HTTPException(403))
const update = vi
.spyOn(transcriptService, 'updateSegmentText')
.mockRejectedValue(new HTTPException(404))
expect((await edit({ text: 'Hello' })).status).toBe(403)
expect(update).not.toHaveBeenCalled()
permission.mockResolvedValue(undefined)
expect((await edit({ text: 'Hello' })).status).toBe(404)
})
it('requires asset edit permission and returns a queued Auto job', async () => {
const permission = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
const generate = vi
.spyOn(transcriptService, 'generate')
.mockResolvedValue({ kind: 'queued', taskId: 'task-id' })
const response = await submit({})
expect(response.status).toBe(202)
expect(await response.json()).toEqual({ kind: 'queued', taskId: 'task-id' })
expect(generate).toHaveBeenCalledWith('file-id', null)
expect(permission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Asset,
permission: Permission.Edit,
id: 'file-id',
}),
)
})
it('returns a saved transcript for an explicit language', async () => {
vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
const saved = { kind: 'existing', transcriptId: 'transcript-id', language: 'en' } as const
vi.spyOn(transcriptService, 'generate').mockResolvedValue(saved)
const response = await submit({ language: 'en' })
expect(response.status).toBe(200)
expect(await response.json()).toEqual(saved)
expect(transcriptService.generate).toHaveBeenCalledWith('file-id', 'en')
})
it('rejects invalid language codes and denies reads and writes without edit permission', async () => {
vi.spyOn(authzService, 'hasPermission').mockRejectedValue(new HTTPException(403))
const generate = vi.spyOn(transcriptService, 'generate')
const status = vi.spyOn(transcriptService, 'getStatus')
expect((await submit({ language: 'auto' })).status).toBe(400)
expect((await submit({ language: 'en' })).status).toBe(403)
expect((await app.request('/files/file-id/transcription-status')).status).toBe(403)
expect(generate).not.toHaveBeenCalled()
expect(status).not.toHaveBeenCalled()
})
})
+100
View File
@@ -0,0 +1,100 @@
import { zValidator } from '@hono/zod-validator'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { transcriptService } from '@shumai/core/src/transcript/transcript'
import type { User } from '@shumai/db'
import {
generateTranscriptRequestSchema,
transcriptLanguageCodeSchema,
updateTranscriptSegmentRequestSchema,
} from '@shumai/dtos'
import { Hono } from 'hono'
import { z } from 'zod'
const route = new Hono<{ Variables: { user: User } }>()
.get('/transcription/languages', async (c) => c.json(await transcriptService.listLanguages()))
.get('/projects/:projectId/transcription-status', async (c) => {
const projectId = c.req.param('projectId')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Edit,
type: ResourceType.Project,
id: projectId,
})
return c.json({ assetIds: await transcriptService.listActiveAssetIds(projectId) })
})
.get('/files/:fileId/transcripts', async (c) => {
const assetId = c.req.param('fileId')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Read,
type: ResourceType.Asset,
id: assetId,
})
return c.json(await transcriptService.listSavedLanguages(assetId))
})
.get(
'/files/:fileId/transcripts/:language',
zValidator('param', z.object({ fileId: z.string(), language: transcriptLanguageCodeSchema })),
async (c) => {
const { fileId, language } = c.req.valid('param')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Read,
type: ResourceType.Asset,
id: fileId,
})
return c.json(await transcriptService.getSavedTranscript(fileId, language))
},
)
.patch(
'/files/:fileId/transcripts/:language/segments/:segmentId',
zValidator(
'param',
z.object({
fileId: z.string(),
language: transcriptLanguageCodeSchema,
segmentId: z.string(),
}),
),
zValidator('json', updateTranscriptSegmentRequestSchema),
async (c) => {
const { fileId, language, segmentId } = c.req.valid('param')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Edit,
type: ResourceType.Asset,
id: fileId,
})
const { text } = c.req.valid('json')
return c.json(await transcriptService.updateSegmentText(fileId, language, segmentId, text))
},
)
.post(
'/files/:fileId/transcripts',
zValidator('json', generateTranscriptRequestSchema),
async (c) => {
const assetId = c.req.param('fileId')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Edit,
type: ResourceType.Asset,
id: assetId,
})
const { language } = c.req.valid('json')
const result = await transcriptService.generate(assetId, language ?? null)
return c.json(result, result.kind === 'queued' || result.kind === 'busy' ? 202 : 200)
},
)
.get('/files/:fileId/transcription-status', async (c) => {
const assetId = c.req.param('fileId')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Edit,
type: ResourceType.Asset,
id: assetId,
})
return c.json(await transcriptService.getStatus(assetId))
})
export default route
+4 -4
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/core", "name": "@shumai/core",
"version": "0.7.1", "version": "0.7.2",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./src/index.ts", "main": "./src/index.ts",
@@ -28,9 +28,9 @@
"@aws-sdk/s3-request-presigner": "3.1121.0", "@aws-sdk/s3-request-presigner": "3.1121.0",
"@better-auth/mcp": "1.7.12", "@better-auth/mcp": "1.7.12",
"@better-auth/oauth-provider": "1.7.12", "@better-auth/oauth-provider": "1.7.12",
"@earendil-works/chord": "1.5.0", "@earendil-works/chord": "1.7.0",
"@earendil-works/pi-ai": "1.5.0", "@earendil-works/pi-ai": "1.7.0",
"@earendil-works/pi-durable": "1.5.0", "@earendil-works/pi-durable": "1.7.0",
"@google/genai": "2.28.0", "@google/genai": "2.28.0",
"@modelcontextprotocol/client": "2.0.0", "@modelcontextprotocol/client": "2.0.0",
"@shumai/db": "workspace:*", "@shumai/db": "workspace:*",
+67 -8
View File
@@ -1040,6 +1040,65 @@ describe('AgentService', () => {
}) })
}) })
describe('Transcript Agent', () => {
test('allows one Transcript Agent per team, including when it is disabled', async () => {
const svc = new AgentService()
const team = await prisma.team.create({ data: { name: 'Transcript agent team' } })
const params = {
teamId: team.id,
type: 'transcription' as const,
name: 'Transcript Agent',
avatar: 'custom-transcript-avatar',
enabled: false,
thinkingLevel: 'off' as const,
}
await expect(svc.createAgent(params)).resolves.toMatchObject({
enabled: false,
providerId: null,
})
await expect(svc.createAgent(params)).rejects.toThrow('already exists for this team')
expect(await prisma.agent.count({ where: { teamId: team.id, type: 'transcription' } })).toBe(
1,
)
})
test('provisions and toggles the same read-only agent from the environment', async () => {
const svc = new AgentService()
const team = await prisma.team.create({ data: { name: 'Managed transcript agent team' } })
try {
vi.stubEnv('ENABLE_TRANSCRIPTION_AGENT', 'false')
await svc.ensureSystemAgentsForTeam(team.id)
expect(
await prisma.agent.count({ where: { teamId: team.id, type: 'transcription' } }),
).toBe(0)
vi.stubEnv('ENABLE_TRANSCRIPTION_AGENT', 'true')
await svc.ensureSystemAgents()
const [agent] = await svc.listAgents({ teamId: team.id })
expect(await svc.toAgentInfo(agent)).toMatchObject({
enabled: true,
readOnly: true,
avatarPreset: 'avatar-2',
})
vi.stubEnv('ENABLE_TRANSCRIPTION_AGENT', 'false')
await svc.ensureSystemAgentsForTeam(team.id)
const [disabled] = await svc.listAgents({ teamId: team.id })
expect(await svc.toAgentInfo(disabled)).toMatchObject({
id: agent.id,
enabled: false,
readOnly: true,
})
vi.stubEnv('ENABLE_TRANSCRIPTION_AGENT', undefined)
expect(await svc.toAgentInfo(disabled)).toMatchObject({ enabled: false, readOnly: false })
} finally {
vi.unstubAllEnvs()
}
})
})
describe('ensureEmbeddingAgent', () => { describe('ensureEmbeddingAgent', () => {
test('creates embedding agent when ENABLE_EMBEDDING_AGENT is true', async () => { test('creates embedding agent when ENABLE_EMBEDDING_AGENT is true', async () => {
const db = prisma const db = prisma
@@ -1048,7 +1107,7 @@ describe('AgentService', () => {
process.env.ENABLE_EMBEDDING_AGENT = 'true' process.env.ENABLE_EMBEDDING_AGENT = 'true'
try { try {
await svc.ensureEmbeddingAgentForTeam(team.id) await svc.ensureSystemAgentsForTeam(team.id)
const agent = await db.agent.findFirst({ const agent = await db.agent.findFirst({
where: { teamId: team.id, type: 'embedding' }, where: { teamId: team.id, type: 'embedding' },
include: { user: true, skills: { include: { skill: true } }, mcpServers: true }, include: { user: true, skills: { include: { skill: true } }, mcpServers: true },
@@ -1063,7 +1122,7 @@ describe('AgentService', () => {
expect(info.readOnly).toBe(true) expect(info.readOnly).toBe(true)
// Ensure idempotency // Ensure idempotency
await svc.ensureEmbeddingAgentForTeam(team.id) await svc.ensureSystemAgentsForTeam(team.id)
const count = await db.agent.count({ const count = await db.agent.count({
where: { teamId: team.id, type: 'embedding' }, where: { teamId: team.id, type: 'embedding' },
}) })
@@ -1093,7 +1152,7 @@ describe('AgentService', () => {
process.env.ENABLE_EMBEDDING_AGENT = 'true' process.env.ENABLE_EMBEDDING_AGENT = 'true'
try { try {
await svc.ensureEmbeddingAgentForTeam(team.id) await svc.ensureSystemAgentsForTeam(team.id)
const agent = await db.agent.findFirst({ const agent = await db.agent.findFirst({
where: { teamId: team.id, type: 'embedding' }, where: { teamId: team.id, type: 'embedding' },
include: { user: true, skills: { include: { skill: true } }, mcpServers: true }, include: { user: true, skills: { include: { skill: true } }, mcpServers: true },
@@ -1113,7 +1172,7 @@ describe('AgentService', () => {
const team = await db.team.create({ data: { name: 'Team No Agent' } }) const team = await db.team.create({ data: { name: 'Team No Agent' } })
delete process.env.ENABLE_EMBEDDING_AGENT delete process.env.ENABLE_EMBEDDING_AGENT
await svc.ensureEmbeddingAgentForTeam(team.id) await svc.ensureSystemAgentsForTeam(team.id)
const agent = await db.agent.findFirst({ const agent = await db.agent.findFirst({
where: { teamId: team.id, type: 'embedding' }, where: { teamId: team.id, type: 'embedding' },
}) })
@@ -1127,7 +1186,7 @@ describe('AgentService', () => {
process.env.ENABLE_EMBEDDING_AGENT = 'false' process.env.ENABLE_EMBEDDING_AGENT = 'false'
try { try {
await svc.ensureEmbeddingAgentForTeam(team.id) await svc.ensureSystemAgentsForTeam(team.id)
const agent = await db.agent.findFirst({ const agent = await db.agent.findFirst({
where: { teamId: team.id, type: 'embedding' }, where: { teamId: team.id, type: 'embedding' },
}) })
@@ -1157,7 +1216,7 @@ describe('AgentService', () => {
process.env.ENABLE_EMBEDDING_AGENT = 'false' process.env.ENABLE_EMBEDDING_AGENT = 'false'
try { try {
await svc.ensureEmbeddingAgentForTeam(team.id) await svc.ensureSystemAgentsForTeam(team.id)
const agent = await db.agent.findFirst({ const agent = await db.agent.findFirst({
where: { teamId: team.id, type: 'embedding' }, where: { teamId: team.id, type: 'embedding' },
include: { user: true, skills: { include: { skill: true } }, mcpServers: true }, include: { user: true, skills: { include: { skill: true } }, mcpServers: true },
@@ -1172,7 +1231,7 @@ describe('AgentService', () => {
} }
}) })
test('ensureSystemEmbeddingAgents updates all teams when ENABLE_EMBEDDING_AGENT is false', async () => { test('ensureSystemAgents updates all teams when ENABLE_EMBEDDING_AGENT is false', async () => {
const db = prisma const db = prisma
const svc = new AgentService() const svc = new AgentService()
const { team: team1 } = await setupTestData(db) const { team: team1 } = await setupTestData(db)
@@ -1194,7 +1253,7 @@ describe('AgentService', () => {
process.env.ENABLE_EMBEDDING_AGENT = 'false' process.env.ENABLE_EMBEDDING_AGENT = 'false'
try { try {
await svc.ensureSystemEmbeddingAgents() await svc.ensureSystemAgents()
const a1 = await db.agent.findFirst({ where: { teamId: team1.id, type: 'embedding' } }) const a1 = await db.agent.findFirst({ where: { teamId: team1.id, type: 'embedding' } })
const a2 = await db.agent.findFirst({ where: { teamId: team2.id, type: 'embedding' } }) const a2 = await db.agent.findFirst({ where: { teamId: team2.id, type: 'embedding' } })
+47 -65
View File
@@ -22,6 +22,7 @@ import AdmZip from 'adm-zip'
import { getAllowedAgentRoles } from './permissions' import { getAllowedAgentRoles } from './permissions'
import { getPresetAvatarBuffer, getPresetAvatarStorageKey, isPresetAvatarId } from './presets' import { getPresetAvatarBuffer, getPresetAvatarStorageKey, isPresetAvatarId } from './presets'
import { agentSessionService } from './session-service' import { agentSessionService } from './session-service'
import { getSystemAgentSetting } from './system-agents'
const agentInclude = { const agentInclude = {
user: true, user: true,
@@ -58,7 +59,27 @@ function extractS3Key(urlOrKey?: string | null): string | null | undefined {
export class AgentService { export class AgentService {
private skillContentCache = new Map<string, string>() private skillContentCache = new Map<string, string>()
constructor(private readonly prismaClient: typeof prisma = prisma) {} constructor(private readonly prismaClient: typeof prisma | Prisma.TransactionClient = prisma) {}
private inTransaction<T>(work: (tx: Prisma.TransactionClient) => Promise<T>): Promise<T> {
const db = this.prismaClient
return '$transaction' in db ? db.$transaction(work) : work(db)
}
private async requireUniqueAgentType(
tx: Prisma.TransactionClient,
teamId: string,
type: AgentType,
agentId?: string,
): Promise<void> {
if (type === 'chat') return
await tx.$queryRaw`SELECT id FROM teams WHERE id = ${teamId} FOR UPDATE`
const existing = await tx.agent.findFirst({
where: { type, teamId, id: agentId ? { not: agentId } : undefined },
})
if (existing) throw new Error(`Agent of type ${type} already exists for this team`)
}
async getSkillContent(skillId: string): Promise<string> { async getSkillContent(skillId: string): Promise<string> {
const skill = await this.prismaClient.skill.findUnique({ const skill = await this.prismaClient.skill.findUnique({
@@ -150,18 +171,6 @@ export class AgentService {
deniedTools, deniedTools,
} = params } = params
if (type === 'embedding' || type === 'autofill') {
const existing = await this.prismaClient.agent.findFirst({
where: {
type,
teamId,
},
})
if (existing) {
throw new Error(`Agent of type ${type} already exists for this team`)
}
}
if (type === 'chat' || type === 'autofill') { if (type === 'chat' || type === 'autofill') {
if (!providerId || !modelId) { if (!providerId || !modelId) {
throw new Error('providerId and modelId are required for chat/autofill agents') throw new Error('providerId and modelId are required for chat/autofill agents')
@@ -192,11 +201,12 @@ export class AgentService {
imageKey = extractS3Key(avatar) imageKey = extractS3Key(avatar)
} }
return this.prismaClient.$transaction(async (tx) => { return this.inTransaction(async (tx) => {
const team = await tx.team.findUnique({ const team = await tx.team.findUnique({
where: { id: teamId }, where: { id: teamId },
}) })
if (!team) throw new Error('team not found') if (!team) throw new Error('team not found')
await this.requireUniqueAgentType(tx, teamId, type)
if (runnerId) { if (runnerId) {
const runner = await tx.runner.findFirst({ const runner = await tx.runner.findFirst({
@@ -298,19 +308,6 @@ export class AgentService {
if (!agent) throw new Error('agent not found') if (!agent) throw new Error('agent not found')
if (type === 'embedding' || type === 'autofill') {
const existing = await this.prismaClient.agent.findFirst({
where: {
type,
id: { not: agentId },
teamId: agent.teamId,
},
})
if (existing) {
throw new Error(`Agent of type ${type} already exists for this team`)
}
}
if (type === 'chat' || type === 'autofill') { if (type === 'chat' || type === 'autofill') {
if (!providerId || !modelId) { if (!providerId || !modelId) {
throw new Error('providerId and modelId are required for chat/autofill agents') throw new Error('providerId and modelId are required for chat/autofill agents')
@@ -364,7 +361,9 @@ export class AgentService {
avatarPreset: newAvatarPreset, avatarPreset: newAvatarPreset,
} }
return this.prismaClient.$transaction(async (tx) => { return this.inTransaction(async (tx) => {
await this.requireUniqueAgentType(tx, agent.teamId, type, agentId)
await tx.user.update({ await tx.user.update({
where: { id: agentId }, where: { id: agentId },
data: { data: {
@@ -476,10 +475,7 @@ export class AgentService {
*/ */
async toAgentInfo(agent: AgentInfoSource): Promise<AgentInfo> { async toAgentInfo(agent: AgentInfoSource): Promise<AgentInfo> {
const config = agent.config as unknown as PrismaJson.AgentConfig const config = agent.config as unknown as PrismaJson.AgentConfig
const isManagedByEnv = const isReadOnly = getSystemAgentSetting(agent.type) !== undefined
process.env.ENABLE_EMBEDDING_AGENT === 'true' ||
process.env.ENABLE_EMBEDDING_AGENT === 'false'
const isReadOnly = agent.type === 'embedding' && isManagedByEnv
return { return {
id: agent.id, id: agent.id,
@@ -652,59 +648,45 @@ export class AgentService {
) )
} }
async ensureSystemEmbeddingAgents(): Promise<void> { async ensureSystemAgents(): Promise<void> {
const envVal = process.env.ENABLE_EMBEDDING_AGENT if (!getSystemAgentSetting('embedding') && !getSystemAgentSetting('transcription')) return
if (envVal !== 'true' && envVal !== 'false') {
return
}
const teams = await this.prismaClient.team.findMany({ const teams = await this.prismaClient.team.findMany({
orderBy: { id: 'desc' },
select: { id: true }, select: { id: true },
}) })
for (const team of teams) { for (const team of teams) {
await this.ensureEmbeddingAgentForTeam(team.id) await this.ensureSystemAgentsForTeam(team.id)
} }
} }
async ensureEmbeddingAgentForTeam(teamId: string): Promise<void> { async ensureSystemAgentsForTeam(teamId: string): Promise<void> {
const envVal = process.env.ENABLE_EMBEDDING_AGENT for (const type of ['embedding', 'transcription'] as const) {
if (envVal !== 'true' && envVal !== 'false') { const setting = getSystemAgentSetting(type)
return if (!setting) continue
}
const existing = await this.prismaClient.agent.findFirst({ await this.inTransaction(async (tx) => {
where: { await tx.$queryRaw`SELECT id FROM teams WHERE id = ${teamId} FOR UPDATE`
teamId, const existing = await tx.agent.findFirst({
type: 'embedding', where: { teamId, type },
},
}) })
if (envVal === 'true') { if (existing && existing.enabled !== setting.enabled) {
if (!existing) { await tx.agent.update({ where: { id: existing.id }, data: { enabled: setting.enabled } })
await this.createAgent({ } else if (!existing && setting.enabled) {
await new AgentService(tx).createAgent({
teamId, teamId,
name: 'embedding-agent', name: type === 'embedding' ? 'embedding-agent' : setting.name,
type: 'embedding', type,
avatar: 'avatar-1', avatar: setting.avatar,
thinkingLevel: 'off', thinkingLevel: 'off',
enabled: true, enabled: true,
}) })
} else if (!existing.enabled) {
await this.prismaClient.agent.update({
where: { id: existing.id },
data: { enabled: true },
})
} }
} else if (envVal === 'false') {
if (existing && existing.enabled) {
await this.prismaClient.agent.update({
where: { id: existing.id },
data: { enabled: false },
}) })
} }
} }
}
} }
export const agentService = new AgentService() export const agentService = new AgentService()
+3 -1
View File
@@ -92,9 +92,11 @@ export async function openSessionCache(sessionId: string) {
throw new Error('Session commit sequence mismatch') throw new Error('Session commit sequence mismatch')
seq = receipt.seq seq = receipt.seq
} }
if (result.stored !== commits.length) if (result.kind === 'refused') {
throw result.refused ?? new Error('Session restoration refused') throw result.refused ?? new Error('Session restoration refused')
} }
if (result.stored !== commits.length) throw new Error('Session restoration was incomplete')
}
await save(true) await save(true)
} catch (error) { } catch (error) {
await storage.close(BACKGROUND_CONTEXT) await storage.close(BACKGROUND_CONTEXT)
@@ -60,6 +60,16 @@ describe('Native session storage and PostgreSQL synchronization', () => {
expect(await prisma.agentSessionEntry.count({ where: { sessionId: session.id } })).toBe(0) expect(await prisma.agentSessionEntry.count({ where: { sessionId: session.id } })).toBe(0)
}) })
it('returns logs with unavailable usage before a session has an accounting checkpoint', async () => {
const { session } = await fixture()
expect(await agentSessionService.getLogs(session.id)).toEqual({ entries: [], usage: null })
const entries = await appendSessionEntries(session.id, [
{ kind: 'pi.user', model: [{ role: 'user', content: 'No usage yet', timestamp: 1 }] },
])
expect(await agentSessionService.getLogs(session.id)).toEqual({ entries, usage: null })
})
it.each(['missing', 'corrupt', 'dirty'] as const)( it.each(['missing', 'corrupt', 'dirty'] as const)(
'rebuilds a %s local cache from mirrored commits', 'rebuilds a %s local cache from mirrored commits',
async (failure) => { async (failure) => {
@@ -438,6 +448,10 @@ describe('Native session storage and PostgreSQL synchronization', () => {
expect(Number(usage.totalTokens)).toBeGreaterThan(0) expect(Number(usage.totalTokens)).toBeGreaterThan(0)
expect(Number(usage.totalTokens)).toBe(checkpoint.totalTokens) expect(Number(usage.totalTokens)).toBe(checkpoint.totalTokens)
expect(Number(usage.cost)).toBe(checkpoint.cost) expect(Number(usage.cost)).toBe(checkpoint.cost)
const logs = await agentSessionService.getLogs(session.id)
expect(logs.entries).not.toHaveLength(0)
expect(logs.entries).toEqual(await agentSessionService.getEntries(session.id))
expect(logs.usage).toEqual(checkpoint)
}) })
it('rolls back usage if PostgreSQL cannot persist the native commit', async () => { it('rolls back usage if PostgreSQL cannot persist the native commit', async () => {
@@ -476,5 +490,6 @@ describe('Native session storage and PostgreSQL synchronization', () => {
await prisma.agentSession.delete({ where: { id: session.id } }) await prisma.agentSession.delete({ where: { id: session.id } })
expect(await prisma.agentSessionCommit.count({ where: { sessionId: session.id } })).toBe(0) expect(await prisma.agentSessionCommit.count({ where: { sessionId: session.id } })).toBe(0)
await expect(agentSessionService.getEntries(session.id)).rejects.toThrow('Session not found') await expect(agentSessionService.getEntries(session.id)).rejects.toThrow('Session not found')
await expect(agentSessionService.getLogs(session.id)).rejects.toThrow('Session not found')
}) })
}) })
+19 -6
View File
@@ -9,6 +9,7 @@ import {
} from '@earendil-works/pi-durable' } from '@earendil-works/pi-durable'
import { prisma, type Prisma, type TeamMemberRole } from '@shumai/db' import { prisma, type Prisma, type TeamMemberRole } from '@shumai/db'
import { acquireAdvisoryLock } from '@shumai/db/src/advisory-lock' import { acquireAdvisoryLock } from '@shumai/db/src/advisory-lock'
import type { AgentSessionLogs } from '@shumai/dtos'
import { AiUsageService } from '../ai-usage/ai-usage' import { AiUsageService } from '../ai-usage/ai-usage'
import { quotaService } from '../quota/quota-service' import { quotaService } from '../quota/quota-service'
import { openSessionCache, removeSessionCaches } from './session-cache' import { openSessionCache, removeSessionCaches } from './session-cache'
@@ -184,20 +185,22 @@ export class AgentSessionService {
private async read<T>( private async read<T>(
sessionId: string, sessionId: string,
use: (storage: SessionReader) => Promise<T>, use: (storage: SessionReader, usage: PrismaJson.AgentSessionUsage | null) => Promise<T>,
{ includeUsage = false } = {},
): Promise<T> { ): Promise<T> {
if (this.closing) throw new Error('Session service is closing') if (this.closing) throw new Error('Session service is closing')
return this.withCacheAccess(sessionId, async () => { return this.withCacheAccess(sessionId, async () => {
const session = await prisma.agentSession.findUnique({ const session = await prisma.agentSession.findUnique({
where: { id: sessionId }, where: { id: sessionId },
select: { id: true }, select: { id: true, accountedUsage: includeUsage },
}) })
if (!session) throw new Error('Session not found') if (!session) throw new Error('Session not found')
const usage = session.accountedUsage ?? null
const writer = this.writers.get(sessionId) const writer = this.writers.get(sessionId)
if (writer) return use(writer.reader) if (writer) return use(writer.reader, usage)
const cache = await openSessionCache(sessionId) const cache = await openSessionCache(sessionId)
try { try {
return await use(cache.storage) return await use(cache.storage, usage)
} finally { } finally {
await cache.storage.close(BACKGROUND_CONTEXT) await cache.storage.close(BACKGROUND_CONTEXT)
} }
@@ -225,7 +228,18 @@ export class AgentSessionService {
} }
async getEntries(sessionId: string): Promise<EntryRecord[]> { async getEntries(sessionId: string): Promise<EntryRecord[]> {
return this.read(sessionId, async (storage) => { return this.read(sessionId, this.readAllEntries)
}
async getLogs(sessionId: string): Promise<AgentSessionLogs> {
return this.read(
sessionId,
async (storage, usage) => ({ entries: await this.readAllEntries(storage), usage }),
{ includeUsage: true },
)
}
private async readAllEntries(storage: SessionReader): Promise<EntryRecord[]> {
const entries: EntryRecord[] = [] const entries: EntryRecord[] = []
if (!(await storage.conversation(ROOT_CONVERSATION_ID, BACKGROUND_CONTEXT))) return entries if (!(await storage.conversation(ROOT_CONVERSATION_ID, BACKGROUND_CONTEXT))) return entries
let cursor: Cursor | undefined let cursor: Cursor | undefined
@@ -240,7 +254,6 @@ export class AgentSessionService {
cursor = page.next cursor = page.next
} while (cursor) } while (cursor)
return entries return entries
})
} }
async getEntryForRequest(sessionId: string, requestId: string) { async getEntryForRequest(sessionId: string, requestId: string) {
+20
View File
@@ -0,0 +1,20 @@
import type { AgentType } from '@shumai/dtos'
const systemAgentSettings = {
embedding: { envKey: 'ENABLE_EMBEDDING_AGENT', name: 'Embedding agent', avatar: 'avatar-1' },
transcription: {
envKey: 'ENABLE_TRANSCRIPTION_AGENT',
name: 'Transcript Agent',
avatar: 'avatar-2',
},
} as const
export function getSystemAgentSetting(type: AgentType) {
if (type !== 'embedding' && type !== 'transcription') return undefined
const { envKey, name, avatar } = systemAgentSettings[type]
const value = process.env[envKey]
if (value !== 'true' && value !== 'false') return undefined
return { name, avatar, enabled: value === 'true' }
}
+630 -7
View File
@@ -1,5 +1,5 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' 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 { setupTestDbHooks } from '@shumai/db/test'
import { HTTPException } from 'hono/http-exception' import { HTTPException } from 'hono/http-exception'
@@ -941,7 +941,7 @@ describe('AssetService', () => {
).resolves.not.toThrow() ).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() const { user, project, assets } = await setupBasicAssets()
// 1. Create StorageKey and Asset for attachment // 1. Create StorageKey and Asset for attachment
@@ -949,15 +949,15 @@ describe('AssetService', () => {
data: { data: {
key: 'attachments/test-attachment-file.png', key: 'attachments/test-attachment-file.png',
status: 'active', status: 'active',
createdAt: new Date(Date.now() - 60_000),
}, },
}) })
const attachmentAsset = await prisma.asset.create({ const attachmentAsset = await prisma.asset.create({
data: { data: {
name: 'test-attachment-file.png', name: 'test-attachment-file.png',
type: AssetType.file, type: AssetType.attachment,
projectId: project.id, projectId: project.id,
parentId: assets.root.id,
creatorId: user.id, creatorId: user.id,
storageKeyId: storageKey.id, storageKeyId: storageKey.id,
sizeByte: 100, sizeByte: 100,
@@ -988,18 +988,278 @@ describe('AssetService', () => {
// 5. Verify the comment is deleted from DB // 5. Verify the comment is deleted from DB
await expect(prisma.assetComment.findUnique({ where: { id: comment.id } })).resolves.toBeNull() 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() 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() 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( expect(s3Service.deleteObject).toHaveBeenCalledWith(
'shumai', 'shumai',
'attachments/test-attachment-file.png', '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 () => { it('can create and retrieve comments with video timestamp', async () => {
const { user, assets } = await setupBasicAssets() const { user, assets } = await setupBasicAssets()
@@ -5704,4 +5964,367 @@ describe('AssetService — natural sort by name', () => {
expect(variant).toContain('http://mock-s3-url') 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 })
})
})
}) })
+314 -75
View File
@@ -61,6 +61,7 @@ import { dedupeSymlinksToTarget } from './symlink'
import { watermarkService } from '@shumai/core/src/watermark/watermark' import { watermarkService } from '@shumai/core/src/watermark/watermark'
import { generateKeyBetween } from 'jittered-fractional-indexing' import { generateKeyBetween } from 'jittered-fractional-indexing'
import { getAvatarUrl } from '@shumai/core/src/user/avatar' 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 { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz' import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
import { metadataService } from '@shumai/core/src/metadata/metadata' import { metadataService } from '@shumai/core/src/metadata/metadata'
@@ -742,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[] let typesToQuery: AssetType[]
if (req.assetType === 'file') { if (req.assetType === 'file') {
typesToQuery = [AssetType.file, AssetType.version_stack] typesToQuery = [AssetType.file, AssetType.version_stack]
@@ -830,6 +834,7 @@ export class AssetService {
const infos = await this.toAssetInfos(assets, undefined, { const infos = await this.toAssetInfos(assets, undefined, {
includeDeletedChildren: req.showDeleted, includeDeletedChildren: req.showDeleted,
excludeInternalComments: options?.excludeInternalComments,
}) })
return { data: infos, pageInfo } return { data: infos, pageInfo }
@@ -1106,7 +1111,10 @@ export class AssetService {
return this.getAsset({ assetId: asset.id }) 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({ const a = await this.prismaClient.asset.findUnique({
where: { id: req.assetId }, where: { id: req.assetId },
include: assetInclude, include: assetInclude,
@@ -1129,7 +1137,9 @@ export class AssetService {
afs.push({ id: row.id, name: row.name }) 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] const info = infos[0]
info.ancestorFolders = afs info.ancestorFolders = afs
@@ -1957,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 * 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 * unless `triggerAgents` is false, which keeps an agent's own comments from starting
@@ -1964,7 +1995,7 @@ export class AssetService {
*/ */
async createComment( async createComment(
req: CreateCommentRequest, req: CreateCommentRequest,
options: { triggerAgents?: boolean } = {}, options: { triggerAgents?: boolean; shareLinkId?: string } = {},
): Promise<CommentInfo> { ): Promise<CommentInfo> {
const triggerAgents = options.triggerAgents ?? true const triggerAgents = options.triggerAgents ?? true
let commentId = '' let commentId = ''
@@ -1979,16 +2010,43 @@ export class AssetService {
let actualReplyToId = req.replyToId let actualReplyToId = req.replyToId
let parentComment = null let parentComment = null
let parentIsInternal = false
if (req.replyToId) { if (req.replyToId) {
parentComment = await tx.assetComment.findUnique({ parentComment = await tx.assetComment.findUnique({
where: { id: req.replyToId }, 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) { if (parentComment?.replyToId) {
actualReplyToId = 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({ const comment = await tx.assetComment.create({
data: { data: {
assetId: a.id, assetId: a.id,
@@ -1997,27 +2055,28 @@ export class AssetService {
annotation: req.annotations, annotation: req.annotations,
second: req.second, second: req.second,
replyToId: actualReplyToId, replyToId: actualReplyToId,
isInternal,
}, },
}) })
commentId = comment.id commentId = comment.id
for (const attachmentId of req.attachmentIds) { if (attachmentIds.length > 0) {
const attachmentAsset = await tx.asset.findUnique({ // Read the links after acquiring the locks to see any claims that committed while waiting.
where: { id: attachmentId }, const unclaimed = await tx.asset.findMany({
where: { id: { in: attachmentIds }, commentAttachments: { none: {} } },
select: { id: true },
}) })
if ( await tx.assetCommentAttachment.createMany({
attachmentAsset && data: unclaimed.map(({ id }) => ({ assetId: id, commentId: comment.id })),
(attachmentAsset.type === AssetType.attachment ||
attachmentAsset.type === AssetType.file) &&
attachmentAsset.projectId === a.projectId
) {
await tx.assetCommentAttachment.create({
data: {
assetId: attachmentAsset.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 if (!triggerAgents) return
@@ -2195,22 +2254,154 @@ export class AssetService {
return this.getComment(commentId, userId) 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> { async deleteComment({ commentId, userId }: { commentId: string; userId: string }): Promise<void> {
const comment = await this.prismaClient.assetComment.findUnique({ const comment = await this.prismaClient.assetComment.findUnique({
where: { id: commentId }, where: { id: commentId },
include: { select: {
attachments: { creatorId: true,
include: { attachments: { select: { assetId: true } },
asset: {
include: {
storageKey: true,
},
},
},
},
asset: { asset: {
select: { select: {
project: { select: { id: true, teamId: true } }, project: { select: { teamId: true } },
}, },
}, },
}, },
@@ -2248,50 +2439,24 @@ export class AssetService {
throw new HTTPException(403, { message: 'You do not have permission to delete this comment' }) 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 await this.prismaClient.$transaction(async (tx) => {
const bucket = process.env.S3_BUCKET || 'shumai' const attachmentIds = await this.lockCommentAttachments(
for (const att of comment.attachments) { tx,
const asset = att.asset comment.attachments.map(({ assetId }) => assetId),
if (asset.storageKey) { )
try { await tx.assetComment.delete({ where: { id: commentId } })
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.asset.delete({ if (attachmentIds.length > 0) {
where: { id: asset.id }, // 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: {} } },
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 },
}) })
} }
async listComments( private getCommentInclude(options?: { excludeInternal?: boolean }) {
assetId: string, return {
params: PaginationParams,
requestingUserId?: string,
): Promise<PaginatedData<CommentInfo[]>> {
const resolvedAssetId = await this.resolveLatestVersionId(assetId)
const { data: comments, pageInfo } = await paginateQuery(
async (skip, take) => {
return this.prismaClient.assetComment.findMany({
where: { assetId: resolvedAssetId, replyToId: null },
include: {
creator: true, creator: true,
completionLastChangedBy: true, completionLastChangedBy: true,
asset: { include: { storageKey: true } }, asset: { include: { storageKey: true } },
@@ -2300,9 +2465,10 @@ export class AssetService {
include: { include: {
user: { select: { id: true, name: true } }, user: { select: { id: true, name: true } },
}, },
orderBy: { createdAt: 'asc' }, orderBy: { createdAt: 'asc' as const },
}, },
replies: { replies: {
...(options?.excludeInternal ? { where: { isInternal: false } } : {}),
include: { include: {
creator: true, creator: true,
completionLastChangedBy: true, completionLastChangedBy: true,
@@ -2311,12 +2477,32 @@ export class AssetService {
include: { include: {
user: { select: { id: true, name: true } }, user: { select: { id: true, name: true } },
}, },
orderBy: { createdAt: 'asc' }, orderBy: { createdAt: 'asc' as const },
}, },
}, },
orderBy: { id: 'asc' }, 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,
include: this.getCommentInclude(options),
skip, skip,
take, take,
orderBy: { id: 'asc' }, orderBy: { id: 'asc' },
@@ -2324,7 +2510,7 @@ export class AssetService {
}, },
async () => async () =>
this.prismaClient.assetComment.count({ this.prismaClient.assetComment.count({
where: { assetId: resolvedAssetId, replyToId: null }, where,
}), }),
params, params,
) )
@@ -2334,6 +2520,36 @@ export class AssetService {
return { data: infos, pageInfo } 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( async exportComments(
assetId: string, assetId: string,
format: CommentExportFormat, format: CommentExportFormat,
@@ -2432,9 +2648,10 @@ export class AssetService {
async toAssetInfos( async toAssetInfos(
assets: AssetWithIncludes[], assets: AssetWithIncludes[],
previewFormat?: PreviewFormat, previewFormat?: PreviewFormat,
options?: { includeDeletedChildren?: boolean }, options?: { includeDeletedChildren?: boolean; excludeInternalComments?: boolean },
): Promise<AssetInfo[]> { ): Promise<AssetInfo[]> {
const includeDeletedChildren = options?.includeDeletedChildren ?? false const includeDeletedChildren = options?.includeDeletedChildren ?? false
const excludeInternalComments = options?.excludeInternalComments ?? false
const stackIds = new Set<string>() const stackIds = new Set<string>()
for (const a of assets) { for (const a of assets) {
@@ -2524,6 +2741,12 @@ export class AssetService {
by: ['assetId'], by: ['assetId'],
where: { where: {
assetId: { in: Array.from(commentTargetIds) }, assetId: { in: Array.from(commentTargetIds) },
...(excludeInternalComments
? {
isInternal: false,
OR: [{ replyToId: null }, { replyTo: { isInternal: false } }],
}
: {}),
}, },
_count: { _all: true }, _count: { _all: true },
}) })
@@ -2715,6 +2938,7 @@ export class AssetService {
type: a.type, type: a.type,
targetType: a.type === AssetType.symlink ? a.target?.type : null, targetType: a.type === AssetType.symlink ? a.target?.type : null,
status: latestVersion.status, status: latestVersion.status,
mediaType: latestVersion.mediaType,
proxyType, proxyType,
latestChildren, latestChildren,
preview, preview,
@@ -3080,6 +3304,10 @@ export class AssetService {
* that belong to an asset they have access to. * that belong to an asset they have access to.
*/ */
async getDownloadUrl(assetId: string, key: string): Promise<string> { 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 targetAssetId = await this.resolveLatestVersionId(assetId)
const asset = await this.prismaClient.asset.findUnique({ const asset = await this.prismaClient.asset.findUnique({
where: { id: targetAssetId }, where: { id: targetAssetId },
@@ -3100,6 +3328,7 @@ export class AssetService {
throw new Error('Key does not belong to this asset') throw new Error('Key does not belong to this asset')
} }
let signedAssetId = asset.id
let storageKey = asset.storageKey.key let storageKey = asset.storageKey.key
let assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1) let assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
let targetName = asset.name let targetName = asset.name
@@ -3115,12 +3344,14 @@ export class AssetService {
storageKey: { key: { startsWith: key.substring(0, key.lastIndexOf('/') + 1) } }, storageKey: { key: { startsWith: key.substring(0, key.lastIndexOf('/') + 1) } },
}, },
select: { select: {
id: true,
name: true, name: true,
status: true, status: true,
storageKey: { select: { key: true, isArchived: true } }, storageKey: { select: { key: true, isArchived: true } },
}, },
}) })
if (sibling?.storageKey?.key) { if (sibling?.storageKey?.key) {
signedAssetId = sibling.id
storageKey = sibling.storageKey.key storageKey = sibling.storageKey.key
assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1) assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
targetStatus = sibling.status targetStatus = sibling.status
@@ -3176,7 +3407,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( async archiveAssets(
@@ -3386,6 +3624,7 @@ export class AssetService {
updatedAt: c.updatedAt.toISOString(), updatedAt: c.updatedAt.toISOString(),
sessionId: c.sessionId, sessionId: c.sessionId,
isCompleted: c.isCompleted, isCompleted: c.isCompleted,
isInternal: c.isInternal,
completionLastChangedBy, completionLastChangedBy,
reactionCounts, reactionCounts,
} }
+65
View File
@@ -595,5 +595,70 @@ describe('AuthzService', () => {
}), }),
).rejects.toThrow('Permission denied') ).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()
})
}) })
}) })
+4 -5
View File
@@ -122,17 +122,16 @@ export class AuthzService {
}) })
if (!member) throw new HTTPException(403, { message: 'User is not a member of the team' }) 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.type === ResourceType.KanbanTask) {
if (req.permission === Permission.Read) { if (req.permission === Permission.Read || req.permission === Permission.Edit) {
return
}
if (req.permission === Permission.Edit) {
const isParticipant = await this.isKanbanTaskParticipant(req.id, req.user.id) const isParticipant = await this.isKanbanTaskParticipant(req.id, req.user.id)
if (isParticipant) { if (isParticipant) {
return return
} }
} }
throw new HTTPException(403, { message: 'User has only project scope' })
} }
// Project-scoped member on a team-level resource (no project context): // Project-scoped member on a team-level resource (no project context):
@@ -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 })
}
})
})
+557
View File
@@ -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()
+3
View File
@@ -12,6 +12,8 @@ export interface PostCommentParams {
/** Timecode in seconds (or the encoded viewing angle for 3D models). */ /** Timecode in seconds (or the encoded viewing angle for 3D models). */
second?: number second?: number
attachmentIds?: string[] 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). */ /** Whether mentions of agents start a chat with them (default true). */
triggerAgents?: boolean triggerAgents?: boolean
} }
@@ -31,6 +33,7 @@ export class CommentService {
annotations: params.annotations, annotations: params.annotations,
second: params.second, second: params.second,
attachmentIds: params.attachmentIds ?? [], attachmentIds: params.attachmentIds ?? [],
isInternal: params.isInternal,
}, },
{ triggerAgents: params.triggerAgents }, { triggerAgents: params.triggerAgents },
) )
+1
View File
@@ -5,6 +5,7 @@ export * from './asset/auto-archive-job'
export * from './auth/auth' export * from './auth/auth'
export * from './authz/authz' export * from './authz/authz'
export * from './collection/collection' export * from './collection/collection'
export * from './comment/comment-frame'
export * from './invite/invite' export * from './invite/invite'
export * from './metadata/metadata' export * from './metadata/metadata'
export * from './notification/index' export * from './notification/index'
+13 -9
View File
@@ -1,6 +1,7 @@
import { prisma } from '@shumai/db' import { prisma } from '@shumai/db'
import '@shumai/db/src/prisma-json-types' import '@shumai/db/src/prisma-json-types'
import { logger } from '@shumai/core/src/logger' import { logger } from '@shumai/core/src/logger'
import { HTTPException } from 'hono/http-exception'
export interface IntegrationEnvKeys { export interface IntegrationEnvKeys {
url: string[] url: string[]
@@ -12,6 +13,7 @@ export interface IntegrationDefinition<TKey extends keyof PrismaJson.Settings> {
name: string name: string
settingsKey: TKey settingsKey: TKey
envKeys: IntegrationEnvKeys envKeys: IntegrationEnvKeys
requireSettingsRead?: boolean
} }
export interface ResolvedIntegrationConfig { export interface ResolvedIntegrationConfig {
@@ -45,7 +47,7 @@ function getFirstEnvValue(keys?: string[]): string | undefined {
export async function resolveIntegrationConfig<TKey extends keyof PrismaJson.Settings>( export async function resolveIntegrationConfig<TKey extends keyof PrismaJson.Settings>(
def: IntegrationDefinition<TKey>, def: IntegrationDefinition<TKey>,
teamId?: string, teamId?: string | null,
): Promise<ResolvedIntegrationConfig> { ): Promise<ResolvedIntegrationConfig> {
const envUrl = getFirstEnvValue(def.envKeys.url) const envUrl = getFirstEnvValue(def.envKeys.url)
const envUsername = getFirstEnvValue(def.envKeys.username) const envUsername = getFirstEnvValue(def.envKeys.username)
@@ -60,12 +62,13 @@ export async function resolveIntegrationConfig<TKey extends keyof PrismaJson.Set
} }
} }
if (teamId) { if (teamId || teamId === null) {
try { try {
const team = await prisma.team.findUnique({ // Instance-wide consumers use the single team when they have no team ID.
where: { id: teamId }, const team =
select: { settings: true }, teamId === null
}) ? await prisma.team.findFirst({ orderBy: { id: 'desc' }, select: { settings: true } })
: await prisma.team.findUnique({ where: { id: teamId }, select: { settings: true } })
const teamSettings = team?.settings as PrismaJson.Settings | null const teamSettings = team?.settings as PrismaJson.Settings | null
const serviceSettings = teamSettings?.[def.settingsKey] as const serviceSettings = teamSettings?.[def.settingsKey] as
{ url?: string; username?: string; password?: string } | undefined { url?: string; username?: string; password?: string } | undefined
@@ -79,6 +82,7 @@ export async function resolveIntegrationConfig<TKey extends keyof PrismaJson.Set
} }
} }
} catch (err) { } catch (err) {
if (def.requireSettingsRead) throw err
logger.error({ err, teamId }, `Failed to load team ${def.name} settings`) logger.error({ err, teamId }, `Failed to load team ${def.name} settings`)
} }
} }
@@ -108,9 +112,9 @@ export async function updateIntegrationSettings<TKey extends keyof PrismaJson.Se
): Promise<IntegrationSettingsResponse> { ): Promise<IntegrationSettingsResponse> {
const currentConfig = await resolveIntegrationConfig(def, teamId) const currentConfig = await resolveIntegrationConfig(def, teamId)
if (currentConfig.isEnv) { if (currentConfig.isEnv) {
throw new Error( throw new HTTPException(400, {
`${def.name} settings are configured via environment variables and cannot be edited`, message: `${def.name} settings are configured via environment variables and cannot be edited`,
) })
} }
const team = await prisma.team.findUnique({ const team = await prisma.team.findUnique({
+296 -2
View File
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest' import { describe, it, expect } from 'vitest'
import { prisma } from '@shumai/db' import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test' 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 { UNASSIGNED_GOAL_ID } from '@shumai/dtos'
import { kanbanService } from './kanban' import { kanbanService } from './kanban'
@@ -646,7 +646,7 @@ describe('KanbanService', () => {
) )
// Create attachment // Create attachment
const att = await kanbanService.createAttachment(team.id, { const att = await kanbanService.createAttachment(team.id, editor.id, {
fileName: 'design.png', fileName: 'design.png',
size: 1024, size: 1024,
contentType: 'image/png', 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 // Task Ordering & Fractional Indexing
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@@ -1139,4 +1252,185 @@ describe('KanbanService', () => {
expect(pdfDetail?.thumbnailUrl).toContain('posters/doc_poster.webp') 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 }),
)
})
})
}) })
+214 -66
View File
@@ -7,6 +7,7 @@ import { paginateQuery } from '../pagination'
import { getAvatarUrl } from '../user/avatar' import { getAvatarUrl } from '../user/avatar'
import { s3Service } from '../s3/s3' import { s3Service } from '../s3/s3'
import { getProxyType } from '../utils/mime' import { getProxyType } from '../utils/mime'
import { sanitizeFilename } from '../utils/filename'
import { assetService } from '../asset/asset' import { assetService } from '../asset/asset'
import type { import type {
CreateKanbanGoalRequest, CreateKanbanGoalRequest,
@@ -28,6 +29,73 @@ import type {
} from '@shumai/dtos' } from '@shumai/dtos'
import { UNASSIGNED_GOAL_ID } 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 { export class KanbanService {
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// Goal CRUD // 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({ const task = await prisma.kanbanTask.findUnique({
where: { id: taskId }, where: { id: taskId },
include: { include: {
@@ -354,27 +422,38 @@ export class KanbanService {
throw new HTTPException(404, { message: 'Task not found' }) 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 latestStatusEvent = await this.resolveLatestStatusEvent(taskId, task.status)
const resolvedAssets = await this.resolveTaskAssetInfos(task.assets) const resolvedAssets = await this.resolveTaskAssetInfos(task.assets)
const baseInfo = await this.toTaskInfo(task, { const baseInfo = await this.toTaskInfo(task, {
latestStatusEvent, latestStatusEvent,
dependencyCount: task.dependencies.length, dependencyCount: dependencies.length,
dependentCount: task.dependents.length, dependentCount: dependents.length,
commentCount: task.comments.length, commentCount: task.comments.length,
assetCount: task.assets.length, assetCount: task.assets.length,
}) })
return { return {
...baseInfo, ...baseInfo,
dependencies: task.dependencies.map((d) => ({ dependencies: dependencies.map((d) => ({
id: d.parent.id, id: d.parent.id,
title: d.parent.title, title: d.parent.title,
isAgentTask: d.parent.isAgentTask, isAgentTask: d.parent.isAgentTask,
status: d.parent.status, status: d.parent.status,
priority: d.parent.priority, priority: d.parent.priority,
})), })),
dependents: task.dependents.map((d) => ({ dependents: dependents.map((d) => ({
id: d.child.id, id: d.child.id,
title: d.child.title, title: d.child.title,
isAgentTask: d.child.isAgentTask, isAgentTask: d.child.isAgentTask,
@@ -392,29 +471,12 @@ export class KanbanService {
image: await getAvatarUrl(c.author.image), image: await getAvatarUrl(c.author.image),
}, },
body: c.body, body: c.body,
attachments: await this.resolveCommentAttachments(c.attachments), attachments: await this.resolveCommentAttachments(c.attachments, task.teamId),
createdAt: c.createdAt.toISOString(), createdAt: c.createdAt.toISOString(),
updatedAt: c.updatedAt.toISOString(), updatedAt: c.updatedAt.toISOString(),
})), })),
), ),
events: await Promise.all( events: await this.resolveTaskEvents(task.events, readableIds),
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(),
})),
),
} }
} }
@@ -659,7 +721,8 @@ export class KanbanService {
} }
const latestStatusEvent = await this.resolveLatestStatusEvent(taskId, updated.status) 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, { return await this.toTaskInfo(updated, {
latestStatusEvent, latestStatusEvent,
@@ -704,10 +767,54 @@ export class KanbanService {
return taskInfo 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( async listTasks(
teamId: string, teamId: string,
params: ListKanbanTasksRequest, params: ListKanbanTasksRequest,
viewerId?: string,
): Promise<{ data: KanbanTaskInfo[]; pageInfo: { total?: number; cursor?: string } }> { ): Promise<{ data: KanbanTaskInfo[]; pageInfo: { total?: number; cursor?: string } }> {
const taskFilter = await this.readableTaskFilter(teamId, viewerId)
const where: Prisma.KanbanTaskWhereInput = { const where: Prisma.KanbanTaskWhereInput = {
teamId, teamId,
...(params.status && { status: params.status }), ...(params.status && { status: params.status }),
@@ -721,6 +828,7 @@ export class KanbanService {
...(params.priority && { priority: params.priority }), ...(params.priority && { priority: params.priority }),
...(params.assigneeId && { assigneeId: params.assigneeId }), ...(params.assigneeId && { assigneeId: params.assigneeId }),
...(params.reporterId && { reporterId: params.reporterId }), ...(params.reporterId && { reporterId: params.reporterId }),
...(taskFilter && { AND: [taskFilter] }),
} }
return await paginateQuery( return await paginateQuery(
@@ -732,14 +840,7 @@ export class KanbanService {
reporter: true, reporter: true,
assignee: true, assignee: true,
goal: true, goal: true,
_count: { _count: { select: taskRelationCountSelect(taskFilter) },
select: {
comments: true,
dependencies: true,
dependents: true,
assets: true,
},
},
}, },
orderBy: [{ sortIndex: 'asc' }, { id: 'asc' }], orderBy: [{ sortIndex: 'asc' }, { id: 'asc' }],
skip, skip,
@@ -869,9 +970,10 @@ export class KanbanService {
async createAttachment( async createAttachment(
teamId: string, teamId: string,
uploaderId: string,
req: { fileName: string; size: number; contentType?: string }, req: { fileName: string; size: number; contentType?: string },
): Promise<PostKanbanAttachmentResponse> { ): 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 uploadUrl = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'PUT')
const proxyType = getProxyType(req.contentType, req.fileName) const proxyType = getProxyType(req.contentType, req.fileName)
@@ -895,6 +997,16 @@ export class KanbanService {
const task = await prisma.kanbanTask.findUnique({ where: { id: taskId } }) const task = await prisma.kanbanTask.findUnique({ where: { id: taskId } })
if (!task) throw new HTTPException(404, { message: 'Task not found' }) 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 comment = await prisma.$transaction(async (tx) => {
const c = await tx.kanbanTaskComment.create({ const c = await tx.kanbanTaskComment.create({
data: { data: {
@@ -917,7 +1029,10 @@ export class KanbanService {
return c return c
}) })
const resolvedAttachments = await this.resolveCommentAttachments(comment.attachments) const resolvedAttachments = await this.resolveCommentAttachments(
comment.attachments,
task.teamId,
)
return { return {
id: comment.id, id: comment.id,
@@ -935,6 +1050,12 @@ export class KanbanService {
} }
async listComments(taskId: string): Promise<KanbanCommentInfo[]> { 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({ const comments = await prisma.kanbanTaskComment.findMany({
where: { taskId }, where: { taskId },
include: { author: true }, include: { author: true },
@@ -951,7 +1072,7 @@ export class KanbanService {
image: await getAvatarUrl(c.author.image), image: await getAvatarUrl(c.author.image),
}, },
body: c.body, body: c.body,
attachments: await this.resolveCommentAttachments(c.attachments), attachments: await this.resolveCommentAttachments(c.attachments, task.teamId),
createdAt: c.createdAt.toISOString(), createdAt: c.createdAt.toISOString(),
updatedAt: c.updatedAt.toISOString(), updatedAt: c.updatedAt.toISOString(),
})), })),
@@ -981,7 +1102,8 @@ export class KanbanService {
} }
private async resolveCommentAttachments( private async resolveCommentAttachments(
attachments?: PrismaJson.KanbanCommentAttachmentList | null, attachments: PrismaJson.KanbanCommentAttachmentList | null | undefined,
teamId: string,
): Promise<KanbanAttachmentInfo[]> { ): Promise<KanbanAttachmentInfo[]> {
if (!attachments || !Array.isArray(attachments) || attachments.length === 0) { if (!attachments || !Array.isArray(attachments) || attachments.length === 0) {
return [] return []
@@ -989,7 +1111,9 @@ export class KanbanService {
const bucket = process.env.S3_BUCKET || 'shumai' const bucket = process.env.S3_BUCKET || 'shumai'
return await Promise.all( return await Promise.all(
attachments.map(async (att) => { attachments
.filter((att) => typeof att.key === 'string' && isReadableAttachmentKey(att.key, teamId))
.map(async (att) => {
const url = await s3Service.presign(bucket, att.key, 'GET') const url = await s3Service.presign(bucket, att.key, 'GET')
return { return {
id: att.id, id: att.id,
@@ -1003,15 +1127,34 @@ export class KanbanService {
) )
} }
async listEvents(taskId: string): Promise<KanbanEventInfo[]> { async listEvents(taskId: string, viewerId?: string): Promise<KanbanEventInfo[]> {
const events = await prisma.kanbanTaskEvent.findMany({ const task = await prisma.kanbanTask.findUnique({
where: { taskId }, where: { id: taskId },
include: { actor: true }, select: {
orderBy: { createdAt: 'desc' }, 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( return await Promise.all(
events.map(async (e) => ({ visibleEvents.map(async (e) => ({
id: e.id, id: e.id,
taskId: e.taskId, taskId: e.taskId,
actor: e.actor actor: e.actor
@@ -1024,7 +1167,7 @@ export class KanbanService {
type: e.type, type: e.type,
fromStatus: e.fromStatus, fromStatus: e.fromStatus,
toStatus: e.toStatus, toStatus: e.toStatus,
data: (e.data as Record<string, unknown>) ?? null, data: e.data ?? null,
createdAt: e.createdAt.toISOString(), createdAt: e.createdAt.toISOString(),
})), })),
) )
@@ -1115,9 +1258,17 @@ export class KanbanService {
return await this.resolveTaskAssetInfos(links) 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({ const links = await prisma.kanbanTaskAsset.findMany({
where: { assetId }, where: {
assetId,
task: { teamId, ...taskFilter },
},
include: { include: {
task: { task: {
include: { include: {
@@ -1125,24 +1276,15 @@ export class KanbanService {
reporter: true, reporter: true,
assignee: true, assignee: true,
goal: true, goal: true,
_count: { _count: { select: taskRelationCountSelect(taskFilter) },
select: {
comments: true,
dependencies: true,
dependents: true,
assets: true,
},
},
}, },
}, },
}, },
orderBy: { createdAt: 'desc' }, orderBy: { createdAt: 'desc' },
}) })
const matchingLinks = links.filter((l) => l.task && l.task.teamId === teamId)
return await Promise.all( return await Promise.all(
matchingLinks.map(async (l) => { links.map(async (l) => {
const t = l.task const t = l.task
const latestStatusEvent = await this.resolveLatestStatusEvent(t.id, t.status) const latestStatusEvent = await this.resolveLatestStatusEvent(t.id, t.status)
return await this.toTaskInfo(t, { 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 commentCount: number
dependencyCount: number dependencyCount: number
dependentCount: number dependentCount: number
assetCount: number assetCount: number
}> { }> {
const [commentCount, dependencyCount, dependentCount, assetCount] = await Promise.all([ const task = await prisma.kanbanTask.findUnique({
prisma.kanbanTaskComment.count({ where: { taskId } }), where: { id: taskId },
prisma.kanbanTaskLink.count({ where: { childId: taskId } }), select: { _count: { select: taskRelationCountSelect(taskFilter) } },
prisma.kanbanTaskLink.count({ where: { parentId: taskId } }), })
prisma.kanbanTaskAsset.count({ where: { taskId } }), return {
]) commentCount: task?._count.comments ?? 0,
return { commentCount, dependencyCount, dependentCount, assetCount } dependencyCount: task?._count.dependencies ?? 0,
dependentCount: task?._count.dependents ?? 0,
assetCount: task?._count.assets ?? 0,
}
} }
private async resolveTaskAssetInfos( private async resolveTaskAssetInfos(
@@ -240,7 +240,12 @@ describe('collaboration Operations', () => {
message: 'Too dark at the start', message: 'Too dark at the start',
second: 2.5, 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), { const reply = await runOperation(createCommentOp, as(owner, 'agent', undefined), {
assetId: file, assetId: file,
@@ -248,9 +253,17 @@ describe('collaboration Operations', () => {
replyToId: comment.id, replyToId: comment.id,
}) })
expect(reply.replyToId).toBe(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 }) const listed = await runOperation(listCommentsOp, as(reviewer), { assetId: file })
expect(listed.total).toBe(1) expect(listed.total).toBe(2)
expect(listed.data).toEqual([ expect(listed.data).toEqual([
expect.objectContaining({ expect.objectContaining({
id: comment.id, id: comment.id,
@@ -258,14 +271,21 @@ describe('collaboration Operations', () => {
author: { id: reviewer.id, name: 'Reviewer' }, author: { id: reviewer.id, name: 'Reviewer' },
second: 2.5, second: 2.5,
resolved: false, resolved: false,
isInternal: false,
replies: [ replies: [
expect.objectContaining({ expect.objectContaining({
id: reply.id, id: reply.id,
message: 'Brightened in v2', message: 'Brightened in v2',
author: { id: owner.id, name: 'Owner' }, author: { id: owner.id, name: 'Owner' },
isInternal: false,
}), }),
], ],
}), }),
expect.objectContaining({
id: internalComment.id,
message: 'Internal budget note',
isInternal: true,
}),
]) ])
await expect( await expect(
@@ -276,7 +296,7 @@ describe('collaboration Operations', () => {
).resolves.toEqual({ commentId: comment.id, resolved: false }) ).resolves.toEqual({ commentId: comment.id, resolved: false })
const created = await auditRows(AuditAction.comment_create) 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) expect(created.every((r) => r.teamId === teamId && r.projectId === projectId)).toBe(true)
const completed = await auditRows(AuditAction.comment_complete) const completed = await auditRows(AuditAction.comment_complete)
expect(completed).toHaveLength(2) expect(completed).toHaveLength(2)
@@ -20,10 +20,16 @@ export const createCommentOp = implementOperation(createComment, {
message: input.message, message: input.message,
replyToId: input.replyToId, replyToId: input.replyToId,
second: input.second, second: input.second,
isInternal: input.isInternal,
// Mentions in comments written by Shumai's own agent must not start more agent runs. // Mentions in comments written by Shumai's own agent must not start more agent runs.
triggerAgents: ctx.via !== 'agent', 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) => [ audit: (input, output) => [
{ action: AuditAction.comment_create, itemId: output.id, contextAssetId: input.assetId }, { action: AuditAction.comment_create, itemId: output.id, contextAssetId: input.assetId },
@@ -15,6 +15,7 @@ function toCommentFields(comment: CommentInfo) {
second: comment.second, second: comment.second,
hasMarkup: Array.isArray(comment.annotations) && comment.annotations.length > 0, hasMarkup: Array.isArray(comment.annotations) && comment.annotations.length > 0,
attachmentCount: comment.attachments.length, attachmentCount: comment.attachments.length,
isInternal: comment.isInternal,
createdAt: comment.createdAt, createdAt: comment.createdAt,
} }
} }
+1 -1
View File
@@ -19,7 +19,7 @@ export const ENV_MAP: Record<string, string> = {
openai: 'OPENAI_API_KEY', openai: 'OPENAI_API_KEY',
anthropic: 'ANTHROPIC_API_KEY', anthropic: 'ANTHROPIC_API_KEY',
'github-copilot': 'COPILOT_GITHUB_TOKEN', 'github-copilot': 'COPILOT_GITHUB_TOKEN',
'azure-openai-responses': 'AZURE_OPENAI_API_KEY', azure: 'AZURE_OPENAI_API_KEY',
deepseek: 'DEEPSEEK_API_KEY', deepseek: 'DEEPSEEK_API_KEY',
google: 'GEMINI_API_KEY', google: 'GEMINI_API_KEY',
'google-vertex': 'GOOGLE_CLOUD_API_KEY', 'google-vertex': 'GOOGLE_CLOUD_API_KEY',
@@ -1,54 +0,0 @@
{
"anthropic": {
"models": {
"claude-3-5-sonnet-20241022": {
"id": "claude-3-5-sonnet-20241022",
"name": "Claude 3.5 Sonnet",
"tool_call": true,
"reasoning": false,
"limit": {
"context": 200000,
"output": 8192
},
"cost": {
"input": 3,
"output": 15,
"cache_read": 0.3,
"cache_write": 3.75
}
}
}
},
"openai": {
"models": {
"gpt-4o": {
"id": "gpt-4o",
"name": "GPT-4o",
"tool_call": true,
"reasoning": false,
"limit": {
"context": 128000,
"output": 4096
},
"cost": {
"input": 2.5,
"output": 10
}
},
"gpt-4o-extra-new": {
"id": "gpt-4o-extra-new",
"name": "GPT-4o Extra New",
"tool_call": true,
"reasoning": false,
"limit": {
"context": 128000,
"output": 4096
},
"cost": {
"input": 2.5,
"output": 10
}
}
}
}
}
@@ -1,7 +0,0 @@
{
"data": [
{
"id": "meta/llama-3.1-70b-instruct"
}
]
}
@@ -1,17 +0,0 @@
{
"data": [
{
"id": "meta-llama/llama-3.1-8b-instruct",
"name": "Meta: Llama 3.1 8B Instruct",
"context_length": 131072,
"pricing": {
"prompt": "0.00000005",
"completion": "0.00000008"
},
"top_provider": {
"max_completion_tokens": 8192
},
"supported_parameters": ["tools"]
}
]
}
File diff suppressed because it is too large Load Diff
@@ -1,42 +0,0 @@
import type { ThinkingLevel, ThinkingLevelMap } from '@earendil-works/pi-ai'
export type ModelsDevReasoningOption =
| { type: 'toggle' }
| {
type: 'effort'
values: Array<
'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'default' | null
>
}
| { type: 'budget_tokens'; min?: number; max?: number }
const THINKING_LEVELS: readonly ThinkingLevel[] = [
'minimal',
'low',
'medium',
'high',
'xhigh',
'max',
]
/**
* Converts models.dev verified effort values into Pi's selectable thinking levels.
* Values without a Pi equivalent (`default` and JSON `null`) are intentionally
* omitted.
*/
export function getEffortThinkingLevelMap(
options: readonly ModelsDevReasoningOption[],
): ThinkingLevelMap | undefined {
const effortValues = options.flatMap((option) => (option.type === 'effort' ? option.values : []))
if (effortValues.length === 0) return undefined
const supported = new Set(effortValues)
if (!THINKING_LEVELS.some((level) => supported.has(level)) && !supported.has('none'))
return undefined
const map: ThinkingLevelMap = { off: supported.has('none') ? 'none' : null }
for (const level of THINKING_LEVELS) {
map[level] = supported.has(level) ? level : null
}
return map
}
+197
View File
@@ -0,0 +1,197 @@
import { PI_AI_VERSION } from '@earendil-works/pi-ai'
import { getBuiltinModels, getBuiltinProviders } from '@earendil-works/pi-ai/providers/all'
import { CompatSchemasByApi } from '@earendil-works/pi-ai/providers/compat-schema'
import { ThinkingLevelMapSchema } from '@earendil-works/pi-ai/providers/model-schema'
import {
providerModelConfigSchema,
type ProviderConfigSerializable,
type ProviderRefreshUnavailableReason,
type RefreshedProviderModel,
} from '@shumai/dtos'
import { HTTPException } from 'hono/http-exception'
import { z } from 'zod'
import { ENV_MAP } from './builtin'
type RefreshConnection =
| { unavailableReason: ProviderRefreshUnavailableReason }
| { unavailableReason: null; piProviderId: string }
type CatalogResult =
| { status: 'unavailable'; reason: 'catalog_unavailable' }
| { status: 'ready'; models: RefreshedProviderModel[] }
const REFRESH_TIMEOUT_MS = 10_000
const builtinConnections = new Map<string, Set<string>>(
getBuiltinProviders().map((id) => [
id,
new Set(getBuiltinModels(id).map(({ api, baseUrl }) => connectionKey(api, baseUrl))),
]),
)
const catalogSchema = z.record(
z.string(),
z.looseObject({
id: z.string().min(1),
provider: z.string(),
api: z.string(),
baseUrl: z.string(),
type: z.string().optional(),
}),
)
const compatSchemas = new Map(
Object.entries(CompatSchemasByApi).map(([api, schema]) => [api, z.fromJSONSchema(schema)]),
)
const thinkingLevelMapSchema = z.fromJSONSchema(ThinkingLevelMapSchema)
const catalogHeaderNames = new Set([
'user-agent',
'editor-version',
'editor-plugin-version',
'copilot-integration-id',
'nvcf-poll-seconds',
])
const catalogHeadersSchema = z.record(
z.string().refine((name) => catalogHeaderNames.has(name.toLowerCase())),
z.string().regex(/^[\t\x20-\x7E]*$/),
)
function normalizeBaseUrl(baseUrl?: string): string {
return baseUrl?.trim().replace(/\/+$/, '') ?? ''
}
function connectionKey(api: string, baseUrl?: string): string {
return JSON.stringify([api, normalizeBaseUrl(baseUrl)])
}
function piProviderName(name: string): string {
return name === 'azure-openai-responses' ? 'azure' : name
}
export function isProviderConfigured(name: string, config: ProviderConfigSerializable): boolean {
const key = config.apiKey?.trim()
if (key) {
const envValue = process.env[key]
if (envValue !== undefined) return Boolean(envValue.trim())
// Existing forms accept literal keys and names such as OPENAI_API_KEY in the same field.
return !/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/.test(key)
}
const envName = ENV_MAP[piProviderName(name)]
if (envName && process.env[envName]?.trim()) return true
if (name === 'amazon-bedrock' && config.api === 'bedrock-converse-stream') {
return Boolean(
process.env.AWS_BEARER_TOKEN_BEDROCK ||
process.env.AWS_PROFILE ||
(process.env.AWS_ACCESS_KEY_ID && process.env.AWS_SECRET_ACCESS_KEY) ||
process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI ||
process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI ||
process.env.AWS_WEB_IDENTITY_TOKEN_FILE,
)
}
const url = URL.parse(config.baseUrl ?? '')
return Boolean(
url &&
config.api === 'openai-completions' &&
(config.authHeader === false ||
/^(?:localhost|127\.\d+\.\d+\.\d+|\[::1\])$/.test(url.hostname)),
)
}
function azureDeploymentIds(): Set<string> {
// Pi uses model-id=deployment-name mappings for Azure's deployment-specific API.
const entries = process.env.AZURE_OPENAI_DEPLOYMENT_NAME_MAP?.split(',') ?? []
return new Set(
entries.flatMap((entry) => {
const [modelId, deployment] = entry.split('=', 2).map((value) => value.trim())
return modelId && deployment ? [modelId] : []
}),
)
}
export function getRefreshConnection(
name: string,
config: ProviderConfigSerializable,
): RefreshConnection {
const providerId = piProviderName(name)
if (providerId === 'azure' && config.api === 'azure-openai-responses') {
const endpoint =
config.baseUrl || process.env.AZURE_OPENAI_BASE_URL || process.env.AZURE_OPENAI_RESOURCE_NAME
return endpoint && azureDeploymentIds().size > 0
? { unavailableReason: null, piProviderId: providerId }
: { unavailableReason: 'azure_deployment_required' }
}
if (
providerId === 'kimi-coding' &&
config.api === 'anthropic-messages' &&
normalizeBaseUrl(config.baseUrl) === 'https://api.kimi.com/coding'
) {
return { unavailableReason: 'legacy_kimi_connection' }
}
const key = connectionKey(config.api, config.baseUrl)
const namedConnections = builtinConnections.get(providerId)
if (namedConnections?.has(key)) return { unavailableReason: null, piProviderId: providerId }
// A renamed provider can still be resolved if its protocol and endpoint identify one catalog.
if (!namedConnections && config.baseUrl) {
const matches = [...builtinConnections].filter(([, connections]) => connections.has(key))
if (matches.length === 1) return { unavailableReason: null, piProviderId: matches[0][0] }
}
return { unavailableReason: 'unsupported_connection' }
}
export async function discoverProviderModels(
piProviderId: string,
config: ProviderConfigSerializable,
): Promise<CatalogResult> {
const url = new URL(`/api/models/providers/${encodeURIComponent(piProviderId)}`, 'https://pi.dev')
url.searchParams.set('pi-version', PI_AI_VERSION)
let catalog: z.infer<typeof catalogSchema>
try {
const response = await fetch(url, {
headers: { Accept: 'application/json' },
redirect: 'error',
signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS),
})
if (response.status === 404 || response.status === 501) {
return { status: 'unavailable', reason: 'catalog_unavailable' }
}
if (!response.ok) throw new Error(`Pi catalog returned HTTP ${response.status}`)
catalog = catalogSchema.parse(await response.json())
} catch (cause) {
throw new HTTPException(502, { message: 'Could not refresh provider models', cause })
}
const key = connectionKey(config.api, config.baseUrl)
const azureDeployments = piProviderId === 'azure' ? azureDeploymentIds() : undefined
const models = Object.entries(catalog).flatMap(([id, model]) => {
if (
model.id !== id ||
model.provider !== piProviderId ||
(model.type && model.type !== 'chat')
) {
return []
}
const matches = azureDeployments
? model.api === config.api && model.baseUrl === '' && azureDeployments.has(id)
: connectionKey(model.api, model.baseUrl) === key
if (!matches) return []
if (
model.compat !== undefined &&
!compatSchemas.get(model.api)?.safeParse(model.compat).success
)
return []
if (
model.thinkingLevelMap !== undefined &&
!thinkingLevelMapSchema.safeParse(model.thinkingLevelMap).success
)
return []
if (model.headers !== undefined && !catalogHeadersSchema.safeParse(model.headers).success)
return []
// Keep omitted flags absent so Pi can apply model- and endpoint-specific defaults.
const modelConfig = providerModelConfigSchema.safeParse(model)
if (!modelConfig.success) return []
const name = typeof model.name === 'string' && model.name ? model.name : id
return [{ modelId: id, name, config: modelConfig.data }]
})
return { status: 'ready', models }
}
+285 -190
View File
@@ -3,46 +3,53 @@ import { setupTestDbHooks } from '@shumai/db/test'
import { teamService } from '@shumai/core/src/team/team' import { teamService } from '@shumai/core/src/team/team'
import { agentService } from '@shumai/core/src/agent/agent' import { agentService } from '@shumai/core/src/agent/agent'
import { providerService } from './provider' import { providerService } from './provider'
import { describe, expect, it, vi } from 'vitest' import { afterEach, describe, expect, it, vi } from 'vitest'
import * as generateModelsModule from './generator/generate-models'
import { ProviderConfigSerializable, providerModelSchema } from '@shumai/dtos' import { ProviderConfigSerializable, providerModelSchema } from '@shumai/dtos'
import { getBuiltinProvidersMap } from '@shumai/core/src/provider/builtin' import { getBuiltinProvidersMap } from '@shumai/core/src/provider/builtin'
import { z } from 'zod' import { z } from 'zod'
import modelsDevFixture from './fixtures/models-dev.json'
import openRouterFixture from './fixtures/openrouter.json'
import nvidiaFixture from './fixtures/nvidia.json'
const originalFetch = globalThis.fetch const openaiConfig = {
api: 'openai-responses',
baseUrl: 'https://api.openai.com/v1',
apiKey: 'saved-test-key',
} satisfies ProviderConfigSerializable
function setupCatalogFetchMock() { const candidateConfig = {
return vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL) => { api: openaiConfig.api,
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url reasoning: true,
if (url.includes('models.dev')) { input: ['text'],
return new Response(JSON.stringify(modelsDevFixture), { contextWindow: 256000,
status: 200, maxTokens: 16000,
headers: { 'Content-Type': 'application/json' }, cost: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0 },
}) } satisfies ProviderModel['config']
function catalogModel(id: string, options?: Record<string, unknown>) {
return {
...candidateConfig,
provider: 'openai',
baseUrl: openaiConfig.baseUrl,
id,
name: id,
...options,
} }
if (url.includes('openrouter.ai')) { }
return new Response(JSON.stringify(openRouterFixture), {
status: 200, function mockCatalog(models: ReturnType<typeof catalogModel>[]) {
headers: { 'Content-Type': 'application/json' }, const requests: Request[] = []
}) vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
const request = new Request(input, init)
requests.push(request)
if (new URL(request.url).origin !== 'https://pi.dev') {
throw new Error('Unexpected catalog host')
} }
if (url.includes('nvidia')) { return Response.json(Object.fromEntries(models.map((model) => [model.id, model])))
return new Response(JSON.stringify(nvidiaFixture), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
if (url.includes('ai-gateway')) {
return new Response(JSON.stringify({ data: [] }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
return originalFetch(input)
}) })
return requests
}
function readyPreview(result: Awaited<ReturnType<typeof providerService.refreshModels>>) {
if (result.status !== 'ready') throw new Error('Expected refreshed models')
return result
} }
type ProviderModel = z.infer<typeof providerModelSchema> type ProviderModel = z.infer<typeof providerModelSchema>
@@ -385,182 +392,270 @@ describe('ProviderService', () => {
expect((modelsAfterUpdate[1].config as { api: string }).api).toBe('anthropic-messages') expect((modelsAfterUpdate[1].config as { api: string }).api).toBe('anthropic-messages')
}) })
it('should check for updates and correctly segregate new vs existing providers', async () => { describe('model refresh', () => {
const fetchSpy = setupCatalogFetchMock() afterEach(() => {
try { vi.restoreAllMocks()
// 1. Check updates with empty team: all discovered providers are new vi.unstubAllEnvs()
const emptyTeam = await prisma.team.create({
data: { name: 'Empty Provider Team' },
})
const initialCheck = await providerService.checkUpdates(emptyTeam.id)
expect(initialCheck.totalNewProviders).toBeGreaterThan(0)
expect(initialCheck.totalNewModels).toBeGreaterThan(0)
expect(initialCheck.providers.every((p) => p.isNewProvider)).toBe(true)
// 2. With default team (which has builtin providers initialized)
const teamWithBuiltins = await teamService.ensureDefaultTeam()
// 3. Check updates after init: existing providers should have isNewProvider: false
const afterInitCheck = await providerService.checkUpdates(teamWithBuiltins.id)
const existing = afterInitCheck.providers.find((p) => !p.isNewProvider)
expect(existing).toBeDefined()
if (existing) {
expect(existing.isNewProvider).toBe(false)
const dbModels = await providerService.listModelsByProvider(
teamWithBuiltins.id,
(await providerService.listByTeam(teamWithBuiltins.id)).find(
(p) => p.name === existing.name,
)!.id,
)
const dbModelIds = new Set(dbModels.map((m) => m.modelId))
for (const m of existing.models) {
expect(dbModelIds.has(m.modelId)).toBe(false)
}
}
} finally {
fetchSpy.mockRestore()
}
}) })
it('should throw an error when upstream catalog fetch fails in checkUpdates', async () => { it('reports resolved credentials and eligibility separately and preserves legacy Kimi', async () => {
const team = await teamService.ensureDefaultTeam() vi.stubEnv('CUSTOM_OPENAI_KEY', 'a-resolved-test-key')
const spy = vi vi.stubEnv('UNSET_ANTHROPIC_KEY', undefined)
.spyOn(generateModelsModule, 'generateModels') const team = await prisma.team.create({ data: { name: 'Providers' } })
.mockRejectedValueOnce(new Error('Failed to load models.dev catalog: 502 Bad Gateway')) const configured = await providerService.create(team.id, 'OpenAI production', {
...openaiConfig,
await expect(providerService.checkUpdates(team.id)).rejects.toThrow( apiKey: 'CUSTOM_OPENAI_KEY',
'Failed to load models.dev catalog: 502 Bad Gateway',
)
spy.mockRestore()
}) })
const unconfigured = await providerService.create(team.id, 'anthropic', {
it('should throw an error when upstream catalog is empty in checkUpdates', async () => {
const team = await teamService.ensureDefaultTeam()
const spy = vi.spyOn(generateModelsModule, 'generateModels').mockResolvedValueOnce({
providers: {},
groupedProviders: {},
sortedProviderIds: [],
})
await expect(providerService.checkUpdates(team.id)).rejects.toThrow(
'Failed to retrieve model catalog from upstream services',
)
spy.mockRestore()
})
it('should apply sync by adding selected providers and models without modifying existing ones', async () => {
const team = await teamService.ensureDefaultTeam()
// Create an existing provider with 1 model and a custom apiKey
const existingProvider = await providerService.create(
team.id,
'test-existing-provider',
{ api: 'openai-responses', apiKey: 'custom-api-key', baseUrl: 'https://example.com' },
[
{
modelId: 'existing-m1',
name: 'Existing Model 1',
config: {
api: 'openai-responses',
reasoning: false,
input: ['text'],
contextWindow: 128000,
maxTokens: 4096,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
},
},
],
)
// Apply sync with 1 new provider and 1 new model on the existing provider
const syncResult = await providerService.applySync(team.id, {
providers: [
{
name: 'test-new-synced-provider',
isNewProvider: true,
config: {
api: 'anthropic-messages', api: 'anthropic-messages',
apiKey: 'ENV_SYNC_KEY',
baseUrl: 'https://api.anthropic.com', baseUrl: 'https://api.anthropic.com',
}, apiKey: 'UNSET_ANTHROPIC_KEY',
models: [ })
{ const legacyConfig = {
modelId: 'new-p-m1',
name: 'New Provider Model 1',
config: {
api: 'anthropic-messages', api: 'anthropic-messages',
reasoning: false, baseUrl: 'https://api.kimi.com/coding',
input: ['text'], apiKey: 'literal-kimi-key',
contextWindow: 200000, } satisfies ProviderConfigSerializable
maxTokens: 8192, const legacy = await providerService.create(team.id, 'kimi-coding', legacyConfig)
cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 }, const local = await providerService.create(team.id, 'Local Ollama', {
}, api: 'openai-completions',
}, baseUrl: 'http://localhost:11434/v1',
], })
}, vi.stubEnv('AWS_PROFILE', 'test-profile')
{ const bedrock = await providerService.create(team.id, 'amazon-bedrock', {
name: 'test-existing-provider', api: 'bedrock-converse-stream',
isNewProvider: false, })
config: { api: 'openai-responses', apiKey: 'should-not-override' }, const providers = await providerService.listByTeam(team.id)
expect(providers).toHaveLength(5)
expect(providers).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: configured.id,
configured: true,
refreshUnavailableReason: null,
config: { ...openaiConfig, apiKey: 'CUSTOM_OPENAI_KEY' },
}),
expect.objectContaining({
id: unconfigured.id,
configured: false,
refreshUnavailableReason: null,
}),
expect.objectContaining({
id: legacy.id,
configured: true,
refreshUnavailableReason: 'legacy_kimi_connection',
}),
expect.objectContaining({
id: local.id,
configured: true,
refreshUnavailableReason: 'unsupported_connection',
}),
expect.objectContaining({ id: bedrock.id, configured: true }),
]),
)
const requests = mockCatalog([])
await expect(providerService.refreshModels(team.id, unconfigured.id)).resolves.toMatchObject({
status: 'ready',
models: [],
})
await expect(providerService.refreshModels(team.id, legacy.id)).resolves.toEqual({
status: 'unavailable',
reason: 'legacy_kimi_connection',
})
expect(requests.map(({ url }) => new URL(url).pathname)).toEqual([
'/api/models/providers/anthropic',
])
expect(await providerService.getById(legacy.id)).toMatchObject({ config: legacyConfig })
})
it('refreshes only the requested provider and filters existing and incompatible models', async () => {
vi.stubEnv('OPENAI_API_KEY', openaiConfig.apiKey)
const team = await teamService.ensureDefaultTeam()
const providers = await providerService.listByTeam(team.id)
const openai = providers.find(({ name }) => name === 'openai')!
const existingModels = await providerService.listModelsByProvider(team.id, openai.id)
const requests = mockCatalog([
catalogModel(existingModels[0].modelId),
catalogModel('new-model', {
compat: { supportsStrictMode: true },
thinkingLevelMap: { low: 'low' },
}),
catalogModel('wrong-api', { api: 'openai-completions' }),
catalogModel('wrong-url', { baseUrl: 'https://other.example/v1' }),
catalogModel('wrong-provider', { provider: 'anthropic' }),
catalogModel('not-chat', { type: 'image' }),
catalogModel('invalid-compat', { compat: { supportsStrictMode: 'yes' } }),
])
const result = await providerService.refreshModels(team.id, openai.id)
expect(result).toMatchObject({
status: 'ready',
models: [ models: [
{ {
modelId: 'existing-m2', modelId: 'new-model',
name: 'Newly Added Model 2', name: 'new-model',
config: { config: {
api: 'openai-responses', ...candidateConfig,
reasoning: true, compat: { supportsStrictMode: true },
input: ['text'], thinkingLevelMap: { low: 'low' },
contextWindow: 128000,
maxTokens: 4096,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
}, },
}, },
// Duplicate model that already exists: should be ignored
{
modelId: 'existing-m1',
name: 'Existing Model 1 Overwrite Attempt',
config: {
api: 'openai-responses',
reasoning: false,
input: ['text'],
contextWindow: 999999,
maxTokens: 999999,
cost: { input: 9, output: 9, cacheRead: 9, cacheWrite: 9 },
},
},
],
},
], ],
}) })
expect(requests.map(({ url }) => new URL(url).pathname)).toEqual([
'/api/models/providers/openai',
])
expect(requests[0].headers.has('Authorization')).toBe(false)
expect(JSON.stringify(result)).not.toContain(openaiConfig.apiKey)
expect(await providerService.listModelsByProvider(team.id, openai.id)).toEqual(existingModels)
expect(await providerService.listByTeam(team.id)).toEqual(providers)
})
expect(syncResult.addedProviders).toBe(1) it('uses the versioned public OpenRouter catalog without sending saved credentials', async () => {
expect(syncResult.addedModels).toBe(2) const openRouterKey = 'saved-openrouter-test-key'
vi.stubEnv('SHUMAI_TEST_OPENROUTER_KEY', openRouterKey)
const team = await prisma.team.create({ data: { name: 'OpenRouter' } })
const baseUrl = 'https://openrouter.ai/api/v1'
const api = 'openai-completions' as const
const provider = await providerService.create(team.id, 'openrouter', {
api,
baseUrl: baseUrl + '/',
apiKey: 'SHUMAI_TEST_OPENROUTER_KEY',
})
const modelId = 'org/new-openrouter-model'
const requests: Request[] = []
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
const request = new Request(input, init)
requests.push(request)
return Response.json({
[modelId]: { ...catalogModel(modelId, { api, baseUrl }), provider: 'openrouter' },
})
})
// Verify existing provider config was NOT modified const { models } = readyPreview(await providerService.refreshModels(team.id, provider.id))
const reloadedExisting = await providerService.getById(existingProvider.id) expect(models.map(({ modelId }) => modelId)).toEqual([modelId])
expect((reloadedExisting?.config as { apiKey: string }).apiKey).toBe('custom-api-key') expect(requests.map(({ url }) => url)).toEqual([
'https://pi.dev/api/models/providers/openrouter?pi-version=1.7.0',
])
expect(requests[0].headers.has('Authorization')).toBe(false)
// Verify existing model was NOT modified const customProvider = await providerService.update(team.id, provider.id, {
const existingModels = await providerService.listModelsByProvider(team.id, existingProvider.id) ...provider.config,
expect(existingModels).toHaveLength(2) baseUrl: 'https://openrouter-proxy.example/api/v1',
const m1 = existingModels.find((m) => m.modelId === 'existing-m1') })
expect(m1?.name).toBe('Existing Model 1') await expect(providerService.refreshModels(team.id, customProvider.id)).resolves.toEqual({
expect((m1?.config as { contextWindow: number }).contextWindow).toBe(128000) status: 'unavailable',
reason: 'unsupported_connection',
})
expect(requests).toHaveLength(1)
})
// Verify newly added model on existing provider it('distinguishes a successful empty preview from an upstream error', async () => {
const m2 = existingModels.find((m) => m.modelId === 'existing-m2') vi.stubEnv('OPENAI_API_KEY', openaiConfig.apiKey)
expect(m2).toBeDefined() const team = await teamService.ensureDefaultTeam()
expect(m2?.name).toBe('Newly Added Model 2') const provider = (await providerService.listByTeam(team.id)).find(
({ name }) => name === 'openai',
)!
mockCatalog([])
await expect(providerService.refreshModels(team.id, provider.id)).resolves.toMatchObject({
status: 'ready',
models: [],
})
vi.restoreAllMocks()
const fetchMock = vi.spyOn(globalThis, 'fetch')
fetchMock.mockResolvedValueOnce(new Response(null, { status: 404 }))
await expect(providerService.refreshModels(team.id, provider.id)).resolves.toEqual({
status: 'unavailable',
reason: 'catalog_unavailable',
})
fetchMock.mockResolvedValueOnce(Response.json({ error: 'malformed catalog' }))
await expect(providerService.refreshModels(team.id, provider.id)).rejects.toMatchObject({
status: 502,
})
fetchMock.mockRejectedValueOnce(new DOMException('Timed out', 'TimeoutError'))
// Verify newly added provider await expect(providerService.refreshModels(team.id, provider.id)).rejects.toMatchObject({
const providers = await providerService.listByTeam(team.id) status: 502,
const newProvider = providers.find((p) => p.name === 'test-new-synced-provider') })
expect(newProvider).toBeDefined() })
expect(newProvider?.isBuiltin).toBe(true)
expect((newProvider?.config as { apiKey: string }).apiKey).toBe('ENV_SYNC_KEY')
const newProviderModels = await providerService.listModelsByProvider(team.id, newProvider!.id) it('imports only the selected models once and preserves existing models and settings', async () => {
expect(newProviderModels).toHaveLength(1) vi.stubEnv('OPENAI_API_KEY', openaiConfig.apiKey)
expect(newProviderModels[0].modelId).toBe('new-p-m1') const team = await teamService.ensureDefaultTeam()
const provider = (await providerService.listByTeam(team.id)).find(
({ name }) => name === 'openai',
)!
const original = await providerService.getById(provider.id)
const existing = await providerService.listModelsByProvider(team.id, provider.id)
mockCatalog([catalogModel('new-model'), catalogModel('unselected-model')])
const preview = readyPreview(await providerService.refreshModels(team.id, provider.id))
const selection = { providerUpdatedAt: preview.providerUpdatedAt, modelIds: ['new-model'] }
await expect(providerService.importModels(team.id, provider.id, selection)).resolves.toEqual({
addedModels: 1,
})
await expect(providerService.importModels(team.id, provider.id, selection)).resolves.toEqual({
addedModels: 0,
})
expect(await providerService.listModelsByProvider(team.id, provider.id)).toEqual([
expect.objectContaining({ modelId: 'new-model', config: candidateConfig }),
...existing,
])
expect(await providerService.getById(provider.id)).toEqual(original)
})
it('rejects out-of-team, unknown, and stale selections without adding models', async () => {
const team = await prisma.team.create({ data: { name: 'Refresh Team' } })
const otherTeam = await prisma.team.create({ data: { name: 'Other Team' } })
const provider = await providerService.create(team.id, 'openai', openaiConfig)
const requests = mockCatalog([catalogModel('new-model')])
await expect(providerService.refreshModels(otherTeam.id, provider.id)).rejects.toMatchObject({
status: 404,
})
expect(requests).toHaveLength(0)
const preview = readyPreview(await providerService.refreshModels(team.id, provider.id))
const selection = { providerUpdatedAt: preview.providerUpdatedAt, modelIds: ['new-model'] }
await expect(
providerService.importModels(otherTeam.id, provider.id, selection),
).rejects.toMatchObject({ status: 404 })
await expect(
providerService.importModels(team.id, provider.id, {
...selection,
modelIds: ['new-model', 'unknown'],
}),
).rejects.toMatchObject({ status: 409 })
await providerService.update(team.id, provider.id, { ...openaiConfig, apiKey: 'changed-key' })
await expect(
providerService.importModels(team.id, provider.id, selection),
).rejects.toMatchObject({ status: 409 })
expect(await providerService.listModelsByProvider(team.id, provider.id)).toEqual([])
})
it('refreshes legacy Azure connections using only configured deployment mappings', async () => {
vi.stubEnv('AZURE_OPENAI_DEPLOYMENT_NAME_MAP', undefined)
const team = await prisma.team.create({ data: { name: 'Azure models' } })
const provider = await providerService.create(team.id, 'azure-openai-responses', {
api: 'azure-openai-responses',
baseUrl: 'https://example.openai.azure.com/openai/v1',
})
const azure = { provider: 'azure', api: 'azure-openai-responses', baseUrl: '' }
const requests = mockCatalog([
catalogModel('gpt-deployed', azure),
catalogModel('gpt-unmapped', azure),
])
await expect(providerService.refreshModels(team.id, provider.id)).resolves.toEqual({
status: 'unavailable',
reason: 'azure_deployment_required',
})
vi.stubEnv('AZURE_OPENAI_DEPLOYMENT_NAME_MAP', 'gpt-deployed=team-deployment')
const preview = readyPreview(await providerService.refreshModels(team.id, provider.id))
expect(preview.models.map(({ modelId }) => modelId)).toEqual(['gpt-deployed'])
expect(requests.map(({ url }) => new URL(url).pathname)).toEqual([
'/api/models/providers/azure',
])
})
}) })
}) })

Some files were not shown because too many files have changed in this diff Show More