Compare commits

...
481 Commits
Author SHA1 Message Date
yiling 3383079787 Release v0.1.10 2026-07-16 16:48:25 +08:00
Yiling-J f888a575b2 Merge pull request #192 from shumaiOne/feat/disable-agent-tools
feat(agent): support disabling specific tools for agents
2026-07-16 16:38:32 +08:00
yiling 0a7d5d1f46 feat(agent): support disabling specific tools for agents 2026-07-16 15:56:56 +08:00
Yiling-J 879922a9fe Merge pull request #191 from shumaiOne/feat/comment-delete-video-shortcuts
feat(comments): support comment deletion and video player shortcuts
2026-07-16 11:16:18 +08:00
yiling 58967d1a63 minor ui improvement 2026-07-16 11:06:26 +08:00
yiling e978878a90 refactor(comments): unconditionally delete S3 attachment objects directly 2026-07-16 10:59:14 +08:00
yiling ecfbfc2bac fix(shortcuts): resolve keyboard accessibility and contenteditable issues 2026-07-16 10:23:47 +08:00
yiling 490c6a3da6 refactor(comments): simplify teamId lookup and clean up comment attachments in S3 and database 2026-07-16 10:17:32 +08:00
yiling 62b1fc1d37 feat(comments): support comment deletion and video player shortcuts 2026-07-16 09:55:05 +08:00
Yiling-J fa6bf73452 Merge pull request #189 from shumaiOne/feat/workflow-e2e-tests
test(e2e): add E2E workflow tests for remaining agent and transcode services
2026-07-15 15:36:41 +08:00
yiling 25c747aa87 test(e2e): add E2E workflow tests for remaining agent and transcode services 2026-07-15 15:19:25 +08:00
Yiling-J ff7712744d Merge pull request #188 from shumaiOne/feat/workflow-e2e-tests
feat(workflow-e2e): add E2E tests for agentAutofillMedia workflow
2026-07-15 14:45:04 +08:00
yiling 6f369625d8 docs(agents): update AGENTS.md with E2E workflow testing requirements 2026-07-15 12:04:45 +08:00
yiling c6acd075e7 refactor(workflow-core): statically import Worker type from @temporalio/worker to ensure activeWorkers type-safety 2026-07-15 11:58:17 +08:00
yiling 7d9f3276f1 test(e2e): verify multiple types in autofill and check that non-autofill field is ignored 2026-07-15 11:54:29 +08:00
yiling d524a81ecd chore(vitest): exclude packages/e2e/** from root unit test suite 2026-07-15 11:40:57 +08:00
yiling 83c427e646 refactor(e2e): mock LLM prompt via AgentHarness prototype spy instead of global activity override 2026-07-15 10:52:01 +08:00
yiling b018fd0fec feat(workflow-e2e): add E2E tests for agentAutofillMedia workflow
- Setup E2E package under packages/e2e
- Use testcontainers to spin up postgres and temporal dev server
- Overwrite activities in global registry to mock AI model output
- Track temporal workers and expose shutdownWorkers() method for clean shutdown
- Integrate test:e2e:workflow into root package.json and GitHub actions CI
2026-07-15 10:14:59 +08:00
yiling 8efc9c1865 Release v0.1.9 2026-07-14 20:21:21 +08:00
Yiling-J 0eeb2f18f3 Merge pull request #187 from shumaiOne/fix/chat-api-db-queries
refactor(api/chat): remove direct Prisma query from API layer
2026-07-14 16:47:44 +08:00
yiling 6643d63e81 refactor(api/chat): remove direct Prisma query from API layer
API layer routes in packages/api/src/chat.ts accessed the database directly via prisma, violating communication layer boundaries.

This refactoring migrates these queries to packages/core/src/chat/chat.ts:
- Added getNewSessionMessages to fetch mapped SSE entries.
- Added getChatWorkflowStatus to check task completions.
- Added abortSession to handle workflow cancellation and task updates in core.
- Updated both core and API tests to match refactored signatures and mock boundaries.
2026-07-14 16:40:55 +08:00
Yiling-J b53b76bc6e Merge pull request #186 from shumaiOne/feat/agent-abort
feat(agent): support aborting agent execution
2026-07-14 16:35:19 +08:00
yiling 636e92af4c fix(agent): unregister temporal cancellation listener on completion 2026-07-14 16:08:43 +08:00
yiling a7dc7bbff2 perf(agent): optimize active task lookup using indexed sessionId column 2026-07-14 15:44:10 +08:00
yiling cd48d2d389 fix(agent): resolve lint, typecheck, and stop button UI issues 2026-07-14 10:35:25 +08:00
yiling 8a942d4f4e feat(agent): support aborting agent execution in local and temporal modes 2026-07-14 10:25:06 +08:00
Yiling-J e772581542 Merge pull request #185 from shumaiOne/feat/chatbot-ui-layout
feat(chat): chatbot UI
2026-07-13 16:55:25 +08:00
yiling 7baf95e48c fix(webui): preserve chatbot sidebar scroll position across navigations 2026-07-13 16:49:04 +08:00
yiling 15cbf12162 fix(webui): render theme-aware markdown code blocks in dark/light mode 2026-07-13 14:52:38 +08:00
yiling d560032013 feat(chat): send SSE keep-alive ping heartbeats during polling 2026-07-13 12:17:00 +08:00
yiling 02f2fde8ac fix(chat): remove explicit any in test mock to fix CI lint 2026-07-13 11:52:44 +08:00
yiling e080167ac5 feat(chat): enforce team-scoped authorization and session creator check
- Update chat API routes and service methods to include and verify teamId context
- Validate that the requesting user is the creator of the chat session during continuation
- Update frontend chatbot store and components to pass teamId parameter
- Update backend API/core and frontend store tests to verify team scoping and creator checks
2026-07-13 11:35:55 +08:00
yiling 61c49b4d7f feat(chat): allow user to choose chatbot in sidebar
- Remove chatbotAgentId from team settings and schema definition
- Make agentId a required parameter in ChatRequest DTO and chatService
- Fetch chatbot agents on chatbot sidebar mount and default to first enabled chat agent
- Render an agent selector dropdown inside the message input area
- Update existing chat sessions to follow the selected agent when continuing a conversation
2026-07-13 10:10:56 +08:00
yiling bad93466ae feat(webui): use filled bot icon when chatbot sidebar is open 2026-07-13 09:37:37 +08:00
yiling 1f8b0bac21 update ui 2026-07-13 09:34:51 +08:00
yiling c55380c0fd feat(webui): make toolCall block collapsible and render footer conditionally 2026-07-12 15:40:21 +08:00
yiling 3de57fd176 feat(webui): refactor chatbot message rendering to type-safe nested switch 2026-07-12 15:18:31 +08:00
yiling 0a4622ed8a syle minor fix 2026-07-12 10:29:29 +08:00
yiling bcb17acaf7 chore(serve): set idleTimeout to 120 seconds in Bun.serve 2026-07-11 21:11:18 +08:00
yiling b57a3e0239 chore(chat): support isNewChat payload flag and fix any casts 2026-07-11 21:05:47 +08:00
yiling c5ce4d07e9 feat(chat): add chatbot session name generation 2026-07-11 20:54:09 +08:00
yiling b5d52a4e56 feat(chat): add AgentSessionType enum and filter chatbot history sessions 2026-07-11 20:14:40 +08:00
yiling 94a3ec0b9b feat(chat): support optimistic context display entry locally during message sending 2026-07-11 17:02:58 +08:00
yiling bd897b951a chore: format codebase 2026-07-11 16:58:37 +08:00
yiling 482df3315c feat(chat): append and display context_display_info custom entry for attached assets 2026-07-11 16:58:09 +08:00
yiling cc9b32716d feat(chat): filter out context messages from API list and SSE stream 2026-07-11 15:47:48 +08:00
yiling 35db3fc49e fix(chatbot): preserve historical message order during SSE playback 2026-07-11 15:12:59 +08:00
yiling 6a5f8db0d6 fix(chatbot): preserve optimistic message during history playback of active sessions 2026-07-11 15:08:07 +08:00
yiling b13c47f207 feat(chatbot): highlight entire sidebar area with semi-transparent cover on dragover 2026-07-11 14:56:21 +08:00
yiling 2f68043e17 fix(chatbot): clear attached assets on message send and remove drag-drop toast 2026-07-11 14:41:23 +08:00
yiling 3d266a5606 feat(chatbot): remove agentId from request and resolve it via team settings, toggle chatbot icon with tooltip guard 2026-07-11 11:49:38 +08:00
yiling 87d811dad6 style(chatbot): move send button inside input border area to match comment input design 2026-07-11 10:59:56 +08:00
yiling 4a7da10ca8 fix(chatbot): prevent Enter from sending message during IME composition 2026-07-11 10:55:01 +08:00
yiling d19200e9ef feat(chatbot): implement chatbot sidebar, message view, history mode and sse stream 2026-07-11 10:49:40 +08:00
yiling 77718a3e1a refactor(webui): render chatbot button as standalone Bot icon outside the toggle group 2026-07-11 10:19:41 +08:00
yiling 8d2d915f36 feat(webui): add chatbot layout and drag-drop context store 2026-07-11 10:16:46 +08:00
Yiling-J 6ede64495f Merge pull request #184 from shumaiOne/feat/app-e2e-tests
feat(e2e): set up fullstack app-level e2e test framework and signup test case
2026-07-10 23:06:16 +08:00
yiling 13f220ef0f refactor(e2e): replace S3 bucket name check with explicit SHUMAI_E2E env flag 2026-07-10 20:11:54 +08:00
yiling 4e9fae96b1 fix(ci): split E2E jobs and support skipping app server via E2E_SKIP_APP_SERVER 2026-07-10 19:41:31 +08:00
yiling 8d23d8b1c3 fix(ci): split E2E tests into harness and app jobs 2026-07-10 19:28:14 +08:00
yiling 1e1ddd1a3d fix(e2e): declare types dependencies and adjust CI projects execution using --no-deps 2026-07-10 19:10:30 +08:00
yiling 55457fcd36 fix(webui): snap playhead to last frame upon ended event in useFramePlayer 2026-07-10 16:35:41 +08:00
yiling 9414ebaefd feat(e2e): run harness tests in parallel and app E2E tests sequentially using project dependencies 2026-07-10 16:27:51 +08:00
yiling 515c491d5d fix(e2e): restore Playwright empty object destructuring for fixture parameters 2026-07-10 16:21:09 +08:00
yiling 0aba2ee557 refactor(e2e): migrate database reset logic to standard Playwright custom fixture 2026-07-10 16:18:45 +08:00
yiling cd96015b9d feat(e2e): add browser selection support for app-level E2E tests 2026-07-10 15:35:59 +08:00
yiling 26982ee494 feat(e2e): set up fullstack app-level e2e test framework and signup test case 2026-07-10 15:21:01 +08:00
Yiling-J af5c85a87b Add installation command for ffmpeg using Chocolatey 2026-07-10 09:57:21 +08:00
yiling 5636a1b581 Release v0.1.8 2026-07-10 09:39:40 +08:00
Yiling-J 27af3a315e Merge pull request #183 from shumaiOne/fix/splitting-build-error
fix(webui): enable build splitting and code-split all page routes
2026-07-09 20:14:23 +08:00
yiling d3bbd42208 fix(web): optimize serveMainHtml performance by processing HTML at startup 2026-07-09 15:50:09 +08:00
yiling c3d88bb972 docs: add concise route code-splitting guideline to AGENTS.md 2026-07-09 15:32:15 +08:00
yiling a80e9de6cc feat(webui): code-split remaining team and share sub-routes to optimize vendor chunk size 2026-07-09 15:16:33 +08:00
yiling 6b5c2d8b23 feat(webui): enable route-level manual code-splitting to optimize bundle size 2026-07-09 15:09:39 +08:00
yiling 8d19b578e7 fix(build): resolve code-splitting chunk import issue on backend and frontend 2026-07-09 15:00:23 +08:00
Yiling-J e20e147445 Merge pull request #182 from shumaiOne/update-readme-notes
docs(readme): clarify displayed file size represents original file size
2026-07-09 10:40:58 +08:00
yiling 2116f2b1ab docs(readme): clarify displayed file size represents original file size 2026-07-09 10:40:24 +08:00
Yiling-J 7889b08008 Merge pull request #180 from shumaiOne/feat/chatbot-backend-apis
feat(chatbot): implement type-safe Chat APIs with compaction support
2026-07-08 10:07:00 +08:00
yiling 10279d74bc feat(chatbot): append turn-specific agentsInstruction as a custom message session entry 2026-07-07 21:51:10 +08:00
yiling 985bf0170c fix(api): prevent SSE connection resource leak by checking stream.aborted 2026-07-07 20:59:25 +08:00
yiling f04729b4bf refactor(chatbot): use SessionTreeEntry type directly in ChatService, removing SimpleMessageEntry 2026-07-07 14:16:31 +08:00
yiling 55026af22e refactor(chatbot): import AgentMessage type statically in DTO layer 2026-07-07 12:30:41 +08:00
yiling b8eddcd854 feat(chatbot): return rich AgentMessage structure directly from listMessages API 2026-07-07 12:25:32 +08:00
yiling d326a4cab8 refactor(chatbot): make mapEntryToMessage fully type-safe without any casts 2026-07-07 12:04:08 +08:00
yiling 243a4ab2c5 feat(chatbot): remove manual AgentSessionEntry creation from ChatService 2026-07-07 11:50:31 +08:00
yiling e4c1830e02 feat(chatbot): delegate context prompt building to AgentChatPromptBuilder in workflow 2026-07-07 11:42:40 +08:00
yiling 7b6db5b56c feat(chatbot): require agentId in ChatRequest and validate agent presence 2026-07-07 11:27:29 +08:00
yiling 63590d5329 feat(chatbot): decouple chatbot sessions from AssetComment table 2026-07-07 11:12:15 +08:00
yiling ccf742e158 refactor(chatbot): make user parameter in startOrContinueChat type-safe 2026-07-07 11:04:51 +08:00
yiling e55ee3a3f0 feat(chatbot): add chatbot backend api support 2026-07-07 10:55:22 +08:00
yiling 5e73fcf4aa update readme 2026-07-07 09:32:23 +08:00
yiling ca5f54b385 update readme 2026-07-07 09:27:50 +08:00
yiling 6e460430dd Release v0.1.7 2026-07-06 13:01:47 +08:00
yiling ffc578cb45 fix(comments): prevent reload of main viewer by invalidating only comments queries 2026-07-06 12:51:25 +08:00
Yiling-J 1414632c4a Merge pull request #179 from shumaiOne/feat/comment-completion
feat(comments): allow marking comments as complete or incomplete
2026-07-06 12:50:04 +08:00
yiling a312ecf7ef style(comments): use custom filled circle check icon and make actions row always visible 2026-07-06 12:40:20 +08:00
yiling e1d3dd46db feat(comments): allow marking comments as complete or incomplete 2026-07-06 12:24:40 +08:00
yiling af7d636f31 update cn translate 2026-07-06 11:49:51 +08:00
yiling b98b710222 update doc 2026-07-06 11:22:32 +08:00
Yiling-J 79b19d3983 Revise feature descriptions in README_CN.md
Updated feature descriptions and improved clarity in the README_CN.md file.
2026-07-06 11:15:29 +08:00
yiling 474fe7ced1 fix(webui): center unread badge count 2026-07-06 11:06:09 +08:00
Yiling-J bf82eff068 Merge pull request #178 from shumaiOne/feat/i18n-fixes
feat(i18n): localize members dialog, notifications, uploads, user menus, dates, and players
2026-07-06 10:59:24 +08:00
yiling 01a9c7cde6 refactor(i18n): address code review feedback on string legos, hardcoded locales, and fragile checks 2026-07-06 10:52:55 +08:00
yiling 45f3255796 feat(i18n): localize members dialog, notifications, uploads, user menus, dates, and players 2026-07-06 10:38:41 +08:00
Yiling-J 64ad183bc1 Merge pull request #177 from shumaiOne/docs-s3-storage
docs: improve documentation and examples for S3 compatible storage
2026-07-06 10:20:31 +08:00
yiling af8bc30409 docs: improve documentation and examples for S3 compatible storage 2026-07-06 10:13:12 +08:00
Yiling-J aac8bea4e8 Merge pull request #176 from shumaiOne/fix/upload-mime-type
fix(upload): resolve empty and generic MIME types in confirmFileUpload
2026-07-05 22:10:22 +08:00
yiling a05c0ac0db fix(upload): resolve empty and generic MIME types in confirmFileUpload
Use Bun's built-in file resolver to fall back to extension-based MIME type detection when the mediaType is missing, empty, or generic ('application/octet-stream').
2026-07-05 21:55:26 +08:00
Yiling-J 714158b5b2 Merge pull request #175 from shumaiOne/feat/audio-support
feat(audio): support frame-accurate audio playback, comments, and AI safeguards
2026-07-05 19:33:37 +08:00
yiling 8ad25215dd refactor(agent): prevent creating autofill and embedding tasks for audio assets 2026-07-05 16:31:14 +08:00
yiling 73aa374b2b feat(agent): prevent exposing screenshot and analyze_image tools and executing autofill/embeddings for audio files 2026-07-05 16:26:48 +08:00
yiling cee4142936 style(webui): use dark background for audio preview to keep duration clear 2026-07-05 16:16:04 +08:00
yiling 0f6912c977 feat(webui): render duration overlay for audio files in file browser 2026-07-05 16:13:00 +08:00
yiling 868e7b2a7b fix(webui): remount file viewer when file ID changes to reset state 2026-07-05 16:10:01 +08:00
yiling ccfcdce23c fix(upload): correct .wma MIME type to audio prefix on upload and add tests 2026-07-05 15:57:29 +08:00
yiling 8d336836cc test(webui): add audio comment seek roundtrip E2E test case 2026-07-05 15:37:30 +08:00
yiling f24c8afa3d test(webui): add e2e test to verify playhead advances immediately for audio assets 2026-07-05 15:28:18 +08:00
yiling e511af219e fix(webui): immediately use currentTime fallback in useFramePlayer for audio files 2026-07-05 15:23:52 +08:00
yiling 5cae1adce1 fix(webui): hide zoom/fit controls and comment draw button for audio assets 2026-07-05 15:19:53 +08:00
yiling a2e982f2e6 feat(transcode): add audio file support with AAC stereo mp4 proxy and styled viewer 2026-07-05 15:11:19 +08:00
Yiling-J 9a7abaed1a Merge pull request #174 from shumaiOne/refactor/file-viewer-registry
refactor(webui): modularize file viewer components into registry-driven architecture
2026-07-05 12:40:41 +08:00
yiling e03c44a00e docs(webui): add file viewer registry developer documentation 2026-07-05 12:26:50 +08:00
yiling 1524d41392 fix(webui): resolve react hook order violation in video viewer 2026-07-05 12:04:35 +08:00
yiling 4cc35d3453 refactor(webui): modularize file viewer components into registry-driven architecture 2026-07-05 10:51:42 +08:00
yiling 229070fe19 Release v0.1.6 2026-07-04 21:39:52 +08:00
Yiling-J 3bfbd2c217 Merge pull request #173 from shumaiOne/fix-version-stack-comments
fix(version-stack): resolve correct latest version ID of version stack
2026-07-04 21:07:00 +08:00
yiling 481c1ff8ba fix(version-stack): resolve correct latest version ID of version stack 2026-07-04 20:56:31 +08:00
Yiling-J 5f6847a373 Merge pull request #172 from shumaiOne/fix/video-player-frame-count-mismatch
fix(webui): resolve video player total frames mismatch
2026-07-04 20:47:09 +08:00
yiling 175b5ac171 fix(webui): resolve video player total frames mismatch
Avoid deriving total frames from container duration when the audio tail mismatch is below the dynamic playback stall threshold. This prevents the rendering of phantom trailing frames that the playhead cannot reach during playback.

Also adds comprehensive unit and E2E tests covering both small and large audio tail gaps.
2026-07-04 16:44:09 +08:00
Yiling-J f32f2d43aa Merge pull request #171 from shumaiOne/feat/compare-versions
feat(webui): compare versions view for version stacks
2026-07-04 15:38:37 +08:00
yiling ba88cdad78 fix(webui): sync compare video pane resolution/source on asset change
currentResolution state and currentSrcRef were only initialized on mount,
so if file.id changed without a remount the video.js init effect (keyed on
file.id) would re-create the player with a stale source. Add an effect
that resets them when file.id changes, before the init effect runs, making
the pane robust even without a per-asset key on the parent.
2026-07-04 15:29:07 +08:00
yiling 0bbb846beb fix(webui): support version switching on public share (no login redirect)
Switching a version in the public share breadcrumb navigated to the
authenticated /projects/:id/files/:id route, which triggered the
authenticated /api/projects/:id/team call (via resolveTeamIdFromPath) ->
401 -> redirect to login.

- breadcrumb handleVersionClick now routes to /share/:shareId/files/:id
  with a version search param when public.
- public share route gains a version param; PublicShareManager fetches the
  stack asset (for the version list) and the active version child asset
  (for display/comments/fields), mirroring the authenticated page.
- compare exit sets version to the active side for parity.
2026-07-04 15:22:38 +08:00
yiling c793e0dd78 fix(webui): keep fullscreen controls visible while cursor is over them
Track when the cursor is over the control bar (VideoControlBar now
forwards mouse enter/leave) and skip the idle-hide timer while it is, so
the bar no longer disappears when the cursor rests on it. Also reduce the
fullscreen auto-hide delay from 2s to 1.2s.
2026-07-04 13:15:52 +08:00
yiling 13833e8144 fix(webui): auto-hide fullscreen controls on idle regardless of play state
The fullscreen control bar only auto-hid while playing, and a separate
effect force-showed it whenever paused, so it stayed visible permanently
when paused in fullscreen. Now in fullscreen the bar shows on cursor move
and hides after the cursor is idle (~2s) whether playing or paused;
windowed mode keeps the bar always visible.
2026-07-04 13:04:25 +08:00
yiling d3c1c641b4 fix(webui): show control bar in single-file fullscreen; theme the overlay
The single-file player fullscreened the inner video-area element, which
is not an ancestor of the control bar, so the bar was never visible in
fullscreen. Fullscreen the player root instead so the floating control
bar is included and the existing show-on-move / hide-after-idle logic
works (YouTube-style).

Also make the control-bar colors theme-aware in all cases. The fullscreen
floating overlay now uses bg-card/90 + backdrop-blur + foreground text
instead of a hardcoded dark overlay, so it follows the app light/dark
theme. The former themedChrome prop is renamed to floatOverlayInFullScreen
(default true = single-file floating overlay; compare passes false to keep
its bar in-flow).
2026-07-04 12:48:15 +08:00
yiling aeaff3bc88 feat(webui): compare fullscreen control bar follows app theme
Add a themedChrome prop to VideoControlBar that keeps the normal
theme-aware chrome (bg-card / foreground text) while fullscreen instead
of the dark video overlay. Compare mode passes it so its fullscreen bar
matches the app light/dark theme for both video- and image-active panes
(ImageControlBar is already themed). The single-file player is unchanged
(themedChrome defaults to false -> dark overlay). The fullscreen toggle
icon still reflects the actual fullscreen state.
2026-07-04 12:28:08 +08:00
yiling cf005797be fix(webui): readable zoom/Fit controls in fullscreen light mode
In the fullscreen control bar the whole bar uses text-white (it overlays
the dark video), but the zoom group and Fit button hardcoded bg-muted,
which is light in light mode -> white text on a light background. Use a
translucent bg-white/15 for those controls when fullscreen so they stay
readable; the normal (non-fullscreen) bar keeps bg-muted. Also fixes the
same latent issue in the single-file video player.
2026-07-04 11:36:04 +08:00
yiling 4b3b31c83d style(webui): compare pane topbar is always dark with light text
Force the dark palette on the compare pane topbar (via a scoped `dark`
class + system tokens, no hardcoded hex) so the bar background is dark in
both light and dark app themes. Active pane text uses text-foreground
(white in the dark scope); inactive pane uses text-muted-foreground
(light gray).
2026-07-04 11:25:39 +08:00
yiling a4e25db0f7 style(webui): emphasize active compare pane topbar
The active version's topbar now uses an inverted bar (bg-foreground /
text-background) so it reads as black background with white text in the
light theme, while the inactive pane keeps the card background with muted
text. Filename/version text color now differs between active and inactive
panes.
2026-07-04 11:19:50 +08:00
yiling 78c8a56183 fix(webui): clicking an inactive compare pane only activates it
Previously clicking a non-active video pane both switched the active
version and toggled playback. Now a click on an inactive pane only makes
it active; play/pause is only toggled when clicking the already-active
pane.
2026-07-04 10:56:55 +08:00
yiling e2d4944060 refactor(webui): extract shared Video/Image control bars and reuse in compare
Extract the video player's inline ControlBar into an exported
viewers/video-control-bar.tsx (VideoControlBar + PlayerState +
DisplayTranscode) and the image toolbar from file-viewer into an exported
viewers/image-control-bar.tsx (ImageControlBar). video-player and
file-viewer now consume the shared components with unchanged behavior.

compare-control-bar composes the same two shared bars (video vs image
active) with fan-out handlers, so the compare control bar can no longer
drift from the single-file players (e.g. the time-format dropdown).
2026-07-04 10:49:00 +08:00
yiling 6c3d3ea2b3 feat(webui): add compare versions view for version stacks
Add a Compare Versions mode to the file detail page (authenticated and
public share) that splits the viewer into two 50/50 panes showing two
versions side by side.

- Breadcrumb file menu gains a Compare Versions entry (version stacks
  with >=2 versions); the file segment is hidden in compare mode.
- URL-driven state (compare/cmpLeft/cmpRight/cmpActive) on both file
  routes so the view is refresh/share-safe.
- Per-side topbar with filename, version, version-switch dropdown, an
  active-side highlight, and an X exit button.
- Shared control bar reflects the active pane; for same-type media it
  coordinates both panes (play/pause, seek, frame-step, zoom, pan sync),
  seekbar length matches the active side while the shorter side holds its
  last frame; only the active side plays audio; resolution/download apply
  to the active side; fullscreen covers the whole compare view.
- Right sidebar (comments/fields) binds to the active side; comment
  selection seeks the active pane and annotations/comments can be created.
- Reuses useFramePlayer + DrawingCanvas without modifying the existing
  single-file video player.
- Unit tests for compare selection/clamp logic.
2026-07-04 10:20:16 +08:00
Yiling-J e7273f1a02 Merge pull request #170 from shumaiOne/feat/video-duration-card-preview
feat(file-browser): show video duration on file card preview
2026-07-03 23:08:03 +08:00
yiling d3efc00902 feat(file-browser): show video duration on file card preview
Display the video duration (mm:ss) in the bottom-right corner of the
video file card preview area with white text and a transparent
background. Duration is sourced from media metadata and exposed via the
preview DTO. The overlay is gated behind a showDuration prop so it only
appears on file cards, not folder card child previews.
2026-07-03 20:48:26 +08:00
Yiling-J 06df7537e0 Merge pull request #169 from shumaiOne/test/video-player-restart-on-end
test(webui): verify video player restarts playback after end
2026-07-03 20:33:04 +08:00
yiling 1de8c4ad32 test(webui): verify video player restarts playback after end
Add an e2e spec covering restart-on-end for the frame-accurate video
player. Drives the real player to its natural end (seek near the tail,
play out the last frames) and asserts both restart triggers resume from
the start: the play/pause control and clicking the video area.

Adds seekToFrame and waitForEnded helpers to VideoPlayerPage.
2026-07-03 20:16:48 +08:00
Yiling-J 278bbdd4fe Merge pull request #168 from shumaiOne/test/video-comment-seek-e2e
test(webui): add frame-accurate comment seek roundtrip e2e
2026-07-03 20:08:13 +08:00
yiling ed40b41e1a test(webui): rework seek-settle wait to avoid overlapping browser polls
Address review feedback: an async predicate with setTimeout inside
page.waitForFunction spawns overlapping executions at rAF rate, and checking
currentTime stability before arrival can resolve prematurely.

Reorder to arrival-first: wait for the target frame via a synchronous rAF-polled
predicate, then wait for currentTime to stabilize using a sequential Node-side
loop so browser evaluations never overlap.
2026-07-03 19:36:39 +08:00
yiling 3dcab584ae test(webui): add frame-accurate comment seek roundtrip e2e
Extend the backend-free video-player harness with the app's real comment↔player
wiring (onTimeUpdate capture, player.currentTime(second) seek on comment click,
and a remount to simulate a second user) and add a Playwright spec.

User A comments on 5 distinct random frames (regenerated each run); user B
reloads and clicks each comment. Asserts the seconds-based roundtrip is
loss-free: frameA -> second=frameA/fps -> seek(second) -> floor(second*fps+0.45)
== frameA, so the comment is stored at the frame the author saw and the reader
lands on that exact frame.
2026-07-03 19:20:17 +08:00
Yiling-J cfbb799ddc Merge pull request #167 from shumaiOne/fix/root-component-conditional-hooks
fix(webui): resolve conditional hooks and setState-in-render errors
2026-07-03 18:59:34 +08:00
yiling 9623da7504 fix(webui): resolve conditional hooks and setState-in-render errors
- __root.tsx: move useTeamContextStore/useEffect/useQuery above the
  conditional 'return <Outlet />' so hooks run unconditionally in a
  stable order (fixes 'Rendered more hooks than during the previous
  render')
- team-selector.tsx: move single-team navigate() into a useEffect to
  avoid updating the router Transitioner during render
2026-07-03 18:53:38 +08:00
Yiling-J 370b0d3050 Merge pull request #166 from shumaiOne/test/video-player-playwright-e2e
test(webui): video player e2e framework + Safari playhead fix
2026-07-03 17:20:51 +08:00
yiling c847649242 docs(webui): update video player design doc for rVFC-gated playhead sync
Reflect the useFramePlayer changes: the currentTime/RAF path only drives the
playhead once rVFC has delivered a frame this session (or is unsupported / a
grace elapsed), pause locks to the last presented mediaTime when fresh, and
document the frame-accurate pause/resume audio-replay tradeoff.
2026-07-03 16:14:19 +08:00
yiling 38694eb77b fix(webui): stop Safari video playhead from rewinding on play/pause
On Safari/WebKit, video.currentTime (the playback clock) runs ahead of the
frame actually presented on screen at playback start, and the first
requestVideoFrameCallback arrives only after a delay. useFramePlayer drove the
playhead from currentTime immediately on play, racing it forward, then snapped
it backward when the first rVFC reported the true (lower) presented frame.

Fix 1 (play-start rewind): reset the per-session VFC state on each play and only
use the currentTime/RAF path when rVFC is unsupported, or has delivered a frame
this session and then stalled (e.g. video track ended while audio continues), or
never delivered within a safety grace. The playhead now follows the actually
presented frame instead of the leading playback clock.

Fix 2 (pause snap): on pause, prefer the last presented mediaTime when rVFC is
fresh so the playhead locks to the frame the user is looking at, instead of
jumping forward to the leading currentTime. Falls back to currentTime when rVFC
is stale/unsupported.

Add a deterministic useFramePlayer hook unit test (happy-dom) that simulates
Safari's leading currentTime and lagging mediaTime; it asserts the playhead is
monotonic on play and locks to the presented frame on pause (both fail on the
old logic), and that the end-of-track currentTime fallback still works.
2026-07-03 15:56:31 +08:00
yiling 8c53685590 chore(webui): remove unused vite dev dependencies
The webui package was migrated from a Vite project but now uses the Bun
fullstack framework (Bun.serve + bun-plugin-tailwind) for dev/prod, and the
e2e harness serves via Bun too. Nothing in webui imports vite, @vitejs/plugin-react,
@tailwindcss/vite or vite-tsconfig-paths (the only vite-tsconfig-paths usage is
the root vitest.config.ts via the root devDependency), so drop them from the
webui package.

Verified: typecheck, lint, vitest and the playwright e2e suite all still pass
(Tailwind compiles via bun-plugin-tailwind).
2026-07-03 14:55:56 +08:00
yiling 469f68b25d test(webui): add playwright e2e framework with video player play/pause test
Add a Playwright UI integration test framework for the frame-accurate video
player. Tests run against a backend-free harness served by Bun's native HTML
bundler (matching the project's Bun-based dev/prod serving), so no database,
auth or transcode pipeline is required.

- Add @playwright/test with chromium/firefox/webkit projects; the browser is
  selectable via the Playwright --project flag (webkit = Safari engine).
- Serve the harness with Bun.serve + bun-plugin-tailwind (no separate Vite
  toolchain); commit a deterministic 16x16/5s/30fps fixture video and matching
  AssetInfo.
- Add a play/pause spec covering both the play control and clicking the video
  area, asserting the native video clock, seekbar fill and frame readout stay
  frame-locked after pause (settle-aware, tolerance-based assertions).
- Mock all backend API calls (anchored /api/ and /files/ routes) for isolation.
- Exclude e2e specs from Vitest; add a separate CI job (webkit on macOS).
2026-07-03 14:50:38 +08:00
yiling 7c3412686c Release v0.1.5 2026-07-02 19:01:12 +08:00
Yiling-J 297c4903fe Merge pull request #165 from shumaiOne/refactor/friendly-storage-filenames
refactor(storage): use original filenames for stored files
2026-07-02 18:18:00 +08:00
yiling b7367bb129 refactor(storage): use original filenames and fix download UX
- Store uploaded files as files/{ulid}/{original-name} instead of files/{ulid}/raw
- Store transcoded videos as {stem}-{resolution}.mp4 (e.g. foo-720p.mp4)
- Store transcoded images as {stem}-{width}p.webp (e.g. foo-1920p.webp)
- Add download?: boolean param to presign - only sets Content-Disposition: attachment when true
- Local storage handler only sets Content-Disposition when ?download=1 query param is present
- Add POST /api/files/download-url endpoint for key-based single file downloads
  - Uses ResourceType.Asset for permission check
  - Validates key belongs to the asset's storage directory
- Fix existing download-links API to pass download: true to presign
- Fix breadcrumb navbar download: video shows resolution submenu, others download directly
- Fix video player download: calls download-url API, shows correct file type label
- Remove filename query param hack from presign URLs
- Add sanitizeFilename() and stemFromKey() utility helpers
- Add key field to VideoTranscode DTO interface
2026-07-02 17:39:23 +08:00
yiling 114cdca4ee update aliyun acr image 2026-07-02 10:51:06 +08:00
Yiling-J 9d7b142129 Improve formatting of commands in README_CN.md
Fix formatting issues in README_CN.md for clarity.
2026-07-02 10:44:57 +08:00
Yiling-J 91fafafeff Merge pull request #164 from shumaiOne/feature/update-release-workflow
ci(release): add Aliyun ACR push to release workflow
2026-07-02 10:10:32 +08:00
yiling d5b9439371 ci(release): add Aliyun ACR push to release workflow 2026-07-02 10:02:13 +08:00
yiling 3725193e72 Release v0.1.4 2026-07-01 20:24:39 +08:00
Yiling-J 62c9fb46ae Merge pull request #163 from shumaiOne/feat/signup-locale
feat(auth): allow setting user locale on signup
2026-07-01 19:29:02 +08:00
yiling 9b1890f57c feat(auth): allow setting user locale on signup 2026-07-01 19:23:49 +08:00
Yiling-J 68a8b67931 Merge pull request #162 from shumaiOne/fix/video-replay
fix(webui): preserve video ended state by skipping playhead snap on ended
2026-07-01 14:56:19 +08:00
yiling d0bda60b9f fix(webui): preserve video ended state by skipping playhead snap on ended 2026-07-01 14:46:12 +08:00
yiling d71b0de056 remove video player debug logs 2026-07-01 14:37:34 +08:00
yiling 8c7d4f5b72 update cn docker setup guide 2026-07-01 14:36:09 +08:00
Yiling-J d8793a89a2 Merge pull request #161 from shumaiOne/feat/video-poster-480p
feat(transcode): change video poster resolution to 480p
2026-07-01 12:55:25 +08:00
yiling 178670fdab feat(transcode): change video poster resolution to 480p 2026-07-01 12:45:16 +08:00
yiling 715b657153 update readme 2026-07-01 12:40:30 +08:00
Yiling-J c0353bb050 Update README_CN.md with English documentation link
Added English link to the README_CN.md file.
2026-07-01 11:14:11 +08:00
Yiling-J 0c1907d868 Add Chinese README link to README.md
Added a link to the Chinese README in the main README.
2026-07-01 11:12:03 +08:00
Yiling-J edbf2c6001 Refine AI feature descriptions in README
Updated descriptions for AI features in README.
2026-07-01 11:04:21 +08:00
Yiling-J fa319d0898 Add Dockerfile syntax version specification 2026-07-01 10:50:37 +08:00
Yiling-J b0a595fe9c Add README_CN.md 2026-07-01 10:44:19 +08:00
Yiling-J b7d250dbac Update README with media processing information
Added note about media processing and storage details.
2026-07-01 09:45:24 +08:00
yiling 2cbc86fdd6 Release v0.1.3 2026-06-30 19:01:50 +08:00
Yiling-J d391705519 Merge pull request #160 from shumaiOne/fix/team-settings-video-strategy
fix(api): fix update team settings and make request schema type-safe
2026-06-30 15:18:39 +08:00
yiling 34a69a33bf fix(api): fix update team settings and make request schema type-safe 2026-06-30 14:41:50 +08:00
Yiling-J d32707d038 Merge pull request #159 from shumaiOne/fix/file-detail-parent-folder
fix(webui): fix missing left sidebar for nested folders
2026-06-30 13:11:06 +08:00
yiling 89777e0b6d fix(webui): fix missing left sidebar for nested folders 2026-06-30 13:00:18 +08:00
Yiling-J 8b800bc792 Merge pull request #158 from shumaiOne/fix/video-player-duration
fix(webui): align video timeline duration and formatting with frameio
2026-06-30 11:35:14 +08:00
yiling 899b600417 fix(webui): resolve 1-frame comment mismatch via 0.45 offset and pause snapping 2026-06-30 11:10:53 +08:00
yiling 954d8ee497 docs(webui): update video player design doc with Zoom Fit section 2026-06-30 10:50:39 +08:00
yiling 86ad68a705 feat(webui): add Fit zoom button in video player control bar 2026-06-30 10:50:30 +08:00
yiling d2ee7f1c45 fix(webui): prevent initial scale fit layout race condition 2026-06-30 10:45:51 +08:00
yiling 7cb1aa3c86 docs(webui): add video player design document 2026-06-30 10:34:19 +08:00
yiling 1704fddc67 refactor(webui): use Floor with Epsilon (0.001) for frame conversion calculations 2026-06-30 10:22:32 +08:00
yiling 07d82377bd fix(webui): implement dynamic stall threshold for requestVideoFrameCallback 2026-06-30 09:47:13 +08:00
yiling 9c8f29e3ba fix(webui): unify playhead loop with requestAnimationFrame to prevent deadlock 2026-06-29 20:33:24 +08:00
yiling 9fd707b23f fix(webui): fallback to requestAnimationFrame when video track freezes 2026-06-29 20:16:06 +08:00
yiling 14f6752de2 fix(webui): align video timeline duration and formatting with frameio 2026-06-29 19:48:28 +08:00
Yiling-J b75b276908 Merge pull request #157 from shumaiOne/refactor-video-accurate-seek
feat(video): add frame-accurate video player, SMPTE timecodes, and format switcher
2026-06-29 16:57:07 +08:00
yiling 95f91cd4de feat(db): add custom migration to backfill totalFrames and startTimecode 2026-06-29 11:27:32 +08:00
yiling bb65c5a0d3 perf(video): optimize keydown listener binding in useFramePlayer 2026-06-29 11:01:10 +08:00
yiling a585718660 fix(video): add fallback timeout to seeked Promise wrapper to prevent permanent freeze 2026-06-29 10:58:34 +08:00
yiling adb5f58535 fix(transcode): replace isNaN with isFinite to guard against Infinity frameRate 2026-06-29 10:55:28 +08:00
yiling 9ca9b2d8e4 fix(video): safely sync startTime seek with VideoJS loadedmetadata status 2026-06-29 10:53:14 +08:00
yiling b173b4910e test(video): extract calculateFrameCenterTime helper and add unit tests 2026-06-29 10:10:47 +08:00
yiling 9576453a72 fix(video): display totalFrames - 1 as duration to align timer at end 2026-06-29 10:02:17 +08:00
yiling 5233615720 fix(video): add centralized playhead nudge for boundary-accurate seeking 2026-06-28 23:22:03 +08:00
yiling 1ebf79edd3 fix(video): resolve 1-frame shift on external seeks due to floor rounding 2026-06-28 21:12:29 +08:00
yiling eee7b5a677 feat(video): add SMPTE timecode support and format selection dropdown 2026-06-28 21:04:40 +08:00
yiling 837fe5bd7a feat(video): add frame-accurate video player and CFR proxy generation 2026-06-28 20:35:47 +08:00
Yiling-J f159fec693 Merge pull request #156 from shumaiOne/feat/i18n-webui
feat(webui): add i18n support using paraglide-js
2026-06-27 15:51:52 +08:00
yiling dc46853582 chore: mark prisma and paraglide generated folders as linguist-generated 2026-06-27 15:00:47 +08:00
yiling 850b1ff667 feat(webui): integrate i18n into file-browser context-menu component 2026-06-27 14:55:25 +08:00
yiling 4475c7bed6 feat(webui): integrate i18n into share-settings-sidebar component 2026-06-27 14:53:09 +08:00
yiling 0fd826b973 feat(webui): integrate i18n into share-manager component 2026-06-27 14:50:17 +08:00
yiling 2d5b4a3753 feat(webui): integrate i18n into project-dialog component 2026-06-27 14:47:31 +08:00
yiling fb63d8b7b6 feat(webui): translate formatCount in file-browser and add plural keys 2026-06-27 14:45:30 +08:00
yiling 7182c00c7d feat(webui): integrate i18n into fields-manager and manage-fields-dialog components 2026-06-27 14:41:47 +08:00
yiling e8058a2292 feat(webui): integrate i18n into folder-tree component and add missing translation keys 2026-06-27 14:30:22 +08:00
yiling 1b60c8df83 feat(webui): integrate i18n into search and sort control components 2026-06-27 10:30:57 +08:00
yiling 4dc53063ea chore: add paraglide generated folders to prettier ignore files 2026-06-27 10:24:20 +08:00
yiling d5dbb3c01b chore(deps): install paraglide-js dev dependency in root and configure compile scripts 2026-06-27 10:20:00 +08:00
yiling 8779ae52a2 fix(webui): rename arguments translation key to tool_arguments to avoid strict mode reserved word error 2026-06-27 10:14:16 +08:00
yiling 5c21463075 feat(webui): complete webui translations and integrate i18n 2026-06-27 10:12:07 +08:00
yiling 914855a25c chore(webui): move paraglide directory to packages/webui root and update imports 2026-06-26 13:35:27 +08:00
Yiling-Jandgemini-code-assist[bot] c7b0346782 Apply suggestions from code review
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-06-26 13:28:53 +08:00
yiling e6818860da chore: ignore markdown files in Prettier 2026-06-26 13:28:00 +08:00
yiling 5dae5740e3 chore(webui): revert formatting changes in root README.md 2026-06-26 13:27:04 +08:00
yiling bbe36a028d ci: revert Compile translations step from CI workflows 2026-06-26 12:24:41 +08:00
yiling ba5f7296a8 chore(i18n): commit generated paraglide code and disable output gitignore 2026-06-26 12:10:37 +08:00
yiling cd4a22d20b ci: compile i18n translations before running lint and typecheck 2026-06-26 11:52:09 +08:00
yiling fc7d1452b0 fix(webui): resolve team ID using target location pathname in beforeLoad 2026-06-26 11:48:38 +08:00
yiling 4fd27ab147 feat(webui): add i18n text keys and translate one static text element per page for verification 2026-06-26 11:24:32 +08:00
yiling 6e2e5bdbc2 refactor(webui): extract shared resolveTeamIdFromPath function for root route and component 2026-06-26 11:18:09 +08:00
yiling b6ff60f8b8 docs: add paraglide-js i18n rules and usage guide to AGENTS.md 2026-06-26 10:44:49 +08:00
yiling 48f4c83cc8 feat(webui): add i18n support using paraglide-js 2026-06-26 10:39:32 +08:00
Yiling-J 81b0083672 Fix formatting for AWS_ENDPOINT_URL_S3 example 2026-06-25 20:38:21 +08:00
yiling 3737418ec3 Release v0.1.2 2026-06-25 19:43:07 +08:00
Yiling-J 6d47ea7466 Update AWS_ENDPOINT_URL_S3 explanation in README
Clarified the default value for AWS_ENDPOINT_URL_S3 and its usage with custom host/port.
2026-06-25 19:15:11 +08:00
Yiling-J 84d96ff83a Revise README for environment variable setup
Updated environment variable configuration instructions for clarity and added optional settings for S3-compatible storage.
2026-06-25 19:11:39 +08:00
Yiling-J 6e985aed61 Merge pull request #155 from shumaiOne/refactor/s3-endpoint
refactor(s3): remove automatic port appending to AWS_ENDPOINT_URL_S3
2026-06-25 18:56:49 +08:00
yiling 8347a9ca15 docs(docker): document SHUMAI_SERVER_PORT and update local docker-compose env 2026-06-25 18:50:29 +08:00
yiling ab9b33320d docs(s3): document SHUMAI_SERVER_PORT and S3 endpoint port configurations 2026-06-25 18:48:23 +08:00
yiling efd6163238 refactor(s3): remove automatic port appending to AWS_ENDPOINT_URL_S3 2026-06-25 18:46:14 +08:00
yiling 0e4bdec0e3 Release v0.1.1 2026-06-23 10:32:41 +08:00
yiling 0eb03b16a4 chore(docker): add AWS_ENDPOINT_URL_S3 to local docker-compose 2026-06-23 10:27:18 +08:00
Yiling-J b216773044 Merge pull request #151 from shumaiOne/docker/entrypoint-privilege-dropping
feat(docker): add root entrypoint with privilege dropping for data volumes
2026-06-23 10:09:57 +08:00
yiling 92801ba14a fix(core): make version stack sort index lookup deterministic
When creating a version stack, the sortIndex was previously extracted
by taking files[0] from the database query result. Because findMany
without orderBy is non-deterministic, this resulted in flakiness
where the sortIndex would sometimes be null (from file2) instead of
'abc' (from file1), causing tests to fail.

We now look up the first file specifically based on the ordered
fileIds array parameter.
2026-06-23 10:02:01 +08:00
yiling 661e836f06 fix(docker): support non-root/restricted container environments in entrypoint
Checks if the container is running as root (UID 0) before executing
chown and gosu. If running directly as a non-root user (e.g. in hardened
environments like Kubernetes runAsNonRoot or via docker run --user),
it directly execs the command, preventing EACCES and permission errors.
2026-06-23 09:56:31 +08:00
yiling fb5c7ecabe chore(docker): ignore dist and data directories in .dockerignore
This adds the `dist` and `data` folders to `.dockerignore` to prevent
them from being transferred as part of the Docker build context.
This reduces the build context size by over 1.5GB+, making the build
much faster.
2026-06-23 09:53:00 +08:00
yiling a390643458 feat(docker): add root entrypoint with privilege dropping for data volumes
This updates the Dockerfile and adds a scripts/docker-entrypoint.sh script.
Under native Linux (like Debian), when docker-compose mounts a host folder
as a volume (e.g. `./data:/app/data`), and the folder doesn't exist, the
docker daemon creates the folder as root-owned (`root:root`).

Because the container runs as a non-root user `bun`, it gets permission
denied (`EACCES`) when trying to write to the data directory.

To resolve this in a beginner-friendly way without manual host-side
permissions updates:
1. The runner stage now installs `gosu`.
2. At the end of the Dockerfile, the user switches back to `root` so the
   container launches as root.
3. On launch, the entrypoint script executes. Since it runs as root, it
   automatically changes ownership of `/app/data` to `bun:bun`.
4. The entrypoint script then uses `gosu` to drop privileges and launch the
   actual server processes as the non-root `bun` user.
2026-06-23 09:46:56 +08:00
yiling 9325c71b51 Release v0.1.0 2026-06-22 21:45:39 +08:00
Yiling-J 2f746d3ce8 Merge pull request #150 from shumaiOne/feat/secure-share-info
feat(share): secure share info API and fix wrong password feedback
2026-06-22 20:53:56 +08:00
yiling bdceda4cb6 refactor(share): use custom strongly-typed error classes 2026-06-22 20:48:47 +08:00
yiling df6e392bf6 feat(share): expose raw password on settings page 2026-06-22 20:32:46 +08:00
yiling 48b2047a84 feat(share): secure share info API and fix wrong password feedback 2026-06-22 20:21:44 +08:00
yiling 2b360b2b2c chore(docker): update shumai image tag to latest 2026-06-22 15:52:00 +08:00
Yiling-J 5d19e6ddfa Merge pull request #149 from shumaiOne/fix-sidebar-overflow
fix(webui): truncate long folder, collection, and share link names in sidebar
2026-06-22 15:46:18 +08:00
yiling 5e70b6f3ee docs: add note blocks for running binaries under Bun runtime 2026-06-22 15:39:47 +08:00
yiling 8eab02ab28 fix(webui): truncate long folder, collection, and share link names in sidebar 2026-06-22 15:22:44 +08:00
yiling 7aa347df92 Release v0.0.11 2026-06-22 14:38:28 +08:00
Yiling-J 5d6462adf0 Merge pull request #148 from shumaiOne/rename-npm-cli-package
chore(cli): rename npm package to @shumai-one/shumai-cli
2026-06-22 14:21:59 +08:00
yiling 5f1e0c1823 chore(cli): rename npm package to @shumai-one/shumai-cli 2026-06-22 14:16:47 +08:00
Yiling-J d8381dff21 Merge pull request #147 from shumaiOne/feat/user-custom-fields
feat(metadata): add single user and multiple user custom fields
2026-06-22 12:01:41 +08:00
yiling b6519431db docs(metadata): document new user custom field types 2026-06-22 11:55:53 +08:00
yiling 02fddf8ebd chore: ignore generated prisma folder in prettier 2026-06-22 11:54:56 +08:00
yiling f4c52d9273 chore(db): migrate generate script to root package.json under db:generate 2026-06-22 11:49:53 +08:00
yiling 77093aa294 fix(webui): lock user-field height and suppress benign ResizeObserver limit warnings 2026-06-22 11:40:48 +08:00
yiling 4806c63906 feat(metadata): add single user and multiple user custom fields 2026-06-22 11:27:00 +08:00
Yiling-J 14d04e9d77 Merge pull request #146 from shumaiOne/feat/auto-expand-folders
feat(folders): auto expand folder tree in left sidebar on navigation
2026-06-22 11:02:14 +08:00
yiling 342cdcdd06 style(folders): fix selection highlight overlap by increasing padding 2026-06-22 10:52:25 +08:00
yiling 98a76e913b style(folders): use Shadcn ScrollArea in left sidebar containers 2026-06-22 10:44:07 +08:00
yiling 2240901d55 feat(folders): auto expand folder tree in left sidebar on navigation 2026-06-22 10:27:21 +08:00
Yiling-J 6892967993 Merge pull request #145 from shumaiOne/feat/agent-settings-singular-ui
feat(settings): use singular headers and remove collapse/counters for single agent types
2026-06-22 10:10:16 +08:00
yiling 7ea5345c52 refactor(settings): dynamically render thinkingLevel dropdown from schema options 2026-06-22 10:04:51 +08:00
yiling bea81a207a fix(settings): support type-safe thinkingLevel and propagate to AgentHarness 2026-06-22 09:58:35 +08:00
yiling c20ef0e4b6 fix(settings): prioritize actual agent type when editing agent configurations 2026-06-22 09:27:37 +08:00
yiling 754131f13a feat(settings): support singular headers and remove collapse/counters for single agent types 2026-06-22 09:23:13 +08:00
Yiling-J 6981706e13 Merge pull request #144 from shumaiOne/feat/shumai-cli
feat(cli): add shumai-cli and token authentication
2026-06-21 23:16:39 +08:00
yiling 280c06b68c docs(cli): move CLI section to the bottom of the root README 2026-06-21 21:56:52 +08:00
yiling 4e21becbe0 docs(cli): add CLI documentation and link to it in root README 2026-06-21 21:54:45 +08:00
yiling 86c1d964a3 feat(cli): add create-version command 2026-06-21 20:14:26 +08:00
yiling 87fc10b62f fix(cli): resolve upload status and CLI progress tracker bugs 2026-06-21 20:06:06 +08:00
yiling 7d91d70a14 feat(cli): add @shumai/tableprinter package to handle terminal-friendly table layouts 2026-06-21 19:28:31 +08:00
yiling 1c994adce9 build(cli): bundle hono and ulid directly into the CLI script for zero dependency distribution 2026-06-21 19:15:41 +08:00
yiling afd55eca85 chore(cli): add @shumai-one/cli to local release testing script 2026-06-21 19:06:12 +08:00
yiling 29e3d3ae03 refactor(cli): rename shumai-cli folder to cli and integrate packaging script 2026-06-21 19:00:38 +08:00
yiling 90ef063d43 feat(cli): add shumai-cli and token authentication 2026-06-21 12:35:12 +08:00
yiling e33cbdb37c Release v0.0.10 2026-06-21 10:52:57 +08:00
Yiling-J 0514a19702 Merge pull request #143 from shumaiOne/docs/polish-readme
docs(readme): polish structure, correct grammar, and add dependencies table
2026-06-21 10:45:04 +08:00
Yiling-Jandgemini-code-assist[bot] 9fb9e608b9 Update README.md
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-06-21 10:44:45 +08:00
yiling cbb25b49e7 docs(readme): add daemon commands documentation under option 2 2026-06-21 10:34:15 +08:00
yiling ce8fc5d128 docs(readme): polish structure, correct grammar, and add dependencies table 2026-06-21 10:24:23 +08:00
Yiling-J 34bacf5421 Merge pull request #142 from shumaiOne/refactor/prod-routes
refactor(web): dynamically register production HTML bundle routes
2026-06-21 09:25:56 +08:00
yiling 98bbfa51ae refactor(web): dynamically register production HTML bundle routes 2026-06-21 00:20:41 +08:00
yiling fc9dd8a5f7 Release v0.0.9 2026-06-20 14:53:22 +08:00
Yiling-J c7fef79860 Merge pull request #141 from shumaiOne/feat/daemon-cli
feat(cli): add background daemonization and subcommands
2026-06-20 14:41:42 +08:00
yiling efa0e75a06 fix(release): bundle zod for shumai webapp and keep it external for workers 2026-06-20 14:39:43 +08:00
yiling b5ff76960f fix(cli): defer PID file cleanup to process exit event for graceful shutdowns 2026-06-20 13:05:50 +08:00
yiling ca0c2ece75 fix(cli): handle EPERM signal errors in isProcessRunning helper 2026-06-20 13:02:06 +08:00
yiling c8b1d521d8 fix(cli): open log files in write mode to truncate on startup 2026-06-20 12:59:58 +08:00
yiling 4bd5083ac1 fix(cli): remove unused watch import in daemon utility 2026-06-20 12:56:15 +08:00
yiling c6527650d0 fix(cli): bypass already running check if matching current process pid 2026-06-20 12:53:14 +08:00
yiling d4a1eff715 fix(cli): resolve Bun compatibility issue with WriteStream stdio redirection 2026-06-20 12:49:05 +08:00
yiling 463cd61cfd test(cli): resolve lint violations in daemon test file 2026-06-20 12:40:14 +08:00
yiling 93b4656939 feat(cli): add daemon mode and stop, logs, restart subcommands 2026-06-20 12:37:49 +08:00
Yiling-J 3e122a86f0 Merge pull request #140 from shumaiOne/ci/smoke-test-local-release
ci(release): add smoke tests to local release stage
2026-06-20 12:07:32 +08:00
yiling 292307e28e test(release): add check flag to app entrypoints and simplify CI smoke tests 2026-06-20 11:54:30 +08:00
yiling 982bca9383 fix(release): resolve correct workspace dependency versions and refine CI smoke tests 2026-06-20 11:43:44 +08:00
yiling d1061a1023 fix(release): exclude zod from inlined dependencies to resolve circular evaluation error 2026-06-20 11:30:22 +08:00
yiling 994f1d3b44 ci(release): add smoke tests to local release stage 2026-06-20 11:23:17 +08:00
Yiling-J e057f17f8e Merge pull request #139 from shumaiOne/feat/avatar-menu-version
feat(webui): show app version in avatar menu
2026-06-19 23:02:09 +08:00
yiling 66d07d1fb0 feat(webui): show app version in avatar menu using local version file 2026-06-19 22:57:26 +08:00
yiling 5542538a64 feat(webui): show app version in avatar menu 2026-06-19 22:34:12 +08:00
yiling 7753721731 Release v0.0.8 2026-06-19 20:42:48 +08:00
Yiling-J ef86cc2713 Merge pull request #138 from shumaiOne/feat/upload-progress-xhr
feat(upload): track byte-level progress with XMLHttpRequest
2026-06-19 20:11:28 +08:00
yiling cc79be7e34 fix(upload): resolve filesToUpload mutation race condition
Capture the files list snapshot at the time the mutation is triggered via React Query's onMutate context, and retrieve it in onSuccess via the context parameter to prevent race conditions during rapid upload successions.
2026-06-19 20:05:02 +08:00
yiling a9c5a3d9fd fix(ui): resolve Cannot access 'displayItem' before initialization ReferenceError
Use item.id directly since it is available at the start of the component from props.
2026-06-19 19:49:30 +08:00
yiling 0d9545f0b5 feat(upload): track byte-level progress with XMLHttpRequest
- Replace fetch uploads with XMLHttpRequest to capture upload progress
- Track active upload tasks and file progress in Zustand store
- Show byte-level uploader progress in the sidebar list
- Replace plain 'Uploading' card status text with a circular percentage animation
- Replace plain document icon in file list view rows with a mini progress circle
2026-06-19 19:44:35 +08:00
Yiling-J 2925fb6bf6 Merge pull request #137 from shumaiOne/feature/switch-and-rating-filter
feat(webui): use Shadcn Switch in toggle field and Rating component in search filter panel
2026-06-19 15:58:41 +08:00
yiling 7ae34a4bc0 feat(webui): use Shadcn Switch in toggle field and Rating component in search filter panel 2026-06-19 15:49:54 +08:00
Yiling-J f645c8fefa Merge pull request #136 from shumaiOne/fix-ui-issues
fix(webui): resolve folder tree sync, search dialog reset, and sidebar actions issues
2026-06-19 15:17:46 +08:00
yiling 1835016a9b fix(webui): use poster field instead of thumbnail for video notifications 2026-06-19 13:34:14 +08:00
yiling 5e92660d1c fix(webui): render sprite image scrubber for video upload notifications 2026-06-19 13:25:00 +08:00
yiling 6cb3ca6874 fix(webui): resolve folder tree sync, search dialog reset, and sidebar actions issues
- Change query key invalidation of folders to the generic ['folders'] key to update the sidebar tree on create/rename/delete/move
- Separate search box from custom filters reset button in search dialog
- Remove unused plus icon from Assets sidebar header
- Add dropdown menu (rename, download, delete) to subfolder tree items in the sidebar
2026-06-19 12:55:30 +08:00
Yiling-J 5d14f4fff1 Merge pull request #135 from shumaiOne/fix/search-dialog-ui-improvements
style(webui): fix search dialog layout height, scroll areas, and restrict filter toggle click
2026-06-19 12:32:30 +08:00
yiling 009566d42f style(webui): add min-h-0 to search results scroll area to allow scrolling 2026-06-19 12:23:15 +08:00
yiling 50777d332b style(webui): fix search dialog layout height, scroll areas, and restrict filter toggle click 2026-06-19 12:11:19 +08:00
Yiling-J 852a9873dc Merge pull request #134 from shumaiOne/fix/search-has-any
fix(search): fix hasAny and hasNone operators on metadata filter
2026-06-19 11:37:35 +08:00
yiling aa265c5322 fix(search): fix hasAny and hasNone operators on metadata filter 2026-06-19 11:29:26 +08:00
Yiling-J 01ab254c21 Merge pull request #133 from shumaiOne/ui/default-right-sidebar-collapsed
feat(webui): default right sidebar to collapsed for new users
2026-06-19 11:03:27 +08:00
yiling ca5ca5e080 feat(share): default right sidebar to collapsed on public share list page and expanded on detail page 2026-06-19 10:58:38 +08:00
yiling 3f27439733 feat(share): show right sidebar toggle in public share topnav and make collapse state local 2026-06-19 10:53:01 +08:00
yiling 2a611f9b5a fix(share): sync layout options and support right sidebar collapse on public page 2026-06-19 10:44:22 +08:00
yiling 7137e00911 fix(share): resolve share link drag-and-drop error and public view render loop 2026-06-19 10:32:21 +08:00
yiling 59db97aedf fix(share): fix right sidebar layout overflow and button cutoff under topnav 2026-06-19 10:24:58 +08:00
yiling a76dbdfc22 feat(share): improve share config page sidebars, layout options, and sorting 2026-06-19 10:22:20 +08:00
yiling 61e2a3c53a feat(webui): add separate sidebar configs for share config pages 2026-06-19 09:57:29 +08:00
yiling 7707498916 feat(webui): default right sidebar to collapsed for new users 2026-06-19 09:50:02 +08:00
Yiling-J 91c8af86db Merge pull request #132 from shumaiOne/feat/demo-mode-refinement
feat(auth): refine demo mode support
2026-06-19 00:44:00 +08:00
Yiling-Jandgemini-code-assist[bot] 286d71133f Update packages/webui/routes/signup.tsx
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-06-19 00:39:02 +08:00
yiling 53c132e41d feat(auth): refine demo mode support using SHUMAI_DEMO_MODE API 2026-06-19 00:36:23 +08:00
Yiling-J 5c285b172b Merge pull request #131 from shumaiOne/feat/demo-mode-support
feat(auth): add demo mode support
2026-06-19 00:22:26 +08:00
yiling f1d52ac44e feat(auth): add demo mode support using PUBLIC_DEMO_MODE 2026-06-19 00:17:14 +08:00
Yiling-J ec6736b452 Merge pull request #130 from shumaiOne/fix/field-colors-and-filter-selects
fix(webui): use system colors for fields and improve search filter select options
2026-06-18 23:27:48 +08:00
yiling 46c975836a fix(webui): render selectMulti 'is exactly' operator as single-select 2026-06-18 23:22:36 +08:00
yiling 5d7ea7d118 refactor(webui): use Popover instead of Combobox for search dialog MultiSelect 2026-06-18 23:18:17 +08:00
yiling 5065346e8a fix(webui): support fallback options for selectMulti fields in filter panel 2026-06-18 23:13:51 +08:00
yiling 60d469c91b fix(webui): use system colors for fields and improve search filter select options 2026-06-18 23:03:57 +08:00
Yiling-J f68c1c56e1 Merge pull request #129 from shumaiOne/fix/project-updated-at-asset-hook
fix(db): automatically update project updatedAt on asset modification
2026-06-18 22:44:20 +08:00
yiling 08cf90477a fix(db): inline project updatedAt touch on asset update 2026-06-18 22:39:23 +08:00
yiling e01c348fde fix(db): automatically update project updatedAt on asset modification 2026-06-18 21:53:16 +08:00
Yiling-J b0eb5b1eef Merge pull request #128 from shumaiOne/feat/video-search-jump-timestamp
feat(webui): support jumping to video timestamp from search results
2026-06-18 21:06:58 +08:00
yiling 3b7fc410b2 feat(webui): support jumping to video timestamp from search results 2026-06-18 20:35:50 +08:00
Yiling-J 4c7ff6f58f Merge pull request #127 from shumaiOne/feat/semantic-search-chunk-overlap
feat(agent): implement overlapping video chunks for semantic search
2026-06-18 20:02:26 +08:00
yiling a197c83580 fix(agent): prevent redundant final video chunks in embedding workflow 2026-06-18 19:57:01 +08:00
yiling 718d9d5b51 feat(transcode): optimize video chunks for embedding by forcing 1 FPS and dropping audio 2026-06-18 19:53:19 +08:00
yiling 212ac3bc0e docs(search): add detail about video chunking and configuration to semantic search docs 2026-06-18 19:46:50 +08:00
yiling eaf2c867b3 feat(agent): implement overlapping video chunks for semantic search and update docs 2026-06-18 19:45:58 +08:00
Yiling-J 570d95fa6f Merge pull request #126 from shumaiOne/feat/external-drag-drop
feat(webui): add external drag-and-drop file and folder upload support
2026-06-18 16:21:23 +08:00
yiling 32892a21c1 fix(webui): guard external drag and drop in share, public, and collection views 2026-06-18 16:13:40 +08:00
yiling 7819a2034e fix(webui): clear external drag state synchronously on folder drops 2026-06-18 15:58:34 +08:00
yiling e0f2698a66 feat(webui): add external drag-and-drop file and folder upload support 2026-06-18 15:39:08 +08:00
Yiling-J 72c50ffd73 Merge pull request #125 from shumaiOne/improve-embedding-workflow
feat(embedding): defer embedding workflow, use transcoded assets, and execute chunks in separate activities
2026-06-18 15:02:21 +08:00
yiling d84950d372 feat(transcode): set loglevel to warning for all ffmpeg commands 2026-06-18 11:57:38 +08:00
yiling 46815736e2 feat(embedding): decouple video chunk transcode and embedding generation 2026-06-18 11:54:30 +08:00
yiling 9d1e8378f7 fix(embedding): resolve transcoded MIME type and validate EMBEDDING_CHUNK_DURATION positive limits 2026-06-18 11:14:09 +08:00
yiling f399d2c469 feat(embedding): defer embedding workflow, use transcoded assets, and execute chunks in separate activities 2026-06-18 10:57:22 +08:00
Yiling-J 4af081f128 Merge pull request #124 from shumaiOne/feat/custom-server-port
feat(server): allow customizing server port via SHUMAI_SERVER_PORT
2026-06-18 10:32:36 +08:00
yiling ce457e1161 fix(s3): remove port from AWS_ENDPOINT_URL_S3 and sync with server port in local mode 2026-06-18 10:22:16 +08:00
yiling a69dd6a660 feat(server): allow customizing server port via SHUMAI_SERVER_PORT 2026-06-18 10:08:31 +08:00
Yiling-J 62d7061cb3 Merge pull request #123 from shumaiOne/fix/fps-transcode-failure
fix(transcode): handle high-precision FPS using rational fractions
2026-06-18 09:24:11 +08:00
yiling 1ad5720f42 fix(transcode): handle high-precision FPS using rational fractions 2026-06-17 22:55:01 +08:00
Yiling-J 0be74dd4ab Merge pull request #122 from shumaiOne/feat/read-only-mode
feat(api): implement read-only mode for reviewers
2026-06-17 22:35:25 +08:00
yiling f4276a19aa feat(api): allow search API in read-only mode 2026-06-17 22:30:09 +08:00
yiling d81fc275f4 fix(api): correct lint errors in authMiddleware tests 2026-06-17 22:19:44 +08:00
yiling ead91455d8 feat(api): implement read-only mode for reviewers controlled by REVIEWER_READ_ONLY env 2026-06-17 21:51:34 +08:00
yiling 438ea79535 Release v0.0.7 2026-06-17 17:02:21 +08:00
Yiling-J 3455cd0b13 Merge pull request #121 from shumaiOne/feat/api-protocol-enum
feat(api): use enum for API protocol in provider config
2026-06-17 16:48:52 +08:00
yiling 2aba1c898b feat(core): allow deleting builtin providers 2026-06-17 16:39:23 +08:00
yiling 6f91b9e809 feat(webui): allow deleting builtin providers and improve dialog layout 2026-06-17 16:31:51 +08:00
yiling 10760f5a57 fix(webui): finalize provider dialog layout for better scrolling 2026-06-17 16:26:10 +08:00
yiling c150f62b4c fix(webui): improve dialog layout for scrollable content 2026-06-17 16:15:04 +08:00
yiling 1284c1de3f fix(webui): make model list in provider dialog scrollable 2026-06-17 16:12:35 +08:00
yiling 0c89616a4e feat(api): use enum for API protocol in provider config 2026-06-17 16:07:48 +08:00
Yiling-J 96a682b414 Merge pull request #118 from shumaiOne/docs/improve-shumai-docs
docs: improve and restructure shumai documentation
2026-06-17 15:48:00 +08:00
Yiling-J 5f8067cbe8 Merge pull request #120 from shumaiOne/feat/replace-overflow-with-scrollarea
feat(webui): replace native overflow with shadcn ScrollArea in settings
2026-06-17 15:43:09 +08:00
yiling ae39a98e84 feat(webui): replace native overflow with shadcn ScrollArea in settings 2026-06-17 15:41:43 +08:00
Yiling-J 0944f1ad8e Merge pull request #119 from shumaiOne/feat/ui-system-colors
feat(webui): replace hardcoded colors with system tokens
2026-06-17 15:23:46 +08:00
yiling 812a8b3b88 feat(webui): replace hardcoded colors with system tokens in settings components 2026-06-17 15:22:46 +08:00
yiling 24a2f74035 update ui 2026-06-17 11:54:42 +08:00
yiling 73d02bf319 docs: convert screenshots to webp and update documentation 2026-06-17 11:37:48 +08:00
yiling 6e98d6ee4a docs: document collection creation from search dialog and dragging assets to share links 2026-06-16 16:34:43 +08:00
yiling af381ff99c docs: update notifications and metadata documentation to match UI/API configurations 2026-06-16 16:27:11 +08:00
yiling c9da7794d9 docs: explain team member visibility scopes and role overrides 2026-06-16 15:51:35 +08:00
yiling 1fb03cd852 docs: describe unified team and project members dialog 2026-06-16 15:45:59 +08:00
yiling 74fff87a2b docs: describe search filter dialog and drag reorder rules 2026-06-16 15:33:33 +08:00
yiling 3af5940ddf docs: update version stack creation workflows 2026-06-16 15:21:10 +08:00
yiling 3bb44041d7 docs: rename upload to asset management and add delete and clipboard paste docs 2026-06-16 15:13:26 +08:00
yiling 29b7124f48 docs: move temporal deployment guide to separate advanced deployment section 2026-06-16 14:56:38 +08:00
yiling 718f50ef10 docs: add temporal deploy guide and link from quickstart 2026-06-16 14:53:03 +08:00
yiling 006774042a docs: refine documentation to be user-oriented and remove database jargon 2026-06-16 14:44:42 +08:00
yiling 2b058bde40 docs: remove legacy introduction and docker docs 2026-06-16 14:39:04 +08:00
yiling fc6ad20329 docs: improve and restructure shumai documentation 2026-06-16 12:15:53 +08:00
Yiling-J 7e5735f0cc Merge pull request #116 from shumaiOne/feat/concurrency-control
feat(workflow): configure transcode and agent concurrency via environment variables
2026-06-16 10:46:45 +08:00
yiling 6e74ede9fe fix(workflow): validate concurrency limits and fallback to defaults on invalid or non-positive values 2026-06-16 10:40:39 +08:00
yiling b8d876d28e feat(workflow): allow configuring transcode and agent concurrency via environment variables 2026-06-16 10:24:45 +08:00
Yiling-J 95984f19b1 Merge pull request #115 from shumaiOne/refactor/transcode-service-and-api-flattening
refactor(transcode): relocate TranscodeService to core and flatten API package
2026-06-16 09:58:25 +08:00
yiling 5111fcd6a5 refactor(transcode): address code review feedback on imports and dataFormatNames typing 2026-06-16 09:53:28 +08:00
yiling f16a8a7069 refactor(transcode): relocate TranscodeService to core and flatten API package 2026-06-16 09:47:27 +08:00
Yiling-J 7f6e41708a Merge pull request #114 from shumaiOne/fix/video-player-carousel-change
fix(webui): reload video player and reset state when switching assets
2026-06-16 09:35:23 +08:00
yiling 6fa69d3310 fix(webui): use fileData?.id as reset dependency to prevent loading race conditions 2026-06-16 09:25:40 +08:00
yiling 7c5f462ba5 fix(webui): reload video player and reset state when switching assets 2026-06-16 09:21:56 +08:00
yiling 5d778f1b43 Release v0.0.6 2026-06-15 23:28:18 +08:00
Yiling-J 6027c2c21c Merge pull request #113 from shumaiOne/fix/video-player-mime-type
fix(webui): force video-player mime type to video/mp4
2026-06-15 23:23:57 +08:00
yiling d0931b7181 fix(webui): force video-player mime type to video/mp4 for transcode compatibility 2026-06-15 23:17:44 +08:00
yiling 2220d35e40 regenerate providers 2026-06-15 22:42:11 +08:00
Yiling-J bbf55e22da Merge pull request #112 from shumaiOne/fix/optimize-reorder-query
fix(webui): avoid refetching all pages on file/folder reorder
2026-06-15 22:20:26 +08:00
yiling 68d0830d05 fix(webui): resolve drag-and-drop cross-row reordering layout shift 2026-06-15 22:13:46 +08:00
yiling 2858274e52 fix(core): inherit sortIndex when creating version stack container 2026-06-15 20:38:46 +08:00
yiling 45318d1eec fix(core): correctly query nextAsset for afterIndex reordering 2026-06-15 20:25:49 +08:00
yiling e8e04edfee fix(webui): address code review feedback for updateLocalCache 2026-06-15 19:57:02 +08:00
yiling cf2546c861 migration(db): add C collation to sort_index column 2026-06-15 19:51:59 +08:00
yiling 1f640ede19 test(core): add test reproducing fractional indexing collation mismatch 2026-06-15 19:33:51 +08:00
yiling 3b4751bcb2 fix(webui): avoid refetching all pages on file/folder reorder 2026-06-15 19:20:45 +08:00
Yiling-J d766edbbd0 Merge pull request #111 from shumaiOne/feat/file-detail-sidebar-carousel
feat(webui): always show right sidebar and implement left vertical carousel
2026-06-15 16:45:58 +08:00
yiling 673041e28a feat(webui): support responsive layout and transparent bg for left sidebar carousel 2026-06-15 16:35:34 +08:00
yiling eabf49f6e3 fix(webui): use callback ref for image viewer to ensure ResizeObserver setup during file type switches 2026-06-15 16:14:30 +08:00
yiling f226bc74c6 feat(webui): render bottom bar for all file types and layout carousel above it 2026-06-15 16:02:18 +08:00
yiling 2159ddfeb5 style(webui): refine carousel item sizes, active states, and background colors 2026-06-15 15:51:23 +08:00
yiling 813c003a10 style(webui): transparent carousel background, hidden scrollbar, and 60x60px active items 2026-06-15 15:45:18 +08:00
yiling 720710dbbf fix(webui): move carousel hooks before early returns to satisfy React Hook rules 2026-06-15 15:39:10 +08:00
yiling 68a1714e7f feat(webui): always show right sidebar and implement left vertical carousel 2026-06-15 15:37:10 +08:00
Yiling-J d8aaed5212 Merge pull request #110 from shumaiOne/fix/mention-agents-file-list
refactor(webui): fetch agents in mention input list dynamically
2026-06-15 11:35:32 +08:00
yiling 60c499c153 refactor(webui): fetch agents in mention input list dynamically 2026-06-15 11:30:49 +08:00
Yiling-J a9c6686843 Merge pull request #109 from shumaiOne/feat/sandbox-pending-domains
feat(sandbox): add pending domains support for network sandbox
2026-06-15 11:03:32 +08:00
yiling c2f6c85194 fix(agent): remove port from sandbox pendingDomains to match allowedDomains format 2026-06-15 10:52:53 +08:00
yiling 8e012f9353 fix(agent): reset SandboxManager before initializing to ensure fresh config for every session 2026-06-15 10:36:01 +08:00
yiling c55abbf724 fix(webui): prevent overflow on long domain names in sandbox settings 2026-06-15 09:34:36 +08:00
yiling e9e096ac9e feat(sandbox): reject blocked request on bash tool result 2026-06-15 09:28:11 +08:00
yiling 6a63e99044 feat(sandbox): add pending domains support for network sandbox 2026-06-15 00:01:55 +08:00
Yiling-J 9c3b808809 Merge pull request #108 from shumaiOne/fix/player-seekbar-drag-color
fix(player): implement seekbar dragging and match hover highlight color
2026-06-14 22:47:51 +08:00
yiling c6387dd4ef fix(player): implement seekbar dragging and match hover highlight color 2026-06-14 22:42:55 +08:00
Yiling-J a1dfc8b4f9 Merge pull request #107 from shumaiOne/feat/smooth-progress-bar
refactor(webui): use requestAnimationFrame for smooth video progress bar updates
2026-06-14 21:11:31 +08:00
yiling 443b099e12 refactor(webui): move onTimeUpdate out of requestAnimationFrame loop
Moves the onTimeUpdate callback back into the native low-frequency timeupdate handler to avoid parent performance degradation, and removes it from the requestAnimationFrame loop and useEffect dependency array.
2026-06-14 21:06:39 +08:00
yiling e9e9be71f4 refactor(webui): use requestAnimationFrame for smooth video progress bar updates
Updates the progress bar currentTime and progress state on requestAnimationFrame loops when playing, while keeping timeupdate as a fallback when paused.
2026-06-14 21:01:15 +08:00
Yiling-J 3ae74d6417 Merge pull request #106 from shumaiOne/refactor/video-player-system-colors
refactor(webui): use system color design tokens in video player components
2026-06-14 20:46:46 +08:00
yiling 821de71719 fix(webui): remove debug console.log from GuestIdentityPopup 2026-06-14 20:25:43 +08:00
yiling cbc0a7960d refactor(webui): use system color design tokens in video player components 2026-06-14 19:47:00 +08:00
Yiling-J 0e2384627d Merge pull request #105 from shumaiOne/docs/improve-readme-deployment-temporal
docs(readme): improve remote deployment and temporal execution instructions
2026-06-14 19:34:57 +08:00
yiling 0a0a8f973d docs(readme): add FFmpeg prerequisites and WORKFLOW_EXECUTOR env variable 2026-06-14 17:21:46 +08:00
yiling fc3baede99 docs(readme): correct S3 endpoint environment variable names 2026-06-14 16:20:55 +08:00
Yiling-J ca31ef02fd Change header level for Shumai Agent section 2026-06-14 16:10:25 +08:00
yiling 2824377600 docs(readme): add Agent Sandbox platform support and OS dependencies details 2026-06-14 16:06:35 +08:00
Yiling-J f285b9e327 Update README with website and documentation links
Added links to website, documentation, and demo in the README.
2026-06-14 15:24:58 +08:00
yiling 42d89eb88d docs(readme): add worker network and region proximity recommendations 2026-06-14 15:18:31 +08:00
Yiling-J 8d8eeaaf47 Update README for clarity and consistency 2026-06-14 15:10:09 +08:00
yiling 8c55897d80 refactor(auth): remove BETTER_AUTH_URL configuration and set a default baseURL fallback 2026-06-14 15:01:44 +08:00
yiling 1790149986 docs(readme): improve remote deployment and temporal execution instructions 2026-06-14 11:04:04 +08:00
Yiling-J 88e5440d5c Merge pull request #104 from shumaiOne/fix/temporal-transcode-retry
fix(transcode): make deterministic transcode activity failures non-retryable in Temporal
2026-06-14 10:39:38 +08:00
yiling d687ea495b fix(transcode): make deterministic transcode activity failures non-retryable in Temporal 2026-06-14 10:00:13 +08:00
Yiling-J e437cdfeaf Merge pull request #103 from shumaiOne/docs/add-readme
docs(readme): add comprehensive README.md
2026-06-13 22:34:32 +08:00
yiling 0294056ad9 docs(readme): clarify background worker requirements in temporal mode 2026-06-13 17:56:30 +08:00
yiling 5cf949abc0 docs(readme): update temporal setup to use curl instead of cd 2026-06-13 17:50:22 +08:00
yiling e21d419bfe docs(readme): update screenshot.webp and remove screenshot.png 2026-06-13 17:47:26 +08:00
yiling 4159c0737c docs(readme): convert screenshot.png to webp format and reference it 2026-06-13 17:44:45 +08:00
yiling 9a2bf1deaf docs(readme): use pre-rendered rounded logo with width 65 2026-06-13 17:30:54 +08:00
yiling 1a43fad77b docs(readme): update logo styling, docker instructions, and env example 2026-06-13 14:21:56 +08:00
yiling b5fb378cf8 docs(readme): add comprehensive README.md 2026-06-13 13:26:42 +08:00
Yiling-J 782316ca97 Merge pull request #102 from shumaiOne/fix/wrapper-cleanup-on-kill
fix(build): propagate termination signals to active child process in wrappers
2026-06-13 12:58:23 +08:00
yiling e5084cc8b3 fix(build): propagate termination signals to active child process in wrappers 2026-06-13 12:51:30 +08:00
yiling 02b009fbe1 Release v0.0.5 2026-06-13 10:32:59 +08:00
Yiling-J 6dcd08ae3a Merge pull request #101 from shumaiOne/feat/npm-auto-migration
feat(npm): auto deploy database migrations on package start
2026-06-13 10:27:11 +08:00
yiling d230a1fd4a feat(npm): add dotenv loading and fix variable interpolation in wrapper 2026-06-13 10:21:36 +08:00
yiling 210ed5f95a feat(npm): auto deploy database migrations on package start 2026-06-13 09:24:54 +08:00
yiling edd550b9f2 Release v0.0.4 2026-06-12 22:02:39 +08:00
Yiling-J ea71954deb Merge pull request #100 from shumaiOne/fix/npm-external-resolution
fix(cli/docker): resolve global CLI external dependencies and fix Docker 404 error
2026-06-12 21:56:22 +08:00
yiling dc63ab3eaf fix(npm): resolve binary output path mapping in build-npm script 2026-06-12 21:54:15 +08:00
yiling d06dfc0ab3 perf(npm): optimize platform binary compilation using dummy runner 2026-06-12 21:50:18 +08:00
yiling 84aa1662be fix(docker): align build output structure and fix web 404 error 2026-06-12 21:24:59 +08:00
yiling 91fedf1477 fix(cli): resolve all external module imports in global CLI package 2026-06-12 21:08:40 +08:00
yiling b0dbb56493 Release v0.0.3 2026-06-12 20:42:52 +08:00
Yiling-J f6a0577585 Merge pull request #99 from shumaiOne/fix/npm-binary-lookup
fix(cli): resolve platform binary path resolution under nested node_modules
2026-06-12 20:36:11 +08:00
yiling 1fee0f5a97 fix(cli): resolve platform binary path resolution under nested node_modules 2026-06-12 20:34:07 +08:00
2079 changed files with 89603 additions and 33601 deletions
+2
View File
@@ -1,4 +1,6 @@
node_modules
dist
data
Dockerfile*
docker-compose*
.dockerignore
+2 -1
View File
@@ -1 +1,2 @@
src/generated/** linguist-generated
packages/db/src/generated/** linguist-generated
packages/webui/paraglide/** linguist-generated
+115 -3
View File
@@ -46,6 +46,118 @@ jobs:
- name: Test Local Release
run: |
bun run release:local --skip-check --out /tmp/shumai-local-release --force
cd /tmp/shumai-local-release/node
npx shumai-agent
npx shumai-transcode
echo "Smoke testing shumai..."
bun run /tmp/shumai-local-release/node/node_modules/@shumai-one/shumai/bin/shumai-app.js --check
echo "Smoke testing shumai-agent..."
bun run /tmp/shumai-local-release/node/node_modules/@shumai-one/shumai-agent/bin/shumai-agent-app.js --check
echo "Smoke testing shumai-transcode..."
bun run /tmp/shumai-local-release/node/node_modules/@shumai-one/shumai-transcode/bin/shumai-transcode-app.js --check
e2e_video_player:
name: Harness E2E (${{ matrix.project }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
project: chromium
- os: ubuntu-latest
project: firefox
# WebKit is the Safari engine; run it on a macOS runner to validate
# Safari compatibility.
- os: macos-latest
project: webkit
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: latest
- name: Install dependencies
run: bun install
- name: Install Playwright browser (${{ matrix.project }})
run: bunx playwright install --with-deps ${{ matrix.project }}
- name: Run video player harness tests
env:
E2E_SKIP_APP_SERVER: true
run: bun run test:e2e --project=harness-${{ matrix.project }}
- name: Upload Playwright report
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v4
with:
name: playwright-report-harness-${{ matrix.project }}
path: playwright-report/
retention-days: 7
e2e_app:
name: App E2E (${{ matrix.project }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
project: chromium
- os: ubuntu-latest
project: firefox
# App E2E needs Docker for testcontainers, run webkit on Ubuntu
- os: ubuntu-latest
project: webkit
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: latest
- name: Install dependencies
run: bun install
- name: Install Playwright browser (${{ matrix.project }})
run: bunx playwright install --with-deps ${{ matrix.project }}
- name: Run app E2E tests
run: bun run test:e2e --project=app-${{ matrix.project }} --no-deps
- name: Upload Playwright report
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v4
with:
name: playwright-report-app-${{ matrix.project }}
path: playwright-report/
retention-days: 7
workflow_e2e:
name: Workflow E2E
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: latest
- name: Install dependencies
run: bun install
- name: Install system dependencies
run: |
sudo apt-get update
sudo apt-get install -y ripgrep bubblewrap socat ffmpeg
- name: Run Workflow E2E Tests
run: bun run test:e2e:workflow
+11 -1
View File
@@ -27,12 +27,22 @@ jobs:
username: shumaione
password: ${{ secrets.DOCKERHUB_TOKEN }}
# Log in to Aliyun ACR
- name: Log in to Aliyun ACR
uses: docker/login-action@v3
with:
registry: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com
username: njjyl723
password: ${{ secrets.ALI_ACR_TOKEN }}
# Extract metadata (tags, labels) for Docker
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v5
with:
images: shumaione/shumai
images: |
shumaione/shumai
crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai
tags: |
type=semver,pattern={{version}}
type=ref,event=branch
+6
View File
@@ -11,3 +11,9 @@ data/
*.db
*.diff
*.orig
# Playwright
/playwright-report/
/test-results/
/blob-report/
/playwright/.cache/
+5 -1
View File
@@ -2,4 +2,8 @@ node_modules
dist
.bun
src/generated
src/ui/components/ui
packages/db/src/generated
src/ui/components/ui
packages/webui/paraglide
*.md
**/*.md
+66 -1
View File
@@ -90,6 +90,8 @@ Add any additional context, caveats, or follow-up work.
- `bun run format`
- `bun run typecheck`
- `bun run test`
- `bun run test:e2e`
- `bun run test:e2e:workflow`
- **Backend Testing Mandate**: Every backend feature, service method, workflow, and activity MUST be accompanied by comprehensive tests. Logic-heavy code without corresponding test coverage is considered incomplete.
@@ -196,10 +198,15 @@ The frontend is built with:
- **Prefer System Colors**: Always prefer using semantic system color design tokens (e.g., `bg-background`, `text-foreground`, `text-sidebar-primary`, `text-muted-foreground`, etc.) over hardcoded color utilities (e.g., `bg-blue-50`, `text-emerald-600`, `bg-emerald-500`). This ensures seamless compatibility with light and dark themes.
### Route Code-Splitting
To optimize initial bundle size, all routes must be code-split into `[route].tsx` (lightweight route definition and loaders) and `[route].lazy.tsx` (UI component and heavy imports).
### Development
- **Run Dev**: `bun run dev` (Runs on port 3000)
## Testing
We use **Vitest** for testing (via `bun run test`). **Do not use `bun test`** as it uses Bun's native test runner which is not compatible with this project's test suite.
@@ -244,7 +251,7 @@ The `bunfig.toml` is configured to run `setup-tests.ts` automatically as a prelo
### API Tests
- Located in `packages/api/src/api/**/*.test.ts`.
- Located in `packages/api/src/**/*.test.ts`.
- Mock the Service layer using `vi.spyOn(service, 'method')` or `vi.mock('@shumai/core/src/team/team')`.
- Verify that the API calls the Service methods correctly.
@@ -267,6 +274,14 @@ describe('Team API', () => {
})
```
### Workflow E2E Tests
- Located in `packages/e2e/workflow/**/*.test.ts`.
- Run via `bun run test:e2e:workflow` (which executes tests against both `local` and `temporal` executors dynamically).
- **Mandatory test coverage**: When creating or updating workflows or activities, you MUST create or update the corresponding E2E tests.
- **Mocking**: Mock ONLY AI API calls. Do not mock S3, databases, or media/transcode extraction services.
- Mock the AI response by spying on `AgentHarness.prototype.prompt`:
## Prisma Configuration & Migrations
- Schema: `packages/db/prisma/schema.prisma`
@@ -299,6 +314,7 @@ We use `prisma-json-types-generator` to enforce strict type-safety for Prisma `J
- Development: Use `bun --bun run prisma migrate dev` to create and apply migrations during development.
- Production: Use `bun --bun run prisma migrate deploy` to apply pending migrations in production environments.
- **No Automatic Dev DB Reset**: Do not run `prisma migrate reset --force` or commands that force-reset the database automatically. If migrations become out of sync or a reset is required, stop executing, report the situation to the user, and present suggested manual cleanup/reset steps for the user to execute.
### Commands
@@ -396,6 +412,7 @@ To prevent Temporal from indefinitely retrying fatal, expected business validati
## Radix UI / Shadcn UI Patterns
- **Modal Overlays**: When triggering a dialog (e.g., `Dialog`, `AlertDialog`) from inside a `DropdownMenu`, you must set `modal={false}` on the `<DropdownMenu>` component. Failing to do so will cause the UI to freeze due to conflicting focus management between the two modal components.
- **Scrollable Content**: Always use the Shadcn `ScrollArea` component (`@/ui/components/ui/scroll-area`) for scrollable content containers to ensure consistent custom scrollbar UI across the application.
## Logging
@@ -407,3 +424,51 @@ We use **pino** for logging. Always use **structured logging** to ensure logs ar
logger.info({ userId: user.id, projectId }, 'Project deleted successfully')
```
- **Levels**: Use appropriate levels: `debug`, `info`, `warn`, `error`.
## Internationalization (i18n)
All user-facing text in the WebUI (`packages/webui`) MUST be internationalized using **Paraglide JS**. Hardcoded text in UI components is strictly forbidden.
### Message Definition
1. Define your English message strings in [packages/webui/messages/en.json](packages/webui/messages/en.json).
2. Define the corresponding Chinese translation strings in [packages/webui/messages/zh.json](packages/webui/messages/zh.json).
3. Keys should use `snake_case`.
Example (`en.json`):
```json
{
"my_key": "My English Text"
}
```
### Compilation
When you add or update translation keys, you must compile them to regenerate the type-safe functions:
```bash
# Compile once (generates type-safe TS/JS functions on disk)
bun run i18n:compile
# Watch and recompile on change during development
bun run i18n:watch
```
### Usage in Components
Import the compiled message namespace `m` and call it as a function:
```typescript
import { m } from '@/ui/paraglide/messages.js'
export function MyComponent() {
return (
<div>
<h1>{m.my_key()}</h1>
</div>
)
}
```
Always use the absolute workspace alias path `@/ui/paraglide/messages.js` (or `runtime.js` for runtime features) when importing Paraglide outputs.
+10 -1
View File
@@ -1,3 +1,4 @@
#syntax=docker/dockerfile:1.7-labs
# Stage 1: Builder
FROM oven/bun:1 AS builder
@@ -47,6 +48,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
socat \
ca-certificates \
bubblewrap \
gosu \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
@@ -69,5 +71,12 @@ COPY --chown=bun:bun --from=builder /app/prisma.config.ts.prod ./prisma.config.t
# Expose port (Bun Hono defaults to 3000)
EXPOSE 3000
# Switch back to root at the end so the container runs the entrypoint as root
USER root
COPY scripts/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
ENTRYPOINT ["docker-entrypoint.sh"]
# Default command: run migrations and start API server
CMD ["sh", "-c", "bun prisma migrate deploy && bun apps/web/src/index.js"]
CMD ["sh", "-c", "bun prisma migrate deploy && bun index.js"]
+296
View File
@@ -0,0 +1,296 @@
<p align="center">
<img src="docs/logo-rounded.png" alt="Shumai Logo" width="65" />
</p>
<h1 align="center">Shumai</h1>
<p align="center">
<strong>An open-source platform for all your creative work.</strong>
</p>
<p align="center">
<a target="_blank" href="https://shumai.one/">Website</a> | <a target="_blank" href="https://docs.shumai.one/introduction">Docs</a> | <a target="_blank" href="https://staging.shumai.one">Demo</a> | <a target="_blank" href="README_CN.md">中文</a>
</p>
![Shumai App Screenshot](docs/screenshot.webp)
## Features
- **S3-Compatible & Local Storage**: Securely store and serve your creative assets using a local filesystem or any S3-compatible cloud storage (AWS S3, Cloudflare R2, MinIO, etc.).
- **Frame-by-Frame Annotations & Comments**: Give precise feedback using frame-specific drawing tools and timestamped comments directly on video and image assets.
- **Secure Sharing & Collections**: Create secure public share links and curated media collections to collaborate with clients and stakeholders.
- **Granular Access Control**: Manage workspace permissions using team-level and project-level role-based access controls.
- **Distributed Transcoding via Temporal**: Offload resource-heavy video transcoding to a background worker pool orchestrated by Temporal.
- **Custom Asset Metadata**: Define and customize dynamic metadata fields tailored to your production pipeline.
#### Shumai Agent
- **Collaborative AI Chat**: Converse with a context-aware AI agent by using `@mentions` directly within the file's comments area.
- **Custom Skills & Tools**: Extend the agent's capabilities by registering custom scripts, tools, and automation skills.
- **Isolated Sandbox Execution**: Run agent-submitted scripts securely within a sandboxed environment.
- **AI Metadata Autofill**: Automatically autofill custom metadata for new assets.
- **Semantic Search**: Find assets based on visual or conceptual search queries using vector embeddings(Gemini Embedding 2).
> [!NOTE]
> **Media Processing & Storage:** When uploading media, Shumai always preserves and stores your original raw file. Note that the file size shown in the system represents the original file size and does not include the size of any transcoded files. For all media types (both images and videos), Shumai creates a 480p WebP poster image to serve as the preview in the file list view. Additionally:
> * **For Images:** Shumai generates a high-quality WebP proxy at the exact same resolution as your original file for optimized viewing.
> * **For Videos:** It generates at least one proxy video (depending on your transcoding settings), alongside a sprite image and a small preview video (capped at 1600 frames) to enable fast timeline scrubbing and lightning-quick previews.
---
## Installation
Below is a quickstart guide for running Shumai with local storage. For advanced configuration options (including S3-compatible storage and Temporal workflow orchestration), see our [Documentation](https://docs.shumai.one/getting-started/overview).
### Option 1: Docker Compose
Docker Compose is the fastest way to get Shumai running. You do not need to clone the repository or install packages manually. Ensure you have [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/) installed, then follow these steps:
1. Create and navigate to a new directory for your configuration and data volumes:
```bash
mkdir shumai && cd shumai
```
2. Download the `docker-compose.yaml` file:
```bash
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose.yaml
```
3. Configure environment variables (optional):
* `SHUMAI_SERVER_PORT` controls the port the Shumai server listens on. The default is `3000`.
* By default, Shumai uses the bundled local storage service in this Docker Compose setup. To use an external S3-compatible storage instead, configure the environment variables for your S3 provider. Here are examples for AWS S3 and Cloudflare R2:
**AWS S3 Example:**
```yaml
STORAGE_BACKEND: s3
S3_BUCKET: your-bucket-name
S3_ACCESS_KEY_ID: your-access-key-id
S3_SECRET_ACCESS_KEY: your-secret-access-key
AWS_ENDPOINT_URL_S3: https://s3.us-east-1.amazonaws.com
```
**Cloudflare R2 Example:**
```yaml
STORAGE_BACKEND: s3
S3_BUCKET: your-bucket-name
S3_REGION: auto
S3_ACCESS_KEY_ID: your-access-key-id
S3_SECRET_ACCESS_KEY: your-secret-access-key
AWS_ENDPOINT_URL_S3: https://<account-id>.r2.cloudflarestorage.com
```
* By default, `AWS_ENDPOINT_URL_S3` is set to: `http://localhost:{SHUMAI_SERVER_PORT}`, if you use local storage and expose Shumai on a custom host/port combination, set `AWS_ENDPOINT_URL_S3` to the external URL that browsers will use to upload files.
For example, if you change the port mapping in `docker-compose.yaml` from `3000:3000` to `12345:3000` and deploy on a server with IP address `12.34.56.78`, set:
```
AWS_ENDPOINT_URL_S3: http://12.34.56.78:12345
```
This value must be reachable from client browsers and should include the externally exposed port.
5. Start the services in detached mode:
```bash
docker compose up -d
```
6. Open your browser and access Shumai at `http://localhost:3000` (or `http://<your-server-ip>:3000` for remote deployments).
### Option 2: Install via NPM / Package Manager
Shumai is published as `@shumai-one/shumai` on NPM. This option allows you to run Shumai globally or locally.
#### Step 1: Start PostgreSQL with pgvector
Shumai requires PostgreSQL with the `pgvector` extension. Start a pre-configured database container using Docker:
```bash
docker run --name shumai_postgres \
-e POSTGRES_USER=shumai \
-e POSTGRES_PASSWORD=shumai_password \
-e POSTGRES_DB=shumai_db \
-p 5432:5432 \
-d pgvector/pgvector:pg18
```
#### Step 2: Create a workspace folder
Create a dedicated directory to store your environment configuration and media files (which are saved in a `./data` directory by default):
```bash
mkdir shumai && cd shumai
```
#### Step 3: Install Platform-Specific Dependencies
#### Linux
Shumai requires the following system packages on Linux:
- **`ffmpeg`** – Used for media transcoding and metadata extraction.
- **`bubblewrap`**, **`socat`**, and **`ripgrep`** – Required by the AI agent sandbox (`anthropic-experimental/sandbox-runtime`) for process isolation, networking, and workspace search.
Install all required packages with one command:
> Ubuntu/Debian
```bash
sudo apt install -y ffmpeg bubblewrap socat ripgrep
```
> Fedora
```bash
sudo dnf install -y ffmpeg bubblewrap socat ripgrep
```
> Arch Linux
```bash
sudo pacman -S --noconfirm ffmpeg bubblewrap socat ripgrep
```
> [!NOTE]
> **Ubuntu 24.04+** restricts unprivileged user namespaces by default. This prevents `anthropic-experimental/sandbox-runtime` from using `bubblewrap` for sandbox isolation.
>
> To temporarily allow user namespaces:
>
> ```bash
> sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
> ```
>
> Alternatively, configure an AppArmor profile that grants the required `userns` permission to the relevant binaries.
---
#### macOS
Shumai requires:
- **`ffmpeg`** – Used for media transcoding and metadata extraction.
- **`ripgrep`** – Required by the AI agent sandbox (`anthropic-experimental/sandbox-runtime`).
Install the required packages with Homebrew:
```bash
brew install ffmpeg ripgrep
```
---
#### Windows (alpha)
> [!WARNING]
> Windows support in anthropic-experimental/sandbox-runtime is **alpha and the design is in flux**.
>
> The current implementation provides:
> - Network egress filtering via the **Windows Filtering Platform (WFP)**.
> - File read/write denial via **ACL stamping**.
>
> However, it is **not a security boundary against a deliberately adversarial sandboxed process**.
>
> The sandbox implementation will be substantially revised in a future release, where sandboxed processes will run under a dedicated sandbox user account.
Shumai requires:
- **`ffmpeg`** – Used for media transcoding and metadata extraction.
Install `ffmpeg` using your preferred package manager:
**winget**
```powershell
winget install Gyan.FFmpeg
```
**Chocolatey**
```powershell
choco install ffmpeg
```
#### Step 4: Install Shumai globally
Install Shumai globally using your preferred package manager:
```bash
# NPM
npm install -g @shumai-one/shumai
# PNPM
pnpm add -g @shumai-one/shumai
# Bun
bun add -g @shumai-one/shumai
```
#### Step 5: Configure Environment Variables
Create a `.env` file in your workspace folder (`shumai/`) and add the following configuration:
```env
DATABASE_URL=postgresql://shumai:shumai_password@localhost:5432/shumai_db?schema=public
BETTER_AUTH_SECRET=ySxs7DxzHDZBbeeHNPEwBuspYwipBqz5Gk5XdBjNhWw=
STORAGE_BACKEND=local
SHUMAI_SERVER_PORT=3000
AWS_ENDPOINT_URL_S3=http://localhost:3000
```
> [!NOTE]
> `SHUMAI_SERVER_PORT` sets the port the server starts on, while `AWS_ENDPOINT_URL_S3` is used by the browser to build file upload URLs.
> If deploying on a remote server (e.g. `http://123.456.7.8`) with a mapped port (e.g. `12345:3000` in docker-compose), set `AWS_ENDPOINT_URL_S3` to `http://123.456.7.8:12345`.
#### Step 6: Run Shumai
> [!IMPORTANT]
> **For Bun Users:** Since the published package binaries contain a `#!/usr/bin/env node` shebang, running the global command directly (e.g., `shumai`) will execute under Node.js. If you installed with Bun and want to run under the Bun runtime, you must prefix all commands with `bun run --bun` (e.g., `bun run --bun shumai`, `bun run --bun shumai -d`, `bun run --bun shumai stop`).
Start the application from your workspace folder:
```bash
shumai
```
Alternatively, you can run and manage Shumai in daemon mode:
- **Start in daemon mode**:
```bash
shumai -d
```
- **Stop Shumai**:
```bash
shumai stop
```
- **Restart Shumai**:
```bash
shumai restart
```
- **Show/tail logs**:
```bash
shumai logs
```
On startup, Shumai will automatically run database migrations and start the web server at `http://localhost:3000`.
---
### Option 3: Run from Source (Development)
To set up Shumai locally for development:
1. Clone the repository and install dependencies:
```bash
git clone https://github.com/shumaiOne/shumai.git
cd shumai
bun install
```
2. Start the `pgvector` database container (as described in **Option 2, Step 1**).
3. Create a `.env` file at the root of the workspace using the configuration from **Option 2, Step 5**.
4. Apply the database schema migrations:
```bash
bun run db:migrate
```
5. Start the local development server:
```bash
bun run dev
```
---
## Command Line Interface (CLI)
Shumai provides a Command Line Interface (CLI) tool to manage projects, folders, and assets, upload files/folders, and create new versions directly from your terminal.
For more details on installation and usage, see the [CLI Readme](apps/cli/README.md).
+334
View File
@@ -0,0 +1,334 @@
<p align="center">
<img src="docs/logo-rounded.png" alt="Shumai Logo" width="65" />
</p>
<h1 align="center">Shumai</h1>
<p align="center">
<strong>为创意工作打造的开源协作平台。</strong>
</p>
<p align="center">
<a target="_blank" href="https://shumai.one/">官方网站</a> | <a target="_blank" href="https://docs.shumai.one/introduction">文档</a> | <a target="_blank" href="https://staging.shumai.one">在线演示</a> | <a target="_blank" href="README.md">English</a>
</p>
</p>
![Shumai 应用截图](docs/screenshot.webp)
## 功能特性
- **兼容 S3 与本地存储**:支持使用本地文件系统或任意兼容 S3 协议的对象存储(AWS S3、Cloudflare R2、MinIO 等)安全存储和访问你的创意资产。
- **逐帧标注与评论**:可直接在图片和视频上进行逐帧绘制标注,并结合时间戳评论,实现精准反馈与协作。
- **安全分享与媒体合集**:支持创建安全的公开分享链接和精心组织的媒体合集,方便与客户及团队成员协同沟通。
- **细粒度权限控制**:基于团队和项目两级角色权限(RBAC),灵活管理工作区访问权限。
- **基于 Temporal 的分布式转码**:将高负载的视频转码任务交由 Temporal 调度的后台 Worker 集群处理,提升系统扩展性与处理效率。
- **自定义资产元数据**:支持定义和扩展动态元数据字段,灵活适配你的制作流程。
#### Shumai Agent
- **协作式 AI 对话**:在文件评论区通过 `@mention` 即可唤起具备上下文感知能力的 AI Agent,参与讨论与协作。
- **自定义技能与工具**:支持为 Agent 注册自定义脚本、工具和自动化技能,扩展其能力边界。
- **隔离沙箱执行**:Agent 提交的脚本会在安全隔离的沙箱环境中运行,保障执行安全。
- **AI 自动填充元数据**:为新上传的资产自动生成并填写自定义元数据。
- **语义搜索**:基于向量进行搜索(Gemini Embedding 2),支持按视觉内容或语义概念搜索资产。
> [!NOTE]
> **媒体处理与存储机制:** 上传媒体文件后,Shumai 始终会保留并存储原始文件。请注意,系统中显示的文件大小为原始文件的大小,不包含转码后生成的代理文件大小。无论图片还是视频,都会额外生成一张 480p 的 WebP 封面图,作为文件列表中的预览图。此外:
>
> * **图片:** 会生成一份与原图分辨率完全一致的高质量 WebP 转码版本,在保证画质的同时提升浏览性能。
> * **视频:** 会根据转码配置生成至少一个代理视频,同时生成雪碧图(Sprite)和一段最长 1600 帧的低分辨率转码视频,用于实现快速拖动时间轴和即时视频预览。
---
## 安装指南
以下是使用本地存储运行 Shumai 的快速上手指南。如需了解高级配置(包括 S3 兼容存储配置、Temporal 工作流编排等),请参阅我们的[官方文档](https://docs.shumai.one/getting-started/overview)。
### 方案一:使用 Docker Compose(推荐)
使用 Docker Compose 是运行 Shumai 最快的方式。您无需克隆仓库,也不需要手动安装依赖包。请确保电脑上已安装 [Docker](https://docs.docker.com/get-docker/) 和 [Docker Compose](https://docs.docker.com/compose/install/),然后按照以下步骤操作:
1. 创建并进入一个新目录,用于存放配置文件和数据卷:
```bash
mkdir shumai && cd shumai
```
2. 下载 `docker-compose.yaml` 配置文件:
```bash
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose-aliyun.yaml
```
3. 配置环境变量(可选):
* `SHUMAI_SERVER_PORT` 用于控制 Shumai 服务监听的端口,默认值为 `3000`。
* 默认情况下,该 Docker Compose 部署会自动启用集成的本地存储。若想切换至外部 S3 兼容存储,请在 `environment` 中配置 S3 提供商的环境变量。以下是 AWS S3 和 Cloudflare R2 的配置示例:
**AWS S3 示例:**
```yaml
STORAGE_BACKEND: s3
S3_BUCKET: your-bucket-name
S3_ACCESS_KEY_ID: your-access-key-id
S3_SECRET_ACCESS_KEY: your-secret-access-key
AWS_ENDPOINT_URL_S3: https://s3.us-east-1.amazonaws.com
```
**Cloudflare R2 示例:**
```yaml
STORAGE_BACKEND: s3
S3_BUCKET: your-bucket-name
S3_REGION: auto
S3_ACCESS_KEY_ID: your-access-key-id
S3_SECRET_ACCESS_KEY: your-secret-access-key
AWS_ENDPOINT_URL_S3: https://<account-id>.r2.cloudflarestorage.com
```
* 默认情况下 `AWS_ENDPOINT_URL_S3` 指向 `http://localhost:{SHUMAI_SERVER_PORT}`。如果您使用本地存储,但希望在自定义的主机名或端口上公开访问 Shumai,请务必将 `AWS_ENDPOINT_URL_S3` 修改为浏览器访问该服务时所使用的外部 URL。
例如,如果您将 `docker-compose.yaml` 中的端口映射从 `3000:3000` 修改为了 `12345:3000`,且服务部署在 IP 为 `12.34.56.78` 的服务器上,请进行如下设置:
```
AWS_ENDPOINT_URL_S3: http://12.34.56.78:12345
```
此地址必须能够从客户端浏览器正常访问,且必须包含对外暴露的实际端口号。
4. 在后台启动所有服务:
```bash
docker compose up -d
```
5. 打开浏览器,访问 `http://localhost:3000` 即可开始使用(若是远程部署,请访问 `http://<您的服务器IP>:3000`)。
### 方案二:通过 NPM / 包管理器安装
通过 NPM 上的 `@shumai-one/shumai` 进行安装。
#### 第一步:启动带 pgvector 支持的 PostgreSQL
Shumai 依赖支持 `pgvector` 扩展的 PostgreSQL 数据库。您可以使用 Docker 快速启动一个预配置好的数据库容器:
```bash
docker run --name shumai_postgres \
-e POSTGRES_USER=shumai \
-e POSTGRES_PASSWORD=shumai_password \
-e POSTGRES_DB=shumai_db \
-p 5432:5432 \
-d docker.m.daocloud.io/pgvector/pgvector:pg18
```
#### 第二步:创建工作区目录
创建一个专属目录用来存放环境配置和媒体文件(媒体文件默认会保存在 `./data` 目录下):
```bash
mkdir shumai && cd shumai
```
#### 步骤 3:安装平台依赖
#### Linux
在 Linux 上运行 Shumai 需要安装以下系统依赖:
- **`ffmpeg`** —— 用于媒体转码和元数据提取。
- **`bubblewrap`**、**`socat`** 和 **`ripgrep`** —— AI Agent 沙箱(`anthropic-experimental/sandbox-runtime`)所需,用于进程隔离、网络通信和工作区搜索。
可以使用以下命令一次性安装所有依赖:
> Ubuntu/Debian
```bash
sudo apt install -y ffmpeg bubblewrap socat ripgrep
```
> Fedora
```bash
sudo dnf install -y ffmpeg bubblewrap socat ripgrep
```
> Arch Linux
```bash
sudo pacman -S --noconfirm ffmpeg bubblewrap socat ripgrep
```
> [!NOTE]
> **Ubuntu 24.04+** 默认限制非特权用户创建 User Namespace,这会导致 `anthropic-experimental/sandbox-runtime` 无法使用 `bubblewrap` 提供沙箱隔离。
>
> 如需临时启用 User Namespace,请执行:
>
> ```bash
> sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
> ```
>
> 或者,配置 AppArmor Profile,为相关可执行文件授予所需的 `userns` 权限。
---
#### macOS
在 macOS 上运行 Shumai 需要:
- **`ffmpeg`** —— 用于媒体转码和元数据提取。
- **`ripgrep`** —— AI Agent 沙箱(`anthropic-experimental/sandbox-runtime`)所需。
使用 Homebrew 安装所需依赖:
```bash
brew install ffmpeg ripgrep
```
---
#### Windows(Alpha)
> [!WARNING]
> anthropic-experimental/sandbox-runtime 的 Windows 支持目前仍处于 **Alpha** 阶段,整体设计仍在持续调整中。
>
> 当前实现提供了以下能力:
> - 通过 **Windows Filtering Platform (WFP)** 实现网络出口(egress)过滤。
> - 通过 **ACL Stamping** 实现文件读写权限限制。
>
> **但这并不能作为针对恶意沙箱进程的安全边界(security boundary)**。
>
> 未来版本将对沙箱机制进行重大调整,届时沙箱进程将运行在独立的沙箱用户账户下。
在 Windows 上运行 Shumai 需要:
- **`ffmpeg`** —— 用于媒体转码和元数据提取。
使用你偏好的包管理器安装 `ffmpeg`:
**winget**
```powershell
winget install Gyan.FFmpeg
```
**Chocolatey**
```powershell
choco install ffmpeg
```
#### 第四步:全局安装 Shumai
使用您常用的包管理器进行全局安装:
```bash
# 使用 NPM
npm install -g @shumai-one/shumai
# 使用 PNPM
pnpm add -g @shumai-one/shumai
# 使用 Bun
bun add -g @shumai-one/shumai
```
#### 第五步:配置环境配置
在刚才创建的工作区目录(`shumai/`)下新建一个 `.env` 文件,并填入以下配置:
```env
DATABASE_URL=postgresql://shumai:shumai_password@localhost:5432/shumai_db?schema=public
BETTER_AUTH_SECRET=ySxs7DxzHDZBbeeHNPEwBuspYwipBqz5Gk5XdBjNhWw=
STORAGE_BACKEND=local
SHUMAI_SERVER_PORT=3000
AWS_ENDPOINT_URL_S3=http://localhost:3000
```
> [!NOTE]
> `SHUMAI_SERVER_PORT` 用于设置 Web 服务的启动端口,而 `AWS_ENDPOINT_URL_S3` 供浏览器端构建文件上传链接。
> 如果您部署在远程服务器(如 `http://123.456.7.8`)并且做了端口映射(如 Docker 中的 `12345:3000`),请将 `AWS_ENDPOINT_URL_S3` 设置为 `http://123.456.7.8:12345`。
#### 第六步:启动 Shumai
> [!IMPORTANT]
> **Bun 用户特别提示:** 由于发布的包二进制文件包含 `#!/usr/bin/env node` 头部声明(Shebang),直接在终端执行全局命令(例如 `shumai`)默认会通过 Node.js 运行。如果您是用 Bun 安装的并且希望调用 Bun 运行时,请在所有命令前加上 `bun run --bun` 前缀(例如:`bun run --bun shumai`、`bun run --bun shumai -d`、`bun run --bun shumai stop`)。
在您的工作区目录下执行以下命令启动应用:
```bash
shumai
```
您也可以让 Shumai 在后台以守护进程(Daemon)模式运行和管理:
* **后台模式启动**:
```bash
shumai -d
```
* **停止服务**:
```bash
shumai stop
```
* **重启服务**:
```bash
shumai restart
```
* **查看并跟踪实时日志**:
```bash
shumai logs
```
启动时,Shumai 会自动执行数据库迁移(Migration)并在 `http://localhost:3000` 拉起 Web 服务。
---
### 方案三:源码编译运行(开发环境)
如果您希望在本地参与 Shumai 的开发,请按以下步骤配置开发环境:
1. 克隆代码仓库并安装依赖项:
```bash
git clone [https://github.com/shumaiOne/shumai.git](https://github.com/shumaiOne/shumai.git)
cd shumai
bun install
```
2. 启动 `pgvector` 数据库容器(参考**方案二中的第一步**)。
3. 参照**方案二中的第五步**,在项目根目录下创建一个 `.env` 文件。
4. 执行数据库结构迁移:
```bash
bun run db:migrate
```
5. 启动本地开发服务器:
```bash
bun run dev
```
---
## 命令行工具 (CLI)
Shumai 自带一个功能完备的命令行工具(CLI),支持您直接在终端里高效管理项目、文件夹、资产,批量上传文件/目录,以及快速创建新版本。
关于 CLI 的安装与详细使用指南,请参阅 [CLI Readme](https://www.google.com/search?q=apps/cli/README.md)。
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/agent-app",
"version": "0.0.2",
"version": "0.1.10",
"private": true,
"type": "module",
"bin": {
+7 -1
View File
@@ -4,6 +4,12 @@ loadEnvConfig(process.cwd(), process.env.NODE_ENV !== 'production')
import { workflowService } from '@shumai/workflow-core'
import { TaskQueueAgent } from '@shumai/workflow-core'
import { initAgentWorkflows } from '@shumai/agent'
import { handleDaemonCommands } from '@shumai/core/src/utils/daemon'
if (process.argv.includes('--check')) {
console.log('✅ Agent worker evaluated successfully!')
process.exit(0)
}
async function run() {
// Initialize workflows and activities
@@ -23,7 +29,7 @@ async function run() {
await workflowService.startWorkers(TaskQueueAgent, options)
}
run().catch((err) => {
handleDaemonCommands('shumai-agent', run).catch((err) => {
console.error(err)
process.exit(1)
})
+100
View File
@@ -0,0 +1,100 @@
# Shumai CLI
A Command Line Interface (CLI) tool for interacting with your Shumai instance.
The CLI allows you to view projects, list folder contents, create folders, upload files and directories, and create new versions of existing files directly from the terminal.
---
## Installation
The CLI package is bundled inside the Shumai workspace.
### Environment Setup
Before using the CLI, you must set the following environment variables to authenticate with your Shumai instance:
```bash
# The endpoint of your Shumai API server (e.g. http://localhost:3000)
export SHUMAI_API_SERVER="http://localhost:3000"
# Your personal API Token (Generate this in the WebUI via Settings -> Developer tab)
export SHUMAI_API_KEY="your-developer-api-token"
```
---
## Usage
> [!IMPORTANT]
> **For Bun Users:** Since the package binary contains a `#!/usr/bin/env node` shebang, running `shumai-cli` directly will run under Node.js. If you wish to run it using Bun, prefix the command with `bun run --bun` (e.g., `bun run --bun shumai-cli project ls`).
Run `shumai-cli` or query specific commands:
```bash
shumai-cli <command> [arguments] [options]
```
### Commands
#### 1. List Projects
List all projects you have access to. Returns the project ID, name, and its root folder ID.
```bash
shumai-cli project ls
```
#### 2. List Directory Contents
List direct children (folders and files) of a parent folder.
```bash
shumai-cli ls -p <parentId>
```
- **Options:**
- `-p`, `--parent <id>`: The parent folder ID (required).
#### 3. Create a New Folder
Create a new folder under a parent folder.
```bash
shumai-cli mkdir <name> -p <parentId>
```
- **Options:**
- `-p`, `--parent <id>`: The parent folder ID (required).
#### 4. Upload Files or Folders
Upload a local file or folder to a target parent folder. File sizes and paths are mapped, and uploads are streamed chunk-by-chunk with a progress bar.
```bash
shumai-cli upload <localPath> -p <parentId>
```
- **Options:**
- `-p`, `--parent <id>`: The parent folder ID (required).
#### 5. Create a New Version of a File
Upload a local file as a new version of an existing asset (which must be a file or a version stack). This wraps the assets into a version stack dynamically on the server.
```bash
shumai-cli create-version <localFilePath> -p <parentAssetId>
```
- **Options:**
- `-p`, `--parent <id>`: The parent asset ID (file or version stack) to version (required).
---
## Development
To run the CLI in development mode inside the repository source code:
```bash
bun run apps/cli/src/index.ts project ls
```
+17
View File
@@ -0,0 +1,17 @@
{
"name": "@shumai/cli",
"version": "0.1.10",
"private": true,
"type": "module",
"bin": {
"shumai-cli": "./src/index.ts"
},
"dependencies": {
"@shumai/api": "workspace:*",
"@shumai/core": "workspace:*",
"@shumai/dtos": "workspace:*",
"@shumai/tableprinter": "workspace:*",
"hono": "4.12.23",
"ulid": "^3.0.2"
}
}
+25
View File
@@ -0,0 +1,25 @@
import { hc } from 'hono/client'
import type { AppType } from '@shumai/api'
export function getClient() {
const apiKey = process.env.SHUMAI_API_KEY
const apiServer = process.env.SHUMAI_API_SERVER
if (!apiServer) {
console.error('Error: SHUMAI_API_SERVER environment variable is not set.')
process.exit(1)
}
if (!apiKey) {
console.error(
'Error: SHUMAI_API_KEY environment variable is not set. Please generate a token in the Settings -> Developer tab.',
)
process.exit(1)
}
return hc<AppType>(apiServer, {
headers: {
Authorization: `Bearer ${apiKey}`,
},
})
}
+364
View File
@@ -0,0 +1,364 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { projectLs } from './project'
import { ls } from './ls'
import { mkdir } from './mkdir'
import { getClient } from '../client'
import { upload } from './upload'
import { createVersion } from './create-version'
import fs from 'node:fs'
import http from 'node:http'
vi.mock('../client', () => ({
getClient: vi.fn(),
}))
vi.mock('node:http', () => ({
default: {
request: vi.fn(),
},
}))
describe('CLI Commands', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let logSpy: any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let writeSpy: any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let errorSpy: any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let exitSpy: any
const mockClient = {
api: {
projects: {
$get: vi.fn(),
':projectId': {
$get: vi.fn(),
},
},
folders: {
$post: vi.fn(),
':folderId': {
$get: vi.fn(),
children: {
$get: vi.fn(),
},
},
},
teams: {
':teamId': {
upload: {
tasks: {
$post: vi.fn(),
':taskId': {
$patch: vi.fn(),
},
},
},
},
},
},
}
beforeEach(() => {
vi.resetAllMocks()
logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
writeSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true)
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
exitSpy = vi
.spyOn(process, 'exit')
.mockImplementation((code?: string | number | null): never => {
throw new Error(`process.exit(${code})`)
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(getClient).mockReturnValue(mockClient as any)
})
afterEach(() => {
logSpy.mockRestore()
writeSpy.mockRestore()
errorSpy.mockRestore()
exitSpy.mockRestore()
})
describe('project ls', () => {
it('prints list of projects correctly', async () => {
mockClient.api.projects.$get.mockResolvedValue({
ok: true,
json: async () => ({
data: [
{ id: 'p1', name: 'Proj 1', rootFolder: 'root1' },
{ id: 'p2', name: 'Proj 2', rootFolder: 'root2' },
],
}),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
await projectLs()
expect(mockClient.api.projects.$get).toHaveBeenCalledWith({
query: { first: '200' },
})
expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('Proj 1'))
expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('Proj 2'))
})
})
describe('ls', () => {
it('queries folders and files and displays table', async () => {
mockClient.api.folders[':folderId'].children.$get
.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [{ id: 'subfolder1', name: 'Sub 1', type: 'folder', sizeByte: 0 }],
}),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [{ id: 'file1', name: 'doc.pdf', type: 'file', sizeByte: 1024 }],
}),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
await ls('parentId123')
expect(mockClient.api.folders[':folderId'].children.$get).toHaveBeenCalledTimes(2)
expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('Sub 1'))
expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('doc.pdf'))
})
})
describe('mkdir', () => {
it('calls POST /folders and prints the folder ID', async () => {
mockClient.api.folders.$post.mockResolvedValue({
ok: true,
json: async () => ({ id: 'new_folder_ulid' }),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
await mkdir('NewFolder', 'parent_ulid')
expect(mockClient.api.folders.$post).toHaveBeenCalledWith({
json: { name: 'NewFolder', parentId: 'parent_ulid' },
})
expect(logSpy).toHaveBeenCalledWith('Created folder with ID: new_folder_ulid')
})
})
describe('upload', () => {
it('uploads a file successfully and confirms the task', async () => {
const tempFile = 'temp-test-file.txt'
fs.writeFileSync(tempFile, 'hello world')
mockClient.api.folders[':folderId'].$get.mockResolvedValue({
ok: true,
json: async () => ({ projectId: 'p123' }),
// We use any here because we are mocking the hono client response shape in a unit test context
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
mockClient.api.projects[':projectId'].$get.mockResolvedValue({
ok: true,
json: async () => ({ teamId: 't123' }),
// We use any here because we are mocking the hono client response shape in a unit test context
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
mockClient.api.teams[':teamId'].upload.tasks.$post.mockImplementation(
async (req: unknown) => {
const rootNodeId = (req as { json: { files: { id: string }[] } }).json.files[0].id
return {
ok: true,
json: async () => ({
taskId: 'task123',
presignedUrls: [
{ id: rootNodeId, fileId: 'file-123', url: 'http://localhost/upload' },
],
createdAssets: [{ tempId: rootNodeId, assetId: 'file-123' }],
}),
// We use any here because we are mocking the hono client response shape in a unit test context
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any
},
)
mockClient.api.teams[':teamId'].upload.tasks[':taskId'].$patch.mockResolvedValue({
ok: true,
// We use any here because we are mocking the hono client response shape in a unit test context
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
const mockRes = {
statusCode: 200,
resume: vi.fn(),
}
let mockReqCallback: ((res: { statusCode: number; resume: () => void }) => void) | null = null
const mockReq = {
on: vi.fn().mockImplementation(() => {
return mockReq
}),
write: vi.fn(),
end: vi.fn().mockImplementation(() => {
if (mockReqCallback) {
mockReqCallback(mockRes)
}
}),
destroy: vi.fn(),
}
vi.mocked(http.request).mockImplementation(((
_options: unknown,
callback: (res: { statusCode: number; resume: () => void }) => void,
) => {
mockReqCallback = callback
return mockReq
// We use any here because we are mocking the http request function in a unit test context
// eslint-disable-next-line @typescript-eslint/no-explicit-any
}) as any)
await upload(tempFile, 'folder-123')
expect(mockClient.api.folders[':folderId'].$get).toHaveBeenCalledWith({
param: { folderId: 'folder-123' },
})
expect(mockClient.api.projects[':projectId'].$get).toHaveBeenCalledWith({
param: { projectId: 'p123' },
})
expect(mockClient.api.teams[':teamId'].upload.tasks.$post).toHaveBeenCalled()
expect(mockClient.api.teams[':teamId'].upload.tasks[':taskId'].$patch).toHaveBeenCalledWith({
param: { teamId: 't123', taskId: 'task123' },
json: { fileId: 'file-123' },
})
try {
fs.unlinkSync(tempFile)
} catch {
// Ignore if file doesn't exist
}
})
})
describe('create-version', () => {
it('fails if local path is a directory', async () => {
const tempDir = 'temp-test-dir'
fs.mkdirSync(tempDir, { recursive: true })
await expect(createVersion(tempDir, 'file-123')).rejects.toThrow('process.exit(1)')
try {
fs.rmdirSync(tempDir)
} catch {
// Ignore
}
})
it('fails if parent asset is not file or version_stack', async () => {
const tempFile = 'temp-test-file-ver.txt'
fs.writeFileSync(tempFile, 'hello ver')
mockClient.api.folders[':folderId'].$get.mockResolvedValue({
ok: true,
json: async () => ({ type: 'folder', projectId: 'p123' }),
// We use any here because we are mocking the hono client response shape in a unit test context
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
await expect(createVersion(tempFile, 'folder-123')).rejects.toThrow('process.exit(1)')
try {
fs.unlinkSync(tempFile)
} catch {
// Ignore
}
})
it('succeeds if parent asset is a file', async () => {
const tempFile = 'temp-test-file-ver.txt'
fs.writeFileSync(tempFile, 'hello ver')
mockClient.api.folders[':folderId'].$get.mockResolvedValue({
ok: true,
json: async () => ({ type: 'file', projectId: 'p123' }),
// We use any here because we are mocking the hono client response shape in a unit test context
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
mockClient.api.projects[':projectId'].$get.mockResolvedValue({
ok: true,
json: async () => ({ teamId: 't123' }),
// We use any here because we are mocking the hono client response shape in a unit test context
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
mockClient.api.teams[':teamId'].upload.tasks.$post.mockImplementation(
async (req: unknown) => {
const rootNodeId = (req as { json: { files: { id: string }[] } }).json.files[0].id
return {
ok: true,
json: async () => ({
taskId: 'task123',
presignedUrls: [
{ id: rootNodeId, fileId: 'file-123', url: 'http://localhost/upload' },
],
createdAssets: [{ tempId: rootNodeId, assetId: 'file-123' }],
}),
// We use any here because we are mocking the hono client response shape in a unit test context
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any
},
)
mockClient.api.teams[':teamId'].upload.tasks[':taskId'].$patch.mockResolvedValue({
ok: true,
// We use any here because we are mocking the hono client response shape in a unit test context
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
const mockRes = {
statusCode: 200,
resume: vi.fn(),
}
let mockReqCallback: ((res: { statusCode: number; resume: () => void }) => void) | null = null
const mockReq = {
on: vi.fn().mockImplementation(() => {
return mockReq
}),
write: vi.fn(),
end: vi.fn().mockImplementation(() => {
if (mockReqCallback) {
mockReqCallback(mockRes)
}
}),
destroy: vi.fn(),
}
vi.mocked(http.request).mockImplementation(((
_options: unknown,
callback: (res: { statusCode: number; resume: () => void }) => void,
) => {
mockReqCallback = callback
return mockReq
// We use any here because we are mocking the http request function in a unit test context
// eslint-disable-next-line @typescript-eslint/no-explicit-any
}) as any)
await createVersion(tempFile, 'file-123')
expect(mockClient.api.folders[':folderId'].$get).toHaveBeenCalledWith({
param: { folderId: 'file-123' },
})
expect(mockClient.api.teams[':teamId'].upload.tasks.$post).toHaveBeenCalledWith({
param: { teamId: 't123' },
json: expect.objectContaining({ parentId: 'file-123' }),
})
try {
fs.unlinkSync(tempFile)
} catch {
// Ignore
}
})
})
})
+155
View File
@@ -0,0 +1,155 @@
import fs from 'node:fs'
import path from 'node:path'
import { ulid } from 'ulid'
import { getClient } from '../client'
import { getMediaType, ProgressTracker, uploadFileWithProgress } from './upload'
export async function createVersion(localPath: string, parentId: string) {
if (!localPath) {
console.error('Error: Local file path is required.')
process.exit(1)
}
if (!parentId) {
console.error('Error: Parent ID (-p/--parent) is required.')
process.exit(1)
}
const resolvedPath = path.resolve(localPath)
if (!fs.existsSync(resolvedPath)) {
console.error(`Error: Local path "${resolvedPath}" does not exist.`)
process.exit(1)
}
const stat = fs.statSync(resolvedPath)
if (stat.isDirectory()) {
console.error(
`Error: Local path "${resolvedPath}" is a directory. create-version only supports uploading single files.`,
)
process.exit(1)
}
const client = getClient()
try {
console.log(`Checking parent asset ${parentId}...`)
const assetRes = await client.api.folders[':folderId'].$get({
param: { folderId: parentId },
})
if (!assetRes.ok) {
const err = (await assetRes.json().catch(() => ({ error: 'Unknown error' }))) as {
error?: string
}
console.error(`Error fetching parent asset details: ${err.error || 'Failed'}`)
process.exit(1)
}
const parentAsset = await assetRes.json()
if (parentAsset.type !== 'file' && parentAsset.type !== 'version_stack') {
console.error(
`Error: Parent asset must be a file or a version_stack (got "${parentAsset.type}").`,
)
process.exit(1)
}
const projectId = parentAsset.projectId
if (!projectId) {
console.error('Error: Parent asset does not belong to any project.')
process.exit(1)
}
const projectRes = await client.api.projects[':projectId'].$get({
param: { projectId },
})
if (!projectRes.ok) {
const err = (await projectRes.json().catch(() => ({ error: 'Unknown error' }))) as {
error?: string
}
console.error(`Error fetching project details: ${err.error || 'Failed'}`)
process.exit(1)
}
const project = await projectRes.json()
const teamId = project.teamId
const name = path.basename(resolvedPath)
const mediaType = getMediaType(name)
const fileNode = {
name,
id: ulid(),
size: stat.size,
children: [],
type: 'file',
mediaType,
}
console.log(`Creating new version task...`)
const taskRes = await client.api.teams[':teamId'].upload.tasks.$post({
param: { teamId },
json: {
parentId,
files: [fileNode],
},
})
if (!taskRes.ok) {
const err = (await taskRes.json().catch(() => ({ error: 'Unknown error' }))) as {
error?: string
}
console.error(`Error creating version task: ${err.error || 'Failed'}`)
process.exit(1)
}
const { taskId, presignedUrls, createdAssets } = await taskRes.json()
if (!presignedUrls || presignedUrls.length === 0) {
console.error('Error: Server did not return presigned upload URLs.')
process.exit(1)
}
const urlObj = presignedUrls[0]
const progress = new ProgressTracker()
progress.addUpload(urlObj.id, name, stat.size)
try {
await uploadFileWithProgress(urlObj.url, resolvedPath, mediaType, (bytes) => {
progress.updateProgress(urlObj.id, bytes)
})
const confirmRes = await client.api.teams[':teamId'].upload.tasks[':taskId'].$patch({
param: { teamId, taskId },
json: { fileId: urlObj.fileId },
})
if (!confirmRes.ok) {
throw new Error('Failed to confirm upload')
}
} catch (err) {
console.error(`\nFailed to upload ${name}:`, err instanceof Error ? err.message : err)
await client.api.teams[':teamId'].upload.tasks[':taskId']
.$patch({
param: { teamId, taskId },
json: {
fileId: urlObj.fileId,
errorMessage: err instanceof Error ? err.message : String(err),
},
})
.catch(() => {})
process.exit(1)
}
console.log('\nVersion upload completed!')
if (createdAssets && createdAssets.length > 0) {
console.log('Created version asset ID:')
for (const asset of createdAssets) {
if (asset.tempId === fileNode.id) {
console.log(`- ${asset.assetId}`)
}
}
}
} catch (err) {
console.error('\nError connecting to API server:', err instanceof Error ? err.message : err)
process.exit(1)
}
}
+87
View File
@@ -0,0 +1,87 @@
import { newTablePrinter, withTruncate } from '@shumai/tableprinter'
import type { AssetInfo } from '@shumai/dtos'
import { getClient } from '../client'
function formatSize(bytes: number): string {
if (bytes === 0) return '-'
const k = 1024
const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
export async function ls(parentId: string) {
if (!parentId) {
console.error('Error: Parent ID (-p/--parent) is required.')
process.exit(1)
}
const client = getClient()
try {
const [foldersRes, filesRes] = await Promise.all([
client.api.folders[':folderId'].children.$get({
param: { folderId: parentId },
query: { assetType: 'folder', first: '200' },
}),
client.api.folders[':folderId'].children.$get({
param: { folderId: parentId },
query: { assetType: 'file', first: '200' },
}),
])
if (!foldersRes.ok) {
const err = (await foldersRes.json().catch(() => ({ error: 'Unknown error' }))) as {
error?: string
}
console.error(`Error: ${err.error || 'Failed to list folders'}`)
process.exit(1)
}
if (!filesRes.ok) {
const err = (await filesRes.json().catch(() => ({ error: 'Unknown error' }))) as {
error?: string
}
console.error(`Error: ${err.error || 'Failed to list files'}`)
process.exit(1)
}
const foldersData = await foldersRes.json()
const filesData = await filesRes.json()
const folders = foldersData.data || []
const files = filesData.data || []
const items = [
...folders.map((f: AssetInfo) => ({ ...f, typeDisplay: 'folder' as const })),
...files.map((f: AssetInfo) => ({ ...f, typeDisplay: 'file' as const })),
]
if (items.length === 0) {
console.log('No assets found in this folder.')
return
}
const isTty = process.stdout.isTTY
const maxWidth = process.stdout.columns || 80
const tp = newTablePrinter(process.stdout, isTty, maxWidth)
tp.addHeader(['ID', 'Name', 'Type', 'Size'])
for (const item of items) {
tp.addField(item.id || '', withTruncate(null))
tp.addField(item.name || '')
tp.addField(item.typeDisplay, withTruncate(null))
tp.addField(
item.typeDisplay === 'folder' ? '-' : formatSize(item.sizeByte || 0),
withTruncate(null),
)
tp.endRow()
}
tp.render()
} catch (err) {
console.error('Error connecting to API server:', err instanceof Error ? err.message : err)
process.exit(1)
}
}
+32
View File
@@ -0,0 +1,32 @@
import { getClient } from '../client'
export async function mkdir(name: string, parentId: string) {
if (!name) {
console.error('Error: Folder name is required.')
process.exit(1)
}
if (!parentId) {
console.error('Error: Parent ID (-p/--parent) is required.')
process.exit(1)
}
const client = getClient()
try {
const res = await client.api.folders.$post({
json: { name, parentId },
})
if (!res.ok) {
const err = (await res.json().catch(() => ({ error: 'Unknown error' }))) as { error?: string }
console.error(`Error: ${err.error || 'Failed to create folder'}`)
process.exit(1)
}
const created = await res.json()
console.log(`Created folder with ID: ${created.id}`)
} catch (err) {
console.error('Error connecting to API server:', err instanceof Error ? err.message : err)
process.exit(1)
}
}
+42
View File
@@ -0,0 +1,42 @@
import { newTablePrinter } from '@shumai/tableprinter'
import { getClient } from '../client'
export async function projectLs() {
const client = getClient()
try {
const res = await client.api.projects.$get({
query: { first: '200' },
})
if (!res.ok) {
const err = (await res.json().catch(() => ({ error: 'Unknown error' }))) as { error?: string }
console.error(`Error: ${err.error || 'Failed to list projects'}`)
process.exit(1)
}
const { data: projects } = await res.json()
if (projects.length === 0) {
console.log('No projects found.')
return
}
const isTty = process.stdout.isTTY
const maxWidth = process.stdout.columns || 80
const tp = newTablePrinter(process.stdout, isTty, maxWidth)
tp.addHeader(['ID', 'Name', 'Root Folder ID'])
for (const p of projects) {
tp.addField(p.id || '')
tp.addField(p.name || '')
tp.addField(p.rootFolder || '')
tp.endRow()
}
tp.render()
} catch (err) {
console.error('Error connecting to API server:', err instanceof Error ? err.message : err)
process.exit(1)
}
}
+332
View File
@@ -0,0 +1,332 @@
import fs from 'node:fs'
import fsPromises from 'node:fs/promises'
import http from 'node:http'
import https from 'node:https'
import path from 'node:path'
import { ulid } from 'ulid'
import { getClient } from '../client'
interface CliFileNode {
name: string
id: string
size: number
children: CliFileNode[]
type: 'file' | 'folder'
mediaType?: string
}
export function getMediaType(filename: string): string {
const ext = path.extname(filename).toLowerCase()
const mimeMap: Record<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.webp': 'image/webp',
'.mp4': 'video/mp4',
'.mkv': 'video/x-matroska',
'.mov': 'video/quicktime',
'.avi': 'video/x-msvideo',
'.webm': 'video/webm',
'.mp3': 'audio/mpeg',
'.wav': 'audio/wav',
'.ogg': 'audio/ogg',
'.txt': 'text/plain',
'.json': 'application/json',
'.pdf': 'application/pdf',
'.zip': 'application/zip',
'.tar': 'application/x-tar',
'.gz': 'application/gzip',
}
return mimeMap[ext] || 'application/octet-stream'
}
async function buildFileTree(
localPath: string,
fileMap: Map<string, { path: string; name: string; size: number; mediaType: string }>,
): Promise<CliFileNode> {
const stat = await fsPromises.stat(localPath)
const name = path.basename(localPath)
const id = ulid()
if (stat.isDirectory()) {
const childrenNames = await fsPromises.readdir(localPath)
const children: CliFileNode[] = []
for (const childName of childrenNames) {
if (childName.startsWith('.')) continue
const childNode = await buildFileTree(path.join(localPath, childName), fileMap)
children.push(childNode)
}
return {
name,
id,
size: 0,
children,
type: 'folder',
}
} else {
const mediaType = getMediaType(name)
fileMap.set(id, { path: localPath, name, size: stat.size, mediaType })
return {
name,
id,
size: stat.size,
children: [],
type: 'file',
mediaType,
}
}
}
export class ProgressTracker {
private uploads = new Map<string, { name: string; size: number; uploadedBytes: number }>()
private isTty = process.stdout.isTTY
private linesPrinted = 0
addUpload(id: string, name: string, size: number) {
this.uploads.set(id, { name, size, uploadedBytes: 0 })
if (this.isTty) {
console.log(`${name.padEnd(30)} [${'░'.repeat(20)}] 0%`)
this.linesPrinted++
console.log('')
this.linesPrinted++
}
}
updateProgress(id: string, uploadedBytes: number) {
const item = this.uploads.get(id)
if (!item) return
item.uploadedBytes = uploadedBytes
if (this.isTty) {
process.stdout.write('\x1B[' + this.linesPrinted + 'A')
this.linesPrinted = 0
for (const upload of this.uploads.values()) {
const pct =
upload.size > 0
? Math.min(Math.round((upload.uploadedBytes / upload.size) * 100), 100)
: 100
const barLength = 20
const filledLength = Math.round((pct / 100) * barLength)
const bar = '█'.repeat(filledLength) + '░'.repeat(barLength - filledLength)
console.log(`${upload.name.padEnd(30)} [${bar}] ${pct}%`)
this.linesPrinted++
console.log('')
this.linesPrinted++
}
} else {
const pct = item.size > 0 ? Math.min(Math.round((uploadedBytes / item.size) * 100), 100) : 100
if (pct === 100 || uploadedBytes === 0 || pct % 25 === 0) {
console.log(`Uploading ${item.name}: ${pct}%`)
}
}
}
}
export async function uploadFileWithProgress(
url: string,
filePath: string,
contentType: string,
onProgress: (bytesUploaded: number) => void,
) {
const stat = fs.statSync(filePath)
const totalSize = stat.size
const parsedUrl = new URL(url)
const isHttps = parsedUrl.protocol === 'https:'
const requestModule = isHttps ? https : http
const options = {
method: 'PUT',
hostname: parsedUrl.hostname,
port: parsedUrl.port || (isHttps ? 443 : 80),
path: parsedUrl.pathname + parsedUrl.search,
headers: {
'Content-Type': contentType,
'Content-Length': totalSize.toString(),
},
}
return new Promise<void>((resolve, reject) => {
const req = requestModule.request(options, (res) => {
res.resume()
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
resolve()
} else {
reject(new Error(`Failed to upload to S3: ${res.statusCode} ${res.statusMessage}`))
}
})
req.on('error', (err) => {
reject(err)
})
const fileStream = fs.createReadStream(filePath)
let bytesUploaded = 0
fileStream.on('data', (chunk) => {
bytesUploaded += chunk.length
onProgress(bytesUploaded)
req.write(chunk)
})
fileStream.on('end', () => {
req.end()
})
fileStream.on('error', (err) => {
req.destroy()
reject(err)
})
})
}
export async function upload(localPath: string, parentId: string) {
if (!localPath) {
console.error('Error: Local file/folder path is required.')
process.exit(1)
}
if (!parentId) {
console.error('Error: Parent ID (-p/--parent) is required.')
process.exit(1)
}
const resolvedPath = path.resolve(localPath)
if (!fs.existsSync(resolvedPath)) {
console.error(`Error: Local path "${resolvedPath}" does not exist.`)
process.exit(1)
}
const client = getClient()
try {
const parentRes = await client.api.folders[':folderId'].$get({
param: { folderId: parentId },
})
if (!parentRes.ok) {
const err = (await parentRes.json().catch(() => ({ error: 'Unknown error' }))) as {
error?: string
}
console.error(`Error fetching parent folder details: ${err.error || 'Failed'}`)
process.exit(1)
}
const parentFolder = await parentRes.json()
const projectId = parentFolder.projectId
if (!projectId) {
console.error('Error: Parent folder does not belong to any project.')
process.exit(1)
}
const projectRes = await client.api.projects[':projectId'].$get({
param: { projectId },
})
if (!projectRes.ok) {
const err = (await projectRes.json().catch(() => ({ error: 'Unknown error' }))) as {
error?: string
}
console.error(`Error fetching project details: ${err.error || 'Failed'}`)
process.exit(1)
}
const project = await projectRes.json()
const teamId = project.teamId
const fileMap = new Map<
string,
{ path: string; name: string; size: number; mediaType: string }
>()
const rootNode = await buildFileTree(resolvedPath, fileMap)
console.log(`Starting upload task for ${fileMap.size} files...`)
const taskRes = await client.api.teams[':teamId'].upload.tasks.$post({
param: { teamId },
json: {
parentId,
files: [rootNode],
},
})
if (!taskRes.ok) {
const err = (await taskRes.json().catch(() => ({ error: 'Unknown error' }))) as {
error?: string
}
console.error(`Error creating upload task: ${err.error || 'Failed'}`)
process.exit(1)
}
const { taskId, presignedUrls, createdAssets } = await taskRes.json()
const progress = new ProgressTracker()
for (const urlObj of presignedUrls) {
const fileMeta = fileMap.get(urlObj.id)
if (fileMeta) {
progress.addUpload(urlObj.id, fileMeta.name, fileMeta.size)
}
}
const concurrencyLimit = 3
const queue = [...presignedUrls]
const activeUploads: Promise<void>[] = []
const uploadNext = async (): Promise<void> => {
if (queue.length === 0) return
const urlObj = queue.shift()!
const fileMeta = fileMap.get(urlObj.id)!
try {
await uploadFileWithProgress(urlObj.url, fileMeta.path, fileMeta.mediaType, (bytes) => {
progress.updateProgress(urlObj.id, bytes)
})
const confirmRes = await client.api.teams[':teamId'].upload.tasks[':taskId'].$patch({
param: { teamId, taskId },
json: { fileId: urlObj.fileId },
})
if (!confirmRes.ok) {
throw new Error('Failed to confirm upload')
}
} catch (err) {
console.error(
`\nFailed to upload ${fileMeta.name}:`,
err instanceof Error ? err.message : err,
)
await client.api.teams[':teamId'].upload.tasks[':taskId']
.$patch({
param: { teamId, taskId },
json: {
fileId: urlObj.fileId,
errorMessage: err instanceof Error ? err.message : String(err),
},
})
.catch(() => {})
}
return uploadNext()
}
for (let i = 0; i < Math.min(concurrencyLimit, presignedUrls.length); i++) {
activeUploads.push(uploadNext())
}
await Promise.all(activeUploads)
console.log('\nUpload completed!')
if (createdAssets && createdAssets.length > 0) {
console.log('Uploaded asset IDs:')
const topLevelTempIds = new Set<string>()
topLevelTempIds.add(rootNode.id)
for (const asset of createdAssets) {
if (topLevelTempIds.has(asset.tempId)) {
console.log(`- ${asset.assetId}`)
}
}
}
} catch (err) {
console.error('\nError connecting to API server:', err instanceof Error ? err.message : err)
process.exit(1)
}
}
+104
View File
@@ -0,0 +1,104 @@
import { projectLs } from './commands/project'
import { ls } from './commands/ls'
import { mkdir } from './commands/mkdir'
import { upload } from './commands/upload'
import { createVersion } from './commands/create-version'
function printHelp() {
console.log(`
Usage: shumai-cli <command> [arguments] [options]
Commands:
project ls List all projects (returns id, name, root folder id)
ls -p <parentId> List direct children of a parent folder (returns id, name, type, size)
mkdir <name> -p <parentId> Create a new folder in a parent folder
upload <path> -p <parentId> Upload a local file or folder to a parent folder
create-version <path> -p <id> Create a new version of an existing file or version stack
Options:
-p, --parent <id> The parent folder/asset ID (required for ls, mkdir, upload, create-version)
-h, --help Show help details
`)
}
async function main() {
const args = process.argv.slice(2)
if (args.length === 0 || args.includes('-h') || args.includes('--help')) {
printHelp()
process.exit(0)
}
const cmd = args[0]
let parentId = ''
const parentIdx = args.findIndex((a) => a === '-p' || a === '--parent')
if (parentIdx !== -1 && parentIdx + 1 < args.length) {
parentId = args[parentIdx + 1]
}
const cleanArgs: string[] = []
for (let i = 0; i < args.length; i++) {
if (args[i] === '-p' || args[i] === '--parent') {
i++
} else {
cleanArgs.push(args[i])
}
}
if (cmd === 'project' && cleanArgs[1] === 'ls') {
await projectLs()
} else if (cmd === 'ls') {
if (!parentId) {
console.error('Error: Option -p/--parent <parentId> is required.')
process.exit(1)
}
await ls(parentId)
} else if (cmd === 'mkdir') {
const name = cleanArgs[1]
if (!name) {
console.error(
'Error: Folder name is required. Usage: shumai-cli mkdir <folderName> -p <parentId>',
)
process.exit(1)
}
if (!parentId) {
console.error('Error: Option -p/--parent <parentId> is required.')
process.exit(1)
}
await mkdir(name, parentId)
} else if (cmd === 'upload') {
const localPath = cleanArgs[1]
if (!localPath) {
console.error(
'Error: File/folder path is required. Usage: shumai-cli upload <localPath> -p <parentId>',
)
process.exit(1)
}
if (!parentId) {
console.error('Error: Option -p/--parent <parentId> is required.')
process.exit(1)
}
await upload(localPath, parentId)
} else if (cmd === 'create-version') {
const localPath = cleanArgs[1]
if (!localPath) {
console.error(
'Error: Local file path is required. Usage: shumai-cli create-version <localPath> -p <parentAssetId>',
)
process.exit(1)
}
if (!parentId) {
console.error('Error: Option -p/--parent <parentAssetId> is required.')
process.exit(1)
}
await createVersion(localPath, parentId)
} else {
console.error(`Error: Unknown command "${cmd}". Run "shumai-cli --help" for usage.`)
process.exit(1)
}
}
main().catch((err) => {
console.error('Unexpected error:', err)
process.exit(1)
})
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.json",
"include": ["src/**/*"]
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/transcode-app",
"version": "0.0.2",
"version": "0.1.10",
"private": true,
"type": "module",
"bin": {
+7 -1
View File
@@ -3,6 +3,12 @@ loadEnvConfig(process.cwd(), process.env.NODE_ENV !== 'production')
import { initTranscodeWorkflows } from '@shumai/transcode'
import { TaskQueueTranscode, workflowService } from '@shumai/workflow-core'
import { handleDaemonCommands } from '@shumai/core/src/utils/daemon'
if (process.argv.includes('--check')) {
console.log('✅ Transcode worker evaluated successfully!')
process.exit(0)
}
async function run() {
// Initialize workflows and activities
@@ -22,7 +28,7 @@ async function run() {
await workflowService.startWorkers(TaskQueueTranscode, options)
}
run().catch((err) => {
handleDaemonCommands('shumai-transcode', run).catch((err) => {
console.error(err)
process.exit(1)
})
+56
View File
@@ -0,0 +1,56 @@
import { test as base } from '@playwright/test'
import { PrismaClient } from '../../../packages/db/src/generated/prisma/client'
import { PrismaPg } from '@prisma/adapter-pg'
import { Pool } from 'pg'
import * as fs from 'fs'
import * as path from 'path'
import { fileURLToPath } from 'url'
const currentDir = path.dirname(fileURLToPath(import.meta.url))
const envPath = path.resolve(currentDir, '.env.e2e')
// Load E2E environment variables if present
if (fs.existsSync(envPath)) {
const content = fs.readFileSync(envPath, 'utf8')
content.split('\n').forEach((line) => {
const parts = line.split('=')
if (parts.length >= 2) {
const key = parts[0].trim()
const value = parts.slice(1).join('=').trim()
process.env[key] = value
}
})
}
export const test = base.extend<{ prisma: PrismaClient }>({
prisma: [
// eslint-disable-next-line no-empty-pattern
async ({}, use) => {
const connectionString = process.env.DATABASE_URL
const pool = new Pool({ connectionString })
const adapter = new PrismaPg(pool)
const prisma = new PrismaClient({ adapter })
// Reset database state before the test runs
await prisma.$executeRawUnsafe(`
DO $$ DECLARE
r RECORD;
BEGIN
FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = 'public' AND tablename <> '_prisma_migrations') LOOP
EXECUTE 'TRUNCATE TABLE ' || quote_ident(r.tablename) || ' CASCADE;';
END LOOP;
END $$;
`)
// Provide the clean prisma instance to the test
await use(prisma)
// Disconnect and clean up resources after the test finishes
await prisma.$disconnect()
await pool.end()
},
{ auto: true },
],
})
export { expect } from '@playwright/test'
+36
View File
@@ -0,0 +1,36 @@
import { teardown as dbTeardown } from '../../../packages/db/src/test-global-setup'
import * as fs from 'fs'
import * as path from 'path'
import { fileURLToPath } from 'url'
const currentDir = path.dirname(fileURLToPath(import.meta.url))
export default async function globalTeardown() {
const envPath = path.resolve(currentDir, '.env.e2e')
if (fs.existsSync(envPath)) {
const content = fs.readFileSync(envPath, 'utf8')
let bucketName: string | undefined
content.split('\n').forEach((line) => {
const parts = line.split('=')
if (parts.length >= 2 && parts[0].trim() === 'S3_BUCKET') {
bucketName = parts.slice(1).join('=').trim()
}
})
if (bucketName) {
const bucketDir = path.resolve('data', bucketName)
if (fs.existsSync(bucketDir)) {
console.log(`Cleaning up E2E local storage bucket: ${bucketDir}`)
fs.rmSync(bucketDir, { recursive: true, force: true })
}
}
// Delete the temp .env.e2e file
fs.unlinkSync(envPath)
}
// Stop pgvector container
await dbTeardown()
console.log('Global teardown complete.')
}
+35
View File
@@ -0,0 +1,35 @@
import { globalTestSetup } from '../../../packages/db/src/test-global-setup'
import { randomBytes } from 'crypto'
import * as fs from 'fs'
import * as path from 'path'
import { fileURLToPath } from 'url'
const currentDir = path.dirname(fileURLToPath(import.meta.url))
async function start() {
console.log('Starting E2E test database container...')
await globalTestSetup()
// Generate a random S3 bucket name
const randomSuffix = randomBytes(4).toString('hex')
const bucketName = `shumai-e2e-${randomSuffix}`
process.env.S3_BUCKET = bucketName
process.env.SHUMAI_SERVER_PORT = '5200'
process.env.BETTER_AUTH_URL = 'http://localhost:5200'
process.env.NODE_ENV = 'development'
process.env.SHUMAI_E2E = 'true'
// Write variables to .env.e2e file so the teardown can load them
const envContent = [`DATABASE_URL=${process.env.DATABASE_URL}`, `S3_BUCKET=${bucketName}`].join(
'\n',
)
fs.writeFileSync(path.resolve(currentDir, '.env.e2e'), envContent)
console.log(`E2E env file written. Starting Web App...`)
// Now run the web app
await import('../src/index.ts')
}
start().catch(console.error)
+75
View File
@@ -0,0 +1,75 @@
import { expect, test } from './fixtures'
import * as fs from 'fs'
import * as path from 'path'
import { fileURLToPath } from 'url'
const currentDir = path.dirname(fileURLToPath(import.meta.url))
const tempImgPath = path.resolve(currentDir, 'temp-cover.png')
test.beforeAll(async () => {
// Create a 1x1 transparent PNG file
const pngBase64 =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='
fs.writeFileSync(tempImgPath, Buffer.from(pngBase64, 'base64'))
})
test.afterAll(async () => {
if (fs.existsSync(tempImgPath)) {
fs.unlinkSync(tempImgPath)
}
})
test('should sign up and create a project with a cover image', async ({ page }) => {
const email = `test-${Date.now()}@shumai.local`
const password = 'Password123!'
// 1. Sign Up Flow
await page.goto('/signup')
await expect(page).toHaveURL(/\/signup/)
// Fill credentials
await page.fill('#email', email)
await page.fill('#password', password)
// Submit sign up
await page.click('button[type="submit"]')
// Wait for the automatic redirect to the team page (since only one team exists)
await expect(page).toHaveURL(/\/teams\/[^/]+/)
// 2. Create Project Flow
// Click the "Create Project" button on the dashboard
await page.click('button:has-text("Create Project")')
const dialog = page.locator('[role="dialog"]')
await expect(dialog).toBeVisible()
// Fill project name
const projectName = `My Project ${Date.now()}`
await dialog.locator('#name').fill(projectName)
// Set cover image
await dialog.locator('input[type="file"]').setInputFiles(tempImgPath)
// Wait for image upload completion and preview
await expect(dialog.locator('img[alt="Cover Preview"]')).toBeVisible({ timeout: 15_000 })
// Click submit in dialog
await dialog.locator('button[type="submit"]').click()
// Wait for navigation to the project page
await expect(page).toHaveURL(/\/projects\/[^/]+/)
// Verify project name appears in the project view
await expect(page.locator(`text=${projectName}`).first()).toBeVisible()
// 3. Verification on Dashboard
// Navigate back to the dashboard via sidebar
await page.click('button[aria-label="Dashboard"]')
// Wait for dashboard URL
await expect(page).toHaveURL(/\/teams\/[^/]+/)
// Verify the project card is visible and displays the cover image with project name alt text
await expect(page.locator(`img[alt="${projectName}"]`)).toBeVisible()
})
+6 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/web-app",
"version": "0.0.2",
"version": "0.1.10",
"private": true,
"type": "module",
"dependencies": {
@@ -13,5 +13,10 @@
"@shumai/transcode": "workspace:*",
"@shumai/webui": "workspace:*",
"hono": "4.12.23"
},
"devDependencies": {
"@prisma/adapter-pg": "7.8.0",
"pg": "8.21.0",
"@types/pg": "8.20.0"
}
}
+134 -59
View File
@@ -1,74 +1,149 @@
import { loadEnvConfig } from '@shumai/core/src/env-loader'
import { join } from 'node:path'
loadEnvConfig(process.cwd(), process.env.NODE_ENV !== 'production')
import index from '@shumai/webui/index.html'
import { initAgentWorkflows } from '@shumai/agent'
import { app } from '@shumai/api'
import { assetService } from '@shumai/core/src/asset/asset'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { initTranscodeWorkflows } from '@shumai/transcode'
import { workflowService } from '@shumai/workflow-core'
import { app } from '@shumai/api'
// Initialize workflows and activities for local executor mode
initAgentWorkflows()
initTranscodeWorkflows()
import { handleDaemonCommands } from '@shumai/core/src/utils/daemon'
// Start services
await metadataService.syncSystemFields().catch(console.error)
assetService.startCleanupJob()
workflowService.start()
if (process.env.WORKFLOW_EXECUTOR === 'temporal') {
const args = process.argv.slice(2)
let workersOption = ''
for (let i = 0; i < args.length; i++) {
if (args[i] === '--workers') {
workersOption = args[i + 1] || ''
} else if (args[i].startsWith('--workers=')) {
workersOption = args[i].split('=')[1]
}
}
const queuesToStart: string[] = []
if (workersOption === 'agent' || workersOption === 'ai') {
queuesToStart.push('agent_queue')
} else if (workersOption === 'transcode') {
queuesToStart.push('transcode_queue')
} else if (workersOption === 'all') {
queuesToStart.push('agent_queue', 'transcode_queue')
}
Promise.all(queuesToStart.map((q) => workflowService.startWorkers(q))).catch(console.error)
}
const server = Bun.serve({
port: 3000,
fetch: app.fetch,
maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE
? parseInt(process.env.MAX_REQUEST_BODY_SIZE)
: 1024 * 1024 * 1024 * 10, // Default 10GB
routes: {
// Serve index.html for root
'/': index,
// Proxy API requests to Hono
'/api/*': app.fetch,
'/files/*': app.fetch,
// Catch-all for SPA routing (fallback to index.html)
'/*': index,
},
development: process.env.NODE_ENV !== 'production',
})
console.log(`🚀 Server running at ${server.url}`)
const shutdown = () => {
console.log('\nShutting down gracefully...')
assetService.stopCleanupJob()
server.stop(true)
if (process.argv.includes('--check')) {
console.log('✅ Web app evaluated successfully!')
process.exit(0)
}
process.on('SIGINT', shutdown)
process.on('SIGTERM', shutdown)
async function run() {
// Initialize workflows and activities for local executor mode
initAgentWorkflows()
initTranscodeWorkflows()
// Start services
await metadataService.syncSystemFields().catch(console.error)
assetService.startCleanupJob()
workflowService.start()
if (process.env.WORKFLOW_EXECUTOR === 'temporal') {
const args = process.argv.slice(2)
let workersOption = ''
for (let i = 0; i < args.length; i++) {
if (args[i] === '--workers') {
workersOption = args[i + 1] || ''
} else if (args[i].startsWith('--workers=')) {
workersOption = args[i].split('=')[1]
}
}
const queuesToStart: string[] = []
if (workersOption === 'agent' || workersOption === 'ai') {
queuesToStart.push('agent_queue')
} else if (workersOption === 'transcode') {
queuesToStart.push('transcode_queue')
} else if (workersOption === 'all') {
queuesToStart.push('agent_queue', 'transcode_queue')
}
Promise.all(queuesToStart.map((q) => workflowService.startWorkers(q))).catch(console.error)
}
const isProd = process.env.NODE_ENV === 'production'
const port = process.env.SHUMAI_SERVER_PORT ? parseInt(process.env.SHUMAI_SERVER_PORT) : 3000
interface HtmlBundleFile {
input: string
path: string
loader: string
isEntry: boolean
headers: Record<string, string>
}
interface HtmlBundle {
index: string
files: HtmlBundleFile[]
}
// Bun's native Serve config routes require specific handler types that are hard
// to dynamically construct without using 'any'.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const routes: Record<string, any> = {
'/api/*': app.fetch,
'/files/*': app.fetch,
}
if (isProd) {
const bundle = index as unknown as HtmlBundle
if (bundle && typeof bundle === 'object' && 'files' in bundle && Array.isArray(bundle.files)) {
for (const file of bundle.files) {
const routePath = file.path.startsWith('.') ? file.path.slice(1) : file.path
const filePath = join(import.meta.dir, file.path)
routes[routePath] = () => new Response(Bun.file(filePath), { headers: file.headers })
}
const mainHtmlPath = join(import.meta.dir, bundle.index)
const mainHtmlFile = Bun.file(mainHtmlPath)
const mainHtmlHeaders = bundle.files.find((f) => f.path === bundle.index)?.headers || {
'content-type': 'text/html;charset=utf-8',
}
const raw = await mainHtmlFile.text()
const mainHtmlText = raw
.replaceAll('href="./', 'href="/')
.replaceAll('src="./', 'src="/')
.replaceAll('content="./', 'content="/')
const serveMainHtml = () => new Response(mainHtmlText, { headers: mainHtmlHeaders })
routes['/'] = serveMainHtml
routes['/*'] = serveMainHtml
} else {
const fallbackHtmlPath = join(import.meta.dir, 'shumai-app.html')
const serveFallbackHtml = () =>
new Response(Bun.file(fallbackHtmlPath), {
headers: { 'content-type': 'text/html;charset=utf-8' },
})
routes['/'] = serveFallbackHtml
routes['/*'] = serveFallbackHtml
}
} else {
routes['/'] = index
routes['/*'] = index
}
const server = Bun.serve({
port,
idleTimeout: 120,
maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE
? parseInt(process.env.MAX_REQUEST_BODY_SIZE)
: 1024 * 1024 * 1024 * 10, // Default 10GB
development: !isProd,
fetch: app.fetch,
routes,
})
console.log(`🚀 Server running at ${server.url}`)
const shutdown = () => {
console.log('\nShutting down gracefully...')
assetService.stopCleanupJob()
server.stop(true)
process.exit(0)
}
process.on('SIGINT', shutdown)
process.on('SIGTERM', shutdown)
}
if (process.env.SHUMAI_E2E === 'true') {
run().catch((err) => {
console.error(err)
process.exit(1)
})
} else {
handleDaemonCommands('shumai', run).catch((err) => {
console.error(err)
process.exit(1)
})
}
+3 -2
View File
@@ -19,7 +19,9 @@ await Bun.build({
root: '.',
target: 'bun',
outdir: outdir,
minify: false,
minify: true,
splitting: true,
naming: '[name].[ext]',
plugins: [
temporalWorkflow({
bundleOptions: {},
@@ -43,5 +45,4 @@ await Bun.build({
define: {
'process.env.NODE_ENV': JSON.stringify('production'),
},
publicPath: '/',
})
+149 -39
View File
@@ -10,7 +10,11 @@
},
"devDependencies": {
"@eslint/js": "10.0.1",
"@inlang/paraglide-js": "2.20.0",
"@playwright/test": "1.61.1",
"@testcontainers/postgresql": "12.0.1",
"@testing-library/dom": "10.4.1",
"@testing-library/react": "16.3.2",
"@types/bun": "1.3.14",
"@types/node": "25.9.1",
"bun-plugin-pino": "1.5.0",
@@ -21,6 +25,7 @@
"eslint-plugin-prettier": "5.5.6",
"eslint-plugin-react": "7.37.5",
"globals": "17.6.0",
"happy-dom": "20.10.6",
"pino-pretty": "13.1.3",
"prisma": "7.8.0",
"testcontainers": "12.0.1",
@@ -32,7 +37,7 @@
},
"apps/agent": {
"name": "@shumai/agent-app",
"version": "0.1.0",
"version": "0.1.9",
"bin": {
"shumai-agent": "./src/index.ts",
},
@@ -42,9 +47,24 @@
"@shumai/workflow-core": "workspace:*",
},
},
"apps/cli": {
"name": "@shumai/cli",
"version": "0.1.9",
"bin": {
"shumai-cli": "./src/index.ts",
},
"dependencies": {
"@shumai/api": "workspace:*",
"@shumai/core": "workspace:*",
"@shumai/dtos": "workspace:*",
"@shumai/tableprinter": "workspace:*",
"hono": "4.12.23",
"ulid": "^3.0.2",
},
},
"apps/transcode": {
"name": "@shumai/transcode-app",
"version": "0.1.0",
"version": "0.1.9",
"bin": {
"shumai-transcode": "./src/index.ts",
},
@@ -56,7 +76,7 @@
},
"apps/web": {
"name": "@shumai/web-app",
"version": "0.1.0",
"version": "0.1.9",
"dependencies": {
"@shumai/agent": "workspace:*",
"@shumai/api": "workspace:*",
@@ -68,10 +88,15 @@
"@shumai/workflow-core": "workspace:*",
"hono": "4.12.23",
},
"devDependencies": {
"@prisma/adapter-pg": "7.8.0",
"@types/pg": "8.20.0",
"pg": "8.21.0",
},
},
"packages/agent": {
"name": "@shumai/agent",
"version": "0.1.0",
"version": "0.1.9",
"dependencies": {
"@anthropic-ai/sandbox-runtime": "0.0.52",
"@earendil-works/pi-agent-core": "0.78.0",
@@ -95,7 +120,7 @@
},
"packages/api": {
"name": "@shumai/api",
"version": "0.1.0",
"version": "0.1.9",
"dependencies": {
"@hono/zod-validator": "0.7.6",
"@shumai/core": "workspace:*",
@@ -109,8 +134,9 @@
},
"packages/core": {
"name": "@shumai/core",
"version": "0.1.0",
"version": "0.1.9",
"dependencies": {
"@earendil-works/pi-agent-core": "0.78.0",
"@shumai/db": "workspace:*",
"@shumai/dtos": "workspace:*",
"@sinclair/typebox": "0.34.49",
@@ -123,6 +149,7 @@
"hono": "4.12.23",
"jittered-fractional-indexing": "1.0.1",
"pino": "10.3.1",
"sharp": "0.34.5",
"tweetnacl": "1.0.3",
"ulid": "3.0.2",
"yaml": "2.9.0",
@@ -135,7 +162,7 @@
},
"packages/db": {
"name": "@shumai/db",
"version": "0.1.0",
"version": "0.1.9",
"dependencies": {
"@earendil-works/pi-agent-core": "0.78.0",
"@prisma/adapter-pg": "7.8.0",
@@ -151,14 +178,33 @@
},
"packages/dtos": {
"name": "@shumai/dtos",
"version": "0.1.0",
"version": "0.1.9",
"dependencies": {
"@earendil-works/pi-agent-core": "0.78.0",
"zod": "4.4.3",
},
},
"packages/e2e": {
"name": "@shumai/e2e",
"version": "0.1.9",
"dependencies": {
"@earendil-works/pi-agent-core": "0.78.0",
"@google/genai": "1.52.0",
"@shumai/agent": "workspace:*",
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
"@shumai/dtos": "workspace:*",
"@shumai/transcode": "workspace:*",
"@shumai/workflow-core": "workspace:*",
},
},
"packages/tableprinter": {
"name": "@shumai/tableprinter",
"version": "0.1.9",
},
"packages/transcode": {
"name": "@shumai/transcode",
"version": "0.1.0",
"version": "0.1.9",
"dependencies": {
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
@@ -167,13 +213,12 @@
"@temporalio/activity": "1.17.2",
"@temporalio/worker": "1.17.2",
"@temporalio/workflow": "1.17.2",
"sharp": "0.34.5",
"ulid": "3.0.2",
},
},
"packages/webui": {
"name": "@shumai/webui",
"version": "0.1.0",
"version": "0.1.9",
"dependencies": {
"@base-ui/react": "1.5.0",
"@dnd-kit/abstract": "0.4.0",
@@ -257,23 +302,20 @@
},
"devDependencies": {
"@tailwindcss/postcss": "4.3.0",
"@tailwindcss/vite": "4.3.0",
"@tanstack/router-cli": "1.167.13",
"@tanstack/router-plugin": "1.168.14",
"@types/react": "19.2.16",
"@types/react-dom": "19.2.3",
"@vitejs/plugin-react": "5.2.0",
"autoprefixer": "10.5.0",
"postcss": "8.5.15",
"tailwindcss": "4.3.0",
"tw-animate-css": "1.3.3",
"vite": "7.3.5",
"vite-tsconfig-paths": "6.1.1",
"typescript": "6.0.3",
},
},
"packages/workflow-core": {
"name": "@shumai/workflow-core",
"version": "0.1.0",
"version": "0.1.9",
"dependencies": {
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
@@ -374,10 +416,6 @@
"@babel/plugin-syntax-typescript": ["@babel/plugin-syntax-typescript@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA=="],
"@babel/plugin-transform-react-jsx-self": ["@babel/plugin-transform-react-jsx-self@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw=="],
"@babel/plugin-transform-react-jsx-source": ["@babel/plugin-transform-react-jsx-source@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q=="],
"@babel/runtime": ["@babel/runtime@7.29.7", "", {}, "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw=="],
"@babel/template": ["@babel/template@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg=="],
@@ -586,6 +624,12 @@
"@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.34.5", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],
"@inlang/paraglide-js": ["@inlang/paraglide-js@2.20.0", "", { "dependencies": { "@inlang/recommend-sherlock": "^0.2.1", "@inlang/sdk": "^2.10.0", "commander": "11.1.0", "consola": "3.4.0", "json5": "2.2.3", "unplugin": "^2.1.2", "urlpattern-polyfill": "^10.0.0" }, "peerDependencies": { "typescript": ">=5.6" }, "optionalPeers": ["typescript"], "bin": { "paraglide-js": "bin/run.js" } }, "sha512-vI8PdPVZSnpYnpagjvm+nWSa3nMDRJKVM/2eLAtUHFrNcZZadxVdmP79r4W95+dkMLDFGEyzSSY9sFxvjdkkyQ=="],
"@inlang/recommend-sherlock": ["@inlang/recommend-sherlock@0.2.1", "", { "dependencies": { "comment-json": "^4.2.3" } }, "sha512-ckv8HvHy/iTqaVAEKrr+gnl+p3XFNwe5D2+6w6wJk2ORV2XkcRkKOJ/XsTUJbPSiyi4PI+p+T3bqbmNx/rDUlg=="],
"@inlang/sdk": ["@inlang/sdk@2.10.2", "", { "dependencies": { "@lix-js/sdk": "0.4.10", "@sinclair/typebox": "^0.31.17", "kysely": "^0.28.12", "sqlite-wasm-kysely": "0.3.0", "uuid": "^14.0.0" } }, "sha512-O1ki72SNK6LPagaGrvlioBb1mWKvump7cO7P85hfGZjdFTmDdn3icI0A6MvaBsB3P9KQHAjzyubnN1OslGufTw=="],
"@isaacs/cliui": ["@isaacs/cliui@8.0.2", "", { "dependencies": { "string-width": "^5.1.2", "string-width-cjs": "npm:string-width@^4.2.0", "strip-ansi": "^7.0.1", "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", "wrap-ansi": "^8.1.0", "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" } }, "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA=="],
"@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
@@ -682,6 +726,10 @@
"@lexical/yjs": ["@lexical/yjs@0.42.0", "", { "dependencies": { "@lexical/offset": "0.42.0", "@lexical/selection": "0.42.0", "lexical": "0.42.0" }, "peerDependencies": { "yjs": ">=13.5.22" } }, "sha512-DplzWnYhfFceGPR+UyDFpZdB287wF/vNOHFuDsBF/nGDdTezvr0Gf60opzyBEF3oXym6p3xTmGygxvO97LZ+vw=="],
"@lix-js/sdk": ["@lix-js/sdk@0.4.10", "", { "dependencies": { "@lix-js/server-protocol-schema": "0.1.1", "dedent": "1.5.1", "human-id": "^4.1.1", "js-sha256": "^0.11.0", "kysely": "^0.28.12", "sqlite-wasm-kysely": "0.3.0", "uuid": "^14.0.0" } }, "sha512-0dMInAJK/67guTG5rRZaCEhvzC5cCXENOjaePA5AqMXrCE97kaY7SRor9e2vnoGsFIiGqXKlT0MCIoZj36G0gg=="],
"@lix-js/server-protocol-schema": ["@lix-js/server-protocol-schema@0.1.1", "", {}, "sha512-jBeALB6prAbtr5q4vTuxnRZZv1M2rKe8iNqRQhFJ4Tv7150unEa0vKyz0hs8Gl3fUGsWaNJBh3J8++fpbrpRBQ=="],
"@mistralai/mistralai": ["@mistralai/mistralai@2.2.1", "", { "dependencies": { "ws": "^8.18.0", "zod": "^3.25.0 || ^4.0.0", "zod-to-json-schema": "^3.25.0" } }, "sha512-uKU8CZmL2RzYKmplsU01hii4p3pe4HqJefpWNRWXm1Tcm0Sm4xXfwSLIy4k7ZCPlbETCGcp69E7hZs+WOJ5itQ=="],
"@noble/ciphers": ["@noble/ciphers@2.2.0", "", {}, "sha512-Z6pjIZ/8IJcCGzb2S/0Px5J81yij85xASuk1teLNeg75bfT07MV3a/O2Mtn1I2se43k3lkVEcFaR10N4cgQcZA=="],
@@ -730,6 +778,8 @@
"@pkgr/core": ["@pkgr/core@0.3.6", "", {}, "sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA=="],
"@playwright/test": ["@playwright/test@1.61.1", "", { "dependencies": { "playwright": "1.61.1" }, "bin": { "playwright": "cli.js" } }, "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig=="],
"@pondwader/socks5-server": ["@pondwader/socks5-server@1.0.10", "", {}, "sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg=="],
"@preact/signals-core": ["@preact/signals-core@1.14.2", "", {}, "sha512-RZHdBj9ZF4n40Rp4jS052EHHjBWf96P9oNdXPfhQTovCuWY9iQn3Gq+gOTJSgBO9A/JBuPfMOWsSX/lIU9Pc/A=="],
@@ -910,8 +960,6 @@
"@reduxjs/toolkit": ["@reduxjs/toolkit@2.12.0", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "@standard-schema/utils": "^0.3.0", "immer": "^11.0.0", "redux": "^5.0.1", "redux-thunk": "^3.1.0", "reselect": "^5.1.0" }, "peerDependencies": { "react": "^16.9.0 || ^17.0.0 || ^18 || ^19", "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0" }, "optionalPeers": ["react", "react-redux"] }, "sha512-KiT+RzZbp6mQET+Mg+h2c97+9j1sNflUxQkIHI7Yuzf6Peu+OYpmkn6nbHWmLLWj+1ZODUJFwGZ7gx3L9R9EOw=="],
"@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-rc.3", "", {}, "sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q=="],
"@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.61.0", "", { "os": "android", "cpu": "arm" }, "sha512-dnxczajOqt0gesZlN5pGQ1s1imQVrsmCw5G2Ci4oM+0WvNz3pyRnlWrT7McoZIb8VlFwCawdmbWRmxRn7HI+VQ=="],
"@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.61.0", "", { "os": "android", "cpu": "arm64" }, "sha512-Bp3JpGP00Vu3f238ivRrjf7z3xSzVPXqCmaJYA9t2c+c8vKYvOzmXF7LkkeUalTEGd6cZcSWe+PFIP3Vy48fRg=="],
@@ -968,12 +1016,18 @@
"@shumai/api": ["@shumai/api@workspace:packages/api"],
"@shumai/cli": ["@shumai/cli@workspace:apps/cli"],
"@shumai/core": ["@shumai/core@workspace:packages/core"],
"@shumai/db": ["@shumai/db@workspace:packages/db"],
"@shumai/dtos": ["@shumai/dtos@workspace:packages/dtos"],
"@shumai/e2e": ["@shumai/e2e@workspace:packages/e2e"],
"@shumai/tableprinter": ["@shumai/tableprinter@workspace:packages/tableprinter"],
"@shumai/transcode": ["@shumai/transcode@workspace:packages/transcode"],
"@shumai/transcode-app": ["@shumai/transcode-app@workspace:apps/transcode"],
@@ -1004,6 +1058,8 @@
"@smithy/util-utf8": ["@smithy/util-utf8@2.3.0", "", { "dependencies": { "@smithy/util-buffer-from": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="],
"@sqlite.org/sqlite-wasm": ["@sqlite.org/sqlite-wasm@3.48.0-build4", "", { "bin": { "sqlite-wasm": "bin/index.js" } }, "sha512-hI6twvUkzOmyGZhQMza1gpfqErZxXRw6JEsiVjUbo7tFanVD+8Oil0Ih3l2nGzHdxPI41zFmfUQG7GHqhciKZQ=="],
"@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
"@standard-schema/utils": ["@standard-schema/utils@0.3.0", "", {}, "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g=="],
@@ -1068,8 +1124,6 @@
"@tailwindcss/postcss": ["@tailwindcss/postcss@4.3.0", "", { "dependencies": { "@alloc/quick-lru": "^5.2.0", "@tailwindcss/node": "4.3.0", "@tailwindcss/oxide": "4.3.0", "postcss": "^8.5.10", "tailwindcss": "4.3.0" } }, "sha512-Jm05Tjx+9yCLGv5qw1c+84Psds8MnyrEQYCB+FFk2lgGiUjlRqdxke4mVTuYrj2xnVZqKim2Apr5ySuQRYAw/w=="],
"@tailwindcss/vite": ["@tailwindcss/vite@4.3.0", "", { "dependencies": { "@tailwindcss/node": "4.3.0", "@tailwindcss/oxide": "4.3.0", "tailwindcss": "4.3.0" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-t6J3OrB5Fc0ExuhohouH0fWUGMYL6PTLhW+E7zIk/pdbnJARZDCwjBznFnkh5ynRnIRSI4YjtTH0t6USjJISrw=="],
"@tanstack/devtools-event-client": ["@tanstack/devtools-event-client@0.4.3", "", { "bin": { "intent": "bin/intent.js" } }, "sha512-OZI6QyULw0FI0wjgmeYzCIfbgPsOEzwJtCpa69XrfLMtNXLGnz3d/dIabk7frg0TmHo+Ah49w5I4KC7Tufwsvw=="],
"@tanstack/form-core": ["@tanstack/form-core@1.33.0", "", { "dependencies": { "@tanstack/devtools-event-client": "^0.4.1", "@tanstack/pacer-lite": "^0.1.1", "@tanstack/store": "^0.11.0" } }, "sha512-AV4Pw9Dk4orFsuPBcDssfWMJFs+yMYBae7zZ4oTqrCf4ftNGQKxvrQRZeqKHG6A4TkiLeSvf2kzIjcVkrW7E6w=="],
@@ -1128,15 +1182,13 @@
"@testcontainers/postgresql": ["@testcontainers/postgresql@12.0.1", "", { "dependencies": { "testcontainers": "^12.0.1" } }, "sha512-6SyyduUM6lTAo4UwKG1aCochP6wTe0k7/W/m5uODZQMUrV3STk6/28Km3474JLGZdw/P793BUEF2IeU7rDyoEg=="],
"@testing-library/dom": ["@testing-library/dom@10.4.1", "", { "dependencies": { "@babel/code-frame": "^7.10.4", "@babel/runtime": "^7.12.5", "@types/aria-query": "^5.0.1", "aria-query": "5.3.0", "dom-accessibility-api": "^0.5.9", "lz-string": "^1.5.0", "picocolors": "1.1.1", "pretty-format": "^27.0.2" } }, "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg=="],
"@testing-library/react": ["@testing-library/react@16.3.2", "", { "dependencies": { "@babel/runtime": "^7.12.5" }, "peerDependencies": { "@testing-library/dom": "^10.0.0", "@types/react": "^18.0.0 || ^19.0.0", "@types/react-dom": "^18.0.0 || ^19.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g=="],
"@types/adm-zip": ["@types/adm-zip@0.5.8", "", { "dependencies": { "@types/node": "*" } }, "sha512-RVVH7QvZYbN+ihqZ4kX/dMiowf6o+Jk1fNwiSdx0NahBJLU787zkULhGhJM8mf/obmLGmgdMM0bXsQTmyfbR7Q=="],
"@types/babel__core": ["@types/babel__core@7.20.5", "", { "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA=="],
"@types/babel__generator": ["@types/babel__generator@7.27.0", "", { "dependencies": { "@babel/types": "^7.0.0" } }, "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg=="],
"@types/babel__template": ["@types/babel__template@7.4.4", "", { "dependencies": { "@babel/parser": "^7.1.0", "@babel/types": "^7.0.0" } }, "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A=="],
"@types/babel__traverse": ["@types/babel__traverse@7.28.0", "", { "dependencies": { "@babel/types": "^7.28.2" } }, "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q=="],
"@types/aria-query": ["@types/aria-query@5.0.4", "", {}, "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw=="],
"@types/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
@@ -1204,6 +1256,10 @@
"@types/use-sync-external-store": ["@types/use-sync-external-store@0.0.6", "", {}, "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg=="],
"@types/whatwg-mimetype": ["@types/whatwg-mimetype@3.0.2", "", {}, "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA=="],
"@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
"@types/yauzl": ["@types/yauzl@2.10.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="],
"@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.60.1", "", { "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.60.1", "@typescript-eslint/type-utils": "8.60.1", "@typescript-eslint/utils": "8.60.1", "@typescript-eslint/visitor-keys": "8.60.1", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.60.1", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-JQ4S5GB0tfjO8BuJ4fcX+HodkzJjYBV+7OJ+wLygaX7OGQ7FudyHL4NSCA6ob+w3Yn+5MkKIozOwQhXeM7opVg=="],
@@ -1234,8 +1290,6 @@
"@videojs/xhr": ["@videojs/xhr@2.7.0", "", { "dependencies": { "@babel/runtime": "^7.5.5", "global": "~4.4.0", "is-function": "^1.0.1" } }, "sha512-giab+EVRanChIupZK7gXjHy90y3nncA2phIOyG3Ne5fvpiMJzvqYwiTOnEVW2S4CoYcuKJkomat7bMXA/UoUZQ=="],
"@vitejs/plugin-react": ["@vitejs/plugin-react@5.2.0", "", { "dependencies": { "@babel/core": "^7.29.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-rc.3", "@types/babel__core": "^7.20.5", "react-refresh": "^0.18.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-YmKkfhOAi3wsB1PhJq5Scj3GXMn3WvtQ/JC0xoopuHoXSdmtdStOpFrYaT1kie2YgFBcIe64ROzMYRjCrYOdYw=="],
"@vitest/expect": ["@vitest/expect@4.1.8", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.1.8", "@vitest/utils": "4.1.8", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" } }, "sha512-h3nDO677RDLEGlBxyQ5CW8RlMThSKSRLUePLOx09gNIWRL40edgA1GCZSZgf1W55MFAG6/Sw14KeaAnqv0NKdQ=="],
"@vitest/mocker": ["@vitest/mocker@4.1.8", "", { "dependencies": { "@vitest/spy": "4.1.8", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-LEiN/xe4OSIbKe9HQIp5OC24agGD9J5CnmMgsLohVVoOPWL9a2sBoR6VBx43jQZb7Kr1l4RCuyCJzcAa0+dojw=="],
@@ -1308,7 +1362,7 @@
"ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
"ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
"ansi-styles": ["ansi-styles@5.2.0", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="],
"ansis": ["ansis@4.3.1", "", {}, "sha512-BJ8/l4R5LRE7hW9WdSuGYrLSHi2ynxeFpDFbH0K/CgNeY/tyhk+vO6TYxXC5r5CpUhNVX310xzPsN/H9lCdfOA=="],
@@ -1318,10 +1372,14 @@
"aria-hidden": ["aria-hidden@1.2.6", "", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="],
"aria-query": ["aria-query@5.3.0", "", { "dependencies": { "dequal": "^2.0.3" } }, "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A=="],
"array-buffer-byte-length": ["array-buffer-byte-length@1.0.2", "", { "dependencies": { "call-bound": "^1.0.3", "is-array-buffer": "^3.0.5" } }, "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw=="],
"array-includes": ["array-includes@3.1.9", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.4", "define-properties": "^1.2.1", "es-abstract": "^1.24.0", "es-object-atoms": "^1.1.1", "get-intrinsic": "^1.3.0", "is-string": "^1.1.1", "math-intrinsics": "^1.1.0" } }, "sha512-FmeCCAenzH0KH381SPT5FZmiA/TmpndpcaShhfgEN9eCVjnFBqq3l1xrI42y8+PPLI6hypzou4GXw00WHmPBLQ=="],
"array-timsort": ["array-timsort@1.0.3", "", {}, "sha512-/+3GRL7dDAGEfM6TseQk/U+mi18TU2Ms9I3UlLdUMhz2hbvGNTKdj9xniwXfUqgYhHxRx0+8UnKkvlNwVU+cWQ=="],
"array.prototype.findlast": ["array.prototype.findlast@1.2.5", "", { "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", "es-abstract": "^1.23.2", "es-errors": "^1.3.0", "es-object-atoms": "^1.0.0", "es-shim-unscopables": "^1.0.2" } }, "sha512-CVvd6FHg1Z3POpBLxO6E6zr+rSKEQ9L6rZHAaY7lLfhKsWYUBBOuMs0e9o24oopj6H+geRCX0YJ+TJLBK2eHyQ=="],
"array.prototype.flat": ["array.prototype.flat@1.3.3", "", { "dependencies": { "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-abstract": "^1.23.5", "es-shim-unscopables": "^1.0.2" } }, "sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg=="],
@@ -1400,6 +1458,8 @@
"buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="],
"buffer-image-size": ["buffer-image-size@0.6.4", "", { "dependencies": { "@types/node": "*" } }, "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ=="],
"buildcheck": ["buildcheck@0.0.7", "", {}, "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA=="],
"bun": ["bun@1.3.14", "", { "optionalDependencies": { "@oven/bun-darwin-aarch64": "1.3.14", "@oven/bun-darwin-x64": "1.3.14", "@oven/bun-darwin-x64-baseline": "1.3.14", "@oven/bun-freebsd-aarch64": "1.3.14", "@oven/bun-freebsd-x64": "1.3.14", "@oven/bun-linux-aarch64": "1.3.14", "@oven/bun-linux-aarch64-android": "1.3.14", "@oven/bun-linux-aarch64-musl": "1.3.14", "@oven/bun-linux-x64": "1.3.14", "@oven/bun-linux-x64-android": "1.3.14", "@oven/bun-linux-x64-baseline": "1.3.14", "@oven/bun-linux-x64-musl": "1.3.14", "@oven/bun-linux-x64-musl-baseline": "1.3.14", "@oven/bun-windows-aarch64": "1.3.14", "@oven/bun-windows-x64": "1.3.14", "@oven/bun-windows-x64-baseline": "1.3.14" }, "os": [ "!aix", "!sunos", "!openbsd", ], "cpu": [ "x64", "arm64", ], "bin": { "bun": "bin/bun.exe", "bunx": "bin/bunx.exe" } }, "sha512-aB6GVd42x1Y5ie1K16SF+oLGtgSkwX9hgoDdIW88pjvfTccU8F1vfpoOt34QLv0dZ1v3XimtaxPlZUG81Gx9Zg=="],
@@ -1458,7 +1518,9 @@
"comma-separated-tokens": ["comma-separated-tokens@2.0.3", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="],
"commander": ["commander@12.1.0", "", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="],
"commander": ["commander@11.1.0", "", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="],
"comment-json": ["comment-json@4.6.2", "", { "dependencies": { "array-timsort": "^1.0.3", "esprima": "^4.0.1" } }, "sha512-R2rze/hDX30uul4NZoIZ76ImSJLFxn/1/ZxtKC1L77y2X1k+yYu1joKbAtMA2Fg3hZrTOiw0I5mwVMo0cf250w=="],
"compress-commons": ["compress-commons@6.0.2", "", { "dependencies": { "crc-32": "^1.2.0", "crc32-stream": "^6.0.0", "is-stream": "^2.0.1", "normalize-path": "^3.0.0", "readable-stream": "^4.0.0" } }, "sha512-6FqVXeETqWPoGcfzrXb37E50NP0LXT8kAMu5ooZayhWWdgEY4lBEEcbQNXtkuKQsGduxiIcI4gOTsxTmuq/bSg=="],
@@ -1466,6 +1528,8 @@
"confbox": ["confbox@0.2.4", "", {}, "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ=="],
"consola": ["consola@3.4.0", "", {}, "sha512-EiPU8G6dQG0GFHNR8ljnZFki/8a+cQwEQ+7wpxdChl02Q8HXlwEZWD5lqAF8vC2sEC3Tehr8hy7vErz88LHyUA=="],
"convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="],
"cookie-es": ["cookie-es@3.1.1", "", {}, "sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg=="],
@@ -1522,6 +1586,8 @@
"decode-named-character-reference": ["decode-named-character-reference@1.3.0", "", { "dependencies": { "character-entities": "^2.0.0" } }, "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q=="],
"dedent": ["dedent@1.5.1", "", { "peerDependencies": { "babel-plugin-macros": "^3.1.0" }, "optionalPeers": ["babel-plugin-macros"] }, "sha512-+LxW+KLWxu3HW3M2w2ympwtqPrqYRzU8fqi6Fhd18fBALe15blJPI/I4+UHveMVG6lJqB4JNd4UG0S5cnVHwIg=="],
"deep-is": ["deep-is@0.1.4", "", {}, "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ=="],
"deepmerge-ts": ["deepmerge-ts@7.1.5", "", {}, "sha512-HOJkrhaYsweh+W+e74Yn7YStZOilkoPb6fycpwNLKzSPtruFs48nYis0zy5yJz1+ktUhHxoRDJ27RQAWLIJVJw=="],
@@ -1554,6 +1620,8 @@
"doctrine": ["doctrine@2.1.0", "", { "dependencies": { "esutils": "^2.0.2" } }, "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw=="],
"dom-accessibility-api": ["dom-accessibility-api@0.5.16", "", {}, "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg=="],
"dom-walk": ["dom-walk@0.1.2", "", {}, "sha512-6QvTW9mrGeIegrFXdtQi9pk7O/nSK6lSdXW2eqUspN5LWD7UTji2Fqw5V2YLjBpHEoU9Xl/eUWNpDeZvoyOv2w=="],
"dotenv": ["dotenv@16.6.1", "", {}, "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow=="],
@@ -1584,6 +1652,8 @@
"enhanced-resolve": ["enhanced-resolve@5.22.1", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-6QEuw3zoX1SJQc7b87aBXke/no+mG2bTBgw29gWMQonLmpEkWoCAVkl+M49e48AZlWzxiDzDZzYdp6kobcyLww=="],
"entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
"env-paths": ["env-paths@3.0.0", "", {}, "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A=="],
"es-abstract": ["es-abstract@1.24.2", "", { "dependencies": { "array-buffer-byte-length": "^1.0.2", "arraybuffer.prototype.slice": "^1.0.4", "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.8", "call-bound": "^1.0.4", "data-view-buffer": "^1.0.2", "data-view-byte-length": "^1.0.2", "data-view-byte-offset": "^1.0.1", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "es-set-tostringtag": "^2.1.0", "es-to-primitive": "^1.3.0", "function.prototype.name": "^1.1.8", "get-intrinsic": "^1.3.0", "get-proto": "^1.0.1", "get-symbol-description": "^1.1.0", "globalthis": "^1.0.4", "gopd": "^1.2.0", "has-property-descriptors": "^1.0.2", "has-proto": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "internal-slot": "^1.1.0", "is-array-buffer": "^3.0.5", "is-callable": "^1.2.7", "is-data-view": "^1.0.2", "is-negative-zero": "^2.0.3", "is-regex": "^1.2.1", "is-set": "^2.0.3", "is-shared-array-buffer": "^1.0.4", "is-string": "^1.1.1", "is-typed-array": "^1.1.15", "is-weakref": "^1.1.1", "math-intrinsics": "^1.1.0", "object-inspect": "^1.13.4", "object-keys": "^1.1.1", "object.assign": "^4.1.7", "own-keys": "^1.0.1", "regexp.prototype.flags": "^1.5.4", "safe-array-concat": "^1.1.3", "safe-push-apply": "^1.0.0", "safe-regex-test": "^1.1.0", "set-proto": "^1.0.0", "stop-iteration-iterator": "^1.1.0", "string.prototype.trim": "^1.2.10", "string.prototype.trimend": "^1.0.9", "string.prototype.trimstart": "^1.0.8", "typed-array-buffer": "^1.0.3", "typed-array-byte-length": "^1.0.3", "typed-array-byte-offset": "^1.0.4", "typed-array-length": "^1.0.7", "unbox-primitive": "^1.1.0", "which-typed-array": "^1.1.19" } }, "sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg=="],
@@ -1626,6 +1696,8 @@
"espree": ["espree@11.2.0", "", { "dependencies": { "acorn": "^8.16.0", "acorn-jsx": "^5.3.2", "eslint-visitor-keys": "^5.0.1" } }, "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw=="],
"esprima": ["esprima@4.0.1", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="],
"esquery": ["esquery@1.7.0", "", { "dependencies": { "estraverse": "^5.1.0" } }, "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g=="],
"esrecurse": ["esrecurse@4.3.0", "", { "dependencies": { "estraverse": "^5.2.0" } }, "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag=="],
@@ -1704,7 +1776,7 @@
"fs-monkey": ["fs-monkey@1.1.0", "", {}, "sha512-QMUezzXWII9EV5aTFXW1UBVUO77wYPpjqIF8/AviUCThNeSYZykpoTixUeaNNBwmCev0AMDWMAni+f8Hxb1IFw=="],
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"fsevents": ["fsevents@2.3.2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="],
"function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
@@ -1768,6 +1840,8 @@
"graphmatch": ["graphmatch@1.1.1", "", {}, "sha512-5ykVn/EXM1hF0XCaWh05VbYvEiOL2lY1kBxZtaYsyvjp7cmWOU1XsAdfQBwClraEofXDT197lFbXOEVMHpvQOg=="],
"happy-dom": ["happy-dom@20.10.6", "", { "dependencies": { "@types/node": ">=20.0.0", "@types/whatwg-mimetype": "^3.0.2", "@types/ws": "^8.18.1", "buffer-image-size": "^0.6.4", "entities": "^7.0.1", "whatwg-mimetype": "^3.0.0", "ws": "^8.21.0" } }, "sha512-6QD0ilzDDt93tX44y8tbmZdAcdTRYDhUP+Asgi6pC8Pp5IA3cvaZGyoVN/EGtlq9ziT65iPuBBn3ASLr6hCgVw=="],
"has-bigints": ["has-bigints@1.1.0", "", {}, "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg=="],
"has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
@@ -1800,6 +1874,8 @@
"https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="],
"human-id": ["human-id@4.2.0", "", { "bin": { "human-id": "dist/cli.js" } }, "sha512-K3GbkIWqyvvlpfhBPlbEvD97TtqBpAYA4kt+cn2lD2x2HuohzZCibcA2nOlnJT6exqvJLggoB5nv2dNf192nEA=="],
"hyperdyperid": ["hyperdyperid@1.2.0", "", {}, "sha512-Y93lCzHYgGWdrJ66yIktxiaGULYc6oGiABxhcO5AufBeOyoIdZF7bIfLaOrbM0iGIOXQQgxxRrFEnb+Y6w1n4A=="],
"iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
@@ -1912,6 +1988,8 @@
"joycon": ["joycon@3.1.1", "", {}, "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw=="],
"js-sha256": ["js-sha256@0.11.1", "", {}, "sha512-o6WSo/LUvY2uC4j7mO50a2ms7E/EAdbP0swigLV+nzHKTTaYnaLIWJ02VdXrsJX0vGedDESQnLsOekr94ryfjg=="],
"js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
"jsesc": ["jsesc@3.1.0", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
@@ -1992,6 +2070,8 @@
"lucide-react": ["lucide-react@1.17.0", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-9FA9evdox/JQL5PT57fdA1x/yg8T7knJ98+zjTL3UfKza6pflQUUh3XtaQIHKvnsJw1lmsEyHVlt5jchYxOQ5w=="],
"lz-string": ["lz-string@1.5.0", "", { "bin": { "lz-string": "bin/bin.js" } }, "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ=="],
"m3u8-parser": ["m3u8-parser@7.2.0", "", { "dependencies": { "@babel/runtime": "^7.12.5", "@videojs/vhs-utils": "^4.1.1", "global": "^4.4.0" } }, "sha512-CRatFqpjVtMiMaKXxNvuI3I++vUumIXVVT/JpCpdU/FynV/ceVw1qpPyyBNindL+JlPMSesx+WX1QJaZEJSaMQ=="],
"magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
@@ -2198,6 +2278,10 @@
"pkg-types": ["pkg-types@2.3.1", "", { "dependencies": { "confbox": "^0.2.4", "exsolve": "^1.0.8", "pathe": "^2.0.3" } }, "sha512-y+ichcgc2LrADuhLNAx8DFjVfgz91pRxfZdI3UDhxHvcVEZsenLO+7XaU5vOp0u/7V/wZ+plyuQxtrDlZJ+yeg=="],
"playwright": ["playwright@1.61.1", "", { "dependencies": { "playwright-core": "1.61.1" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ=="],
"playwright-core": ["playwright-core@1.61.1", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg=="],
"possible-typed-array-names": ["possible-typed-array-names@1.1.0", "", {}, "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg=="],
"postcss": ["postcss@8.5.15", "", { "dependencies": { "nanoid": "^3.3.12", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A=="],
@@ -2220,6 +2304,8 @@
"prettier-linter-helpers": ["prettier-linter-helpers@1.0.1", "", { "dependencies": { "fast-diff": "^1.1.2" } }, "sha512-SxToR7P8Y2lWmv/kTzVLC1t/GDI2WGjMwNhLLE9qtH8Q13C+aEmuRlzDst4Up4s0Wc8sF2M+J57iB3cMLqftfg=="],
"pretty-format": ["pretty-format@27.5.1", "", { "dependencies": { "ansi-regex": "^5.0.1", "ansi-styles": "^5.0.0", "react-is": "^17.0.1" } }, "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ=="],
"prisma": ["prisma@7.8.0", "", { "dependencies": { "@prisma/config": "7.8.0", "@prisma/dev": "0.24.3", "@prisma/engines": "7.8.0", "@prisma/studio-core": "0.27.3", "mysql2": "3.15.3", "postgres": "3.4.7" }, "peerDependencies": { "better-sqlite3": ">=9.0.0", "typescript": ">=5.4.0" }, "optionalPeers": ["better-sqlite3", "typescript"], "bin": { "prisma": "build/index.js" } }, "sha512-yfN4yrw7HV9kEJhoy1+jgah0jafEIQsf7uWouSsM8MvJtlubsk+kM7AIBWZ8+GJl74Yj3c+nbYqBkMOxtsZ3Lw=="],
"prisma-json-types-generator": ["prisma-json-types-generator@4.1.1", "", { "dependencies": { "@prisma/generator-helper": "^7.2.0", "semver": "^7.7.3", "try": "^1.0.3", "tslib": "^2.8.1" }, "peerDependencies": { "@prisma/client": "^7.2.0", "prisma": "^7.2.0", "typescript": "^5.9.3" }, "bin": { "prisma-json-types-generator": "index.js" } }, "sha512-oz0MYu1r2Jqu3qOGCEGulz6RjPsECVjyS3ZAz3HEmz0jkKbVkZEwQyksNJm0X5utV1TZCmaG/98EPExN7S22xw=="],
@@ -2278,8 +2364,6 @@
"react-redux": ["react-redux@9.3.0", "", { "dependencies": { "@types/use-sync-external-store": "^0.0.6", "use-sync-external-store": "^1.4.0" }, "peerDependencies": { "@types/react": "^18.2.25 || ^19", "react": "^18.0 || ^19", "redux": "^5.0.0" }, "optionalPeers": ["@types/react", "redux"] }, "sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g=="],
"react-refresh": ["react-refresh@0.18.0", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="],
"react-remove-scroll": ["react-remove-scroll@2.7.2", "", { "dependencies": { "react-remove-scroll-bar": "^2.3.7", "react-style-singleton": "^2.2.3", "tslib": "^2.1.0", "use-callback-ref": "^1.3.3", "use-sidecar": "^1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q=="],
"react-remove-scroll-bar": ["react-remove-scroll-bar@2.3.8", "", { "dependencies": { "react-style-singleton": "^2.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q=="],
@@ -2400,6 +2484,8 @@
"split2": ["split2@4.2.0", "", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="],
"sqlite-wasm-kysely": ["sqlite-wasm-kysely@0.3.0", "", { "dependencies": { "@sqlite.org/sqlite-wasm": "^3.48.0-build2" }, "peerDependencies": { "kysely": "*" } }, "sha512-TzjBNv7KwRw6E3pdKdlRyZiTmUIE0UttT/Sl56MVwVARl/u5gp978KepazCJZewFUnlWHz9i3NQd4kOtP/Afdg=="],
"sqlstring": ["sqlstring@2.3.3", "", {}, "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg=="],
"ssh-remote-port-forward": ["ssh-remote-port-forward@1.0.4", "", { "dependencies": { "@types/ssh2": "^0.5.48", "ssh2": "^1.4.0" } }, "sha512-x0LV1eVDwjf1gmG7TTnfqIzf+3VPRz7vrNIjX6oYLbeCrf/PeVY6hkT68Mg+q02qXxQhrLjB0jfgvhevoCRmLQ=="],
@@ -2550,12 +2636,14 @@
"unist-util-visit-parents": ["unist-util-visit-parents@6.0.2", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ=="],
"unplugin": ["unplugin@3.0.0", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "picomatch": "^4.0.3", "webpack-virtual-modules": "^0.6.2" } }, "sha512-0Mqk3AT2TZCXWKdcoaufeXNukv2mTrEZExeXlHIOZXdqYoHHr4n51pymnwV8x2BOVxwXbK2HLlI7usrqMpycdg=="],
"unplugin": ["unplugin@2.3.11", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "acorn": "^8.15.0", "picomatch": "^4.0.3", "webpack-virtual-modules": "^0.6.2" } }, "sha512-5uKD0nqiYVzlmCRs01Fhs2BdkEgBS3SAVP6ndrBsuK42iC2+JHyxM05Rm9G8+5mkmRtzMZGY8Ct5+mliZxU/Ww=="],
"update-browserslist-db": ["update-browserslist-db@1.2.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],
"uri-js": ["uri-js@4.4.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="],
"urlpattern-polyfill": ["urlpattern-polyfill@10.1.0", "", {}, "sha512-IGjKp/o0NL3Bso1PymYURCJxMPNAf/ILOpendP9f5B6e1rTJgdgiOvgfoT8VxCAdY+Wisb9uhGaJJf3yZ2V9nw=="],
"use-callback-ref": ["use-callback-ref@1.3.3", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg=="],
"use-image": ["use-image@1.1.4", "", { "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-P+swhszzHHgEb2X2yQ+vQNPCq/8Ks3hyfdXAVN133pvnvK7UK++bUaZUa5E+A3S02Mw8xOCBr9O6CLhk2fjrWA=="],
@@ -2602,6 +2690,8 @@
"webpack-virtual-modules": ["webpack-virtual-modules@0.6.2", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="],
"whatwg-mimetype": ["whatwg-mimetype@3.0.0", "", {}, "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q=="],
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
"which-boxed-primitive": ["which-boxed-primitive@1.1.1", "", { "dependencies": { "is-bigint": "^1.1.0", "is-boolean-object": "^1.2.1", "is-number-object": "^1.1.1", "is-string": "^1.1.1", "is-symbol": "^1.1.1" } }, "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA=="],
@@ -2656,6 +2746,8 @@
"zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],
"@anthropic-ai/sandbox-runtime/commander": ["commander@12.1.0", "", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="],
"@anthropic-ai/sandbox-runtime/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"@aws-sdk/client-bedrock-runtime/@smithy/node-http-handler": ["@smithy/node-http-handler@4.7.6", "", { "dependencies": { "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-3fya8i7GrJilQouk4cZJKdy5k8MWQBpjfXrRNaXDedH8r779tr0jcxyH3+yoTmsluc2+vF4S343yFbnvu8ExDQ=="],
@@ -2674,6 +2766,10 @@
"@grpc/grpc-js/@grpc/proto-loader": ["@grpc/proto-loader@0.8.1", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.5.5", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg=="],
"@inlang/sdk/@sinclair/typebox": ["@sinclair/typebox@0.31.28", "", {}, "sha512-/s55Jujywdw/Jpan+vsy6JZs1z2ZTGxTmbZTPiuSL2wz9mfzA2gN1zzaqmvfi4pq+uOt7Du85fkiwv5ymW84aQ=="],
"@inlang/sdk/uuid": ["uuid@14.0.0", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-Qo+uWgilfSmAhXCMav1uYFynlQO7fMFiMVZsQqZRMIXp0O7rR7qjkj+cPvBHLgBqi960QCoo/PH2/6ZtVqKvrg=="],
"@isaacs/cliui/string-width": ["string-width@5.1.2", "", { "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" } }, "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA=="],
"@isaacs/cliui/strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="],
@@ -2688,6 +2784,8 @@
"@jsonjoy.com/util/@jsonjoy.com/buffers": ["@jsonjoy.com/buffers@1.2.1", "", { "peerDependencies": { "tslib": "2" } }, "sha512-12cdlDwX4RUM3QxmUbVJWqZ/mrK6dFQH4Zxq6+r1YXKXYBNgZXndx2qbCJwh3+WWkCSn67IjnlG3XYTvmvYtgA=="],
"@lix-js/sdk/uuid": ["uuid@14.0.0", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-Qo+uWgilfSmAhXCMav1uYFynlQO7fMFiMVZsQqZRMIXp0O7rR7qjkj+cPvBHLgBqi960QCoo/PH2/6ZtVqKvrg=="],
"@prisma/dev/std-env": ["std-env@3.10.0", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="],
"@prisma/engines/@prisma/get-platform": ["@prisma/get-platform@7.8.0", "", { "dependencies": { "@prisma/debug": "7.8.0" } }, "sha512-WlxgRGnolL8VH2EmkH1R/DkKNr/mVdS3G2h42IZFFZ3eUrH9OT6t73kIOSlkkrv50wG123Iq8d96ufv5LlZktw=="],
@@ -2892,6 +2990,8 @@
"@tanstack/react-router/@tanstack/react-store": ["@tanstack/react-store@0.9.3", "", { "dependencies": { "@tanstack/store": "0.9.3", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-y2iHd/N9OkoQbFJLUX1T9vbc2O9tjH0pQRgTcx1/Nz4IlwLvkgpuglXUx+mXt0g5ZDFrEeDnONPqkbfxXJKwRg=="],
"@tanstack/router-plugin/unplugin": ["unplugin@3.0.0", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "picomatch": "^4.0.3", "webpack-virtual-modules": "^0.6.2" } }, "sha512-0Mqk3AT2TZCXWKdcoaufeXNukv2mTrEZExeXlHIOZXdqYoHHr4n51pymnwV8x2BOVxwXbK2HLlI7usrqMpycdg=="],
"@temporalio/common/ms": ["ms@3.0.0-canary.1", "", {}, "sha512-kh8ARjh8rMN7Du2igDRO9QJnqCb2xYTJxyQYK7vJJS4TvLLmsbyhiKpSW+t+y26gyOyMd0riphX0GeWKU3ky5g=="],
"@temporalio/proto/protobufjs": ["protobufjs@7.5.5", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.4", "@protobufjs/eventemitter": "^1.1.0", "@protobufjs/fetch": "^1.1.0", "@protobufjs/float": "^1.0.2", "@protobufjs/inquire": "^1.1.0", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.0", "@types/node": ">=13.7.0", "long": "^5.0.0" } }, "sha512-3wY1AxV+VBNW8Yypfd1yQY9pXnqTAN+KwQxL8iYm3/BjKYMNg4i0owhEe26PWDOMaIrzeeF98Lqd5NGz4omiIg=="],
@@ -2962,6 +3062,8 @@
"pg-types/postgres-array": ["postgres-array@2.0.0", "", {}, "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA=="],
"pretty-format/react-is": ["react-is@17.0.2", "", {}, "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="],
"prisma-json-types-generator/semver": ["semver@7.8.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-rkVq3IXh+4FDGch+KwzX3aV9W3kO54GyEgpvBzSyctDA6Xtd7RJQV1xmXbeQp5v7+VzLOfVqiutSE6GICgPFvg=="],
"protobufjs/@types/node": ["@types/node@22.19.19", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-dyh/xO2Fh5bYrfWaaqGrRQQGkNdmYw6AmaAUvYeUMNTWQtvb796ikLdmTchRmOlOiIJ1TDXfWgVx1QkUlQ6Hew=="],
@@ -3048,6 +3150,8 @@
"readdir-glob/minimatch": ["minimatch@5.1.9", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw=="],
"rollup/fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"schema-utils/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
"sharp/semver": ["semver@7.8.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-rkVq3IXh+4FDGch+KwzX3aV9W3kO54GyEgpvBzSyctDA6Xtd7RJQV1xmXbeQp5v7+VzLOfVqiutSE6GICgPFvg=="],
@@ -3062,8 +3166,14 @@
"thread-stream/real-require": ["real-require@1.0.0", "", {}, "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g=="],
"vite/fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"webpack/eslint-scope": ["eslint-scope@5.1.1", "", { "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^4.1.1" } }, "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw=="],
"wrap-ansi/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=="],
"yauzl/buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
"@isaacs/cliui/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="],
@@ -0,0 +1,45 @@
services:
postgres:
image: docker.m.daocloud.io/pgvector/pgvector:pg18
container_name: shumai_postgres
environment:
POSTGRES_USER: shumai
POSTGRES_PASSWORD: shumai_password
POSTGRES_DB: shumai_db
ports:
- '5432:5432'
volumes:
- postgres_data:/var/lib/postgresql/18/docker
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U shumai -d shumai_db']
interval: 5s
timeout: 5s
retries: 5
shumai:
image: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai:latest
container_name: shumai_app
ports:
- '3000:3000'
volumes:
- ./data:/app/data
environment:
# Database Configuration
DATABASE_URL: postgres://shumai:shumai_password@shumai_postgres:5432/shumai_db?search_path=public&sslmode=disable
# Server Configuration
SHUMAI_SERVER_PORT: 3000
# S3 Configuration
STORAGE_BACKEND: local
AWS_ENDPOINT_URL_S3: http://localhost:3000
# Better Auth
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
depends_on:
postgres:
condition: service_healthy
volumes:
postgres_data:
+6 -3
View File
@@ -17,22 +17,25 @@ services:
retries: 5
shumai:
image: shumaione/shumai:main
image: shumaione/shumai:latest
container_name: shumai_app
ports:
- '3000:3000'
volumes:
- ../../data:/app/data
- ./data:/app/data
environment:
# Database Configuration
DATABASE_URL: postgres://shumai:shumai_password@shumai_postgres:5432/shumai_db?search_path=public&sslmode=disable
# Server Configuration
SHUMAI_SERVER_PORT: 3000
# S3 Configuration
STORAGE_BACKEND: local
AWS_ENDPOINT_URL_S3: http://localhost:3000
# Better Auth
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
BETTER_AUTH_URL: https://staging.shumai.one/
depends_on:
postgres:
@@ -33,7 +33,6 @@ services:
S3_ACCESS_KEY_ID: ID
S3_SECRET_ACCESS_KEY: KEY
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
BETTER_AUTH_URL: http://localhost:3000
WORKFLOW_EXECUTOR: temporal
TEMPORAL_ADDRESS: temporal:7233
GEMINI_API_KEY: KEY
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

+94
View File
@@ -0,0 +1,94 @@
---
title: Environment Variables
description: Comprehensive configuration reference for Shumai.
---
Shumai is configured via environment variables. You can define these variables in a `.env` file at the root of your application workspace, or pass them directly to your Docker containers.
---
## Database Config
| Variable | Description | Example / Default |
| :------------- | :----------------------------------------------------------------------------------------- | :------------------------------------------------------- |
| `DATABASE_URL` | PostgreSQL connection URL. Must target a database with the `pgvector` extension installed. | `postgresql://user:pass@localhost:5432/db?schema=public` |
---
## Server Config
| Variable | Description | Example / Default |
| :---------------------- | :------------------------------------------------------------------------------------------------ | :---------------- |
| `SHUMAI_SERVER_PORT` | The port on which the Shumai web server will listen. | `3000` (default) |
| `MAX_REQUEST_BODY_SIZE` | Maximum allowed size for request bodies (e.g., for large file uploads). Default is 10GB in bytes. | `10737418240` |
---
## Authentication Config
| Variable | Description | Example / Default |
| :------------------- | :--------------------------------------------------------------------- | :--------------------------------------------------------------- |
| `BETTER_AUTH_SECRET` | A secure, random 32-byte secret used to sign session cookies and JWTs. | Generate with `openssl rand -base64 32` |
| `BETTER_AUTH_URL` | The public URL of your Hono backend API. Used for redirect flows. | `http://localhost:3000` (respects `SHUMAI_SERVER_PORT` fallback) |
---
## Storage Config
Shumai supports storing files locally or on S3-compatible endpoints.
| Variable | Description | Example / Default |
| :------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------ |
| `STORAGE_BACKEND` | Storage type. Use `local` for local file system storage, or `s3` for S3-compatible cloud storage. | `local` (default) or `s3` |
| `AWS_ENDPOINT_URL_S3` | Endpoint for S3 storage or local storage. Used by the browser to build file upload URLs. Must include port if deploying remotely or using custom ports. | `http://localhost:3000` (respects `SHUMAI_SERVER_PORT` fallback if unset) |
| `S3_BUCKET` | S3 bucket name. | `shumai` (default) |
| `S3_ACCESS_KEY_ID` | Access key credentials for S3. | `minioadmin` (default) |
| `S3_SECRET_ACCESS_KEY` | Secret key credentials for S3. | `minioadmin` (default) |
| `S3_REGION` | S3 storage region. | `auto` (default) |
| `PRESIGNED_URL_EXPIRES_IN` | Number of hours for which generated presigned download/upload links are valid. | `5` (default) |
### Local Storage Port Configuration
When `STORAGE_BACKEND` is set to `local` (default):
- `SHUMAI_SERVER_PORT` configures the port on which the Shumai web server starts and listens.
- `AWS_ENDPOINT_URL_S3` configures the public/external endpoint used by client browsers to upload and download files. It must include the scheme and port.
For example, if you deploy Shumai on a remote server at `http://123.456.7.8` and configure port mapping `12345:3000` (exposing port 3000 internally as port 12345 externally) in Docker Compose:
- Set `SHUMAI_SERVER_PORT` to `3000`.
- Set `AWS_ENDPOINT_URL_S3` to `http://123.456.7.8:12345`.
---
## Workflow Config
Configures whether background transcoding and AI agents are executed locally or offloaded to a Temporal cluster.
| Variable | Description | Example / Default |
| :------------------------- | :------------------------------------------------------------------------------------------------- | :------------------------------ |
| `WORKFLOW_EXECUTOR` | Engine choice. Use `local` for in-process database polling, or `temporal` for distributed workers. | `local` (default) or `temporal` |
| `TEMPORAL_ADDRESS` | Host and port of the Temporal cluster gRPC service. | `localhost:7233` (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) |
---
## Logging Config
| Variable | Description | Example / Default |
| :----------- | :--------------------------------------------------------------------------------------------------- | :---------------- |
| `LOG_LEVEL` | Pino logging level. Options: `debug`, `info`, `warn`, `error`. | `info` (default) |
| `LOG_FORMAT` | Log format style. Use `json` for production logging, or `pretty` for human-readable terminal output. | `json` (default) |
---
## LLM API Key
API keys to AI providers on startup.
| Variable | Description | Example / Default |
| :------------------ | :---------------------------------- | :---------------- |
| `GEMINI_API_KEY` | API key for Google Gemini provider. | `AIzaSy...` |
| `OPENAI_API_KEY` | API key for OpenAI provider. | `sk-proj-...` |
| `ANTHROPIC_API_KEY` | API key for Anthropic provider. | `sk-ant-...` |
+85
View File
@@ -0,0 +1,85 @@
---
title: Deploy with Temporal
description: Configure a high-scale production deployment using Temporal and S3-compatible storage.
---
For production environments or workloads with high-volume video processing and heavy AI agent usage, running background tasks on a single server can cause bottlenecks. Shumai resolves this by offloading task queue management, retries, and background executions to **Temporal**.
This allows you to decouple workloads and run specialized worker nodes on separate, dedicated machines.
---
## How it Works
When configured for Temporal, the core Shumai web application does not process background jobs itself. Instead, it publishes tasks to a Temporal Cluster queue.
```mermaid
graph TD
UserUpload[User Uploads Video] --> WebApp[Shumai Web UI / API]
WebApp -->|Register Task| Temporal[Temporal Cluster]
Temporal -->|Queue: Transcoding| TranscodeWorker[Transcode Worker Machine]
Temporal -->|Queue: AI Agents| AgentWorker[Agent Worker Machine]
```
- **Transcoding Workers**: Can be run on GPU-accelerated or high-CPU compute instances.
- **AI Agent Workers**: Can be run on isolated, sandboxed hosts to safely execute automation scripts.
> [!IMPORTANT]
> **Storage Requirement**: Because the core application and the background workers run on separate machines in a distributed setup, **you must configure an S3-compatible storage backend** (such as AWS S3, Cloudflare R2, or MinIO). Local storage (`STORAGE_BACKEND=local`) is not supported in this mode because the workers and the web application do not share a common filesystem.
---
## Step 1: Deploy the Core Stack
On your primary host machine, spin up the database, Temporal cluster services, and the main Shumai web application:
1. **Download the Temporal Stack Configuration**:
```bash
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/temporal/docker-compose.yaml
```
2. **Configure S3 Settings**:
Open the `docker-compose.yaml` file and set your S3 credentials and endpoint environment variables under the `shumai` service.
3. **Start the Services**:
```bash
docker compose up -d
```
This exposes the web application on port `3000`, the database on `5432`, the Temporal gRPC service on `7233`, and the Temporal management dashboard on `8080`.
---
## Step 2: Configure & Run Workers
On your specialized worker machines, you will run the dedicated background worker services. Each worker requires a `.env` file referencing the database, S3 storage, and the Temporal cluster:
```env
DATABASE_URL=postgresql://shumai:shumai_password@<primary-host-ip>:5432/shumai_db?schema=public
WORKFLOW_EXECUTOR=temporal
TEMPORAL_ADDRESS=<primary-host-ip>:7233
STORAGE_BACKEND=s3
AWS_ENDPOINT_URL_S3=https://your-s3-endpoint.com
S3_BUCKET=shumai
S3_REGION=us-east-1
S3_ACCESS_KEY_ID=your-access-key-id
S3_SECRET_ACCESS_KEY=your-secret-access-key
```
### Media Transcoding Worker
Run this on your media processing nodes (requires system installations of `ffmpeg` and `ffprobe`):
```bash
npm install -g @shumai-one/shumai-transcode
shumai-transcode
```
### AI Agent Worker
Run this on your sandboxed agent execution nodes (requires sandbox dependencies like `bubblewrap` or `sandbox-exec`):
```bash
npm install -g @shumai-one/shumai-agent
shumai-agent
```
> [!IMPORTANT]
> **For Bun Users:** Since the worker package binaries contain a `#!/usr/bin/env node` shebang, running `shumai-transcode` or `shumai-agent` directly will run under Node.js. If you wish to run them using Bun, prefix the commands with `bun run --bun` (e.g., `bun run --bun shumai-transcode` or `bun run --bun shumai-agent`).
+42 -1
View File
@@ -16,7 +16,48 @@
"groups": [
{
"group": "Getting Started",
"pages": ["introduction", "getting-started/docker"]
"pages": [
"getting-started/overview",
"getting-started/quickstart",
"getting-started/s3-storage"
]
},
{
"group": "Using Shumai",
"pages": [
"using-shumai/asset-management",
"using-shumai/comments",
"using-shumai/version-stack",
"using-shumai/sort-and-search",
"using-shumai/semantic-search",
"using-shumai/team-project-management",
"using-shumai/notifications",
"using-shumai/metadata",
"using-shumai/collections",
"using-shumai/share-links"
]
},
{
"group": "Shumai Agent Settings",
"pages": [
"using-shumai/agent-providers",
"using-shumai/agents",
"using-shumai/agent-skills",
"using-shumai/agent-tools",
"using-shumai/agent-sandbox"
]
},
{
"group": "Media Transcoding Settings",
"pages": ["using-shumai/transcode-settings"]
},
{
"group": "Configuration",
"pages": ["configuration/env-variables"]
},
{
"group": "Temporal Deployment",
"pages": ["configuration/temporal"]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

-98
View File
@@ -1,98 +0,0 @@
---
title: Get Started with Docker
description: Learn how to spin up the Shumai stack using Docker Compose.
---
We support two Docker Compose setups depending on your environment and use case:
1. **Local Pre-built Stack**: A lightweight setup to run the core API and frontend using pre-built images.
2. **Temporal Stack**: A production-like environment with full background worker orchestration (Agent and Transcode workers) and Temporal services, built from your local source code.
---
## Prerequisites
Before starting, ensure you have the following installed on your machine:
- **Docker**: [Install Docker Desktop](https://docs.docker.com/get-docker/) or Docker Engine.
- **Docker Compose**: Included in Docker Desktop, or [installed separately](https://docs.docker.com/compose/install/).
- **Git**: To clone and manage the repository.
---
## 1. Local Pre-built Stack
This setup runs a PostgreSQL database (with `pgvector`) and the Shumai application container.
### Step 1: Navigate to the local docker-compose folder
From the root of your Shumai workspace, run:
```bash
cd docker-compose/local
```
### Step 2: Start the services
Spin up the containers in detached mode:
```bash
docker compose up -d
```
### Step 3: Access the application
Once all containers are running and healthy:
- Open your browser and navigate to **`http://localhost:3000`** to access the Shumai Web UI.
### Step 4: Tear down
To stop and remove the containers, run:
```bash
docker compose down
```
---
## 2. Temporal Stack (Recommended for Development)
This setup builds the containers from your local workspace source code and starts the API, workers, and Temporal scheduler.
### Step 1: Navigate to the temporal docker-compose folder
From the root of your Shumai workspace, run:
```bash
cd docker-compose/temporal
```
### Step 2: Start the services
Build the images and run the full stack:
```bash
docker compose up -d --build
```
### Step 3: Access the services
- **Web UI**: Access the Shumai application at **`http://localhost:3000`**.
- **Temporal Dashboard**: View active workflows and orchestration logs at **`http://localhost:8080`**.
### Step 4: Tear down
To stop the services and clean up volumes, run:
```bash
docker compose down -v
```
---
## Troubleshooting
### Port Conflicts
If you receive port conflict errors, ensure that port `3000` (Web UI), `5432` (PostgreSQL), `7233` (Temporal), or `8080` (Temporal UI) are not currently being used by other processes on your machine.
+37
View File
@@ -0,0 +1,37 @@
---
title: Overview
description: Learn about Shumai, a modern collaboration and media review platform.
---
## What is Shumai?
**Shumai** is a self-hosted media collaboration platform designed for creative teams, video editors, designers, and clients. It provides a centralized workspace where you can upload, organize, and review assets (video, audio, images, and documents) in real-time. With built-in AI capabilities and background transcoding, Shumai helps streamline asset organization and feedback workflows.
![Shumai Dashboard](/screenshot.webp)
---
## Core Features
- **Secure Storage**: Host your creative assets locally on your server or connect directly to any S3-compatible cloud storage provider (like AWS S3, Cloudflare R2, or MinIO).
- **Media Commenting & Drawing**: Speed up review cycles with frame-level comments and drawing tools that let you sketch directly onto video frames or images.
- **Version Control**: Stack multiple versions of the same file into a single entry to keep your workspace organized and track revision history.
- **AI-Powered Tags & Search**: Automatically tag your files on upload using Google Gemini, and find assets based on visual or conceptual meaning.
- **Custom Automations**: Build tailored background workflows using custom scripts to automate repetitive team actions.
- **Proxy Transcoding**: Automatically convert heavy camera and design files in the background into web-friendly streaming formats for smooth playback.
---
## Deployment Scales
Depending on your team size and production volume, Shumai can be configured to run in one of two modes:
### 1. Single-Server Deployment (Default)
Ideal for small teams, local development, or low-volume workflows. In this setup, the main web server, database, and background tasks (like transcoding and AI tagging) all run on a single machine.
### 2. High-Scale Distributed Deployment
Recommended for production environments with high-volume video uploads. In this setup, background tasks are managed via a centralized queue (Temporal). This allows you to offload heavy workloads to specialized worker machines (for example, putting video transcoding tasks on high-CPU/GPU machines and AI agents on separate sandboxed environments).
_Note: S3-compatible cloud storage is required for distributed deployments so that all workers can access the uploaded files._
+118
View File
@@ -0,0 +1,118 @@
---
title: Quickstart
description: Get Shumai up and running using Docker, NPM, or from source.
---
We support three installation options. For most administrators, **Docker Compose** is the fastest and easiest way to deploy Shumai.
---
## Option 1: Docker Compose (Recommended)
Docker Compose automatically configures and spins up all required services (the web application, a database, and local storage).
1. **Download the Configuration**:
```bash
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose.yaml
```
2. **Start the Services**:
```bash
docker compose up -d
```
3. **Access the Dashboard**:
Open your browser and navigate to **`http://localhost:3000`** to access the Shumai Web UI.
### Production Deployments (Temporal)
If you are deploying Shumai for a production team with high-volume video uploads, we recommend setting up a distributed deployment using **Temporal** and an S3-compatible storage backend. This offloads resource-heavy video transcoding and AI agents to separate, dedicated worker nodes to keep your main dashboard fast and responsive. For setup instructions, see the [Deploy with Temporal](/configuration/temporal) guide.
---
## Option 2: Install via NPM
You can run Shumai as a global service using the Node Package Manager (NPM).
### System Prerequisites
To handle media processing and security isolation, the host machine must have the following system utilities installed:
- **FFmpeg & FFprobe**: Required for video transcoding and metadata extraction.
- _macOS_: `brew install ffmpeg`
- _Linux (Ubuntu/Debian)_: `sudo apt-get install ffmpeg`
- **Agent Sandbox Utilities**: Used to run custom automation scripts securely.
- _macOS_: `brew install ripgrep`
- _Linux (Ubuntu/Debian)_: `sudo apt-get install bubblewrap socat ripgrep`
### Step-by-Step Setup
1. **Start a Database**:
Shumai requires a PostgreSQL database with the `pgvector` extension. Start a database container:
```bash
docker run --name shumai_postgres \
-e POSTGRES_USER=shumai \
-e POSTGRES_PASSWORD=shumai_password \
-e POSTGRES_DB=shumai_db \
-p 5432:5432 \
-d pgvector/pgvector:pg18
```
2. **Install Shumai**:
```bash
npm install -g @shumai-one/shumai
```
3. **Configure Environment Variables**:
Create a new directory, navigate into it, and create a `.env` file:
```bash
mkdir shumai && cd shumai
```
Create a `.env` file with the following variables:
```env
DATABASE_URL=postgresql://shumai:shumai_password@localhost:5432/shumai_db?schema=public
BETTER_AUTH_SECRET=your-random-32-character-secret-key
STORAGE_BACKEND=local
AWS_ENDPOINT_URL_S3=http://localhost:3000
```
> [!TIP]
> `AWS_ENDPOINT_URL_S3` must include the scheme and port (e.g. `http://localhost:3000`) where Shumai is publicly accessible. This URL is used directly by client browsers for file uploads.
4. **Start Shumai**:
> [!IMPORTANT]
> **For Bun Users:** Since the published package binaries contain a `#!/usr/bin/env node` shebang, running `shumai` directly will execute under Node.js. If you installed using Bun and want to run it under the Bun runtime, prefix the command with `bun run --bun` (e.g., `bun run --bun shumai`).
```bash
shumai
```
Open your browser to `http://localhost:3000`.
---
## Option 3: Run from Source (For Developers)
If you wish to run Shumai locally to customize the platform or contribute:
1. **Clone the Repository**:
```bash
git clone https://github.com/shumaiOne/shumai.git
cd shumai
```
2. **Install Dependencies**:
```bash
bun install
```
3. **Start a Database**:
Launch a local database container (as described in the NPM section above).
4. **Run Migrations**:
Set up your `.env` file at the root, then apply database migrations:
```bash
bun run db:migrate
```
5. **Start the Dev Server**:
```bash
bun run dev
```
This spins up the web server on port `3000` with hot-reloading active.
+125
View File
@@ -0,0 +1,125 @@
---
title: S3 Compatible Storage
description: Configure AWS S3 or any S3-compatible storage backend (Cloudflare R2, MinIO, Google Cloud Storage, etc.) for Shumai.
---
Shumai uses Bun's high-performance native S3 client to store and serve creative assets. By utilizing standard S3 APIs, Shumai can connect to any S3-compatible storage provider, including AWS S3, Cloudflare R2, MinIO, Google Cloud Storage, and more.
Using external S3 storage is highly recommended for production teams. It allows you to separate storage from the application server, scale storage capacity independently, and support distributed media transcoding.
---
## Configuration Variables
To enable S3-compatible storage, update the following environment variables in your `.env` file or Docker Compose configuration:
| Variable | Description | Required | Default / Example |
| :------------------------- | :------------------------------------------------------------------------ | :------- | :----------------------------------- |
| `STORAGE_BACKEND` | Set to `s3` to enable S3 compatible storage. | Yes | `s3` |
| `S3_BUCKET` | The name of the S3 bucket where files will be stored. | Yes | `shumai-bucket` |
| `S3_REGION` | The region of your S3 bucket. | No | `auto` |
| `S3_ACCESS_KEY_ID` | The access key ID for your storage service. | Yes | `your-access-key-id` |
| `S3_SECRET_ACCESS_KEY` | The secret access key for your storage service. | Yes | `your-secret-access-key` |
| `AWS_ENDPOINT_URL_S3` | The endpoint URL of your S3 compatible storage provider. | Yes | `https://s3.us-east-1.amazonaws.com` |
| `PRESIGNED_URL_EXPIRES_IN` | Duration in hours before generated presigned download/upload URLs expire. | No | `5` |
---
## Provider Examples
Below are configuration templates for popular S3 providers. Add these variables to your `.env` file or under the `environment` section in your `docker-compose.yaml`.
### AWS S3
For standard AWS S3, configure the corresponding endpoint URL:
```env
STORAGE_BACKEND=s3
S3_BUCKET=your-shumai-bucket
S3_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
S3_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
AWS_ENDPOINT_URL_S3=https://s3.us-east-1.amazonaws.com
```
### Cloudflare R2
Cloudflare R2 requires your Cloudflare account ID to construct the endpoint URL. Set the region to `auto`:
```env
STORAGE_BACKEND=s3
S3_BUCKET=your-shumai-bucket
S3_ACCESS_KEY_ID=your-r2-access-key-id
S3_SECRET_ACCESS_KEY=your-r2-secret-access-key
AWS_ENDPOINT_URL_S3=https://<account-id>.r2.cloudflarestorage.com
```
### MinIO (Self-Hosted)
For local development or self-hosted environments using MinIO, set the endpoint to your MinIO server URL and port (usually `9000`):
```env
STORAGE_BACKEND=s3
S3_BUCKET=shumai
S3_ACCESS_KEY_ID=minioadmin
S3_SECRET_ACCESS_KEY=minioadmin
AWS_ENDPOINT_URL_S3=http://localhost:9000
```
### Google Cloud Storage (GCS)
Google Cloud Storage provides an S3-compatible XML API. Configure your HMAC credentials and set the endpoint to standard GCS storage:
```env
STORAGE_BACKEND=s3
S3_BUCKET=your-gcs-bucket
S3_ACCESS_KEY_ID=GOOG1EXAMPLETOCKENKEY
S3_SECRET_ACCESS_KEY=your-gcs-hmac-secret-access-key
AWS_ENDPOINT_URL_S3=https://storage.googleapis.com
```
### DigitalOcean Spaces
For DigitalOcean Spaces, set the endpoint URL to match your space's region:
```env
STORAGE_BACKEND=s3
S3_BUCKET=your-spaces-bucket
S3_ACCESS_KEY_ID=your-spaces-access-key-id
S3_SECRET_ACCESS_KEY=your-spaces-secret-access-key
AWS_ENDPOINT_URL_S3=https://nyc3.digitaloceanspaces.com
```
### Supabase Storage
To connect to Supabase Storage via S3, ensure you have enabled S3 connection support in the Supabase Dashboard (`Settings > Storage > Enable connection via S3 protocol`). Copy the endpoint URL and region details from the same settings page:
```env
STORAGE_BACKEND=s3
S3_BUCKET=your-supabase-bucket
S3_REGION=us-east-1
S3_ACCESS_KEY_ID=your-supabase-access-key-id
S3_SECRET_ACCESS_KEY=your-supabase-secret-access-key
AWS_ENDPOINT_URL_S3=https://<account-id>.supabase.co/storage/v1/s3
```
---
## CORS Configuration
Since Shumai uploads files directly from the user's browser using presigned URLs, you must configure **Cross-Origin Resource Sharing (CORS)** on your storage bucket. Without CORS configuration, uploads will fail with network or origin errors.
Ensure your bucket CORS policy allows the following rules from your Shumai application URL (e.g., `http://localhost:3000` or `https://app.shumai.one`):
### CORS JSON Policy Example (AWS S3, R2, GCS)
```json
[
{
"AllowedHeaders": ["*"],
"AllowedMethods": ["GET", "PUT", "POST", "DELETE", "HEAD"],
"AllowedOrigins": ["http://localhost:3000", "https://your-shumai-domain.com"],
"ExposeHeaders": ["ETag"],
"MaxAgeSeconds": 3000
}
]
```
-26
View File
@@ -1,26 +0,0 @@
---
title: Introduction
description: Welcome to Shumai, a modern AI agent and media processing platform.
---
## What is Shumai?
**Shumai** is a highly decoupled, modular platform built with a layered monorepo architecture. It integrates a React-based frontend, a fast Hono API backend, business logic services, and background workflow engines (supporting both local and Temporal-based execution).
### Key Features
- **Decoupled Monorepo Structure**: Managed via Bun Workspaces, ensuring each domain or layer is its own self-contained package.
- **Robust API & Core Service Layers**: Built on Bun and Hono, featuring strict end-to-end type safety with Zod schemas and DTOs.
- **Workflow & Activity Engine**: An orchestration engine capable of polling-based execution locally and enterprise-grade execution via Temporal.
- **Modern UI**: A responsive, clean React interface powered by Tailwind CSS and Shadcn UI.
- **Database Resilience**: Prisma ORM with PostgreSQL and `pgvector` for vector similarity and search capabilities.
## Explore the Documentation
Start by setting up Shumai on your local machine using our step-by-step guides.
<CardGroup cols={2}>
<Card title="Get Started with Docker" icon="docker" href="/getting-started/docker">
Learn how to build and spin up the Shumai stack quickly using Docker Compose.
</Card>
</CardGroup>
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 309 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

+49
View File
@@ -0,0 +1,49 @@
---
title: AI Providers
description: Connect Shumai to OpenAI, Anthropic, Gemini, or custom LLM gateways.
---
When creating agents for chat or metadata autofill, you must select an underlying AI model. The available models and providers are configured globally within your team settings.
> 🔒 **Access Control:** Only **Team Owner** can manage AI providers. To update these settings, click your avatar, navigate to **Settings**, and select **Providers** from the left sidebar.
---
## 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.
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.
---
## Configuration Reference
### Provider Settings
When configuring a provider, you will need to specify the following fields:
| Field | Description | Example / Notes |
| :---------------- | :------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------- |
| **Provider Name** | A unique, human-readable label for the provider. | `Ollama-Local`, `Enterprise-Gateway` |
| **Base URL** | The target API endpoint URL. | `http://localhost:11434/v1` |
| **API Protocol** | The streaming and payload implementation format. | Most OpenAI-compatible gateways use `openai-completions`. |
| **API Key** | The authentication token. Leave blank for unauthenticated or local setups. | Accepts a literal value (`sk-...`) or an environment variable name (`MY_API_KEY`) to load secrets securely from the host system. |
### Model Settings
Each provider can host multiple models. You can configure the following attributes per model:
| Field | Description | Example / Notes |
| :-------------------- | :---------------------------------------------------------- | :------------------------------------------------- |
| **Model ID** | The exact identifier string expected by the upstream API. | `gpt-4o`, `claude-3-5-sonnet-20240620` |
| **Display Name** | An optional, friendly label shown to users in dropdowns. | `GPT-4 Omni`, `Claude 3.5` |
| **Reasoning Support** | Toggle to enable extended thinking protocols. | Use for models with native reasoning capabilities. |
| **Context Window** | The maximum total token capacity (input + output). | |
| **Max Output Tokens** | The hard ceiling for generated response tokens per request. | |
| **Input Cost** | Cost tracking specified per million input tokens. | Optional; used to calculate usage metrics. |
| **Output Cost** | Cost tracking specified per million output tokens. | Optional; used to calculate usage metrics. |
---
![AI Providers List](../providers.webp)
+45
View File
@@ -0,0 +1,45 @@
---
title: Agent Sandbox
description: Secure execution environment and network domain restrictions for AI agent scripts.
---
Running automated scripts poses security risks. Shumai resolves this by executing all agent skills inside a secure, isolated **Sandbox** environment.
---
## Sandbox Security
The sandbox restricts the execution process from accessing the host filesystem, system processes, and internal networks:
- **Isolation**: Scripts run in a virtualized workspace container that prevents them from modifying critical system files or reading other project data.
- **Network Bridging**: External network calls from inside the sandbox are strictly monitored.
### File System Restrictions
To protect your workspace environments and sensitive data, the sandbox enforces strict file-level access controls:
- **Read Access**: The sandbox is allowed to read files within the workspace, with a strict exception for sensitive environment and certificate files. It cannot read: `['.env', '.env.*', '*.pem', '*.key']`.
- **Write Access**: The sandbox is heavily restricted and may only write to the `.pi` folder located in the current working directory (cwd). Even within this allowed directory, the sandbox is explicitly blocked from writing or creating sensitive files matching: `['.env', '.env.*', '*.pem', '*.key']`.
---
## Domain Whitelisting
By default, sandboxed scripts cannot make network requests to the internet. Team Owners must explicitly authorize external APIs by managing domain access:
### Allowed Domains
A list of domains that sandboxed scripts are permitted to access.
- Default whitelisted domains include standard package registries (like npm or python package hosts) and repository hosts (like `github.com`).
- If a script needs to call an external API (e.g. `api.slack.com`), the administrator must add it to the allowed list.
### Pending Domains
When an agent script attempts to reach a domain that is not currently authorized:
1. The network connection is blocked immediately.
2. The target domain is logged and added to the **Pending Domains** list.
3. Admins can review this list and click **Approve** to authorize the domain, or **Reject** to keep it blocked.
![Agent Sandbox Settings](../sandbox.webp)
+54
View File
@@ -0,0 +1,54 @@
---
title: Agent Skills
description: Extend your agents' capabilities with custom automation tools.
---
By default, AI models can only process text and image. In Shumai, you can extend both your **Chat Agents** and **Autofill Agents'** capabilities by registering **Skills**—custom scripts that the agent can run when solving a task.
---
## How Skills Work
Skills are actions that you define and make available to your AI agents.
- **Descriptions for the AI**: When you register a skill, the AI agent reads its metadata to understand exactly when and how it should use the tool to solve a problem.
- **Execution & Local Caching**: When an agent decides it needs to use a skill, Shumai handles the execution. Newly added skill data is synced to the database first. Upon execution, the agent downloads and caches the skill locally from the database for fast, reliable access.
---
## Adding a Skill
To install a new skill into Shumai:
1. Navigate to the **Settings** page and open the **Skills** tab.
2. Click the **Add Skill** button.
3. In the dialog box, choose your installation method:
- **Upload**: Select and upload a `.zip` file containing your skill.
- **GitHub**: Provide a valid GitHub repository path.
> **Important:** Regardless of the installation method, the root folder of the skill must contain a `SKILL.md` file.
### Updating an Existing Skill
To update a skill, simply follow the steps above and install the new version using the exact same skill name. Shumai will automatically replace the older version.
---
## Configuring Environment Variables
If your custom skill requires environment variables (e.g., API keys, external tokens) to function:
1. Click on the installed **Skill Card** in the Skills tab to open the configuration dialog.
2. Add the required environment variables.
3. _(Optional)_ Set a default value for the variable. If no default value is provided, the skill will dynamically load the required value from the system environment at runtime.
---
## Enabling Skills for Agents
**All skills are disabled by default.** Merely installing a skill does not give agents access to it. To allow an agent to use an installed skill:
1. Navigate to your specific **Agent Settings**.
2. Explicitly enable the skills you want to authorize for that particular agent.
![Skills List View](../skills.webp)
+61
View File
@@ -0,0 +1,61 @@
---
title: Agent Tools
description: Configure the tools and capabilities permitted for each agent.
---
Shumai agents are equipped with built-in tools that allow them to interact with the file system, view files, extract video frames, and execute commands.
By default, **all tools are enabled** for new agents. Team Owners can deny specific tools to restrict agent capabilities.
<Warning>
**Caution:** Disabling tools can cause agents or skills to fail. For example, disabling the **Sandboxed Terminal** tool will break almost all custom skills that rely on executing commands or script environments. Disable tools only when you have a specific security policy or isolation requirement.
</Warning>
---
## Available Tools
The following tools can be individually toggled in the agent configuration dialog:
### 1. Sandboxed Terminal (`bash`)
- **Description:** Allows the agent to run terminal/shell commands in a highly isolated environment.
- **Why it matters:** Essential for running custom scripts, processing files on disk, or using standard Unix utilities. If disabled, the agent won't be able to run command-line code.
### 2. Read Skills (`read_skill`)
- **Description:** Allows the agent to load and read skill definitions to perform specialized actions.
- **Why it matters:** Enables the agent to inspect the instructions/configurations of custom skills registered in your workspace before executing them.
### 3. Analyze Image (`analyze_image`)
- **Description:** Allows the agent to view and analyze the visual contents of an image file.
- **Why it matters:** Enables multimodal agents to "see" image assets uploaded to Shumai, allowing them to answer comments or write metadata about images.
### 4. Video Frame Extraction (`screenshot`)
- **Description:** Allows the agent to extract still image frames from video files for analysis.
- **Why it matters:** Enables the agent to perform frame-by-frame analysis on videos (e.g. for comments, annotation, or search).
### 5. Browse Shumai (`list_assets`)
- **Description:** Allows the agent to list folders and browse files in Shumai.
- **Why it matters:** Gives the agent visual mapping of the project structure so it can search for other files or locate related assets.
### 6. Create Folder (`create_folder`)
- **Description:** Allows the agent to create new folders in Shumai.
- **Why it matters:** Needed if the agent organizes outputs or places files in custom subdirectory folders.
### 7. Create File (`create_file`)
- **Description:** Allows the agent to create and upload new files to Shumai.
- **Why it matters:** Allows the agent to generate new assets (e.g. text logs, transcoded clips, reports) and save them directly back into your project.
### 8. Create Version (`create_version`)
- **Description:** Allows the agent to upload and stack a new version of an existing file in Shumai.
- **Why it matters:** Allows the agent to update files in a clean, non-destructive way by stacking revisions rather than creating duplicate files.
---
## Restricting Tools
To change which tools an agent can use:
1. Navigate to **Team Settings** > **Agents** (Note: Only Team Owners can view and modify these settings).
2. Click on the agent you want to edit.
3. Scroll down below the **Skills** section to find the **Tools** configuration panel.
4. Toggle the switches next to the tools to enable or disable them.
5. Click **Save Changes**.
+51
View File
@@ -0,0 +1,51 @@
---
title: AI Agents
description: Create and configure specialized AI agents for chat, metadata autofill, and vector embedding.
---
Shumai uses specialized AI Agents to perform background automation, chat workflows, and semantic indexing. **Only Team Owner** can create, manage, and change agent settings.
---
## Agent Types
Shumai supports three types of agents:
### 1. Chat Agent
An interactive, conversational bot that appears in your project workspace.
- You can create as many chat agents as you want.
- You can use "@" to mention chat agents directly in file comments.
- The agent is context-aware: it can read files, search the project folder, inspect metadata, and read comment threads.
- You can add "Skills" to a chat agent, enabling it to write files, run scripts, or interact with external APIs on your behalf.
### 2. Autofill Agent
A background agent that monitors file uploads. You can create **only one** Autofill Agent.
- Once created and enabled, Shumai automatically triggers the agent when a new file is uploaded, provided the file type is supported (image or video).
- It analyzes the file's content (multimodal images, text descriptions) and populates any metadata fields flagged for "AI Autofill".
### 3. Embedding Agent
A specialized utility agent that processes assets to generate search indexes. You can create **only one** Embedding Agent.
- Once created and enabled, Shumai automatically runs embedding generation for new file uploads if the file type is supported (image or video).
- These search indexes are saved to power Shumai's natural language semantic search capabilities.
- **Note:** The Embedding Agent is hardcoded to use `google-embedding-2` as the LLM model. Because of this, you cannot choose a provider or model. Make sure you set the `GEMINI_API_KEY` environment variable to make it work.
- **Chunk Duration:** You can configure the duration of chunks used for long video indexing via the `EMBEDDING_CHUNK_DURATION` environment variable (defaults to 60 seconds).
---
## Configuring an Agent
To edit or create an agent, navigate to **Team Settings** > **Agents** (Note: Only Team Owners can change these settings):
- **Avatar**: Choose an avatar for the agent by picking from the predefined avatars.
- **Enabled / Disabled Toggle**: Stop or start the agent. If the embedding agent is disabled, semantic search indexing is paused.
- **System Prompt / Soul**: The core instructions that define the agent's behavior, guidelines, formatting requirements, and operational limits.
- **Model Provider**: Select which registered provider and model the agent should use for execution. _(Note: This option is disabled for Embedding Agents)._
- **Assigned Skills**: Select which custom skills this agent is permitted to execute.
![Agent Config Panel](../agents.webp)
+54
View File
@@ -0,0 +1,54 @@
---
title: Asset Management
description: Learn how to upload, organize, delete, and recover assets in your workspace.
---
Shumai makes it easy to bring creative media into your workspace, organize them in folders, and manage their lifecycle from upload to deletion.
---
## Uploading Assets
You can upload files and folders into Shumai using three methods:
1. **Drag and Drop**: Drag files or entire folder directories directly from your computer's file explorer and drop them anywhere on the Shumai dashboard interface.
2. **Upload Buttons**: Click the **Upload File** or **Upload Folder** buttons in the toolbar.
3. **Copy and Paste**: Copy an image or file from another website, application, or your clipboard, and paste it directly (`Ctrl+V` or `Cmd+V`) into the Shumai browser window to upload it instantly.
![Asset Management - Drag and Drop Upload](../dragdrop.webp)
---
## Folder Organization
When you upload an entire folder, Shumai replicates your folder hierarchy exactly inside the project.
- All subfolders are created automatically.
- Nested files remain in their respective subfolders.
- There is no limit to the depth of nested folders you can upload.
---
## Upload and Processing States
Once an upload starts, your assets progress through the following states:
- **Uploading**: The file is transferring to your storage server. The UI displays an active progress percentage.
- **Processing**: The file has successfully uploaded. Shumai is now extracting media parameters (such as resolution, video length, and audio codecs) and creating a web-friendly streaming preview (proxy).
- **Ready**: Processing is complete. The asset is fully visible, playable, and ready for comments, metadata tagging, or search.
---
## Deleting and Restoring Assets
If you no longer need an asset, you can delete it to clean up your workspace:
### The Trash Bin (Recently Deleted)
- When you delete a file or folder, it is moved to the **Recently Deleted** tab in your project settings.
- Deleted assets are kept in the Trash for **30 days**. During this window, you can select any asset and click **Recover** to restore it to its original location.
- If you want to free up space immediately, you can open the Recently Deleted tab and click **Empty Trash** to permanently purge the files.
### Permanent Removal
After **30 days** in the Trash, assets are automatically and permanently purged. Once purged, the records are removed from the database, and the files are deleted from your storage backend (local file system or S3 bucket) and cannot be recovered.
+55
View File
@@ -0,0 +1,55 @@
---
title: Collections
description: Build dynamic virtual folders using metadata filters and search criteria.
---
Instead of copying files into static folders, Shumai uses **Collections**—dynamic, query-based virtual views. A collection automatically groups files that match specific criteria in real-time.
---
## What is a Collection?
A **Collection** does not duplicate files on disk. Instead, it runs a pre-defined filter query against your project assets database. Whenever a new file is uploaded or metadata is updated to match the collection's query, the file automatically appears inside the collection.
---
## Creating a Collection
You can create collections in two ways:
- **From the Sidebar**: Click the `+` icon next to **Collections** in the project sidebar to open the query builder, configure your search rules, and save it.
- **From the Search Dialog**: When searching and filtering files within the Search Dialog, you can save your active search criteria by clicking the **Save as collection** button at the bottom of the dialog. This will create a dynamic collection that mirrors your search filters.
---
## Setting Up Collection Filters
When creating or editing a collection, you specify a name and set up a filter query in the builder interface:
### 1. Source Folder
Specify the starting folder directory. The collection will scan this folder and all its nested subfolders recursively.
### 2. Operators and Conditions
- **Logical Operators**: Combine conditions using **AND** (all conditions must be met) or **OR** (at least one condition must be met).
- **Fields**: Filter on standard fields (name, type, size) or custom metadata fields (such as "Status" or "Approval").
- **Comparison Rules**:
- _Equals / Does Not Equal_: Match exact values.
- _Contains / Does Not Contain_: Match parts of words.
- _Greater Than / Less Than_: Set up numeric or date ranges (e.g., date uploaded is after yesterday).
- _Is Empty / Is Not Empty_: Check if fields have values.
### 3. Collection Default Sorting
Define a custom sorting rule specific to the collection (e.g., sort by the custom field "Publication Date" ascending) to override the default project sort order.
---
## Example Use Cases
- **Review Dashboard**: A collection named "Pending Review" that displays assets where `Status` equals `In Review`.
- **Daily Deliverables**: A collection filtering files uploaded in the last 24 hours.
- **Approved Assets**: A collection filtering assets matching `Tag` contains `marketing` AND `Approved` is `Yes`.
![Collection Creation](../collection.webp)
+51
View File
@@ -0,0 +1,51 @@
---
title: Comments & Annotations
description: Collaborate on media assets using drawings and timestamped comments.
---
Shumai provides a review workspace designed for video, audio, and image feedback. Instead of generic text comments, you can drop timestamped feedback and sketch directly onto the media.
---
## Timestamped Comments
When reviewing video or audio files, comments can be anchored to specific seconds on the timeline:
1. Play or scrub the video player to the exact frame or timestamp you want to review.
2. Type your feedback in the comment box.
3. Click **Submit**. Your comment will be saved with a timestamp marker shown on the video timeline.
4. Collaborators can click your comment card in the sidebar to jump the video player to the exact moment you commented on.
![Timestamped Comments](../timestamp-comment.webp)
---
## Draw Annotations (Canvas)
To give clear visual feedback, you can draw directly onto image or video frames:
1. Pause the video on the frame you wish to annotate.
2. Select a drawing tool (brush, rectangle, circle, arrow) from the annotation toolbar overlaying the player.
3. Draw directly on the video screen.
4. Type your comment and click **Submit**. Your drawing is saved along with your comment.
5. When other users select your comment, your drawings will overlay on the player screen automatically at that frame.
![Draw Annotations](../draw_annotation.webp)
---
## Comment Threads (Replies)
Keep discussions organized by replying directly to feedback:
- Click **Reply** on any comment.
- Replies are nested under the parent comment card, making it easy to track resolution conversations.
---
## Attachments
You can attach reference documents, style guides, or other assets to your comments:
- Click the **Paperclip** icon inside the comment input box.
- Choose a file to upload. It will appear as a downloadable link directly on your comment card.
+70
View File
@@ -0,0 +1,70 @@
---
title: Asset Metadata
description: Customize your assets with dynamic, scoped metadata fields and AI-driven autofill features.
---
Standard file systems limit you to basic attributes like file name and modification date. Shumai lets you create structured metadata fields tailored to your creative pipeline—from tracking review statuses to capturing technical specs automatically.
---
## Metadata Scopes
Fields are grouped and displayed in the sidebar inspector by their scope:
- **Essentials (System Scope)**: Core fields built into Shumai that appear across all teams and projects. Many of these (like resolution, duration, and codec) are automatically extracted during file upload.
- **Team Attributes (Team Scope)**: Custom fields defined at the team level, which are inherited by all projects under that team. Excellent for enforcing company-wide metadata guidelines.
- **Custom Fields (Project Scope)**: Unique metadata fields defined specifically for a single project workspace.
---
## Custom Field Types
When building or editing your metadata schema, you can choose from these custom types:
- **Text**: A single-line input field for simple strings, codes, or labels.
- **Long Text**: A paragraph input area for detailed descriptions, summaries, or notes.
- **Dropdown (Select)**: A single-choice dropdown menu where options can be styled with custom background colors (e.g., Green for Approved, Yellow for In Progress).
- **Tags (Multi-Select)**: A multi-choice tag field allowing you to assign multiple custom colored labels to a single asset.
- **Star Rating**: An interactive star rating scale (supports configurations from 2 to 6 stars) for scoring and ranking.
- **Number**: A numeric field supporting custom decimal precision (from 0 to 3 decimal places) for values like frame rates, counts, or scores.
- **Checkbox (Toggle)**: A simple Yes/No switch for binary indicators (e.g., "VFX Required").
- **Date**: A calendar date selector with support for custom display formats (Local, ISO, USA, Euro, Friendly) and optional time tracking.
- **Single User**: A dropdown select field populated dynamically with team members, displaying their name and avatar.
- **Multiple User**: A multi-choice user select field populated dynamically with team members, allowing you to assign multiple team members.
![Asset Metadata Fields](../metafields.webp)
---
## Default Built-in Fields
Every project comes pre-configured with several essential fields populated automatically during upload or status changes:
- **Technical Specs**: File Size, Format, File Type (Video, Audio, Image, Document, File), Resolution Width/Height, Video/Audio Codecs, Duration, Frame Rate, and Audio Sample Rates.
- **Collaborative Fields**:
- **Status**: A dropdown select field containing `Needs Review` (Red), `In Progress` (Yellow), and `Approved` (Green).
- **Rating**: A 5-star rating scale for quick review evaluations.
- **Keywords**: A tags (multi-select) field to categorize assets.
---
## Field Settings & Controls
### Read-Only Fields
Marking a custom field as **Read-Only** prevents team members from editing its value directly. This is ideal for fields meant to be populated programmatically or by automated integrations.
### AI Autofill
When you enable **AI Autofill** on a metadata field, Shumai automatically analyzes uploaded assets using your team's default Gemini AI model. The AI will populate the field with extracted insights:
- For text/long text: AI generates summaries, descriptions, or shot logs.
- For select/multi-select: AI automatically categorizes themes or applies matching tags.
- For numbers: AI can output confidence scores or other metrics.
### Visibility & Ordering
In the metadata inspector:
- **Visibility**: Toggle fields on or off to clean up the sidebar and only show what is relevant to your current review process.
- **Ordering**: Drag and drop fields in the builder to arrange their display order within the Custom Fields section.
+46
View File
@@ -0,0 +1,46 @@
---
title: Notifications
description: Stay updated on comment activity, uploads, and project updates.
---
Shumai includes a built-in notification system to keep you informed of team activities, file statuses, and review comments. You can fully customize which events trigger notifications, check updates from your inbox, or toggle notifications for specific projects.
---
## Notification Settings
You can customize your notification preferences for each team to avoid unnecessary noise. To manage your notification events:
1. Click on **Team Settings** in the sidebar.
2. Select the **Notifications** tab.
3. Toggle the switches to enable or disable notifications for specific events:
### Comments & Replies
- **General Comments**: Notify me when someone comments on an asset I collaborate on.
- **Comment Replies**: Notify me when someone replies to my comment threads.
- **@Mentions**: Notify me when someone tags me (using `@username`) in any comment.
### Assets & Statuses
- **Your Uploads**: Notify me when files I upload finish transcoding and are ready for review.
- **Other Uploads**: Notify me when other team members upload new assets.
- **Status Updates**: Notify me when someone changes an asset's status (e.g., from "In Progress" to "Approved").
---
## Project-Level Notifications
If you want to mute a specific project entirely (except for direct `@mentions` which are always delivered):
1. Navigate to the **Project** dashboard.
2. Open **Project Settings**.
3. Toggle **Enable Notifications** on or off.
---
## The Notification Inbox
- The **Bell** icon in the navigation bar displays a red badge when you have unread notifications.
- Click the bell to open your notification feed panel.
- Click any notification card to mark it as read and jump directly to the relevant file and comment thread.
+41
View File
@@ -0,0 +1,41 @@
---
title: Semantic Search
description: Find files based on visual and textual meaning using AI vector similarity.
---
Traditional search relies on matching exact characters (e.g., searching "dog" will not find files named "golden_retriever.jpg"). Shumai resolves this with **Semantic Search**, which indexes the conceptual meaning of your files.
---
## How Semantic Search Works
Semantic search translates text queries and file contents into conceptual profiles. Similar ideas and visuals are mapped near each other.
1. **Index Generation**: When you upload an asset, Shumai's background agent scans the file's visual elements, text contents, or descriptions, translating them into a concept profile.
- **Video Processing**: Shumai uses **gemini-embedding-2** for video indexing.
- **Chunking**: For long videos, Shumai breaks them into chunks to ensure high-quality indexing. By default, chunks are **60 seconds** long with a **5-second overlap** to ensure no context is lost at the boundaries.
- **Sampling**: The model processes a maximum of 32 frames per chunk: short chunks (≤32s) are sampled at 1 fps, while longer chunks are uniformly sampled to 32 frames.
- **Optimization**: To optimize processing, Shumai automatically transcodes each chunk to **1 FPS** and **removes the audio track** before sending it to the embedding agent.
- **Configuration**: Administrators can customize these settings using the `EMBEDDING_CHUNK_DURATION` and `EMBEDDING_CHUNK_OVERLAP` environment variables.
2. **Concept Matching**: When you search with the "Semantic" toggle enabled, Shumai matches the conceptual meaning of your query against your assets.
3. **Result**: Searching "sunset at the beach" will successfully find a video file of ocean waves at dusk, even if the filename is `IMG_4029.mp4`.
### Understanding Search Results
Semantic search works differently than traditional keyword filtering:
- **Sort vs. Filter**: Semantic search acts more like a **sort** than a strict filter. While the most relevant results will appear at the top, less related content may still be present further down the list, ranked lower. If you need to exclude specific types of files, use the **Filter** panel in conjunction with semantic search.
- **Video Chunks**: Because Shumai indexes videos in chunks, a single long video may appear multiple times in your search results. Each result corresponds to a specific segment of the video where the match was found.
- **Match Timestamps**: When a search result comes from a video chunk, Shumai displays the matching start and end time. Clicking on these results will open the video and automatically jump to the relevant timestamp.
---
## Activating Semantic Search
To use semantic search:
1. Verify that your administrator has enabled the **Embedding Agent** under **Team Settings** > **Agents**.
2. Once active, Shumai will automatically begin indexing new uploads.
3. Toggle the **Semantic** button next to the search input in the file explorer to search by conceptual meaning.
![Semantic Search Toggle](../semantic-search.webp)
+57
View File
@@ -0,0 +1,57 @@
---
title: Share Links
description: Share files and folders securely with external clients and stakeholders.
---
Shumai allows you to collaborate with external stakeholders who do not have accounts in your workspace. Using **Share Links**, you can grant view and comment access to specific folders or assets.
---
## Creating a 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.
3. Configure the share link in the right sidebar. You can:
- Add password protection
- Set an expiration date
- Configure which metadata fields are visible to recipients
4. Click **Copy Link** at the bottom of the sidebar, then send the link to your client or stakeholder.
![Share Link Configuration](../sharelink.webp)
---
## Adding Assets to an Existing Share Link
Once a share link is created, you can easily add more files or folders to it without generating a new link:
1. Select the files or folders you want to add from your file browser.
2. Drag and drop them directly onto the share link item in the project sidebar.
3. The share link will immediately update to include the newly added assets.
---
## Security and Settings
### Expiration Date
Set an optional date and time after which the link becomes inactive. Once the date passes, the link returns a `404 Not Found` page to anyone attempting to access it.
### Password Protection
Secure sensitive work by adding a password. External users visiting the link will be prompted to enter the correct password before they can view the assets.
### Default Sort Order
Set a default sorting rule for the shared page (e.g. sorting by name or version) to ensure the client views the files in the intended order.
### Column Visibility
To protect proprietary information, you can configure exactly which metadata columns are visible to external users. For example:
- **Visible**: `Asset Name`, `Resolution`, `Download Link`.
- **Hidden**: `Internal Budget Code`, `Assignee Notes`, `Cost`.
### Disabling a Link
If you need to revoke access immediately, navigate to the **Share Links** tab under Project settings and toggle the **Disabled** switch. You can re-enable the link at any time.
+39
View File
@@ -0,0 +1,39 @@
---
title: Sort & Search
description: Find assets using the search dialog and organize them with custom sort orders.
---
As your projects grow, finding the right media files quickly is critical. Shumai provides a powerful search dialog and flexible sorting controls.
---
## Searching Assets
Searching is performed inside a dedicated **Search Dialog** that you can open by clicking the search icon in the toolbar.
![Search Dialog](../search-dialog.webp)
### Search Dialog Features
- **Keyword Matches**: Type a keyword in the text input to instantly filter file and folder names.
- **Advanced Filtering**: Click to expand the filters panel and build multi-conditional queries (e.g. searching for files where the custom field "Status" equals "In Progress" AND the file type is "Video").
- **Semantic Search Toggle**: If enabled by your team administrator, toggle "Semantic" on to search by conceptual meaning (e.g. searching "sunny beach" to find clips of oceans even if the filenames do not contain those words).
- **Save as Collection**: Easily convert your active search criteria into a dynamic folder. Click **Save as Collection** inside the dialog to create the collection and navigate to it instantly.
- **Infinite Scroll Results**: Search results load dynamically in real-time as you type or adjust filters.
---
## Sorting and Reordering Assets
You can change the sorting order of the asset list using the sort dropdown or by clicking metadata column headers:
- **Custom Sort (Default)**: By default, the project file explorer is set to **Custom** sorting. In this mode, you can manually drag and drop files and folders to reorder them exactly as you wish.
- **Standard Sort Options**: You can also sort files by:
- _Newest Upload_: Displays recently uploaded assets first.
- _Name_: Sorts alphabetically (A-Z or Z-A).
- _Size_: Sorts by file size.
- _Type_: Groups folders together at the top, followed by version stacks and individual files.
- _Custom Columns_: Sorts by dynamic metadata fields (e.g., sorting by "Due Date" or "Priority").
> [!NOTE]
> **Drag and Drop Reordering Limit**: Drag-and-drop manual reordering is **only** available when the sort order is set to **Custom**. If you select any other sort option (such as Name or Size), manual reordering is disabled.
@@ -0,0 +1,58 @@
---
title: Team & Project Management
description: Organize your workspaces, define roles, and manage members.
---
Shumai uses a two-tier organizational hierarchy—**Teams** and **Projects**—to manage file access and collaboration.
---
## Member Visibility & Scopes
Members added to a team belong to one of two permission scopes:
- **Team Scope**: Team-scoped members can view all projects inside the team by default.
- **Project Scope**: Project-scoped members can only see and access the specific projects they have been explicitly granted permission to join.
---
## Member Roles
Shumai uses permission roles to control what actions team and project members can perform:
- **Owner**: Full administrative control. Team Owners can modify team settings, skills, and AI providers. Project Owners can edit project configurations, manage members, and generate invites.
- **Editor**: Can upload files, edit custom metadata, create folders, and add comments or canvas annotations.
- **Reviewer**: Read-only access. Can view media assets, toggle versions, and leave text comments or canvas drawings, but cannot upload/delete files or modify metadata.
---
## Project Role Overrides
Administrators can add existing team members to specific projects to override their permissions:
- Project-level roles take higher priority than team-level roles within that project.
- _Example_: If Peter is a team member with an **Editor** role, an administrator can add Peter to _Project A_ with a **Reviewer** role. Peter will act as a Reviewer inside Project A, but maintain his Editor role across the rest of the team's projects.
---
## Managing Members
Member management is handled using a unified **Members Dialog** popup:
### 1. Managing Team Members
- **Access**: Open your **Team Dashboard** and click the members list or avatar group in the header.
- **Settings**:
- Change member roles between Editor and Reviewer.
- Remove members from the team.
- **Invite New Members**: Select a role (Editor or Reviewer) and click **Generate Link**. Copy the signup URL to invite new users to the team.
### 2. Managing Project Members
- **Access**: Open your project **File Browser** and click the members avatars or button in the top toolbar.
- **Settings**:
- Change project member roles or remove them from the project.
- **Add Team Members**: The dialog displays a list of active team members who are not yet added to this project. Select their project role (which will override their team role inside this project) and click **Add** to add them instantly.
- **Invite External Collaborators**: Select a role (Editor or Reviewer) and click **Generate Link** to invite new users directly into this specific project.
![Members Dialog](../members.webp)
+36
View File
@@ -0,0 +1,36 @@
---
title: Media Transcoding Settings
description: Configure video transcode strategies and preview proxy generation.
---
High-resolution camera formats and raw media files cannot be rendered natively in web browsers. Shumai transcodes these assets into web-friendly streaming formats in the background.
Regardless of the selected transcoding strategy, Shumai's pipeline will **always** generate at least one lightweight `180p` proxy version of the raw file to ensure fast scrubbing, thumbnail generation, and instant previews.
---
## Video Transcode Strategies
Team Owners can select how the transcoding engine handles uploaded files. Shumai evaluates the original file's dimensions against its standard target resolutions (2160p, 1080p, 720p, 540p, and 360p) to determine the output.
### 1. Best Match
- **Behavior**: Shumai checks the longest dimension (width or height) of the uploaded file. It then finds the highest standard resolution that is equal to or smaller than the original file, preventing unnecessary upscaling. If the original video is exceptionally small, it defaults to a minimum target of `360p`.
- **Output**: Generates exactly two web-optimized files: the universal `180p` proxy and the single calculated "best match" resolution.
- **Use Case**: This is the recommended option. It ensures web compatibility without wasting processing time and storage space on redundant lower-resolution versions.
### 2. Transcode All
- **Behavior**: Shumai calculates the "best match" resolution exactly as it does in the previous strategy. However, instead of stopping at one version, it processes the video into the best match _and_ every standard resolution smaller than it.
- **Output**: Generates a full cascade of files. For example, if the best match for an upload is `1080p`, Shumai will generate the `180p` proxy, `1080p`, `720p`, `540p`, and `360p` versions.
- **Use Case**: Ideal for environments requiring adaptive bitrate streaming, ensuring consistent playback performance across all client devices regardless of varying network conditions.
![Transcode Settings](../transcode.webp)
---
## Processing Architecture
Transcoding is resource-intensive. Depending on your scaling needs, your administrator can run the transcode engine on the main server (Single-Server mode) or delegate tasks to specialized transcoding worker machines (Temporal Worker mode).
Note: In all modes, the processing machine must have the standard system media utilities (`ffmpeg` and `ffprobe`) installed.
+44
View File
@@ -0,0 +1,44 @@
---
title: File Version Stack
description: Group multiple revisions of an asset under a single version-controlled stack.
---
When collaborating on creative assets, files naturally go through multiple iterations (e.g. `draft_v1.mp4`, `draft_v2.mp4`, `draft_final.mp4`). To prevent workspace clutter, Shumai allows you to bundle these revisions into a **Version Stack**.
---
## What is a Version Stack?
A **Version Stack** groups multiple revisions of the same file into a single entry. Instead of cluttering your folder with several similar files, Shumai collapses them into one item with a version badge (e.g., "V3") and a dropdown list of older versions.
![Version Stack Selector](../versionstack.webp)
---
## Creating & Adding to a Version Stack
You can create a version stack or add new versions to an existing stack using two interactive methods:
- **Drag and Drop**:
- _To create a stack_: Drag one standalone file directly over another standalone file in your file explorer.
- _To add a version_: Drag a standalone file directly onto an existing version stack.
- **Context Menu (Right-Click)**:
- Right-click any standalone file or existing version stack.
- Choose **Create New Version** from the menu.
- Select the revision file from your computer to upload it directly into the stack.
---
## Managing Versions
### Active Version
The file at the top of the stack is the **Active Version**. This is the version displayed on your project dashboard, search results, and metadata panels.
### Reordering and Reverting Versions
You can promote a past version or reorder your stack:
- Open the version stack details sidebar.
- Drag and drop the versions in the list to change their order. The version you drag to the top automatically becomes the active version.
- To remove a file from the stack, drag it out or select **Unstack**. This moves the file back to the parent folder as a standalone file.
Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

+1
View File
@@ -75,6 +75,7 @@ export default tseslint.config(
'**/packages/core/src/generated/**',
'**/data/**',
'**/packages/webui/components/ui/**',
'**/packages/webui/paraglide/**',
],
},
js.configs.recommended,
+18 -4
View File
@@ -1,6 +1,6 @@
{
"name": "shumai",
"version": "0.0.2",
"version": "0.1.10",
"private": true,
"type": "module",
"repository": {
@@ -13,12 +13,21 @@
],
"scripts": {
"dev": "bun run --hot apps/web/src/index.ts",
"i18n:compile": "paraglide-js compile --project ./packages/webui/project.inlang --outdir ./packages/webui/paraglide --emit-ts-declarations --no-emit-git-ignore",
"i18n:watch": "paraglide-js compile --project ./packages/webui/project.inlang --outdir ./packages/webui/paraglide --watch --emit-ts-declarations --no-emit-git-ignore",
"typecheck": "tsc --noEmit",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"test": "bun --bun vitest run",
"test:e2e": "playwright test",
"test:e2e:workflow": "bun --bun vitest run -c packages/e2e/vitest.config.ts",
"test:e2e:ui": "playwright test --ui",
"test:e2e:report": "playwright show-report",
"test:e2e:install": "playwright install --with-deps",
"harness:dev": "bun run packages/webui/e2e/harness/serve.ts",
"format": "prettier --write .",
"db:migrate": "bun run prisma migrate dev",
"db:deploy": "bun run prisma migrate deploy",
"db:generate": "cd packages/db && bunx prisma generate",
"generate-providers": "bun run scripts/generate-builtin-providers.ts",
"worker:agent": "bun apps/agent/src/index.ts",
"worker:transcode": "bun apps/transcode/src/index.ts",
@@ -34,24 +43,29 @@
},
"devDependencies": {
"@eslint/js": "10.0.1",
"@inlang/paraglide-js": "2.20.0",
"@playwright/test": "1.61.1",
"@testcontainers/postgresql": "12.0.1",
"@testing-library/dom": "10.4.1",
"@testing-library/react": "16.3.2",
"@types/bun": "1.3.14",
"@types/node": "25.9.1",
"bun-plugin-pino": "1.5.0",
"bun-plugin-tailwind": "0.1.2",
"bun-types": "1.3.14",
"pino-pretty": "13.1.3",
"eslint": "10.4.1",
"eslint-config-prettier": "10.1.8",
"eslint-plugin-prettier": "5.5.6",
"eslint-plugin-react": "7.37.5",
"globals": "17.6.0",
"happy-dom": "20.10.6",
"pino-pretty": "13.1.3",
"prisma": "7.8.0",
"testcontainers": "12.0.1",
"typescript": "6.0.3",
"typescript-eslint": "8.60.1",
"vitest": "4.1.8",
"vite-tsconfig-paths": "6.1.1"
"vite-tsconfig-paths": "6.1.1",
"vitest": "4.1.8"
},
"dependencies": {
"@tanstack/react-virtual": "3.14.2",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/agent",
"version": "0.0.2",
"version": "0.1.10",
"private": true,
"type": "module",
"main": "./src/index.ts",
+366 -1
View File
@@ -15,10 +15,15 @@ import {
updateAssetMetadataActivity,
getAssetPathContextActivity,
executeAgentToolActivity,
generateSessionNameActivity,
type GenerateSessionNameParams,
} from './agent'
import * as piAgent from '../index'
import { type AgentHarness, type Session } from '@earendil-works/pi-agent-core'
import { type DatabaseSessionMetadata } from '../database-session-storage'
import { triggerLocalCancel } from '@shumai/workflow-core'
import { Context } from '@temporalio/activity'
import {
prisma,
AssetType,
@@ -44,6 +49,9 @@ vi.mock('../index', async () => {
describe('Agent Activities', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.spyOn(Context, 'current').mockImplementation(() => {
throw new Error('Not in Temporal')
})
})
it('should call agentChatActivity and prompt the harness', async () => {
@@ -87,6 +95,143 @@ describe('Agent Activities', () => {
expect(piAgent.createAgentSession).toHaveBeenCalled()
})
it('should register local cancellation handler and call harness.abort when cancelled in local mode', async () => {
let resolvePrompt!: (value: {
content: Array<{ type: string; text: string } | { type: string }>
usage: { input: number; output: number }
stopReason?: string
errorMessage?: string
}) => void
const promptPromise = new Promise<Parameters<typeof resolvePrompt>[0]>((resolve) => {
resolvePrompt = resolve
})
const mockHarness = {
prompt: vi.fn().mockReturnValue(promptPromise),
abort: vi.fn(),
}
const mockSession = {
getEntries: vi.fn().mockResolvedValue([]),
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
}
vi.mocked(piAgent.createAgentSession).mockResolvedValue({
session: mockSession as unknown as Session<DatabaseSessionMetadata>,
harness: mockHarness as unknown as AgentHarness,
})
const context = {
agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } },
dbProviders: [],
teamSkills: [],
allowedDomains: [],
} as unknown as AgentExecutionContext
const executionPromise = agentChatActivity({
taskId: 'task-123',
teamId: 't1',
agentId: 'b1',
message: 'Hi',
imageUrls: [],
projectId: 'p1',
folderId: 'f1',
sessionId: 'mock-session-id',
context,
})
// Yield to let the asynchronous setup register the cancel handler
await new Promise((resolve) => setTimeout(resolve, 50))
// Simulate user cancellation
const cancelled = triggerLocalCancel('task-123')
expect(cancelled).toBe(true)
expect(mockHarness.abort).toHaveBeenCalled()
// Resolve the prompt promise to allow the activity to finish clean
resolvePrompt({
content: [{ type: 'text', text: 'AI response' }],
usage: { input: 10, output: 20 },
})
await executionPromise
})
it('should listen to Temporal cancellation signal and call harness.abort when cancelled in Temporal mode', async () => {
const mockTemporalContext = {
cancellationSignal: new EventTarget(),
heartbeat: vi.fn(),
} as unknown as Context
vi.spyOn(Context, 'current').mockReturnValue(mockTemporalContext)
let resolvePrompt!: (value: {
content: Array<{ type: string; text: string } | { type: string }>
usage: { input: number; output: number }
stopReason?: string
errorMessage?: string
}) => void
const promptPromise = new Promise<Parameters<typeof resolvePrompt>[0]>((resolve) => {
resolvePrompt = resolve
})
const mockHarness = {
prompt: vi.fn().mockReturnValue(promptPromise),
abort: vi.fn(),
}
const mockSession = {
getEntries: vi.fn().mockResolvedValue([]),
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
}
vi.mocked(piAgent.createAgentSession).mockResolvedValue({
session: mockSession as unknown as Session<DatabaseSessionMetadata>,
harness: mockHarness as unknown as AgentHarness,
})
const context = {
agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } },
dbProviders: [],
teamSkills: [],
allowedDomains: [],
} as unknown as AgentExecutionContext
const addEventListenerSpy = vi.spyOn(mockTemporalContext.cancellationSignal, 'addEventListener')
const removeEventListenerSpy = vi.spyOn(
mockTemporalContext.cancellationSignal,
'removeEventListener',
)
const executionPromise = agentChatActivity({
teamId: 't1',
agentId: 'b1',
message: 'Hi',
imageUrls: [],
projectId: 'p1',
folderId: 'f1',
sessionId: 'mock-session-id',
context,
})
// Yield to let the asynchronous setup add the abort event listener
await new Promise((resolve) => setTimeout(resolve, 50))
expect(addEventListenerSpy).toHaveBeenCalledWith('abort', expect.any(Function), { once: true })
// Simulate Temporal cancellation event
mockTemporalContext.cancellationSignal.dispatchEvent(new Event('abort'))
expect(mockHarness.abort).toHaveBeenCalled()
// Resolve the prompt promise to allow the activity to finish clean
resolvePrompt({
content: [{ type: 'text', text: 'AI response' }],
usage: { input: 10, output: 20 },
})
await executionPromise
expect(removeEventListenerSpy).toHaveBeenCalledWith('abort', expect.any(Function))
addEventListenerSpy.mockRestore()
removeEventListenerSpy.mockRestore()
})
it('should include error message in text when stopReason is error', async () => {
const mockHarness = {
prompt: vi.fn().mockResolvedValue({
@@ -127,6 +272,54 @@ describe('Agent Activities', () => {
expect(res.text).toBe('Error: API key not valid')
})
it('should pass thinkingLevel from agent config to createAgentSession', async () => {
const mockHarness = {
prompt: vi.fn().mockResolvedValue({
content: [],
usage: { input: 0, output: 0 },
}),
getThinkingLevel: vi.fn().mockReturnValue('high'),
}
const mockSession = {
getEntries: vi.fn().mockResolvedValue([]),
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
}
vi.mocked(piAgent.createAgentSession).mockResolvedValue({
session: mockSession as unknown as Session<DatabaseSessionMetadata>,
harness: mockHarness as unknown as AgentHarness,
})
const context = {
agent: {
id: 'b1',
provider: { name: 'google' },
modelRef: { modelId: 'gemini' },
config: { thinkingLevel: 'high' },
},
dbProviders: [],
teamSkills: [],
allowedDomains: [],
} as unknown as AgentExecutionContext
await agentChatActivity({
teamId: 't1',
agentId: 'b1',
message: 'Hi',
imageUrls: [],
projectId: 'p1',
folderId: 'f1',
sessionId: 'mock-session-id',
context,
})
expect(piAgent.createAgentSession).toHaveBeenCalledWith(
expect.objectContaining({
thinkingLevel: 'high',
}),
)
})
it('should call autofillAiActivity and run autofill tool', async () => {
const mockHarness = {
prompt: vi.fn().mockResolvedValue({
@@ -306,7 +499,7 @@ describe('Agent Database Activities Integration', () => {
teamId: team.id,
name: 'openai',
config: {
api: 'openai',
api: 'openai-completions',
apiKey: 'mock-key',
},
},
@@ -693,4 +886,176 @@ describe('Agent Database Activities Integration', () => {
})
})
})
describe('generateSessionNameActivity', () => {
it('should generate and save session name for chat sessions', async () => {
await prisma.team.create({
data: { id: 't1', name: 'Test Team' },
})
const user = await prisma.user.create({
data: { id: 'u1', name: 'Test User', email: 'u1@test.com' },
})
const agentUser = await prisma.user.create({
data: {
id: 'agent-123',
name: 'Chat Agent User',
email: 'agent@shumai.ai',
type: 'agent',
},
})
const agent = await prisma.agent.create({
data: {
id: agentUser.id,
teamId: 't1',
type: 'chat',
config: { provider: 'openai', model: 'gpt-4' },
},
})
await prisma.agentSession.create({
data: {
id: 'session-123',
agentId: 'agent-123',
userId: user.id,
cwd: process.cwd(),
type: 'chat',
name: null,
},
})
const mockHarness = {
prompt: vi.fn().mockResolvedValue({
content: [{ type: 'text', text: ' "Summarized Chat Title" ' }],
}),
}
vi.mocked(piAgent.createAgentSession).mockResolvedValue({
session: {} as unknown as Session<DatabaseSessionMetadata>,
harness: mockHarness as unknown as AgentHarness,
})
await generateSessionNameActivity({
teamId: 't1',
agentId: 'agent-123',
prompt: 'hello world prompt',
sessionId: 'session-123',
context: {
agent: {
...agent,
provider: { name: 'openai' },
modelRef: {
id: 'm1',
providerName: 'openai',
modelId: 'gpt-4',
name: 'GPT-4',
config: {},
createdAt: new Date(),
updatedAt: new Date(),
},
} as unknown as GenerateSessionNameParams['context']['agent'],
dbProviders: [
{
name: 'openai',
config: { api: 'openai-responses', apiKey: 'fake-key' },
models: [
{
modelId: 'gpt-4',
name: 'GPT-4',
config: {
reasoning: false,
input: ['text'],
contextWindow: 4096,
maxTokens: 4096,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
},
},
],
},
],
},
})
const updatedSession = await prisma.agentSession.findUnique({
where: { id: 'session-123' },
})
expect(updatedSession?.name).toBe('Summarized Chat Title')
expect(mockHarness.prompt).toHaveBeenCalledWith('hello world prompt')
// Verify that transient naming session was cleaned up (deleted)
const namingSessions = await prisma.agentSession.findMany({
where: { type: 'naming' },
})
expect(namingSessions).toHaveLength(0)
})
it('should skip name generation for comment sessions or if name is already set', async () => {
await prisma.team.create({
data: { id: 't1', name: 'Test Team' },
})
const user = await prisma.user.create({
data: { id: 'u1', name: 'Test User', email: 'u1@test.com' },
})
const agentUser = await prisma.user.create({
data: {
id: 'agent-123',
name: 'Chat Agent User',
email: 'agent2@shumai.ai',
type: 'agent',
},
})
await prisma.agent.create({
data: {
id: agentUser.id,
teamId: 't1',
type: 'chat',
config: { provider: 'openai', model: 'gpt-4' },
},
})
await prisma.agentSession.create({
data: {
id: 'session-comment',
agentId: 'agent-123',
userId: user.id,
cwd: process.cwd(),
type: 'comment',
name: null,
},
})
await prisma.agentSession.create({
data: {
id: 'session-named',
agentId: 'agent-123',
userId: user.id,
cwd: process.cwd(),
type: 'chat',
name: 'Existing Name',
},
})
vi.mocked(piAgent.createAgentSession).mockClear()
await generateSessionNameActivity({
teamId: 't1',
agentId: 'agent-123',
prompt: 'hello comment',
sessionId: 'session-comment',
context: {
agent: {} as unknown as GenerateSessionNameParams['context']['agent'],
dbProviders: [],
},
})
await generateSessionNameActivity({
teamId: 't1',
agentId: 'agent-123',
prompt: 'hello named',
sessionId: 'session-named',
context: {
agent: {} as unknown as GenerateSessionNameParams['context']['agent'],
dbProviders: [],
},
})
expect(piAgent.createAgentSession).not.toHaveBeenCalled()
})
})
})
+211 -16
View File
@@ -1,23 +1,29 @@
import { createAgentSession, fieldsToTypeBoxSchema, type AutofillField } from '../index'
import { DatabaseSessionStorage } from '../database-session-storage'
import { prisma, AssetType, Prisma, type Skill } from '@shumai/db'
import { logger } from '@shumai/core/src/logger'
import { s3Service } from '@shumai/core/src/s3/s3'
import {
type AgentTool,
type AgentMessage,
type AgentTool,
type SessionTreeEntry,
} from '@earendil-works/pi-agent-core'
import { type ImageContent } from '@earendil-works/pi-ai'
import { ApplicationFailure } from '@temporalio/activity'
import { assetService } from '@shumai/core/src/asset/asset'
import { VersionStackService } from '@shumai/core/src/versionStack/versionStack'
import { uploadService } from '@shumai/core/src/upload/upload'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { generateKeyBetween } from 'jittered-fractional-indexing'
import { paginateQuery, encodeCursor } from '@shumai/core/src/pagination'
import { ulid } from 'ulid'
import { logger } from '@shumai/core/src/logger'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { encodeCursor, paginateQuery } from '@shumai/core/src/pagination'
import { s3Service } from '@shumai/core/src/s3/s3'
import { uploadService } from '@shumai/core/src/upload/upload'
import { VersionStackService } from '@shumai/core/src/versionStack/versionStack'
import { AssetType, prisma, Prisma, type Skill } from '@shumai/db'
import { ApplicationFailure, Context } from '@temporalio/activity'
import { registerLocalCancelHandler, unregisterLocalCancelHandler } from '@shumai/workflow-core'
import { generateKeyBetween } from 'jittered-fractional-indexing'
import { ulid } from 'ulid'
import { DatabaseSessionStorage } from '../database-session-storage'
import {
createAgentSession,
fieldsToTypeBoxSchema,
type AutofillField,
type DbProviderInfo,
} from '../index'
import { UpdateAssetMetadataRequest } from '@shumai/dtos'
@@ -48,6 +54,7 @@ export interface AgentExecutionContext {
}
async function executeAgentPrompt(params: {
taskId?: string
teamId: string
agentId: string
prompt: string
@@ -58,6 +65,7 @@ async function executeAgentPrompt(params: {
userCommentId?: string | null
tools?: AgentTool[]
context: AgentExecutionContext
attachedAssets?: Array<{ id: string; name: string; type: string }>
}): Promise<{ text: string; usage: Usage; sessionId: string }> {
const { agent, dbProviders, teamSkills, allowedDomains } = params.context
@@ -88,20 +96,24 @@ If you need to create files in the local filesystem (for example, a temporary fi
systemPrompt = `${systemPrompt}\n\nAgent Personality and Core Instructions:\n${agent.soul}`
}
if (params.agentsInstruction) {
systemPrompt = `${systemPrompt}\n\nContext and Instructions:\n${params.agentsInstruction}`
}
// Note: params.agentsInstruction is no longer appended to systemPrompt here.
// Instead, it is persisted as a custom message session entry in the conversation history below.
const modelConfig = agent.modelRef?.config
if (modelConfig?.input) {
systemPrompt += `\n\nYour current model supports the following input types: ${modelConfig.input.join(', ')}.`
}
const agentConfig = agent.config as PrismaJson.AgentConfig | null | undefined
const thinkingLevel = agentConfig?.thinkingLevel || 'off'
const { session, harness } = await createAgentSession({
teamId: params.teamId,
agentId: params.agentId,
providerName,
modelId,
systemPrompt,
thinkingLevel,
teamSkills: teamSkills.map((s) => ({
id: s.id,
name: s.name,
@@ -139,7 +151,64 @@ If you need to create files in the local filesystem (for example, a temporary fi
}
}
let heartbeatInterval: ReturnType<typeof setInterval> | null = null
const onAbort = () => {
harness.abort()
}
let temporalSignal: EventTarget | undefined
try {
temporalSignal = Context.current().cancellationSignal
} catch {
// Ignore
}
if (temporalSignal) {
temporalSignal.addEventListener('abort', onAbort, { once: true })
heartbeatInterval = setInterval(() => {
try {
Context.current().heartbeat()
} catch (err) {
logger.debug({ err }, 'Failed to send activity heartbeat')
}
}, 2000)
} else if (params.taskId) {
registerLocalCancelHandler(params.taskId, () => {
harness.abort()
})
}
try {
if (params.agentsInstruction && params.agentsInstruction.trim()) {
const storage = session.getStorage()
const parentId = await storage.getLeafId()
await storage.appendEntry({
id: ulid(),
type: 'custom_message',
parentId,
timestamp: new Date().toISOString(),
customType: 'context',
content: params.agentsInstruction.trim(),
} as unknown as SessionTreeEntry)
}
if (params.attachedAssets && params.attachedAssets.length > 0) {
const storage = session.getStorage()
const parentId = await storage.getLeafId()
await storage.appendEntry({
id: ulid(),
type: 'custom',
parentId,
timestamp: new Date().toISOString(),
customType: 'context_display_info',
data: {
assets: params.attachedAssets,
},
} as unknown as SessionTreeEntry)
}
const assistantMessage = await harness.prompt(params.prompt, { images: imagesToPass })
const sessionEntries = await session.getEntries()
@@ -185,11 +254,20 @@ If you need to create files in the local filesystem (for example, a temporary fi
}
return { text, usage, sessionId }
} finally {
// Cleanup handled by agent session if needed
if (heartbeatInterval) {
clearInterval(heartbeatInterval)
}
if (temporalSignal) {
temporalSignal.removeEventListener('abort', onAbort)
}
if (params.taskId) {
unregisterLocalCancelHandler(params.taskId)
}
}
}
export interface AgentChatParams {
taskId?: string
teamId: string
agentId: string
message: string
@@ -202,6 +280,7 @@ export interface AgentChatParams {
userCommentId?: string | null
explicitMention?: boolean
context: AgentExecutionContext
attachedAssets?: Array<{ id: string; name: string; type: string }>
}
export async function agentChatActivity(params: AgentChatParams) {
@@ -209,6 +288,7 @@ export async function agentChatActivity(params: AgentChatParams) {
const sessionId = params.sessionId
return executeAgentPrompt({
taskId: params.taskId,
teamId: params.teamId,
agentId: params.agentId,
prompt: cleanMessage,
@@ -218,6 +298,7 @@ export async function agentChatActivity(params: AgentChatParams) {
userId: params.userId,
userCommentId: params.userCommentId,
context: params.context,
attachedAssets: params.attachedAssets,
})
}
@@ -1103,3 +1184,117 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
})
}
}
export interface GenerateSessionNameParams {
teamId: string
agentId: string
prompt: string
sessionId: string
context: {
agent: Prisma.AgentGetPayload<{ include: { modelRef: true; provider: true } }>
dbProviders: DbProviderInfo[]
}
}
export async function generateSessionNameActivity(
params: GenerateSessionNameParams,
): Promise<void> {
const { sessionId, prompt, teamId, agentId } = params
const { agent, dbProviders } = params.context
// 1. Fetch current session and verify it is a chatbot session and unnamed
const sessionRecord = await prisma.agentSession.findUnique({
where: { id: sessionId },
})
if (!sessionRecord || sessionRecord.type !== 'chat' || sessionRecord.name !== null) {
logger.info({ sessionId }, 'Skipping session name generation: not an unnamed chatbot session')
return
}
if (!agent || !agent.modelRef || !agent.provider) {
logger.warn(
{ sessionId },
'Skipping session name generation: Agent, model, or provider configuration not found',
)
return
}
const providerName = agent.provider.name
const modelId = agent.modelRef.modelId
let namingSessionId: string | undefined
try {
// 2. Create transient naming session in database
const namingSession = await prisma.agentSession.create({
data: {
agentId,
userId: sessionRecord.userId,
cwd: process.cwd(),
assetId: sessionRecord.assetId,
type: 'naming',
},
})
namingSessionId = namingSession.id
const systemInstruction =
"You are a helpful assistant. Generate a short 2 to 4 words title/name for a chat session based on the user's first message. " +
'Do NOT include quotation marks, markdown formatting, or any extra conversational text. Return only the title.'
// 3. Create agent session and harness using the naming session
const { harness } = await createAgentSession({
teamId,
agentId,
providerName,
modelId,
systemPrompt: systemInstruction,
teamSkills: [],
allowedDomains: [],
sessionId: namingSessionId,
userId: sessionRecord.userId || undefined,
providers: dbProviders,
})
const result = await harness.prompt(prompt)
const resultText = result.content
.filter((c) => c.type === 'text')
.map((c) => {
if ('text' in c && typeof c.text === 'string') {
return c.text
}
return ''
})
.join('\n')
let chatName = resultText.trim()
// Clean up quotes if returned
if (
(chatName.startsWith('"') && chatName.endsWith('"')) ||
(chatName.startsWith("'") && chatName.endsWith("'"))
) {
chatName = chatName.slice(1, -1).trim()
}
if (chatName) {
await prisma.agentSession.update({
where: { id: sessionId },
data: { name: chatName },
})
logger.info({ sessionId, chatName }, 'Session name generated successfully')
}
} catch (err) {
logger.error({ sessionId, err }, 'Failed to generate session name')
} finally {
if (namingSessionId) {
await prisma.agentSession
.delete({
where: { id: namingSessionId },
})
.catch((deleteErr) => {
logger.error({ namingSessionId, deleteErr }, 'Failed to delete naming session')
})
}
}
}
+72 -30
View File
@@ -1,16 +1,16 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
generateEmbeddingActivity,
generateTextEmbeddingActivity,
extractAiMetadataActivity,
getEmbeddingContextActivity,
saveAssetEmbeddingsActivity,
generateImageEmbeddingActivity,
generateVideoChunkEmbeddingActivity,
} from './ai'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/transcode'
import { transcodeService } from '@shumai/core'
import { prisma, AssetType, AssetStatus } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import * as fs from 'fs'
vi.mock('fs', async (importOriginal) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- importOriginal returns the raw fs module, typed dynamically as any here
@@ -38,7 +38,7 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
},
}))
vi.mock('@shumai/transcode', () => ({
vi.mock('@shumai/core/src/transcode/transcode', () => ({
transcodeService: {
extractVideoFrames: vi.fn(),
},
@@ -93,19 +93,13 @@ describe('AI Activities Unit Tests', () => {
contentType: 'image/png',
} as unknown as { buffer: Buffer; contentType: string })
const context = {
agent: { config: { provider: 'google', model: 'gemini' } },
asset: { id: 'a1', mediaType: 'image/png', storageKey: { key: 'test.png' } },
}
const res = await generateEmbeddingActivity({
const res = await generateImageEmbeddingActivity({
teamId: 't1',
assetId: 'a1',
context,
assetKey: 'test.png',
mediaType: 'image/png',
})
expect(res.embeddings.length).toBe(1)
expect(res.embeddings[0].embedding).toEqual([0.1, 0.2, 0.3])
expect(res.embedding).toEqual([0.1, 0.2, 0.3])
expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'test.png')
})
@@ -115,25 +109,16 @@ describe('AI Activities Unit Tests', () => {
contentType: 'video/mp4',
} as unknown as { buffer: Buffer; contentType: string })
const context = {
agent: { config: { provider: 'google', model: 'gemini' } },
asset: { id: 'a2', mediaType: 'video/mp4', storageKey: { key: 'test.mp4' } },
}
const res = await generateEmbeddingActivity({
const res = await generateVideoChunkEmbeddingActivity({
teamId: 't1',
assetId: 'a2',
context,
chunkKey: 'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
})
// Duration is 120s, chunks are 60s, so it should generate 2 chunks (0-60, 60-120)
expect(res.embeddings.length).toBe(2)
expect(res.embeddings[0]).toEqual({ embedding: [0.1, 0.2, 0.3], startTime: 0, endTime: 60 })
expect(res.embeddings[1]).toEqual({ embedding: [0.1, 0.2, 0.3], startTime: 60, endTime: 120 })
expect(vi.mocked(fs.writeFileSync)).toHaveBeenCalled()
expect(vi.mocked(fs.readFileSync)).toHaveBeenCalled()
expect(vi.mocked(fs.unlinkSync)).toHaveBeenCalled()
expect(res.embedding).toEqual([0.1, 0.2, 0.3])
expect(s3Service.getObject).toHaveBeenCalledWith(
'shumai',
'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
)
})
it('should generate text embedding successfully', async () => {
@@ -291,6 +276,63 @@ describe('AI Database Activities Integration', () => {
expect(ctx.asset.id).toBe(asset.id)
expect(ctx.asset.mediaType).toBe('video/mp4')
})
it('should parse valid positive chunk duration and fallback on invalid or negative ones', async () => {
// Create embedding agent if not already present
const existingAgent = await prisma.agent.findUnique({ where: { id: user.id } })
if (!existingAgent) {
await prisma.agent.create({
data: {
id: user.id,
teamId: team.id,
type: 'embedding',
enabled: true,
config: {
provider: 'openai',
model: 'gpt-4',
},
},
})
}
// Test default/fallback
delete process.env.EMBEDDING_CHUNK_DURATION
let ctx = await getEmbeddingContextActivity({
teamId: team.id,
assetId: asset.id,
})
expect(ctx.chunkDuration).toBe(60.0)
expect(ctx.chunkOverlap).toBe(5.0)
// Test valid positive
process.env.EMBEDDING_CHUNK_DURATION = '45.5'
process.env.EMBEDDING_CHUNK_OVERLAP = '10.0'
ctx = await getEmbeddingContextActivity({
teamId: team.id,
assetId: asset.id,
})
expect(ctx.chunkDuration).toBe(45.5)
expect(ctx.chunkOverlap).toBe(10.0)
// Test negative/invalid for overlap
process.env.EMBEDDING_CHUNK_OVERLAP = '-5.0'
ctx = await getEmbeddingContextActivity({
teamId: team.id,
assetId: asset.id,
})
expect(ctx.chunkOverlap).toBe(5.0)
process.env.EMBEDDING_CHUNK_OVERLAP = 'invalid'
ctx = await getEmbeddingContextActivity({
teamId: team.id,
assetId: asset.id,
})
expect(ctx.chunkOverlap).toBe(5.0)
// Cleanup env
delete process.env.EMBEDDING_CHUNK_DURATION
delete process.env.EMBEDDING_CHUNK_OVERLAP
})
})
describe('saveAssetEmbeddingsActivity', () => {
+100 -1
View File
@@ -1,6 +1,6 @@
import { GoogleGenAI } from '@google/genai'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/transcode'
import { transcodeService } from '@shumai/core'
import { execFile } from 'child_process'
import * as fs from 'fs'
import * as os from 'os'
@@ -140,6 +140,8 @@ export async function generateEmbeddingActivity(params: GenerateEmbeddingParams)
const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}.mp4`)
await execFileAsync('ffmpeg', [
'-y',
'-loglevel',
'warning',
'-i',
tmpFile,
'-ss',
@@ -309,9 +311,18 @@ export async function getEmbeddingContextActivity(params: { teamId: string; asse
throw ApplicationFailure.create({ message: 'asset has no media type', nonRetryable: true })
}
const parsedDuration = parseFloat(process.env.EMBEDDING_CHUNK_DURATION || '')
const chunkDuration =
Number.isFinite(parsedDuration) && parsedDuration > 0 ? parsedDuration : 60.0
const parsedOverlap = parseFloat(process.env.EMBEDDING_CHUNK_OVERLAP || '')
const chunkOverlap = Number.isFinite(parsedOverlap) && parsedOverlap >= 0 ? parsedOverlap : 5.0
return {
agent,
asset,
chunkDuration,
chunkOverlap,
}
}
@@ -338,3 +349,91 @@ export async function saveAssetEmbeddingsActivity(params: {
}
}
}
export interface GenerateImageEmbeddingParams {
teamId: string
assetKey: string
mediaType: string
}
export async function generateImageEmbeddingActivity(
params: GenerateImageEmbeddingParams,
): Promise<{
embedding: number[]
usage: Usage
}> {
const apiKey = process.env.GEMINI_API_KEY
if (!apiKey) {
throw ApplicationFailure.create({
message: 'GEMINI_API_KEY environment variable is not configured',
nonRetryable: true,
})
}
const resolvedApiKey = process.env[apiKey] || apiKey
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
const usage: Usage = {
model: 'gemini-embedding-2',
inputTokens: 0,
outputTokens: 0,
}
const { buffer: data } = await s3Service.getObject(
process.env.S3_BUCKET || 'shumai',
params.assetKey,
)
const embVec = await generateMultimodalEmbedding(ai, data, params.mediaType)
return {
embedding: embVec,
usage,
}
}
export interface GenerateVideoChunkEmbeddingParams {
teamId: string
chunkKey: string
}
export async function generateVideoChunkEmbeddingActivity(
params: GenerateVideoChunkEmbeddingParams,
): Promise<{
embedding: number[]
usage: Usage
}> {
const apiKey = process.env.GEMINI_API_KEY
if (!apiKey) {
throw ApplicationFailure.create({
message: 'GEMINI_API_KEY environment variable is not configured',
nonRetryable: true,
})
}
const resolvedApiKey = process.env[apiKey] || apiKey
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
const usage: Usage = {
model: 'gemini-embedding-2',
inputTokens: 0,
outputTokens: 0,
}
try {
const { buffer: data } = await s3Service.getObject(
process.env.S3_BUCKET || 'shumai',
params.chunkKey,
)
const embVec = await generateMultimodalEmbedding(ai, data, 'video/mp4')
return {
embedding: embVec,
usage,
}
} catch (err) {
throw ApplicationFailure.create({
message: `Failed to generate video chunk embedding for key ${params.chunkKey}: ${err instanceof Error ? err.message : String(err)}`,
nonRetryable: false,
})
}
}
@@ -2,7 +2,7 @@ import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { s3Service } from '@shumai/core/src/s3/s3'
import { type SessionTreeEntry } from '@earendil-works/pi-agent-core'
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it, vi, afterEach } from 'vitest'
import { DatabaseSessionStorage } from './database-session-storage'
import { agentService } from '@shumai/core/src/agent/agent'
import { createAgentSession } from './index'
@@ -13,6 +13,10 @@ import * as screenshotModule from './tools/screenshot'
describe('DatabaseSessionStorage', () => {
setupTestDbHooks()
afterEach(() => {
vi.restoreAllMocks()
})
const mockModelConfig: PrismaJson.ModelConfig = {
reasoning: false,
input: ['text'],
@@ -316,6 +320,7 @@ describe('DatabaseSessionStorage', () => {
// 6. Resume the session via createAgentSession
await createAgentSession({
teamId: 't1',
agentId: agent.id,
providerName: 'test-provider',
modelId: 'test-model',
@@ -334,6 +339,7 @@ describe('DatabaseSessionStorage', () => {
expect.objectContaining({
MOCK_ENV_VAR: 'mocked-value',
}),
expect.any(Object),
)
})
@@ -390,7 +396,7 @@ describe('DatabaseSessionStorage', () => {
expect(entries[2].id).toBe('01C')
})
it('should use the current comment ID for media tools in subsequent turns', async () => {
it('should use the current comment ID for media tools in subsequent turns (image)', async () => {
const { agent, user, team } = await setupTestData()
// Create a project and asset to satisfy FK constraints
@@ -424,6 +430,7 @@ describe('DatabaseSessionStorage', () => {
// 3. Resume the session via createAgentSession with a NEW comment ID
await createAgentSession({
teamId: 't1',
agentId: agent.id,
providerName: 'test-provider',
modelId: 'test-model',
@@ -438,6 +445,58 @@ describe('DatabaseSessionStorage', () => {
// 4. Assert that the tools were instantiated using the new comment ID, not the original one
expect(createAnalyzeImageToolSpy).toHaveBeenCalledWith(asset.id, 'new-comment-456')
expect(createScreenshotToolSpy).not.toHaveBeenCalled()
})
it('should use the current comment ID for media tools in subsequent turns (video)', async () => {
const { agent, user, team } = await setupTestData()
// Create a project and asset to satisfy FK constraints
const project = await prisma.project.create({
data: { name: 'Test Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
id: 'asset-456',
name: 'test.mp4',
type: 'file',
mediaType: 'video/mp4',
projectId: project.id,
status: 'uploaded',
},
})
// 1. Create a session with an original comment ID and an asset ID using the storage class
const initialStorage = await DatabaseSessionStorage.create({
agentId: agent.id,
userId: user.id,
cwd: '/test/cwd',
assetId: asset.id,
userCommentId: 'original-comment-123',
})
const sessionId = initialStorage.sessionId
// 2. Spy on media tools constructors
const createAnalyzeImageToolSpy = vi.spyOn(analyzeImageModule, 'createAnalyzeImageTool')
const createScreenshotToolSpy = vi.spyOn(screenshotModule, 'createScreenshotTool')
// 3. Resume the session via createAgentSession with a NEW comment ID
await createAgentSession({
teamId: 't1',
agentId: agent.id,
providerName: 'test-provider',
modelId: 'test-model',
systemPrompt: 'Test prompt',
teamSkills: [],
allowedDomains: [],
sessionId: sessionId,
userId: user.id,
userCommentId: 'new-comment-456',
providers: [],
})
// 4. Assert that the tools were instantiated using the new comment ID, not the original one
expect(createScreenshotToolSpy).toHaveBeenCalledWith(asset.id, 'new-comment-456')
expect(createAnalyzeImageToolSpy).not.toHaveBeenCalled()
})
})
+344 -2
View File
@@ -1,6 +1,27 @@
import { describe, it, expect } from 'vitest'
import { formatSkillsForPrompt } from './index'
import { describe, it, expect, vi } from 'vitest'
import { formatSkillsForPrompt, createAgentSession } from './index'
import { createSandboxedBashTool } from './tools/sandboxed-bash'
import { SandboxManager, type SandboxAskCallback } from '@anthropic-ai/sandbox-runtime'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import * as path from 'path'
import * as childProcess from 'node:child_process'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let mockSpawn: any = null
vi.mock('node:child_process', async () => {
const actual = (await vi.importActual('node:child_process')) as typeof childProcess
return {
...actual,
spawn: (...args: Parameters<typeof childProcess.spawn>) => {
if (mockSpawn) {
return mockSpawn(...args)
}
return actual.spawn(...args)
},
}
})
describe('formatSkillsForPrompt', () => {
it('should return empty string if skills array is empty', () => {
@@ -31,3 +52,324 @@ describe('formatSkillsForPrompt', () => {
expect(result).toContain('</available_skills>')
})
})
describe('Sandbox Network isolation integration', () => {
setupTestDbHooks()
it('should register callback that pushes blocked hosts to database and propagates to bash tool', async () => {
// 1. Create a team
const team = await prisma.team.create({
data: { name: 'Test Sandbox Team' },
})
// Ensure agent user and agent exist in database to avoid foreign key violation
await prisma.user.create({
data: {
id: 'test-agent',
name: 'Ai Agent',
email: 'test-agent@shumai.ai',
type: 'agent',
},
})
await prisma.agent.create({
data: {
id: 'test-agent',
teamId: team.id,
type: 'chat',
config: {
provider: 'openai',
model: 'gpt-4',
},
},
})
// 2. Mock / spy SandboxManager
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
const wrapSpy = vi
.spyOn(SandboxManager, 'wrapWithSandbox')
.mockImplementation(async (cmd) => cmd)
// 3. Call createAgentSession
await createAgentSession({
teamId: team.id,
agentId: 'test-agent',
providerName: 'google',
modelId: 'gemini',
systemPrompt: 'prompt',
teamSkills: [],
allowedDomains: [],
providers: [],
})
// 4. Verify SandboxManager.initialize was called and extract the callback
expect(initializeSpy).toHaveBeenCalled()
const callback = initializeSpy.mock.calls[0][1]
expect(callback).toBeDefined()
// 5. Trigger the callback with a blocked host
const result = await callback!({ host: 'blocked-api.com', port: 443 })
expect(result).toBe(false) // should always return false to block
// 6. Verify it was pushed to database
const sandbox = await prisma.sandbox.findUnique({
where: { teamId: team.id },
})
expect(sandbox?.pendingDomains).toContain('blocked-api.com')
// 7. Verify that if the bash tool is run while a domain is blocked, it rejects with correct error
const sandboxState = { blockedHost: '' }
const bashTool = createSandboxedBashTool(
process.cwd(),
{},
{
getBlockedHost: () => sandboxState.blockedHost,
clearBlockedHost: () => {
sandboxState.blockedHost = ''
},
},
)
// Mock spawn to simulate process exit and trigger network block
mockSpawn = () => {
sandboxState.blockedHost = 'blocked-api.com'
const mockChild = {
pid: 123,
stdout: { on: vi.fn() },
stderr: { on: vi.fn() },
on: vi.fn((event: string, cb: (code: number) => void) => {
if (event === 'close') {
setTimeout(() => cb(1), 10)
}
}),
} as unknown as childProcess.ChildProcess
return mockChild
}
const bashPromise = bashTool.execute('1', { command: 'curl blocked-api.com' })
try {
await expect(bashPromise).rejects.toThrow(
'Network request to blocked-api.com is blocked, please ask admin to allow it in sandbox settings.',
)
} finally {
mockSpawn = null
initializeSpy.mockRestore()
wrapSpy.mockRestore()
}
})
it('should correctly route sandbox callback to the active session when multiple sessions are created sequentially', async () => {
// 1. Create two teams
const team1 = await prisma.team.create({
data: { name: 'Team 1' },
})
const team2 = await prisma.team.create({
data: { name: 'Team 2' },
})
// Ensure agent user and agents exist in database
await prisma.user.create({
data: {
id: 'agent-1',
name: 'Ai Agent 1',
email: 'agent1@shumai.ai',
type: 'agent',
},
})
await prisma.user.create({
data: {
id: 'agent-2',
name: 'Ai Agent 2',
email: 'agent2@shumai.ai',
type: 'agent',
},
})
await prisma.agent.create({
data: {
id: 'agent-1',
teamId: team1.id,
type: 'chat',
config: { provider: 'openai', model: 'gpt-4' },
},
})
await prisma.agent.create({
data: {
id: 'agent-2',
teamId: team2.id,
type: 'chat',
config: { provider: 'openai', model: 'gpt-4' },
},
})
// Mock SandboxManager.initialize to behave like a process-global singleton
let registeredCallback: SandboxAskCallback | null = null
const initializeSpy = vi
.spyOn(SandboxManager, 'initialize')
.mockImplementation(async (config, cb) => {
if (!registeredCallback) {
registeredCallback = cb || null
}
})
const resetSpy = vi.spyOn(SandboxManager, 'reset').mockImplementation(async () => {
// In the real SandboxManager, reset clears the global initialization promise and servers,
// which allows subsequent initialize calls to register a new callback.
registeredCallback = null
})
try {
// 2. Call createAgentSession for Session 1
await createAgentSession({
teamId: team1.id,
agentId: 'agent-1',
providerName: 'google',
modelId: 'gemini',
systemPrompt: 'prompt',
teamSkills: [],
allowedDomains: [],
providers: [],
})
// 3. Call createAgentSession for Session 2
await createAgentSession({
teamId: team2.id,
agentId: 'agent-2',
providerName: 'google',
modelId: 'gemini',
systemPrompt: 'prompt',
teamSkills: [],
allowedDomains: [],
providers: [],
})
expect(registeredCallback).toBeDefined()
// 4. Trigger the globally registered callback (which is from Session 1)
const result = await registeredCallback!({ host: 'blocked-for-session-2.com', port: 443 })
expect(result).toBe(false)
// 5. Verify that the pending domain was pushed to the DB record of Team 2
const sandbox2 = await prisma.sandbox.findUnique({
where: { teamId: team2.id },
})
expect(sandbox2?.pendingDomains).toContain('blocked-for-session-2.com')
} finally {
initializeSpy.mockRestore()
resetSpy.mockRestore()
}
})
it('should pass thinkingLevel to AgentHarness and default to off', async () => {
const team = await prisma.team.create({
data: { name: 'Test Team' },
})
await prisma.user.create({
data: {
id: 'test-agent-1',
name: 'Agent 1',
email: 'agent1@test.com',
type: 'agent',
},
})
await prisma.agent.create({
data: {
id: 'test-agent-1',
teamId: team.id,
type: 'chat',
config: { provider: 'google', model: 'gemini' },
},
})
await prisma.user.create({
data: {
id: 'test-agent-2',
name: 'Agent 2',
email: 'agent2@test.com',
type: 'agent',
},
})
await prisma.agent.create({
data: {
id: 'test-agent-2',
teamId: team.id,
type: 'chat',
config: { provider: 'google', model: 'gemini' },
},
})
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
try {
// Call createAgentSession with thinkingLevel
const { harness: harnessHigh } = await createAgentSession({
teamId: team.id,
agentId: 'test-agent-1',
providerName: 'google',
modelId: 'gemini',
systemPrompt: 'prompt',
teamSkills: [],
allowedDomains: [],
providers: [],
thinkingLevel: 'high',
})
expect(harnessHigh.getThinkingLevel()).toBe('high')
// Call createAgentSession without thinkingLevel
const { harness: harnessDefault } = await createAgentSession({
teamId: team.id,
agentId: 'test-agent-2',
providerName: 'google',
modelId: 'gemini',
systemPrompt: 'prompt',
teamSkills: [],
allowedDomains: [],
providers: [],
})
expect(harnessDefault.getThinkingLevel()).toBe('off')
} finally {
initializeSpy.mockRestore()
}
})
it('should filter out denied tools from AgentHarness', async () => {
const team = await prisma.team.create({
data: { name: 'Test Team 3' },
})
await prisma.user.create({
data: {
id: 'test-agent-3',
name: 'Agent 3',
email: 'agent3@shumai.ai',
type: 'agent',
},
})
await prisma.agent.create({
data: {
id: 'test-agent-3',
teamId: team.id,
type: 'chat',
config: { provider: 'google', model: 'gemini', deniedTools: ['bash'] },
},
})
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
try {
const { harness } = await createAgentSession({
teamId: team.id,
agentId: 'test-agent-3',
providerName: 'google',
modelId: 'gemini',
systemPrompt: 'prompt',
teamSkills: [],
allowedDomains: [],
providers: [],
})
const tools = harness.getTools()
const bashTool = tools.find((t) => t.name === 'bash')
expect(bashTool).toBeUndefined()
const readSkillTool = tools.find((t) => t.name === 'read_skill')
expect(readSkillTool).toBeDefined()
} finally {
initializeSpy.mockRestore()
}
})
})
+165 -83
View File
@@ -1,14 +1,21 @@
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import { AgentHarness, Session, type AgentTool } from '@earendil-works/pi-agent-core'
import {
AgentHarness,
Session,
type AgentTool,
type ThinkingLevel,
} from '@earendil-works/pi-agent-core'
import { NodeExecutionEnv } from '@earendil-works/pi-agent-core/node'
import { getModel } from '@earendil-works/pi-ai'
import { Type, type TSchema } from '@sinclair/typebox'
import * as fs from 'fs'
import * as path from 'path'
import { prisma } from '@shumai/db'
import { agentService } from '@shumai/core/src/agent/agent'
import { DatabaseSessionStorage } from './database-session-storage'
import { createAnalyzeImageTool } from './tools/analyze-image'
import { createScreenshotTool } from './tools/screenshot'
import { getSimpleMediaType } from './workflows/agent-chat-prompt-builder'
import { createCreateFileTool } from './tools/create-file'
import { createCreateFolderTool } from './tools/create-folder'
import { createCreateVersionTool } from './tools/create-version'
@@ -16,7 +23,77 @@ import { createListAssetsTool } from './tools/list-assets'
import { createReadSkillTool } from './tools/read-skill'
import { createSandboxedBashTool } from './tools/sandboxed-bash'
export interface DbModelInfo {
modelId: string
name: string | null
config: PrismaJson.ModelConfig
}
export interface DbProviderInfo {
name: string
config: PrismaJson.ProviderConfig
models: DbModelInfo[]
}
export function getModelFromDb(providers: DbProviderInfo[], providerName: string, modelId: string) {
const dbProvider = providers.find((p) => p.name === providerName)
const dbModel = dbProvider?.models.find((m) => m.modelId === modelId)
if (!dbProvider || !dbModel) return undefined
// Model contains complex internal types from pi-ai
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let m: any
try {
// Try to get built-in model as template
// eslint-disable-next-line @typescript-eslint/no-explicit-any
m = { ...(getModel as any)(providerName, modelId) }
} catch {
// Not a built-in model
m = {
id: modelId,
name: dbModel.name || modelId,
provider: providerName,
api: 'openai-responses',
baseUrl: '',
reasoning: false,
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 4096,
maxTokens: 4096,
}
}
// Override with database config
if (dbProvider.config.baseUrl) {
m.baseUrl = dbProvider.config.baseUrl
}
if (dbProvider.config.api) {
m.api = dbProvider.config.api
}
Object.assign(m, dbModel.config)
if (dbModel.name) {
m.name = dbModel.name
}
return m
}
export function getApiKeyAndHeadersFromDb(providers: DbProviderInfo[], providerName: string) {
// Helper to resolve key from ENV if it matches an ENV var name
const resolveKey = (key: string | undefined) => (key ? process.env[key] || key : undefined)
// Look up the provider in our providers list
const dbProvider = providers.find((p) => p.name === providerName)
const providerApiKey = dbProvider?.config?.apiKey
if (providerApiKey) {
return { apiKey: resolveKey(providerApiKey)! }
}
return undefined
}
export interface CreateAgentSessionParams {
teamId: string
agentId: string
providerName: string
modelId: string
@@ -27,19 +104,13 @@ export interface CreateAgentSessionParams {
userId?: string
userCommentId?: string | null
customTools?: AgentTool[]
providers: Array<{
name: string
config: PrismaJson.ProviderConfig
models: Array<{
modelId: string
name: string | null
config: PrismaJson.ModelConfig
}>
}>
thinkingLevel?: string
providers: DbProviderInfo[]
}
export async function createAgentSession(params: CreateAgentSessionParams) {
const {
teamId,
agentId,
providerName,
modelId,
@@ -50,6 +121,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
userId,
userCommentId: passedUserCommentId,
customTools = [],
thinkingLevel,
} = params
const storage = await DatabaseSessionStorage.create({
@@ -63,70 +135,66 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
const agentDir = path.join(process.cwd(), '.pi', 'agents', agentId)
if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true })
// Helper to construct a Model object from database providers list
const getModelFromDb = (pName: string, mId: string) => {
const dbProvider = params.providers.find((p) => p.name === pName)
const dbModel = dbProvider?.models.find((m) => m.modelId === mId)
if (!dbProvider || !dbModel) return undefined
// Model contains complex internal types from pi-ai
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let m: any
try {
// Try to get built-in model as template
// eslint-disable-next-line @typescript-eslint/no-explicit-any
m = { ...(getModel as any)(pName, mId) }
} catch {
// Not a built-in model
m = {
id: mId,
name: dbModel.name || mId,
provider: pName,
api: 'openai-responses',
baseUrl: '',
reasoning: false,
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 4096,
maxTokens: 4096,
}
}
// Override with database config
if (dbProvider.config.baseUrl) {
m.baseUrl = dbProvider.config.baseUrl
}
if (dbProvider.config.api) {
m.api = dbProvider.config.api
}
Object.assign(m, dbModel.config)
if (dbModel.name) {
m.name = dbModel.name
}
return m
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const model = getModelFromDb(providerName, modelId) || (getModel as any)(providerName, modelId)
const model =
getModelFromDb(params.providers, providerName, modelId) ||
(getModel as unknown as (p: string, m: string) => unknown)(providerName, modelId)
const piDir = path.join(process.cwd(), '.pi')
if (!fs.existsSync(piDir)) fs.mkdirSync(piDir, { recursive: true })
const allowWrite = [piDir]
const sandboxState = {
blockedHost: '',
}
const sandboxAskCallback = async ({ host }: { host: string; port?: number }) => {
try {
const sandbox = await prisma.sandbox.findUnique({
where: { teamId },
})
const pendingDomains = sandbox?.pendingDomains || []
if (!pendingDomains.includes(host)) {
await prisma.sandbox.upsert({
where: { teamId },
create: {
teamId,
pendingDomains: [host],
},
update: {
pendingDomains: {
push: host,
},
},
})
}
} catch (err) {
console.error('Failed to update sandbox pending domains:', err)
}
sandboxState.blockedHost = host
return false
}
// SandboxManager.initialize is a global operation that applies to the entire process.
await SandboxManager.initialize({
network: {
allowedDomains,
deniedDomains: [],
// We reset it first to ensure any previous process-global SOCKS/HTTP proxy servers
// and callbacks are cleaned up, allowing the new callback and allowedDomains to take effect.
await SandboxManager.reset()
await SandboxManager.initialize(
{
network: {
allowedDomains,
deniedDomains: [],
},
filesystem: {
denyRead: ['.env', '.env.*', '*.pem', '*.key'],
allowWrite,
denyWrite: ['.env', '.env.*', '*.pem', '*.key'],
},
},
filesystem: {
denyRead: ['.env', '.env.*', '*.pem', '*.key'],
allowWrite,
denyWrite: ['.env', '.env.*', '*.pem', '*.key'],
},
})
sandboxAskCallback,
)
const skillEnvs: Record<string, string> = {}
const onEnvsAdded = (envs: Record<string, string>) => {
@@ -163,13 +231,25 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
const mediaTools: AgentTool[] = []
if (assetId) {
mediaTools.push(
createAnalyzeImageTool(assetId, userCommentId),
createScreenshotTool(assetId, userCommentId),
)
const asset = await prisma.asset.findUnique({
where: { id: assetId },
})
if (asset?.mediaType) {
const type = getSimpleMediaType(asset.mediaType)
if (type === 'image') {
mediaTools.push(createAnalyzeImageTool(assetId, userCommentId))
} else if (type === 'video') {
mediaTools.push(createScreenshotTool(assetId, userCommentId))
}
}
}
const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs)
const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs, {
getBlockedHost: () => sandboxState.blockedHost,
clearBlockedHost: () => {
sandboxState.blockedHost = ''
},
})
const readSkill = createReadSkillTool(onEnvsAdded)
const systemTools: AgentTool[] = []
@@ -182,10 +262,20 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
)
}
const agent = await prisma.agent.findUnique({
where: { id: agentId },
})
const agentConfig = agent?.config as PrismaJson.AgentConfig | null | undefined
const deniedTools = agentConfig?.deniedTools || []
const allTools = [...mediaTools, readSkill, sandboxedBash, ...systemTools, ...customTools]
const enabledTools = allTools.filter((tool) => !deniedTools.includes(tool.name))
const harness = new AgentHarness({
env: new NodeExecutionEnv({ cwd: process.cwd() }),
session,
model,
thinkingLevel: (thinkingLevel || 'off') as ThinkingLevel,
systemPrompt: async () => {
let prompt = systemPrompt
@@ -206,19 +296,9 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
return prompt
},
getApiKeyAndHeaders: async (targetModel) => {
// Helper to resolve key from ENV if it matches an ENV var name
const resolveKey = (key: string | undefined) => (key ? process.env[key] || key : undefined)
// Look up the provider in our providers list
const dbProvider = params.providers.find((p) => p.name === targetModel.provider)
const providerApiKey = dbProvider?.config?.apiKey
if (providerApiKey) {
return { apiKey: resolveKey(providerApiKey)! }
}
return undefined
return getApiKeyAndHeadersFromDb(params.providers, targetModel.provider)
},
tools: [...mediaTools, readSkill, sandboxedBash, ...systemTools, ...customTools],
tools: enabledTools,
})
return { session, harness }
@@ -333,6 +413,8 @@ export {
generateTextEmbeddingActivity,
type ExtractAiMetadataParams,
extractAiMetadataActivity,
generateImageEmbeddingActivity,
generateVideoChunkEmbeddingActivity,
} from './activities/ai'
export * from './workflows/agent-autofill'
export * from './workflows/agent-chat'
+2 -1
View File
@@ -6,6 +6,7 @@ import * as path from 'path'
import { s3Service } from '@shumai/core/src/s3/s3'
import { detectSupportedMimeType } from '@shumai/core/src/utils/mime'
import { ulid } from 'ulid'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
function getMimeType(filePath: string): string {
try {
@@ -64,7 +65,7 @@ export function createCreateFileTool(userId: string): AgentTool<typeof createFil
const mimeType = getMimeType(absolutePath)
// Generate compliant S3 key matching normal file upload format
const s3Key = `files/${ulid()}/raw`
const s3Key = `files/${ulid()}/${sanitizeFilename(path.basename(absolutePath))}`
await s3Service.uploadFileToKey(absolutePath, s3Key, mimeType)
const result = await executeAgentToolWorkflow({
+2 -1
View File
@@ -6,6 +6,7 @@ import * as path from 'path'
import { s3Service } from '@shumai/core/src/s3/s3'
import { detectSupportedMimeType } from '@shumai/core/src/utils/mime'
import { ulid } from 'ulid'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
function getMimeType(filePath: string): string {
try {
@@ -65,7 +66,7 @@ export function createCreateVersionTool(userId: string): AgentTool<typeof create
const mimeType = getMimeType(absolutePath)
// Generate compliant S3 key matching normal file upload format
const s3Key = `files/${ulid()}/raw`
const s3Key = `files/${ulid()}/${sanitizeFilename(path.basename(absolutePath))}`
await s3Service.uploadFileToKey(absolutePath, s3Key, mimeType)
const result = await executeAgentToolWorkflow({
@@ -15,9 +15,15 @@ type BashDetails = {
stderr: string
}
export interface SandboxedBashOptions {
getBlockedHost?: () => string
clearBlockedHost?: () => void
}
export const createSandboxedBashTool = (
cwd: string,
skillEnvs: Record<string, string> = {},
options?: SandboxedBashOptions,
): AgentTool<typeof BashParameters, BashDetails> => {
return {
name: 'bash',
@@ -29,6 +35,7 @@ export const createSandboxedBashTool = (
{ command, timeout },
signal,
): Promise<AgentToolResult<BashDetails>> => {
options?.clearBlockedHost?.()
const wrappedCommand = await SandboxManager.wrapWithSandbox(command)
return new Promise((resolve, reject) => {
@@ -94,12 +101,20 @@ export const createSandboxedBashTool = (
if (timeoutHandle) clearTimeout(timeoutHandle)
signal?.removeEventListener('abort', onAbort)
const blocked = options?.getBlockedHost?.()
if (signal?.aborted) {
logger.error({ command, stdout, stderr }, 'Sandboxed bash command aborted')
reject(new Error('aborted'))
} else if (timedOut) {
logger.error({ timeout, command, stdout, stderr }, 'Sandboxed bash command timed out')
reject(new Error(`bash command timed out after ${timeout} seconds`))
} else if (blocked) {
reject(
new Error(
`Network request to ${blocked} is blocked, please ask admin to allow it in sandbox settings.`,
),
)
} else if (code !== 0 && code !== null) {
logger.error(
{ exitCode: code, command, stdout, stderr },
@@ -283,4 +283,32 @@ describe('Agent Autofill Workflow', () => {
tmpDir: '/tmp/test-dir',
})
})
it('should fail with non-retryable ApplicationFailure for unsupported audio files', async () => {
mockActivities.getAssetActivity.mockResolvedValue({
id: 'a1',
storageKey: { key: 'asset-key' },
project: { id: 'p1', teamId: 't1' },
mediaType: 'audio/mp3',
})
const task = await prisma.workflowTask.create({
data: {
type: 'ai_metadata_autofill',
status: 'pending',
assetId: 'a1',
},
})
await expect(agentAutofillMedia(task)).rejects.toThrow(
'unsupported media type for autofill: audio/mp3',
)
// Verify task failed status
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: task.id,
status: 'failed',
output: { error: 'unsupported media type for autofill: audio/mp3' },
})
})
})
@@ -65,6 +65,14 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
// 2. Prepare Data (Images)
const isImage = asset.mediaType?.startsWith('image/') || false
const isVideo = asset.mediaType?.startsWith('video/') || false
if (!isImage && !isVideo) {
throw ApplicationFailure.create({
message: `unsupported media type for autofill: ${asset.mediaType}`,
nonRetryable: true,
})
}
const download = await executeActivity(transcodeWorkerQueue, downloadMediaToTmpActivity, {
assetKey: key,
@@ -73,4 +73,34 @@ describe('AgentChatPromptBuilder', () => {
expect(result).toContain("call the 'screenshot' tool")
expect(result).toContain('The user explicitly mentioned you')
})
it('should build prompt with attached files and referenced assets', () => {
const builder = new AgentChatPromptBuilder('a1')
.withAttachedFiles(['- file1.txt', '- file2.png'])
.withReferencedAssets(['- folder1', '- file3.mp4'])
const result = builder.build()
expect(result).toContain('[Context: Attached Files & Referenced Assets]')
expect(result).toContain('Attached Files:\n- file1.txt\n- file2.png')
expect(result).toContain('Referenced Workspace Assets:\n- folder1\n- file3.mp4')
})
it('should build prompt for continuation mode returning only turn-specific modifications', () => {
const builder = new AgentChatPromptBuilder('a1')
.withContinuation(true)
.withAssetDetails('movie.mp4', 'video/mp4', 12.34)
.withPathContext('src/main.ts')
.withCommentTimestamp(8.2)
.withAttachedFiles(['- file1.txt'])
.withReferencedAssets(['- folder1'])
const result = builder.build()
expect(result).not.toContain('The user is discussing an asset with ID:')
expect(result).not.toContain('File Name: movie.mp4')
expect(result).not.toContain('Asset Path Context:')
expect(result).toContain('Comment Timestamp: 8.20 seconds')
expect(result).toContain('[Context: New Attached Files & Referenced Assets]')
expect(result).toContain('Attached Files:\n- file1.txt')
expect(result).toContain('Referenced Workspace Assets:\n- folder1')
})
})
@@ -22,11 +22,34 @@ export class AgentChatPromptBuilder {
private commentTimestamp?: number
private pathContext?: string
private explicitMention = false
private attachedFiles: string[] = []
private referencedAssets: string[] = []
private isContinuation = false
constructor(assetId: string) {
this.assetId = assetId
}
withContinuation(isContinuation: boolean): this {
this.isContinuation = isContinuation
return this
}
withAttachedFiles(files?: string[]): this {
if (files) {
this.attachedFiles = files
}
return this
}
withReferencedAssets(assets?: string[]): this {
if (assets) {
this.referencedAssets = assets
}
return this
}
withPathContext(pathContext?: string): this {
this.pathContext = pathContext
return this
@@ -52,6 +75,23 @@ export class AgentChatPromptBuilder {
}
build(): string {
if (this.isContinuation) {
let instruction = ''
if (this.commentTimestamp !== undefined) {
instruction += `Comment Timestamp: ${this.commentTimestamp.toFixed(2)} seconds`
}
if (this.attachedFiles.length > 0 || this.referencedAssets.length > 0) {
instruction += `\n\n[Context: New Attached Files & Referenced Assets]`
if (this.attachedFiles.length > 0) {
instruction += `\nAttached Files:\n${this.attachedFiles.join('\n')}`
}
if (this.referencedAssets.length > 0) {
instruction += `\nReferenced Workspace Assets:\n${this.referencedAssets.join('\n')}`
}
}
return instruction.trim()
}
let instruction = `The user is discussing an asset with ID: ${this.assetId}.`
if (this.assetName) {
instruction += `\nFile Name: ${this.assetName}`
@@ -70,6 +110,16 @@ export class AgentChatPromptBuilder {
instruction += `\n\nAsset Path Context:\n${this.pathContext}`
}
if (this.attachedFiles.length > 0 || this.referencedAssets.length > 0) {
instruction += `\n\n[Context: Attached Files & Referenced Assets]`
if (this.attachedFiles.length > 0) {
instruction += `\nAttached Files:\n${this.attachedFiles.join('\n')}`
}
if (this.referencedAssets.length > 0) {
instruction += `\nReferenced Workspace Assets:\n${this.referencedAssets.join('\n')}`
}
}
if (this.mediaType) {
const type = getSimpleMediaType(this.mediaType)
if (type === 'image') {
@@ -46,11 +46,15 @@ describe('Agent Chat Workflow', () => {
getAssetPathContextActivity: Object.assign(vi.fn(), {
_activityName: 'getAssetPathContextActivity',
}),
generateSessionNameActivity: Object.assign(vi.fn(), {
_activityName: 'generateSessionNameActivity',
}),
}
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
mockActivities.generateSessionNameActivity.mockResolvedValue(undefined)
mockActivities.getAssetActivity.mockResolvedValue({
id: 'a1',
project: { teamId: 't1' },
@@ -166,6 +170,15 @@ describe('Agent Chat Workflow', () => {
status: 'completed',
output: { sessionId: 'session-123' },
})
// Verify session name generation triggered
expect(mockActivities.generateSessionNameActivity).toHaveBeenCalledWith({
teamId: 't1',
agentId: 'b1',
prompt: 'hello agent',
sessionId: 'session-123',
context: expect.any(Object),
})
})
it('should skip session initialization if sessionId is already provided', async () => {
@@ -185,6 +198,7 @@ describe('Agent Chat Workflow', () => {
expect(mockActivities.initializeAgentSessionActivity).not.toHaveBeenCalled()
const expectedInstruction2 = new AgentChatPromptBuilder('a1')
.withContinuation(true)
.withPathContext('Path: folder/subfolder/file.png')
.withAssetDetails('test-file.png', 'image/png', undefined)
.withCommentTimestamp(null)
@@ -197,6 +211,9 @@ describe('Agent Chat Workflow', () => {
agentsInstruction: expectedInstruction2,
}),
)
// Verify session name generation is skipped
expect(mockActivities.generateSessionNameActivity).not.toHaveBeenCalled()
})
it('should delete placeholder comment and finish when AI responds with __NO_REPLY__', async () => {
@@ -397,4 +414,102 @@ describe('Agent Chat Workflow', () => {
message: 'Sorry, I encountered an error while processing your request.',
})
})
it('should execute direct-context chatbot flow resolving file metadata and skipping comment placeholder', async () => {
mockActivities.getAssetActivity.mockImplementation(async (id: string) => {
if (id === 'file-attachment-1') {
return {
id: 'file-attachment-1',
name: 'attachment.png',
type: 'file',
mediaType: 'image/png',
projectId: 'p1',
}
}
if (id === 'referenced-asset-1') {
return {
id: 'referenced-asset-1',
name: 'ref-folder',
type: 'folder',
mediaType: null,
projectId: 'p1',
}
}
return {
id,
name: 'test-file.png',
type: 'file',
mediaType: 'image/png',
projectId: 'p1',
project: { teamId: 't1' },
}
})
mockActivities.getAssetPathContextActivity.mockImplementation(async (id: string) => {
if (id === 'file-attachment-1') return 'attachment.png'
if (id === 'referenced-asset-1') return 'ref-folder'
return 'folder/subfolder/file.png'
})
const task = await prisma.workflowTask.create({
data: {
type: 'chat',
status: 'pending',
assetId: 'a1',
payload: {
projectId: 'p1',
agent: {
agentId: 'b1',
sessionId: 'session-direct-123',
prompt: 'chatbot prompt',
attachedFiles: ['file-attachment-1'],
assetIds: ['referenced-asset-1'],
explicitMention: true,
},
},
},
})
await agentChat(task)
// Verify placeholder comment is NOT created
expect(mockActivities.createCommentActivity).not.toHaveBeenCalled()
expect(mockActivities.updateCommentActivity).not.toHaveBeenCalled()
// Verify prompt builder is populated and workflow runs agentChatActivity with context instruction
const expectedInstruction = new AgentChatPromptBuilder('a1')
.withContinuation(true)
.withPathContext('folder/subfolder/file.png')
.withAssetDetails('test-file.png', 'image/png', undefined)
.withCommentTimestamp(undefined)
.withExplicitMention(true)
.withAttachedFiles([
'- Name: attachment.png (ID: file-attachment-1, Type: file, Media Type: image/png, Project ID: p1, Path: attachment.png)',
])
.withReferencedAssets([
'- Name: ref-folder (ID: referenced-asset-1, Type: folder, Media Type: unknown, Project ID: p1, Path: ref-folder)',
])
.build()
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
expect.objectContaining({
teamId: 't1',
agentId: 'b1',
message: 'chatbot prompt',
imageUrls: [],
projectId: 'p1',
folderId: '',
agentsInstruction: expectedInstruction,
sessionId: 'session-direct-123',
userId: undefined,
userCommentId: undefined,
explicitMention: true,
context: { agent: { id: 'b1' } },
attachedAssets: [
{ id: 'file-attachment-1', name: 'attachment.png', type: 'file' },
{ id: 'referenced-asset-1', name: 'ref-folder', type: 'folder' },
],
}),
)
})
})
+118 -36
View File
@@ -17,6 +17,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
deleteCommentActivity,
initializeAgentSessionActivity,
getAssetPathContextActivity,
generateSessionNameActivity,
} = getActivities()
let placeholderCommentId: string | undefined
@@ -46,26 +47,42 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
// 1. Get User Comment
const userCommentId = payload.agent?.userCommentId
if (!userCommentId) {
throw ApplicationFailure.create({
message: 'userCommentId missing in payload',
nonRetryable: true,
})
}
const userComment = await executeActivity(agentWorkerQueue, getCommentActivity, userCommentId)
if (!userComment) {
throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true })
}
let prompt = ''
let attachmentImageUrls: string[] = []
let commentTimestamp: number | undefined
// 2. Create Placeholder Comment
const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, {
assetId: task.assetId,
message: '__CHAT__',
sessionId: sessionId || 'pending',
agentId: agentId,
replyToId: userComment.replyToId ?? userComment.id,
})
placeholderCommentId = placeholder.id
if (userCommentId) {
const userComment = await executeActivity(agentWorkerQueue, getCommentActivity, userCommentId)
if (!userComment) {
throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true })
}
prompt = userComment.message || ''
if (userComment.second !== null && userComment.second !== undefined) {
commentTimestamp = userComment.second
}
// 2. Create Placeholder Comment
const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, {
assetId: task.assetId,
message: '__CHAT__',
sessionId: sessionId || 'pending',
agentId: agentId,
replyToId: userComment.replyToId ?? userComment.id,
})
placeholderCommentId = placeholder.id
// 5. Prepare Images (Attachments only)
if (userComment.attachments) {
for (const att of userComment.attachments) {
if (att.asset?.mediaType?.startsWith('image/') && att.asset?.storageKey?.key) {
attachmentImageUrls.push(att.asset.storageKey.key)
}
}
}
} else {
prompt = payload.agent?.prompt || ''
attachmentImageUrls = payload.agent?.imageUrls || []
}
// 3. Get Asset
const asset = await executeActivity(agentWorkerQueue, getAssetActivity, task.assetId)
@@ -75,13 +92,21 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
const teamId = asset.project.teamId
// 4. Initialize Session if missing
let isNewChat = !payload.agent?.sessionId || payload.agent?.isNewChat === true
if (!sessionId) {
if (!userCommentId) {
throw ApplicationFailure.create({
message: 'sessionId is required when userCommentId is missing',
nonRetryable: true,
})
}
sessionId = await executeActivity(agentWorkerQueue, initializeAgentSessionActivity, {
teamId,
agentId: agentId,
userCommentId,
userId: payload.agent?.userId,
})
isNewChat = true
}
// 4b. Fetch Agent Context
@@ -90,16 +115,6 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
agentId: agentId,
})
// 5. Prepare Images (Attachments only)
const attachmentImageUrls: string[] = []
if (userComment?.attachments) {
for (const att of userComment.attachments) {
if (att.asset?.mediaType?.startsWith('image/') && att.asset?.storageKey?.key) {
attachmentImageUrls.push(att.asset.storageKey.key)
}
}
}
const pathContext = await executeActivity(
agentWorkerQueue,
getAssetPathContextActivity,
@@ -110,11 +125,49 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
const mediaInfo = asset.media as any
const duration = mediaInfo?.duration
// Resolve Attached Files Details
const attachedFileDetailsList: string[] = []
const attachedAssets: Array<{ id: string; name: string; type: string }> = []
if (payload.agent?.attachedFiles) {
for (const fileId of payload.agent.attachedFiles) {
const file = await executeActivity(agentWorkerQueue, getAssetActivity, fileId)
if (file) {
const path = await executeActivity(agentWorkerQueue, getAssetPathContextActivity, fileId)
attachedFileDetailsList.push(
`- Name: ${file.name} (ID: ${file.id}, Type: ${file.type}, Media Type: ${file.mediaType || 'unknown'}, Project ID: ${file.projectId || 'unknown'}, Path: ${path})`,
)
attachedAssets.push({ id: file.id, name: file.name, type: file.type })
}
}
}
// Resolve Referenced Workspace Assets Details
const referencedAssetDetailsList: string[] = []
if (payload.agent?.assetIds) {
for (const assetId of payload.agent.assetIds) {
const referencedAsset = await executeActivity(agentWorkerQueue, getAssetActivity, assetId)
if (referencedAsset) {
const path = await executeActivity(agentWorkerQueue, getAssetPathContextActivity, assetId)
referencedAssetDetailsList.push(
`- Name: ${referencedAsset.name} (ID: ${referencedAsset.id}, Type: ${referencedAsset.type}, Media Type: ${referencedAsset.mediaType || 'unknown'}, Project ID: ${referencedAsset.projectId || 'unknown'}, Path: ${path})`,
)
attachedAssets.push({
id: referencedAsset.id,
name: referencedAsset.name,
type: referencedAsset.type,
})
}
}
}
const instruction = new AgentChatPromptBuilder(asset.id)
.withContinuation(!isNewChat)
.withPathContext(pathContext)
.withAssetDetails(asset.name, asset.mediaType, duration)
.withCommentTimestamp(userComment.second)
.withCommentTimestamp(commentTimestamp)
.withExplicitMention(payload.agent?.explicitMention)
.withAttachedFiles(attachedFileDetailsList)
.withReferencedAssets(referencedAssetDetailsList)
.build()
// 6. Call AI Chat
@@ -126,20 +179,34 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
}
const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, {
taskId: task.id,
teamId,
agentId: agentId,
message: userComment.message || '',
message: prompt,
imageUrls: attachmentImageUrls,
projectId: payload.projectId,
folderId,
agentsInstruction: instruction,
sessionId,
userId: payload.agent?.userId,
userCommentId,
userCommentId: userCommentId || undefined,
explicitMention: payload.agent?.explicitMention,
context,
attachedAssets,
})
if (isNewChat) {
await executeActivity(agentWorkerQueue, generateSessionNameActivity, {
teamId,
agentId,
prompt,
sessionId,
context,
}).catch((err) => {
console.error('Failed to run generateSessionNameActivity:', err)
})
}
// 7. Update Placeholder Comment
if (placeholderCommentId) {
if (aiResult.text.trim() === '__NO_REPLY__') {
@@ -175,10 +242,25 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
// Update placeholder comment with error message
if (placeholderCommentId && agentWorkerQueue) {
try {
const errorMessage =
err instanceof Error && err.message.startsWith('AI error:')
? `AI error: ${err.message.substring(9)}`
: 'Sorry, I encountered an error while processing your request.'
let errorMessage = 'Sorry, I encountered an error while processing your request.'
if (err instanceof Error) {
if (err.message.startsWith('AI error:')) {
errorMessage = `AI error: ${err.message.substring(9)}`
} else if (
err.message.includes('aborted') ||
err.message.includes('abort') ||
err.name === 'AbortError' ||
err.message.includes('cancel')
) {
errorMessage = 'Agent execution stopped.'
}
} else if (
String(err).includes('aborted') ||
String(err).includes('abort') ||
String(err).includes('cancel')
) {
errorMessage = 'Agent execution stopped.'
}
await executeActivity(agentWorkerQueue, updateCommentActivity, {
commentId: placeholderCommentId,
@@ -29,8 +29,11 @@ describe('Agent Embedding Workflow', () => {
getEmbeddingContextActivity: Object.assign(vi.fn(), {
_activityName: 'getEmbeddingContextActivity',
}),
generateEmbeddingActivity: Object.assign(vi.fn(), {
_activityName: 'generateEmbeddingActivity',
generateImageEmbeddingActivity: Object.assign(vi.fn(), {
_activityName: 'generateImageEmbeddingActivity',
}),
generateVideoChunkEmbeddingActivity: Object.assign(vi.fn(), {
_activityName: 'generateVideoChunkEmbeddingActivity',
}),
saveAssetEmbeddingsActivity: Object.assign(vi.fn(), {
_activityName: 'saveAssetEmbeddingsActivity',
@@ -41,20 +44,58 @@ describe('Agent Embedding Workflow', () => {
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
_activityName: 'getAgentWorkerQueueActivity',
}),
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
_activityName: 'getTranscodeWorkerQueueActivity',
}),
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
_activityName: 'downloadMediaToTmpActivity',
}),
cleanupTmpDirActivity: Object.assign(vi.fn(), {
_activityName: 'cleanupTmpDirActivity',
}),
transcodeVideoChunkActivity: Object.assign(vi.fn(), {
_activityName: 'transcodeVideoChunkActivity',
}),
deleteS3ObjectActivity: Object.assign(vi.fn(), {
_activityName: 'deleteS3ObjectActivity',
}),
}
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_queue')
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: { id: 'a1' },
dbProvider: { name: 'google' },
asset: {
id: 'a1',
mediaType: 'image/png',
storageKey: { key: 'test.png' },
},
chunkDuration: 60.0,
chunkOverlap: 5.0,
})
mockActivities.generateEmbeddingActivity.mockResolvedValue({
embeddings: [{ embedding: [0.1, 0.2] }],
mockActivities.generateImageEmbeddingActivity.mockResolvedValue({
embedding: [0.1, 0.2],
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
})
mockActivities.generateVideoChunkEmbeddingActivity.mockResolvedValue({
embedding: [0.3, 0.4],
usage: { inputTokens: 3, outputTokens: 3, model: 'gpt' },
})
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
filePath: '/tmp/test.mp4',
tmpDir: '/tmp/test-dir',
})
mockActivities.transcodeVideoChunkActivity.mockImplementation(
async (params: { assetId: string; startTime: number; endTime: number }) => {
return {
chunkKey: `files/${params.assetId}/tmp-embedding-chunks/chunk-${params.startTime}-${params.endTime}.mp4`,
}
},
)
mockActivities.deleteS3ObjectActivity.mockResolvedValue(undefined)
mockActivities.cleanupTmpDirActivity.mockResolvedValue(undefined)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
@@ -64,7 +105,7 @@ describe('Agent Embedding Workflow', () => {
})
})
it('should run agent embedding workflow successfully', async () => {
it('should run agent embedding workflow successfully for image', async () => {
const task = await prisma.workflowTask.create({
data: {
type: 'ai_embedding',
@@ -103,15 +144,11 @@ describe('Agent Embedding Workflow', () => {
assetId: 'a1',
})
// Verify embedding generation
expect(mockActivities.generateEmbeddingActivity).toHaveBeenCalledWith({
// Verify image embedding generation
expect(mockActivities.generateImageEmbeddingActivity).toHaveBeenCalledWith({
teamId: 't1',
assetId: 'a1',
context: {
agent: { id: 'b1' },
asset: { id: 'a1' },
dbProvider: { name: 'google' },
},
assetKey: 'test.png',
mediaType: 'image/png',
})
// Verify embeddings saved
@@ -125,7 +162,7 @@ describe('Agent Embedding Workflow', () => {
taskId: task.id,
inputTokens: 5,
outputTokens: 5,
model: 'gpt',
model: 'gemini-embedding-2',
})
// Verify placeholder comment updated
@@ -141,6 +178,142 @@ describe('Agent Embedding Workflow', () => {
})
})
it('should run agent embedding workflow successfully for image with transcoded format', async () => {
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: {
id: 'a1',
mediaType: 'image/png',
storageKey: { key: 'test.png' },
media: {
imageTranscodes: [{ key: 'test-transcoded.webp', isRaw: false, format: 'webp' }],
},
},
chunkDuration: 60.0,
chunkOverlap: 5.0,
})
const task = await prisma.workflowTask.create({
data: {
type: 'ai_embedding',
status: 'pending',
assetId: 'a1',
teamId: 't1',
},
})
await agentEmbeddingMedia(task)
expect(mockActivities.generateImageEmbeddingActivity).toHaveBeenCalledWith({
teamId: 't1',
assetKey: 'test-transcoded.webp',
mediaType: 'image/webp',
})
})
it('should run agent embedding workflow successfully for video in chunks', async () => {
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: {
id: 'a1',
mediaType: 'video/mp4',
storageKey: { key: 'test.mp4' },
media: {
duration: 150.0,
videoTranscodes: [{ key: 'test-transcoded.mp4', isRaw: false }],
},
},
chunkDuration: 60.0,
chunkOverlap: 5.0,
})
const task = await prisma.workflowTask.create({
data: {
type: 'ai_embedding',
status: 'pending',
assetId: 'a1',
teamId: 't1',
payload: {
projectId: 'p1',
agent: { sessionId: 's1', agentId: 'agent-1' },
},
},
})
await agentEmbeddingMedia(task)
// Verify video transcode queue discovery & download
expect(mockActivities.getTranscodeWorkerQueueActivity).toHaveBeenCalled()
expect(mockActivities.downloadMediaToTmpActivity).toHaveBeenCalledWith({
assetKey: 'test-transcoded.mp4',
})
// Verify video chunk slicing activity called 3 times on transcode queue
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(3)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(1, {
assetId: 'a1',
filePath: '/tmp/test.mp4',
startTime: 0,
endTime: 60,
})
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(2, {
assetId: 'a1',
filePath: '/tmp/test.mp4',
startTime: 55,
endTime: 115,
})
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(3, {
assetId: 'a1',
filePath: '/tmp/test.mp4',
startTime: 110,
endTime: 150,
})
// Verify video chunk embedding generation (3 chunks) on agent queue
expect(mockActivities.generateVideoChunkEmbeddingActivity).toHaveBeenCalledTimes(3)
expect(mockActivities.generateVideoChunkEmbeddingActivity).toHaveBeenNthCalledWith(1, {
teamId: 't1',
chunkKey: 'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
})
expect(mockActivities.generateVideoChunkEmbeddingActivity).toHaveBeenNthCalledWith(2, {
teamId: 't1',
chunkKey: 'files/a1/tmp-embedding-chunks/chunk-55-115.mp4',
})
expect(mockActivities.generateVideoChunkEmbeddingActivity).toHaveBeenNthCalledWith(3, {
teamId: 't1',
chunkKey: 'files/a1/tmp-embedding-chunks/chunk-110-150.mp4',
})
// Verify deletion of temporary chunks from S3
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenCalledTimes(3)
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenNthCalledWith(1, {
key: 'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
})
// Verify temp directory cleanup on transcode queue
expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({
tmpDir: '/tmp/test-dir',
})
// Verify usage update (3 chunks * 3 tokens = 9)
expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({
taskId: task.id,
inputTokens: 9,
outputTokens: 9,
model: 'gemini-embedding-2',
})
// Verify embeddings saved
expect(mockActivities.saveAssetEmbeddingsActivity).toHaveBeenCalledWith({
assetId: 'a1',
embeddings: [
{ embedding: [0.3, 0.4], startTime: 0, endTime: 60 },
{ embedding: [0.3, 0.4], startTime: 55, endTime: 115 },
{ embedding: [0.3, 0.4], startTime: 110, endTime: 150 },
],
})
})
it('should throw if task has no teamId', async () => {
const task = await prisma.workflowTask.create({
data: {
@@ -160,10 +333,19 @@ describe('Agent Embedding Workflow', () => {
})
})
it('should skip saving embeddings if none are returned', async () => {
mockActivities.generateEmbeddingActivity.mockResolvedValue({
embeddings: [],
usage: null,
it('should skip saving embeddings if none are returned (video duration 0)', async () => {
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: {
id: 'a1',
mediaType: 'video/mp4',
storageKey: { key: 'test.mp4' },
media: {
duration: 0.0,
},
},
chunkDuration: 60.0,
chunkOverlap: 5.0,
})
const task = await prisma.workflowTask.create({
@@ -178,7 +360,6 @@ describe('Agent Embedding Workflow', () => {
await agentEmbeddingMedia(task)
expect(mockActivities.saveAssetEmbeddingsActivity).not.toHaveBeenCalled()
expect(mockActivities.updateTaskUsageActivity).not.toHaveBeenCalled()
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: task.id,
status: 'completed',
@@ -186,7 +367,9 @@ describe('Agent Embedding Workflow', () => {
})
it('should handle failures, update placeholder with error, and set status to failed', async () => {
mockActivities.generateEmbeddingActivity.mockRejectedValue(new Error('AI Service Unavailable'))
mockActivities.generateImageEmbeddingActivity.mockRejectedValue(
new Error('AI Service Unavailable'),
)
const task = await prisma.workflowTask.create({
data: {
@@ -212,4 +395,40 @@ describe('Agent Embedding Workflow', () => {
output: { error: 'AI Service Unavailable' },
})
})
it('should not create redundant chunks when video exactly matches chunk duration', async () => {
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: {
id: 'a1',
mediaType: 'video/mp4',
storageKey: { key: 'test.mp4' },
media: {
duration: 60.0,
},
},
chunkDuration: 60.0,
chunkOverlap: 5.0,
})
const task = await prisma.workflowTask.create({
data: {
type: 'ai_embedding',
status: 'pending',
assetId: 'a1',
teamId: 't1',
},
})
await agentEmbeddingMedia(task)
// Verify only 1 chunk was created instead of 2 (0-60 and 55-60)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(1)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledWith(
expect.objectContaining({
startTime: 0,
endTime: 60,
}),
)
})
})
+173 -19
View File
@@ -1,25 +1,48 @@
import { ApplicationFailure } from '@temporalio/workflow'
import type { WorkflowTask } from '@shumai/db'
import { getActivities, executeActivity, TaskQueueAgent } from '@shumai/workflow-core'
import {
getActivities,
executeActivity,
TaskQueueAgent,
TaskQueueTranscode,
} from '@shumai/workflow-core'
export interface GeneratedEmbedding {
embedding: number[]
startTime?: number
endTime?: number
}
export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
const {
updateTaskStatusActivity,
getEmbeddingContextActivity,
generateEmbeddingActivity,
generateImageEmbeddingActivity,
generateVideoChunkEmbeddingActivity,
saveAssetEmbeddingsActivity,
updateTaskUsageActivity,
createCommentActivity,
updateCommentActivity,
getAgentWorkerQueueActivity,
getTranscodeWorkerQueueActivity,
downloadMediaToTmpActivity,
cleanupTmpDirActivity,
transcodeVideoChunkActivity,
deleteS3ObjectActivity,
} = getActivities()
let placeholderCommentId: string | undefined
let agentWorkerQueue = ''
let transcodeWorkerQueue = ''
let tmpDir: string | undefined
try {
// 0. Discover queue
// 0. Discover queues
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
transcodeWorkerQueue = await executeActivity(
TaskQueueTranscode,
getTranscodeWorkerQueueActivity,
)
// Update status to processing
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
@@ -47,30 +70,153 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
assetId: task.assetId,
})
// Call the activity to generate embeddings
const result = await executeActivity(agentWorkerQueue, generateEmbeddingActivity, {
teamId: task.teamId,
assetId: task.assetId,
context,
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { asset, chunkDuration, chunkOverlap } = context as any
const isImage = asset.mediaType?.startsWith('image/')
const isVideo = asset.mediaType?.startsWith('video/')
if (!isImage && !isVideo) {
throw ApplicationFailure.create({
message: `unsupported media type for embeddings: ${asset.mediaType}`,
nonRetryable: true,
})
}
// Resolve the S3 key to use for embedding (preferring transcoded version)
let embeddingKey = asset.storageKey?.key
let embeddingMediaType = asset.mediaType
if (asset.media) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const media = asset.media as any
if (isVideo) {
if (media.videoTranscodes && media.videoTranscodes.length > 0) {
// Find first non-raw transcode or fallback to first transcode
const transcode =
media.videoTranscodes.find((t: PrismaJson.VideoTranscode) => !t.isRaw) ||
media.videoTranscodes[0]
if (transcode?.key) {
embeddingKey = transcode.key
}
}
} else if (isImage) {
if (media.imageTranscodes && media.imageTranscodes.length > 0) {
// Find first non-raw transcode or fallback to first transcode
const transcode =
media.imageTranscodes.find((t: PrismaJson.ImageTranscode) => !t.isRaw) ||
media.imageTranscodes[0]
if (transcode?.key) {
embeddingKey = transcode.key
if (transcode.format) {
embeddingMediaType = `image/${transcode.format}`
}
}
}
}
}
if (!embeddingKey) {
throw ApplicationFailure.create({ message: 'asset has no key', nonRetryable: true })
}
const results: GeneratedEmbedding[] = []
const usage = {
model: 'gemini-embedding-2',
inputTokens: 0,
outputTokens: 0,
}
if (isImage) {
const result = await executeActivity(agentWorkerQueue, generateImageEmbeddingActivity, {
teamId: task.teamId,
assetKey: embeddingKey,
mediaType: embeddingMediaType,
})
results.push({ embedding: result.embedding })
if (result.usage) {
usage.inputTokens += result.usage.inputTokens || 0
usage.outputTokens += result.usage.outputTokens || 0
}
} else if (isVideo) {
// 1. Download full video to transcode worker temp space
const download = await executeActivity(transcodeWorkerQueue, downloadMediaToTmpActivity, {
assetKey: embeddingKey,
})
const { filePath } = download
tmpDir = download.tmpDir
// Get video duration
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const duration = (asset.media as any)?.duration || 0
const limit = chunkDuration || 60.0
const overlap = chunkOverlap ?? 5.0
const step = Math.max(1, limit - overlap)
for (let start = 0.0; start < duration; start += step) {
let end = start + limit
if (end >= duration) {
end = duration
}
// Step A: Slice chunk on transcode worker and upload to S3
const chunkRes = await executeActivity(transcodeWorkerQueue, transcodeVideoChunkActivity, {
assetId: asset.id,
filePath,
startTime: start,
endTime: end,
})
const { chunkKey } = chunkRes
try {
// Step B: Generate embedding on agent worker
const chunkResult = await executeActivity(
agentWorkerQueue,
generateVideoChunkEmbeddingActivity,
{
teamId: task.teamId,
chunkKey,
},
)
results.push({
embedding: chunkResult.embedding,
startTime: start,
endTime: end,
})
if (chunkResult.usage) {
usage.inputTokens += chunkResult.usage.inputTokens || 0
usage.outputTokens += chunkResult.usage.outputTokens || 0
}
} finally {
// Step C: Delete temporary chunk from S3
await executeActivity(transcodeWorkerQueue, deleteS3ObjectActivity, {
key: chunkKey,
})
}
// If this chunk reached the end of the video, stop to avoid redundant overlapping chunks
if (end >= duration) {
break
}
}
}
// Save computed embeddings
if (result.embeddings.length > 0) {
if (results.length > 0) {
await executeActivity(agentWorkerQueue, saveAssetEmbeddingsActivity, {
assetId: task.assetId,
embeddings: result.embeddings,
embeddings: results,
})
}
// Update Usage
if (result.usage) {
await executeActivity(agentWorkerQueue, updateTaskUsageActivity, {
taskId: task.id,
inputTokens: result.usage.inputTokens,
outputTokens: result.usage.outputTokens,
model: result.usage.model,
})
}
await executeActivity(agentWorkerQueue, updateTaskUsageActivity, {
taskId: task.id,
inputTokens: usage.inputTokens,
outputTokens: usage.outputTokens,
model: usage.model,
})
// 7. Update Placeholder Comment
if (placeholderCommentId) {
@@ -109,6 +255,14 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
})
}
throw err
} finally {
if (tmpDir && transcodeWorkerQueue) {
try {
await executeActivity(transcodeWorkerQueue, cleanupTmpDirActivity, { tmpDir })
} catch (cleanupErr) {
console.error('Failed to cleanup transcode worker tmp dir:', cleanupErr)
}
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/api",
"version": "0.0.2",
"version": "0.1.10",
"private": true,
"type": "module",
"main": "./src/index.ts",
@@ -27,6 +27,7 @@ describe('Agent API', () => {
model: 'model1',
thinkingLevel: 'high',
systemPrompt: 'prompt',
deniedTools: ['bash'],
},
skills: [],
},
@@ -43,6 +44,7 @@ describe('Agent API', () => {
expect(data).toHaveLength(1)
expect(data[0].name).toBe('Bot 1')
expect(data[0].providerId).toBe('prov1')
expect(data[0].deniedTools).toEqual(['bash'])
})
})
@@ -55,7 +57,13 @@ describe('Agent API', () => {
providerId: 'prov1',
modelId: 'model1',
soul: 'New Soul',
config: { provider: 'prov1', model: 'model1', thinkingLevel: 'low', systemPrompt: 'p' },
config: {
provider: 'prov1',
model: 'model1',
thinkingLevel: 'low',
systemPrompt: 'p',
deniedTools: ['bash'],
},
skills: [],
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -73,6 +81,7 @@ describe('Agent API', () => {
systemPrompt: 'p',
soul: 'New Soul',
skills: ['skill1'],
deniedTools: ['bash'],
}),
})
@@ -80,6 +89,7 @@ describe('Agent API', () => {
const data = await res.json()
expect(data.name).toBe('New Agent')
expect(data.soul).toBe('New Soul')
expect(data.deniedTools).toEqual(['bash'])
})
it('validates request', async () => {
@@ -105,7 +115,7 @@ describe('Agent API', () => {
providerId: 'prov1',
modelId: 'model1',
soul: 'Updated Soul',
config: { provider: 'prov1', model: 'model1' },
config: { provider: 'prov1', model: 'model1', deniedTools: ['bash'] },
skills: [],
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -121,6 +131,7 @@ describe('Agent API', () => {
modelId: 'model1',
soul: 'Updated Soul',
skills: [],
deniedTools: ['bash'],
}),
})
@@ -128,6 +139,7 @@ describe('Agent API', () => {
const data = await res.json()
expect(data.name).toBe('Updated Agent')
expect(data.soul).toBe('Updated Soul')
expect(data.deniedTools).toEqual(['bash'])
})
})

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