mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-20 17:09:03 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2b0415580 | ||
|
|
c9d0b476cd | ||
|
|
bf5ac566b6 | ||
|
|
af8f24aa95 | ||
|
|
d98f486c9d | ||
|
|
94ea4c917a | ||
|
|
941bf0fd1b | ||
|
|
59742dde78 | ||
|
|
29cd5d807c | ||
|
|
f6e27095a5 | ||
|
|
55637bc9a8 | ||
|
|
0d6671c3e1 | ||
|
|
c3375ee935 | ||
|
|
f579947770 | ||
|
|
53c9485f10 | ||
|
|
75bf9b3b88 | ||
|
|
657cd761bc | ||
|
|
de634a5dc5 | ||
|
|
09b65a1eb6 | ||
|
|
b52b2ce7d8 | ||
|
|
145aa6bfb4 | ||
|
|
a91d8c4521 | ||
|
|
3a509537fd |
@@ -68,18 +68,42 @@ jobs:
|
||||
- name: Build NPM packages
|
||||
run: bun run build-npm
|
||||
|
||||
- name: Generate release notes
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
CHANGELOG_NOTES=$(bun run scripts/extract-changelog.ts "${{ env.RELEASE_TAG }}" 2>/dev/null || true)
|
||||
PR_NOTES=$(gh api "repos/${{ github.repository }}/releases/generate-notes" -f tag_name="${{ env.RELEASE_TAG }}" --jq .body 2>/dev/null || true)
|
||||
|
||||
{
|
||||
if [ -n "$CHANGELOG_NOTES" ]; then
|
||||
echo "$CHANGELOG_NOTES"
|
||||
echo ""
|
||||
echo "---"
|
||||
echo ""
|
||||
fi
|
||||
if [ -n "$PR_NOTES" ]; then
|
||||
echo "$PR_NOTES"
|
||||
fi
|
||||
} > /tmp/release-notes.md
|
||||
|
||||
- name: Create GitHub Release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
if [ ! -s /tmp/release-notes.md ]; then
|
||||
NOTES_FLAG="--generate-notes"
|
||||
else
|
||||
NOTES_FLAG="--notes-file /tmp/release-notes.md"
|
||||
fi
|
||||
if gh release view "${{ env.RELEASE_TAG }}" >/dev/null 2>&1; then
|
||||
gh release edit "${{ env.RELEASE_TAG }}" \
|
||||
--title "${{ env.RELEASE_TAG }}" \
|
||||
--generate-notes
|
||||
$NOTES_FLAG
|
||||
else
|
||||
gh release create "${{ env.RELEASE_TAG }}" \
|
||||
--title "${{ env.RELEASE_TAG }}" \
|
||||
--generate-notes
|
||||
$NOTES_FLAG
|
||||
fi
|
||||
|
||||
- name: Upgrade npm for trusted publishing
|
||||
|
||||
@@ -4,6 +4,12 @@ on:
|
||||
push:
|
||||
branches: ['main']
|
||||
tags: ['v*']
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Docker image tag (e.g. feature-vaapi)'
|
||||
required: false
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
@@ -46,6 +52,7 @@ jobs:
|
||||
tags: |
|
||||
type=semver,pattern={{version}}
|
||||
type=ref,event=branch
|
||||
type=raw,value=${{ inputs.tag }},enable=${{ github.event_name == 'workflow_dispatch' && inputs.tag != '' }}
|
||||
|
||||
# Build and push Docker image
|
||||
- name: Build and push Docker image
|
||||
|
||||
+2
-1
@@ -7,4 +7,5 @@ packages/core/src/generated
|
||||
src/ui/components/ui
|
||||
packages/webui/paraglide
|
||||
*.md
|
||||
**/*.md
|
||||
**/*.md
|
||||
docs/changelog.mdx
|
||||
|
||||
@@ -14,9 +14,10 @@ Complete the task on that branch.
|
||||
|
||||
After finishing the work and verifying that all checks pass:
|
||||
|
||||
1. Stage and commit your changes.
|
||||
2. Push the branch to `origin`.
|
||||
3. Open a pull request using the GitHub CLI.
|
||||
1. Update `CHANGELOG.md` under `## [Unreleased]` for user-facing changes (see [Changelog Guidelines](#changelog-guidelines)).
|
||||
2. Stage and commit your changes.
|
||||
3. Push the branch to `origin`.
|
||||
4. Open a pull request using the GitHub CLI.
|
||||
|
||||
```bash
|
||||
git add .
|
||||
@@ -61,6 +62,19 @@ https://www.conventionalcommits.org/en/v1.0.0/#summary
|
||||
|
||||
---
|
||||
|
||||
## Changelog Guidelines
|
||||
|
||||
We maintain `CHANGELOG.md` following [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
Before opening a pull request, add an entry under `## [Unreleased]` for any user-facing changes:
|
||||
|
||||
- **End-User Friendly**: Make entries easy to understand for end users. For new features, explain what they actually do in plain language without heavy technical jargon. For bug fixes, describe what the bug was in a friendly, relatable way rather than focusing on internal code mechanics, file paths, or private symbols.
|
||||
- **Formatting**: `- **<scope>**: <Description>` (e.g. `- **asset**: Fix an issue where moving a video to trash while it was still transcoding could cause it to lose its trashed status`).
|
||||
- **No PR Numbers**: Do not include PR numbers or links; the release pipeline automatically appends the detailed PR list.
|
||||
- **Internal Changes**: Routine refactors, test additions, or internal chores without external behavior changes may omit changelog updates.
|
||||
|
||||
---
|
||||
|
||||
## Pull Request Template
|
||||
|
||||
```md
|
||||
|
||||
+749
@@ -0,0 +1,749 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
### Fixed
|
||||
|
||||
### Changed
|
||||
|
||||
## [0.4.9] - 2026-09-28
|
||||
|
||||
### Added
|
||||
|
||||
- **notification**: You can now receive notifications via email, with batched digest emails and configurable team-level SMTP settings
|
||||
- **transcode**: Add VA-API hardware acceleration support for Linux hosts and Docker environments with Intel and AMD GPUs, featuring automatic DRI render node discovery, variable bitrate control, and structured transcoding observability logs
|
||||
- **transcode**: Add automatic fallback to software transcoding (libx264) when hardware-accelerated video encoding encounters GPU resolution constraints or runtime driver errors
|
||||
- **docker**: Add modular hardware-accelerated transcoding presets matching Immich's compose configuration via `hwaccel.transcoding.yaml` with support for NVENC, QuickSync, RKMPP, and VA-API
|
||||
|
||||
### Fixed
|
||||
|
||||
### Changed
|
||||
|
||||
- **transcode**: Improve video poster selection using intelligent scene detection and color variance filtering to automatically skip black frames, fade-ins, and blank intros in favor of representative video content
|
||||
- **transcode**: Optimize video sprite generation for large and long videos using a concurrent fast-seek pool and image compositing, avoiding full-video decoding while preserving instant single-pass generation for short clips
|
||||
|
||||
## [0.4.8] - 2026-09-24
|
||||
|
||||
### Added
|
||||
|
||||
- **transcode**: Add HDR video proxy support: HDR videos automatically generate HDR video proxies and preview videos preserving HDR color characteristics, tone-mapped SDR thumbnails and posters, and automatic HDR player playback on supported displays with hardware EDR acceleration
|
||||
- **docs**: Add a Changelog section to the documentation site so users can explore release notes and updates directly in Mintlify
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Only show the center play button and darkened tint on initial video open before playback starts; once played, pausing or scrubbing back to start keeps the video canvas clean and unobstructed for review
|
||||
- **transcode**: Fix an issue where videos with orientation or rotation metadata (such as smartphone vertical videos) were incorrectly displayed with stretched aspect ratios in the video player
|
||||
- **cli**: Only manage and check PID files in daemon mode, preventing stale PID files, crash-loop conflicts, or spurious process checks during normal foreground and Docker execution
|
||||
|
||||
### Changed
|
||||
|
||||
- **transcode**: Improve video proxy visual quality and disable B-frames for smoother frame-by-frame seeking and scrubbing
|
||||
|
||||
|
||||
## [0.4.7] - 2026-09-19
|
||||
|
||||
### Added
|
||||
|
||||
- **changelog**: Introduce Keep a Changelog support, historical release summaries, and automated release notes extraction
|
||||
- **release**: Automatically populate GitHub release bodies from CHANGELOG.md and promote unreleased notes during version bumps
|
||||
- **settings**: Add FFmpeg threads slider to team media processing settings
|
||||
- **asset**: Show previews of a folder's contents and a "days left" countdown for each item in Recently Deleted
|
||||
- **asset**: Show the poster and hover preview for a video in the file list while it is still transcoding, with a gently pulsing cover (or an animated waiting circle before the poster is ready), "Uploading..."/"Preparing..." labels, and the duration hidden until it is ready
|
||||
|
||||
### Fixed
|
||||
|
||||
- **asset**: Fix an issue where moving a video to trash while it was still transcoding could cause it to lose its trashed status
|
||||
- **transcode**: Immediately stop background video processing and transcoding when a file is permanently deleted from the trash
|
||||
- **asset**: Fix proxy download filename using original file extension instead of proxy extension
|
||||
- **asset**: Fix an issue where deleting or restoring a version stack from the file list did nothing
|
||||
- **webui**: Center breadcrumb file action popup menu on the chevron icon
|
||||
|
||||
## [0.4.6] - 2026-09-17
|
||||
|
||||
### Added
|
||||
|
||||
- **comment**: Add emoji reaction support for comments ([#405](https://github.com/shumaiOne/shumai/pull/405))
|
||||
- **premiere-uxp**: Introduce Adobe Premiere Pro UXP plugin for Shumai ([#407](https://github.com/shumaiOne/shumai/pull/407))
|
||||
- **settings**: Add team appearance setting to hide agent features ([#411](https://github.com/shumaiOne/shumai/pull/411))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **premiere-uxp**: Preserve remote cloud storage presigned URLs in asset resolution ([#408](https://github.com/shumaiOne/shumai/pull/408))
|
||||
- **premiere-uxp**: Scope sequence links by server endpoint and surface sync errors ([#409](https://github.com/shumaiOne/shumai/pull/409))
|
||||
- **api**: Enforce SHUMAI_DEMO_MODE for API token and CLI requests ([#413](https://github.com/shumaiOne/shumai/pull/413))
|
||||
|
||||
### Documentation
|
||||
|
||||
- Add NLE export and Premiere Pro UXP plugin documentation ([#412](https://github.com/shumaiOne/shumai/pull/412))
|
||||
|
||||
## [0.4.5] - 2026-09-13
|
||||
|
||||
### Added
|
||||
|
||||
- **core**: Export comments to FCP, Premiere, Media Composer, and Resolve ([#400](https://github.com/shumaiOne/shumai/pull/400))
|
||||
- **webui**: Add NLE comments export and migrate export API to POST ([#401](https://github.com/shumaiOne/shumai/pull/401))
|
||||
- **webui**: Add space key quick preview for files and folders ([#402](https://github.com/shumaiOne/shumai/pull/402))
|
||||
- **webui**: Show comments count badge in file card preview area ([#403](https://github.com/shumaiOne/shumai/pull/403))
|
||||
- **agent**: Use deterministic storage keys for preset avatars ([#404](https://github.com/shumaiOne/shumai/pull/404))
|
||||
|
||||
## [0.4.4] - 2026-09-09
|
||||
|
||||
### Added
|
||||
|
||||
- **upload**: S3 multipart upload with offline resume and wake lock ([#391](https://github.com/shumaiOne/shumai/pull/391))
|
||||
- **transcode**: Optimize video operations using ffmpeg http range requests ([#393](https://github.com/shumaiOne/shumai/pull/393))
|
||||
- **agent**: Enable read_asset tool for autofill agent ([#396](https://github.com/shumaiOne/shumai/pull/396))
|
||||
- **sandbox**: Abstract SandboxService and hot-reload allowed domains ([#398](https://github.com/shumaiOne/shumai/pull/398))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **s3**: Stream downloadToFile and putObject to prevent OOM on large files ([#392](https://github.com/shumaiOne/shumai/pull/392))
|
||||
- **agent**: Pass agent thinkingLevel to session name generation ([#395](https://github.com/shumaiOne/shumai/pull/395))
|
||||
- **agent**: Restrict pageCount and duration recommendations to matching media types ([#397](https://github.com/shumaiOne/shumai/pull/397))
|
||||
- **transcode**: Co-locate screenshots and derived artifacts in asset storage directory ([#399](https://github.com/shumaiOne/shumai/pull/399))
|
||||
|
||||
## [0.4.3] - 2026-09-06
|
||||
|
||||
### Added
|
||||
|
||||
- **asset**: Record and display agent provenance on assets and audit logs ([#380](https://github.com/shumaiOne/shumai/pull/380))
|
||||
- **agent**: Store preset avatars as real files in s3 storage ([#381](https://github.com/shumaiOne/shumai/pull/381))
|
||||
- **agent**: Add built-in image and video generation tools and settings ([#382](https://github.com/shumaiOne/shumai/pull/382))
|
||||
- **media-generation**: Add gemini-omni-1.1-flash video model and redesign settings UI ([#383](https://github.com/shumaiOne/shumai/pull/383))
|
||||
- **settings**: Redesign image/video settings to provider dialog with model toggles ([#385](https://github.com/shumaiOne/shumai/pull/385))
|
||||
- **agent**: Add asset management tools and CLI commands ([#387](https://github.com/shumaiOne/shumai/pull/387))
|
||||
- **cli**: Control asset deletion via SHUMAI_ALLOW_DELETE env var ([#388](https://github.com/shumaiOne/shumai/pull/388))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Clamp file card creation info to 2 lines and show tooltip on hover ([#390](https://github.com/shumaiOne/shumai/pull/390))
|
||||
|
||||
### Documentation
|
||||
|
||||
- **agents**: Add documentation for image and video generation settings ([#389](https://github.com/shumaiOne/shumai/pull/389))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **deps**: Upgrade bun to 1.4.2 and update packages ([#384](https://github.com/shumaiOne/shumai/pull/384))
|
||||
- **i18n**: Update paraglide-js to 2.25.0 and stop checking in generated code ([#386](https://github.com/shumaiOne/shumai/pull/386))
|
||||
|
||||
## [0.4.2] - 2026-09-03
|
||||
|
||||
### Added
|
||||
|
||||
- **chat**: Support markups, attachments, and timestamps in agent 1-to-1 chat ([#368](https://github.com/shumaiOne/shumai/pull/368))
|
||||
- **agent**: Move thread metadata to structured context XML ([#373](https://github.com/shumaiOne/shumai/pull/373))
|
||||
- **agent**: Improve timestamp precision and proxy selection for video screenshots ([#374](https://github.com/shumaiOne/shumai/pull/374))
|
||||
- **agent**: Support dynamic annotationId resolution across chat and comments ([#375](https://github.com/shumaiOne/shumai/pull/375))
|
||||
- **agent**: Consolidate media tools into read_asset and add S3 key support to download_asset ([#376](https://github.com/shumaiOne/shumai/pull/376))
|
||||
- **provider**: Optimize provider and model configuration management ([#377](https://github.com/shumaiOne/shumai/pull/377))
|
||||
- **provider**: Add provider and model sync feature with vendored generator ([#378](https://github.com/shumaiOne/shumai/pull/378))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **agent**: Set empty details in asset tool results to avoid data duplication ([#370](https://github.com/shumaiOne/shumai/pull/370))
|
||||
- **webui**: Strip styles and preserve multiline text on paste in chat input ([#371](https://github.com/shumaiOne/shumai/pull/371))
|
||||
- **agent**: Hide main comment sessions in dashboard sessions list ([#372](https://github.com/shumaiOne/shumai/pull/372))
|
||||
|
||||
### Changed
|
||||
|
||||
- **webui**: Use semantic system colors in notification settings ([#379](https://github.com/shumaiOne/shumai/pull/379))
|
||||
|
||||
## [0.4.1] - 2026-08-30
|
||||
|
||||
### Added
|
||||
|
||||
- **webui**: Add manage versions option to file card context menu ([#364](https://github.com/shumaiOne/shumai/pull/364))
|
||||
- **agent**: Refactor message context into unified shumai_message ([#365](https://github.com/shumaiOne/shumai/pull/365))
|
||||
- **webui**: Redesign comment attachment display into compact rows ([#366](https://github.com/shumaiOne/shumai/pull/366))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **asset,webui**: Disallow dropping version stacks onto files and version stacks ([#363](https://github.com/shumaiOne/shumai/pull/363))
|
||||
- **webui**: Prevent empty folder flash during initial loading ([#367](https://github.com/shumaiOne/shumai/pull/367))
|
||||
|
||||
### Changed
|
||||
|
||||
- **agent**: Remove executeAgentToolWorkflow and invoke core services directly ([#362](https://github.com/shumaiOne/shumai/pull/362))
|
||||
|
||||
## [0.4.0] - 2026-08-28
|
||||
|
||||
### Added
|
||||
|
||||
- **transcode**: Add hardware-accelerated video transcoding support ([#352](https://github.com/shumaiOne/shumai/pull/352))
|
||||
- **webui**: Truncate long file names with 100ms hover tooltip ([#355](https://github.com/shumaiOne/shumai/pull/355))
|
||||
- **webui**: Add simplified mobile-friendly layout for file and share lists ([#356](https://github.com/shumaiOne/shumai/pull/356))
|
||||
- **webui**: Add mobile friendly file detail and public share view ([#359](https://github.com/shumaiOne/shumai/pull/359))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **transcode**: Apply team hardware acceleration and source bitrate capping to watermark transcoding ([#353](https://github.com/shumaiOne/shumai/pull/353))
|
||||
- **share**: Hide and soft-delete symlinks when target assets are trashed ([#354](https://github.com/shumaiOne/shumai/pull/354))
|
||||
- **webui**: Fix breadcrumb file dropdown trigger stretching and alignment ([#360](https://github.com/shumaiOne/shumai/pull/360))
|
||||
- **webui**: Align mobile comment cards and thread vertical indicator ([#361](https://github.com/shumaiOne/shumai/pull/361))
|
||||
|
||||
### Documentation
|
||||
|
||||
- Add SECURITY.md with a private disclosure path ([#357](https://github.com/shumaiOne/shumai/pull/357))
|
||||
|
||||
## [0.3.11] - 2026-08-25
|
||||
|
||||
### Added
|
||||
|
||||
- **auth**: Add admin password reset CLI command and reset password web UI ([#347](https://github.com/shumaiOne/shumai/pull/347))
|
||||
- **project**: Add recent viewed files section to project folder tree ([#348](https://github.com/shumaiOne/shumai/pull/348))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Prevent left carousel remounting and scroll jump on file selection ([#351](https://github.com/shumaiOne/shumai/pull/351))
|
||||
|
||||
## [0.3.10] - 2026-08-23
|
||||
|
||||
### Added
|
||||
|
||||
- **agentic kanban**: Phase 1 not-agentic kanban board ([#330](https://github.com/shumaiOne/shumai/pull/330))
|
||||
- **kanban**: Resolve latest version for linked version stack assets and update demo login text ([#342](https://github.com/shumaiOne/shumai/pull/342))
|
||||
- **kanban**: Update task status permissions, reporter defaults, and participant access ([#345](https://github.com/shumaiOne/shumai/pull/345))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **kanban**: Use true thumbnail and poster for task asset previews ([#343](https://github.com/shumaiOne/shumai/pull/343))
|
||||
- **webui**: Sidebar selection styling, kanban active state, pointer cursors, and owner dashboard ([#344](https://github.com/shumaiOne/shumai/pull/344))
|
||||
- **kanban**: Improve drag-drop to column bottom, remove empty drop line, and fix timeline alignment ([#346](https://github.com/shumaiOne/shumai/pull/346))
|
||||
|
||||
## [0.3.9] - 2026-08-18
|
||||
|
||||
### Added
|
||||
|
||||
- **agent**: Add permission controls for chat agents ([#313](https://github.com/shumaiOne/shumai/pull/313))
|
||||
- **authz**: Enforce project-aware roles for agent/skill/mcp permissions ([#314](https://github.com/shumaiOne/shumai/pull/314))
|
||||
- **webui**: Use project members for asset comment mentions ([#315](https://github.com/shumaiOne/shumai/pull/315))
|
||||
- **quota**: Add 2-level database-backed resource quota system ([#318](https://github.com/shumaiOne/shumai/pull/318))
|
||||
- **settings**: Reorganize settings into personal, team, and AI sections ([#324](https://github.com/shumaiOne/shumai/pull/324))
|
||||
- **quota**: Move usage monitoring to team dashboard ([#327](https://github.com/shumaiOne/shumai/pull/327))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Preserve selected chatbot agent preference on reload ([#323](https://github.com/shumaiOne/shumai/pull/323))
|
||||
- **quota**: Exclude agents from quota rules and usage records ([#325](https://github.com/shumaiOne/shumai/pull/325))
|
||||
|
||||
### Documentation
|
||||
|
||||
- **team-settings**: Add resource quotas documentation and update readme features ([#326](https://github.com/shumaiOne/shumai/pull/326))
|
||||
|
||||
## [0.3.8] - 2026-08-15
|
||||
|
||||
### Added
|
||||
|
||||
- **webui**: Replace legacy markdown editor with new lexical wysiwyg editor ([#308](https://github.com/shumaiOne/shumai/pull/308))
|
||||
- **agent**: Add nested agents.md support across backend and webui ([#309](https://github.com/shumaiOne/shumai/pull/309))
|
||||
- **webui**: Improve AGENTS.md editor placeholder and read-only notice ([#310](https://github.com/shumaiOne/shumai/pull/310))
|
||||
- **version-stack**: Add manage versions dialog and version removal ([#311](https://github.com/shumaiOne/shumai/pull/311))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **core**: Rename latest version child record on version stack rename ([#312](https://github.com/shumaiOne/shumai/pull/312))
|
||||
|
||||
## [0.3.7] - 2026-08-14
|
||||
|
||||
### Added
|
||||
|
||||
- **metadata**: Replace aiAutofill boolean with autofillSource enum ([#302](https://github.com/shumaiOne/shumai/pull/302))
|
||||
- **agent**: Type-safe CREATION_CONTEXT metadata on create_file/create_version ([#303](https://github.com/shumaiOne/shumai/pull/303))
|
||||
- **sandbox**: Default Network Sandbox to off and add settings toggle switch ([#304](https://github.com/shumaiOne/shumai/pull/304))
|
||||
- **webui**: Redesign select metadata fields and improve long text field widget ([#305](https://github.com/shumaiOne/shumai/pull/305))
|
||||
- **agent**: Support dynamic newOption in select and selectMulti metadata fields ([#306](https://github.com/shumaiOne/shumai/pull/306))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Fix select field height and multi-select overflow/interaction issues ([#307](https://github.com/shumaiOne/shumai/pull/307))
|
||||
|
||||
## [0.3.6] - 2026-08-12
|
||||
|
||||
### Added
|
||||
|
||||
- **mcp**: Add MCP server support with proxy tool and OAuth flow ([#289](https://github.com/shumaiOne/shumai/pull/289))
|
||||
- **mcp**: Support tool-level directTools array and 3-state UI configuration ([#297](https://github.com/shumaiOne/shumai/pull/297))
|
||||
- **webui**: Direct canvas PDF rendering with selectable text ([#299](https://github.com/shumaiOne/shumai/pull/299))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **agent**: Prevent agents from accessing disabled skills ([#292](https://github.com/shumaiOne/shumai/pull/292))
|
||||
- **agent**: Resolve version stack name and size in list_assets ([#296](https://github.com/shumaiOne/shumai/pull/296))
|
||||
- **webui**: Content-only pinch-zoom and two-finger pan in media viewers ([#298](https://github.com/shumaiOne/shumai/pull/298))
|
||||
- **i18n**: Update Chinese translation for dashboard to 仪表板 ([#301](https://github.com/shumaiOne/shumai/pull/301))
|
||||
|
||||
### Documentation
|
||||
|
||||
- **mcp**: Add MCP support documentation to README and docs ([#300](https://github.com/shumaiOne/shumai/pull/300))
|
||||
|
||||
## [0.3.5] - 2026-08-09
|
||||
|
||||
### Added
|
||||
|
||||
- **transcode**: Add Gotenberg support for Office, HTML, CSV, and Markdown PDF proxies ([#283](https://github.com/shumaiOne/shumai/pull/283))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Resolve upload card freeze for unsupported files ([#284](https://github.com/shumaiOne/shumai/pull/284))
|
||||
- **webui**: Exclude file extension when selecting file name during inline rename ([#285](https://github.com/shumaiOne/shumai/pull/285))
|
||||
- Use renamed asset name in download Content-Disposition ([#286](https://github.com/shumaiOne/shumai/pull/286))
|
||||
- **webui**: Batch download no longer flashes a tab per file ([#287](https://github.com/shumaiOne/shumai/pull/287))
|
||||
- **webui**: Enable rename and delete actions in file detail top bar breadcrumb ([#288](https://github.com/shumaiOne/shumai/pull/288))
|
||||
|
||||
## [0.3.4] - 2026-08-08
|
||||
|
||||
### Added
|
||||
|
||||
- **sharelink**: Add sharelink watermark support ([#270](https://github.com/shumaiOne/shumai/pull/270))
|
||||
- **webui**: Remove original-file display fallbacks, use proxies only ([#273](https://github.com/shumaiOne/shumai/pull/273))
|
||||
- **share**: Add allow download config to share links ([#275](https://github.com/shumaiOne/shumai/pull/275))
|
||||
- **transcode**: Update preview thumbnail resolution to 300p with max length constraint ([#281](https://github.com/shumaiOne/shumai/pull/281))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **share**: Resolve symlink asset downloads in public share pages ([#274](https://github.com/shumaiOne/shumai/pull/274))
|
||||
- **webui**: Persist project sorting and prevent full page flash ([#276](https://github.com/shumaiOne/shumai/pull/276))
|
||||
|
||||
### Documentation
|
||||
|
||||
- **share-links**: Document allow download and lazy watermark settings ([#278](https://github.com/shumaiOne/shumai/pull/278))
|
||||
- **agent**: Clarify create_file/create_version context param guidance ([#282](https://github.com/shumaiOne/shumai/pull/282))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **e2e**: Watermarked download-disabled share link coverage (image + video) ([#277](https://github.com/shumaiOne/shumai/pull/277))
|
||||
- **e2e**: Stabilize watermark share spec on Firefox ([#279](https://github.com/shumaiOne/shumai/pull/279))
|
||||
- Split e2e scripts into app and webui targets ([#280](https://github.com/shumaiOne/shumai/pull/280))
|
||||
|
||||
## [0.3.3] - 2026-08-05
|
||||
|
||||
### Added
|
||||
|
||||
- **agent**: Enable LLM API call retries in AgentHarness ([#250](https://github.com/shumaiOne/shumai/pull/250))
|
||||
- **audit**: Add audit log support for APIs and WebUI dashboard ([#251](https://github.com/shumaiOne/shumai/pull/251))
|
||||
- **webui**: Persist agent preference in localStorage ([#254](https://github.com/shumaiOne/shumai/pull/254))
|
||||
- **e2e**: Add file domain comment and draw tests ([#260](https://github.com/shumaiOne/shumai/pull/260))
|
||||
- **agent**: Restrict bash access for non-owner users ([#262](https://github.com/shumaiOne/shumai/pull/262))
|
||||
- **agent**: Allow create_file tool to create files directly from content ([#263](https://github.com/shumaiOne/shumai/pull/263))
|
||||
- **agent**: Propagate autofill context from chat to autofill workflow ([#264](https://github.com/shumaiOne/shumai/pull/264))
|
||||
- **webui**: Render select options in field creation mode and pick random option color ([#265](https://github.com/shumaiOne/shumai/pull/265))
|
||||
- **project**: Include team-scoped members in project member list and add 3-section dialog layout ([#267](https://github.com/shumaiOne/shumai/pull/267))
|
||||
- **webui**: Disable role dropdown for project-scoped members in team view ([#269](https://github.com/shumaiOne/shumai/pull/269))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Mention popup avatars, keyboard auto-scroll, and non-sticky section headers ([#256](https://github.com/shumaiOne/shumai/pull/256))
|
||||
- **webui**: Persist field order on drag and drop ([#266](https://github.com/shumaiOne/shumai/pull/266))
|
||||
|
||||
### Changed
|
||||
|
||||
- **agent**: Load models directly from database without pi fallback ([#253](https://github.com/shumaiOne/shumai/pull/253))
|
||||
- **core**: Replace generated provider files with pi-ai dynamic methods ([#255](https://github.com/shumaiOne/shumai/pull/255))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **core**: Add missing tests for methods introduced in 97069042 ([#252](https://github.com/shumaiOne/shumai/pull/252))
|
||||
- **e2e**: Add domain-based auth and project web app e2e tests ([#257](https://github.com/shumaiOne/shumai/pull/257))
|
||||
- **e2e**: Add file, share, and collection web app e2e tests ([#258](https://github.com/shumaiOne/shumai/pull/258))
|
||||
- **e2e**: Add project-level invite and file-move e2e tests ([#259](https://github.com/shumaiOne/shumai/pull/259))
|
||||
- **e2e**: Add search in file list and save-search-as-collection cases ([#261](https://github.com/shumaiOne/shumai/pull/261))
|
||||
- **e2e**: Add member permission change tests ([#268](https://github.com/shumaiOne/shumai/pull/268))
|
||||
|
||||
## [0.3.2] - 2026-07-30
|
||||
|
||||
### Added
|
||||
|
||||
- **agent**: Add output truncation and streaming limits to sandboxed bash tool ([#248](https://github.com/shumaiOne/shumai/pull/248))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **agent**: Download original document asset instead of pdf proxy ([#247](https://github.com/shumaiOne/shumai/pull/247))
|
||||
- **webui**: Persist chatbot sidebar input text across route navigation ([#249](https://github.com/shumaiOne/shumai/pull/249))
|
||||
|
||||
## [0.3.1] - 2026-07-30
|
||||
|
||||
### Added
|
||||
|
||||
- **transcode**: Trigger ai metadata autofill post transcode ([#234](https://github.com/shumaiOne/shumai/pull/234))
|
||||
- **dashboard**: Add agent sessions view for team owners ([#237](https://github.com/shumaiOne/shumai/pull/237))
|
||||
- **db**: Preserve agent sessions on asset deletion by setting onDelete to SetNull ([#240](https://github.com/shumaiOne/shumai/pull/240))
|
||||
- **agent**: Add download_asset tool and prompt instructions ([#242](https://github.com/shumaiOne/shumai/pull/242))
|
||||
- **db**: Update Asset.sizeByte and AiUsage token fields to BigInt ([#244](https://github.com/shumaiOne/shumai/pull/244))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **agent**: Include select option labels and field name in autofill schema ([#235](https://github.com/shumaiOne/shumai/pull/235))
|
||||
- **agent**: Scope agent comment sessions to thread sessions anchored at root comments ([#239](https://github.com/shumaiOne/shumai/pull/239))
|
||||
- **agent**: Disable tools for session naming and make naming non-blocking ([#241](https://github.com/shumaiOne/shumai/pull/241))
|
||||
- **webui**: Update file size formatting to SI decimal standard ([#245](https://github.com/shumaiOne/shumai/pull/245))
|
||||
- **s3**: Enforce property syntax in S3Service interface and fix ReadableStream handling in S3StorageService ([#246](https://github.com/shumaiOne/shumai/pull/246))
|
||||
|
||||
## [0.3.0] - 2026-07-28
|
||||
|
||||
### Added
|
||||
|
||||
- **file-browser**: Add copy name and path option to context menu ([#225](https://github.com/shumaiOne/shumai/pull/225))
|
||||
- **agent**: Inject user name and role into chat context ([#226](https://github.com/shumaiOne/shumai/pull/226))
|
||||
- **agent**: Refactor database session storage to normalized DAG entries and lazy thread sync ([#229](https://github.com/shumaiOne/shumai/pull/229))
|
||||
- **agent**: Support ENABLE_WEAKER_NESTED_SANDBOX environment variable ([#233](https://github.com/shumaiOne/shumai/pull/233))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **agent**: Ensure atomic appendEntry and persist leaf entries in DatabaseSessionStorage ([#224](https://github.com/shumaiOne/shumai/pull/224))
|
||||
- Sharp version mismatch bug ([#230](https://github.com/shumaiOne/shumai/pull/230))
|
||||
- **agent**: Resolve S3 MIME type detection and prompt parameter in image analysis ([#232](https://github.com/shumaiOne/shumai/pull/232))
|
||||
|
||||
### Changed
|
||||
|
||||
- **agent**: Remove implicit agent mention trigger in comment threads ([#227](https://github.com/shumaiOne/shumai/pull/227))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **workflow**: Add docker compose deployment verification job ([#231](https://github.com/shumaiOne/shumai/pull/231))
|
||||
|
||||
## [0.2.3] - 2026-07-25
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Show right sidebar by default on file detail page ([#219](https://github.com/shumaiOne/shumai/pull/219))
|
||||
- **webui**: Refresh file list and detail when agent executes asset creation tools ([#220](https://github.com/shumaiOne/shumai/pull/220))
|
||||
- **webui**: Fix space key drag overlay and shift range selection for version stacks ([#221](https://github.com/shumaiOne/shumai/pull/221))
|
||||
- **transcode**: Handle timestamp rounding tolerance for screenshot annotations ([#223](https://github.com/shumaiOne/shumai/pull/223))
|
||||
|
||||
### Changed
|
||||
|
||||
- **e2e**: Split transcode workflow E2E tests into per-workflow test files ([#222](https://github.com/shumaiOne/shumai/pull/222))
|
||||
|
||||
## [0.2.2] - 2026-07-23
|
||||
|
||||
### Added
|
||||
|
||||
- **webui**: Integrate AI usage API into dashboard page ([#216](https://github.com/shumaiOne/shumai/pull/216))
|
||||
- **ai-usage**: Add team and member token usage tracking and APIs ([#215](https://github.com/shumaiOne/shumai/pull/215))
|
||||
- **transcode**: Add PSD support via ImageMagick and enforce sRGB conversion ([#217](https://github.com/shumaiOne/shumai/pull/217))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **search**: Fix buildSqlCondition date range, numeric metadata, and string parsing bugs ([#213](https://github.com/shumaiOne/shumai/pull/213))
|
||||
- **webui**: Prevent horizontal overflow in search dialog result rows ([#214](https://github.com/shumaiOne/shumai/pull/214))
|
||||
- **webui**: Invalidate upload tasks query when upload task starts and completes ([#218](https://github.com/shumaiOne/shumai/pull/218))
|
||||
|
||||
## [0.2.1] - 2026-07-22
|
||||
|
||||
### Added
|
||||
|
||||
- **skill**: Add team owner skill permission control ([#209](https://github.com/shumaiOne/shumai/pull/209))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **agent**: Handle non-builtin models in getModelFromDb and upgrade pi-ai ([#211](https://github.com/shumaiOne/shumai/pull/211))
|
||||
- **provider**: Preserve model ids on provider update ([#212](https://github.com/shumaiOne/shumai/pull/212))
|
||||
|
||||
### Changed
|
||||
|
||||
- **core**: Split generated providers into per-provider files ([#210](https://github.com/shumaiOne/shumai/pull/210))
|
||||
|
||||
## [0.2.0] - 2026-07-21
|
||||
|
||||
### Added
|
||||
|
||||
- **transcode**: Add PDF preview, sprite generation, and annotation support ([#193](https://github.com/shumaiOne/shumai/pull/193))
|
||||
- **web**: Register pdf.worker route in production ([#195](https://github.com/shumaiOne/shumai/pull/195))
|
||||
- **agent**: Add read_pdf_pages tool and PDF page context support ([#196](https://github.com/shumaiOne/shumai/pull/196))
|
||||
- **transcode**: Split monolithic transcodeMedia into focused workflows ([#197](https://github.com/shumaiOne/shumai/pull/197))
|
||||
- **transcode**: Add PDF proxy support for TXT and CSV files ([#199](https://github.com/shumaiOne/shumai/pull/199))
|
||||
- **asset**: Replace mediaType/mimeType logic with proxyType ([#200](https://github.com/shumaiOne/shumai/pull/200))
|
||||
- **docker**: Install fonts-noto-cjk in runner stage ([#202](https://github.com/shumaiOne/shumai/pull/202))
|
||||
- **transcode**: Add markdown file to pdf proxy support ([#203](https://github.com/shumaiOne/shumai/pull/203))
|
||||
- **chat**: Track context asset changes and update agent context ([#204](https://github.com/shumaiOne/shumai/pull/204))
|
||||
- **agent**: Refactor media tools to static injection with mandatory assetId and authz ([#208](https://github.com/shumaiOne/shumai/pull/208))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **transcode**: Mark pdfkit as external and extract for docker runtime ([#201](https://github.com/shumaiOne/shumai/pull/201))
|
||||
- **agent**: Include skill id in formatSkillsForPrompt ([#205](https://github.com/shumaiOne/shumai/pull/205))
|
||||
- **asset**: Exclude soft-deleted children from latestChildren preview ([#206](https://github.com/shumaiOne/shumai/pull/206))
|
||||
- **agent**: Pass latest version asset from version stack to prompt builder ([#207](https://github.com/shumaiOne/shumai/pull/207))
|
||||
|
||||
## [0.1.10] - 2026-07-16
|
||||
|
||||
### Added
|
||||
|
||||
- **workflow-e2e**: Add E2E tests for agentAutofillMedia workflow ([#188](https://github.com/shumaiOne/shumai/pull/188))
|
||||
- **comments**: Support comment deletion and video player shortcuts ([#191](https://github.com/shumaiOne/shumai/pull/191))
|
||||
- **agent**: Support disabling specific tools for agents ([#192](https://github.com/shumaiOne/shumai/pull/192))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **e2e**: Add E2E workflow tests for remaining agent and transcode services ([#189](https://github.com/shumaiOne/shumai/pull/189))
|
||||
|
||||
## [0.1.9] - 2026-07-14
|
||||
|
||||
### Added
|
||||
|
||||
- **e2e**: Set up fullstack app-level e2e test framework and signup test case ([#184](https://github.com/shumaiOne/shumai/pull/184))
|
||||
- **chat**: Chatbot UI ([#185](https://github.com/shumaiOne/shumai/pull/185))
|
||||
- **agent**: Support aborting agent execution ([#186](https://github.com/shumaiOne/shumai/pull/186))
|
||||
|
||||
### Changed
|
||||
|
||||
- **api/chat**: Remove direct Prisma query from API layer ([#187](https://github.com/shumaiOne/shumai/pull/187))
|
||||
|
||||
## [0.1.8] - 2026-07-10
|
||||
|
||||
### Added
|
||||
|
||||
- **chatbot**: Implement type-safe Chat APIs with compaction support ([#180](https://github.com/shumaiOne/shumai/pull/180))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Enable build splitting and code-split all page routes ([#183](https://github.com/shumaiOne/shumai/pull/183))
|
||||
|
||||
### Documentation
|
||||
|
||||
- **readme**: Clarify displayed file size represents original file size ([#182](https://github.com/shumaiOne/shumai/pull/182))
|
||||
|
||||
## [0.1.7] - 2026-07-06
|
||||
|
||||
### Added
|
||||
|
||||
- **audio**: Support frame-accurate audio playback, comments, and AI safeguards ([#175](https://github.com/shumaiOne/shumai/pull/175))
|
||||
- **i18n**: Localize members dialog, notifications, uploads, user menus, dates, and players ([#178](https://github.com/shumaiOne/shumai/pull/178))
|
||||
- **comments**: Allow marking comments as complete or incomplete ([#179](https://github.com/shumaiOne/shumai/pull/179))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **upload**: Resolve empty and generic MIME types in confirmFileUpload ([#176](https://github.com/shumaiOne/shumai/pull/176))
|
||||
|
||||
### Changed
|
||||
|
||||
- **webui**: Modularize file viewer components into registry-driven architecture ([#174](https://github.com/shumaiOne/shumai/pull/174))
|
||||
|
||||
### Documentation
|
||||
|
||||
- Improve documentation and examples for S3 compatible storage ([#177](https://github.com/shumaiOne/shumai/pull/177))
|
||||
|
||||
## [0.1.6] - 2026-07-04
|
||||
|
||||
### Added
|
||||
|
||||
- **file-browser**: Show video duration on file card preview ([#170](https://github.com/shumaiOne/shumai/pull/170))
|
||||
- **webui**: Compare versions view for version stacks ([#171](https://github.com/shumaiOne/shumai/pull/171))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Resolve conditional hooks and setState-in-render errors ([#167](https://github.com/shumaiOne/shumai/pull/167))
|
||||
- **webui**: Resolve video player total frames mismatch ([#172](https://github.com/shumaiOne/shumai/pull/172))
|
||||
- **version-stack**: Resolve correct latest version ID of version stack ([#173](https://github.com/shumaiOne/shumai/pull/173))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **webui**: Video player e2e framework + Safari playhead fix ([#166](https://github.com/shumaiOne/shumai/pull/166))
|
||||
- **webui**: Add frame-accurate comment seek roundtrip e2e ([#168](https://github.com/shumaiOne/shumai/pull/168))
|
||||
- **webui**: Verify video player restarts playback after end ([#169](https://github.com/shumaiOne/shumai/pull/169))
|
||||
|
||||
## [0.1.5] - 2026-07-02
|
||||
|
||||
### Changed
|
||||
|
||||
- **storage**: Use original filenames for stored files ([#165](https://github.com/shumaiOne/shumai/pull/165))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **release**: Add Aliyun ACR push to release workflow ([#164](https://github.com/shumaiOne/shumai/pull/164))
|
||||
|
||||
## [0.1.4] - 2026-07-01
|
||||
|
||||
### Added
|
||||
|
||||
- **transcode**: Change video poster resolution to 480p ([#161](https://github.com/shumaiOne/shumai/pull/161))
|
||||
- **auth**: Allow setting user locale on signup ([#163](https://github.com/shumaiOne/shumai/pull/163))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Preserve video ended state by skipping playhead snap on ended ([#162](https://github.com/shumaiOne/shumai/pull/162))
|
||||
|
||||
## [0.1.3] - 2026-06-30
|
||||
|
||||
### Added
|
||||
|
||||
- **webui**: Add i18n support using paraglide-js ([#156](https://github.com/shumaiOne/shumai/pull/156))
|
||||
- **video**: Add frame-accurate video player, SMPTE timecodes, and format switcher ([#157](https://github.com/shumaiOne/shumai/pull/157))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Align video timeline duration and formatting with frameio ([#158](https://github.com/shumaiOne/shumai/pull/158))
|
||||
- **webui**: Fix missing left sidebar for nested folders ([#159](https://github.com/shumaiOne/shumai/pull/159))
|
||||
- **api**: Fix update team settings and make request schema type-safe ([#160](https://github.com/shumaiOne/shumai/pull/160))
|
||||
|
||||
## [0.1.2] - 2026-06-25
|
||||
|
||||
### Changed
|
||||
|
||||
- **s3**: Remove automatic port appending to AWS_ENDPOINT_URL_S3 ([#155](https://github.com/shumaiOne/shumai/pull/155))
|
||||
|
||||
## [0.1.1] - 2026-06-23
|
||||
|
||||
### Added
|
||||
|
||||
- **docker**: Add root entrypoint with privilege dropping for data volumes ([#151](https://github.com/shumaiOne/shumai/pull/151))
|
||||
|
||||
## [0.1.0] - 2026-06-22
|
||||
|
||||
### Added
|
||||
|
||||
- **share**: Secure share info API and fix wrong password feedback ([#150](https://github.com/shumaiOne/shumai/pull/150))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Truncate long folder, collection, and share link names in sidebar ([#149](https://github.com/shumaiOne/shumai/pull/149))
|
||||
|
||||
## [0.0.11] - 2026-06-22
|
||||
|
||||
### Added
|
||||
|
||||
- **cli**: Add shumai-cli and token authentication ([#144](https://github.com/shumaiOne/shumai/pull/144))
|
||||
- **settings**: Use singular headers and remove collapse/counters for single agent types ([#145](https://github.com/shumaiOne/shumai/pull/145))
|
||||
- **folders**: Auto expand folder tree in left sidebar on navigation ([#146](https://github.com/shumaiOne/shumai/pull/146))
|
||||
- **metadata**: Add single user and multiple user custom fields ([#147](https://github.com/shumaiOne/shumai/pull/147))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **cli**: Rename npm package to @shumai-one/shumai-cli ([#148](https://github.com/shumaiOne/shumai/pull/148))
|
||||
|
||||
## [0.0.10] - 2026-06-21
|
||||
|
||||
### Changed
|
||||
|
||||
- **web**: Dynamically register production HTML bundle routes ([#142](https://github.com/shumaiOne/shumai/pull/142))
|
||||
|
||||
### Documentation
|
||||
|
||||
- **readme**: Polish structure, correct grammar, and add dependencies table ([#143](https://github.com/shumaiOne/shumai/pull/143))
|
||||
|
||||
## [0.0.9] - 2026-06-20
|
||||
|
||||
### Added
|
||||
|
||||
- **webui**: Show app version in avatar menu ([#139](https://github.com/shumaiOne/shumai/pull/139))
|
||||
- **cli**: Add background daemonization and subcommands ([#141](https://github.com/shumaiOne/shumai/pull/141))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **release**: Add smoke tests to local release stage ([#140](https://github.com/shumaiOne/shumai/pull/140))
|
||||
|
||||
## [0.0.8] - 2026-06-19
|
||||
|
||||
### Added
|
||||
|
||||
- **api**: Implement read-only mode for reviewers ([#122](https://github.com/shumaiOne/shumai/pull/122))
|
||||
- **server**: Allow customizing server port via SHUMAI_SERVER_PORT ([#124](https://github.com/shumaiOne/shumai/pull/124))
|
||||
- **embedding**: Defer embedding workflow, use transcoded assets, and execute chunks in separate activities ([#125](https://github.com/shumaiOne/shumai/pull/125))
|
||||
- **webui**: Add external drag-and-drop file and folder upload support ([#126](https://github.com/shumaiOne/shumai/pull/126))
|
||||
- **agent**: Implement overlapping video chunks for semantic search ([#127](https://github.com/shumaiOne/shumai/pull/127))
|
||||
- **webui**: Support jumping to video timestamp from search results ([#128](https://github.com/shumaiOne/shumai/pull/128))
|
||||
- **auth**: Add demo mode support ([#131](https://github.com/shumaiOne/shumai/pull/131))
|
||||
- **auth**: Refine demo mode support ([#132](https://github.com/shumaiOne/shumai/pull/132))
|
||||
- **webui**: Default right sidebar to collapsed for new users ([#133](https://github.com/shumaiOne/shumai/pull/133))
|
||||
- **webui**: Use Shadcn Switch in toggle field and Rating component in search filter panel ([#137](https://github.com/shumaiOne/shumai/pull/137))
|
||||
- **upload**: Track byte-level progress with XMLHttpRequest ([#138](https://github.com/shumaiOne/shumai/pull/138))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **transcode**: Handle high-precision FPS using rational fractions ([#123](https://github.com/shumaiOne/shumai/pull/123))
|
||||
- **db**: Automatically update project updatedAt on asset modification ([#129](https://github.com/shumaiOne/shumai/pull/129))
|
||||
- **webui**: Use system colors for fields and improve search filter select options ([#130](https://github.com/shumaiOne/shumai/pull/130))
|
||||
- **search**: Fix hasAny and hasNone operators on metadata filter ([#134](https://github.com/shumaiOne/shumai/pull/134))
|
||||
- **webui**: Resolve folder tree sync, search dialog reset, and sidebar actions issues ([#136](https://github.com/shumaiOne/shumai/pull/136))
|
||||
|
||||
### Changed
|
||||
|
||||
- **webui**: Fix search dialog layout height, scroll areas, and restrict filter toggle click ([#135](https://github.com/shumaiOne/shumai/pull/135))
|
||||
|
||||
## [0.0.7] - 2026-06-17
|
||||
|
||||
### Added
|
||||
|
||||
- **workflow**: Configure transcode and agent concurrency via environment variables ([#116](https://github.com/shumaiOne/shumai/pull/116))
|
||||
- **webui**: Replace hardcoded colors with system tokens ([#119](https://github.com/shumaiOne/shumai/pull/119))
|
||||
- **webui**: Replace native overflow with shadcn ScrollArea in settings ([#120](https://github.com/shumaiOne/shumai/pull/120))
|
||||
- **api**: Use enum for API protocol in provider config ([#121](https://github.com/shumaiOne/shumai/pull/121))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Reload video player and reset state when switching assets ([#114](https://github.com/shumaiOne/shumai/pull/114))
|
||||
|
||||
### Changed
|
||||
|
||||
- **transcode**: Relocate TranscodeService to core and flatten API package ([#115](https://github.com/shumaiOne/shumai/pull/115))
|
||||
|
||||
### Documentation
|
||||
|
||||
- Improve and restructure shumai documentation ([#118](https://github.com/shumaiOne/shumai/pull/118))
|
||||
|
||||
## [0.0.6] - 2026-06-15
|
||||
|
||||
### Added
|
||||
|
||||
- **sandbox**: Add pending domains support for network sandbox ([#109](https://github.com/shumaiOne/shumai/pull/109))
|
||||
- **webui**: Always show right sidebar and implement left vertical carousel ([#111](https://github.com/shumaiOne/shumai/pull/111))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **build**: Propagate termination signals to active child process in wrappers ([#102](https://github.com/shumaiOne/shumai/pull/102))
|
||||
- **transcode**: Make deterministic transcode activity failures non-retryable in Temporal ([#104](https://github.com/shumaiOne/shumai/pull/104))
|
||||
- **player**: Implement seekbar dragging and match hover highlight color ([#108](https://github.com/shumaiOne/shumai/pull/108))
|
||||
- **webui**: Avoid refetching all pages on file/folder reorder ([#112](https://github.com/shumaiOne/shumai/pull/112))
|
||||
- **webui**: Force video-player mime type to video/mp4 ([#113](https://github.com/shumaiOne/shumai/pull/113))
|
||||
|
||||
### Changed
|
||||
|
||||
- **webui**: Use system color design tokens in video player components ([#106](https://github.com/shumaiOne/shumai/pull/106))
|
||||
- **webui**: Use requestAnimationFrame for smooth video progress bar updates ([#107](https://github.com/shumaiOne/shumai/pull/107))
|
||||
- **webui**: Fetch agents in mention input list dynamically ([#110](https://github.com/shumaiOne/shumai/pull/110))
|
||||
|
||||
### Documentation
|
||||
|
||||
- **readme**: Add comprehensive README.md ([#103](https://github.com/shumaiOne/shumai/pull/103))
|
||||
- **readme**: Improve remote deployment and temporal execution instructions ([#105](https://github.com/shumaiOne/shumai/pull/105))
|
||||
|
||||
## [0.0.5] - 2026-06-13
|
||||
|
||||
### Added
|
||||
|
||||
- **npm**: Auto deploy database migrations on package start ([#101](https://github.com/shumaiOne/shumai/pull/101))
|
||||
|
||||
## [0.0.4] - 2026-06-12
|
||||
|
||||
### Fixed
|
||||
|
||||
- **cli/docker**: Resolve global CLI external dependencies and fix Docker 404 error ([#100](https://github.com/shumaiOne/shumai/pull/100))
|
||||
|
||||
## [0.0.3] - 2026-06-12
|
||||
|
||||
### Fixed
|
||||
|
||||
- **cli**: Resolve platform binary path resolution under nested node_modules ([#99](https://github.com/shumaiOne/shumai/pull/99))
|
||||
|
||||
## [0.0.2] - 2026-06-12
|
||||
|
||||
### Fixed
|
||||
|
||||
- **npm**: Add repository metadata to package.json for provenance verification ([#98](https://github.com/shumaiOne/shumai/pull/98))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- Add release-npm.yaml workflow ([#97](https://github.com/shumaiOne/shumai/pull/97))
|
||||
|
||||
## [0.0.1] - 2026-06-12
|
||||
|
||||
### Added
|
||||
|
||||
- Initial release of Shumai
|
||||
+16
-7
@@ -30,11 +30,7 @@ RUN bun run scripts/extract-runtime-deps.ts
|
||||
# Stage 2: Runner
|
||||
FROM oven/bun:1.4.2 AS runner
|
||||
|
||||
# Install ffmpeg/ffprobe
|
||||
COPY --from=mwader/static-ffmpeg:8.1 /ffmpeg /usr/local/bin/
|
||||
COPY --from=mwader/static-ffmpeg:8.1 /ffprobe /usr/local/bin/
|
||||
|
||||
# Install system dependencies for sandbox runtime and agent
|
||||
# Install system dependencies and Jellyfin-FFmpeg (with VA-API support)
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
python3 \
|
||||
make \
|
||||
@@ -56,11 +52,24 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
poppler-utils \
|
||||
imagemagick \
|
||||
fonts-noto-cjk \
|
||||
&& . /etc/os-release \
|
||||
&& TARGETARCH=$(dpkg --print-architecture) \
|
||||
&& FFMPEG_VERSION="8.1.2-5" \
|
||||
&& curl -fsSL -o /tmp/jellyfin-ffmpeg.deb "https://github.com/jellyfin/jellyfin-ffmpeg/releases/download/v${FFMPEG_VERSION}/jellyfin-ffmpeg8_${FFMPEG_VERSION}-${VERSION_CODENAME}_${TARGETARCH}.deb" \
|
||||
&& apt-get install -y --no-install-recommends /tmp/jellyfin-ffmpeg.deb \
|
||||
&& rm -f /tmp/jellyfin-ffmpeg.deb \
|
||||
&& ldconfig /usr/lib/jellyfin-ffmpeg/lib \
|
||||
&& ln -sf /usr/lib/jellyfin-ffmpeg/ffmpeg /usr/local/bin/ffmpeg \
|
||||
&& ln -sf /usr/lib/jellyfin-ffmpeg/ffprobe /usr/local/bin/ffprobe \
|
||||
&& ln -sf /usr/lib/jellyfin-ffmpeg/ffmpeg /usr/bin/ffmpeg \
|
||||
&& ln -sf /usr/lib/jellyfin-ffmpeg/ffprobe /usr/bin/ffprobe \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Set up working directory and make it owned by the bun user
|
||||
RUN mkdir -p /app/data && chown -R bun:bun /app
|
||||
# Set up working directory and make it owned by the bun user, ensure video/render group access
|
||||
RUN usermod -a -G video,render bun 2>/dev/null || true \
|
||||
&& mkdir -p /app/data \
|
||||
&& chown -R bun:bun /app
|
||||
|
||||
# Switch to the non-root bun user
|
||||
USER bun
|
||||
|
||||
@@ -86,6 +86,9 @@ Docker Compose is the fastest way to get Shumai running. You do not need to clon
|
||||
```bash
|
||||
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose.yaml
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> By default, the standard `docker-compose.yaml` uses CPU software transcoding. If your server has a GPU (NVIDIA NVENC, Intel QuickSync, AMD/Intel VA-API, or Rockchip RKMPP) and you want to enable GPU hardware acceleration, check the [Hardware Transcoding Guide](https://docs.shumai.one/configuration/hardware-transcoding).
|
||||
3. Configure environment variables (optional):
|
||||
|
||||
* `SHUMAI_SERVER_PORT` controls the port the Shumai server listens on. The default is `3000`.
|
||||
|
||||
+3
-1
@@ -101,9 +101,11 @@ https://gh-proxy.com/https://raw.githubusercontent.com/shumaiOne/shumai/main/REA
|
||||
2. 下载 `docker-compose.yaml` 配置文件:
|
||||
```bash
|
||||
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose-aliyun.yaml
|
||||
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> 默认的 Docker Compose 配置使用基于 CPU 的软件转码。如果您的服务器配备了支持的显卡(NVIDIA NVENC、Intel QuickSync、AMD/Intel VA-API 或 Rockchip RKMPP)并需要开启 GPU 硬件加速转码,请参考 [硬件加速转码配置文档](https://docs.shumai.one/configuration/hardware-transcoding)。
|
||||
|
||||
|
||||
3. 配置环境变量(可选):
|
||||
* `SHUMAI_SERVER_PORT` 用于控制 Shumai 服务监听的端口,默认值为 `3000`。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent-app",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/premiere-uxp",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"private": true,
|
||||
"type": "commonjs",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -73,6 +73,8 @@ apps/web/e2e/
|
||||
| Owner creates a project with a cover image | `tests/project/create-project.spec.ts` |
|
||||
| Owner uploads a file or an unsupported file via the "Upload File" context menu action | `tests/project/upload-file.spec.ts` |
|
||||
| Owner deletes a file, finds it in recently deleted, and restores it | `tests/project/delete-restore.spec.ts` |
|
||||
| Owner deletes a folder and still sees its contents preview and countdown in recently deleted | `tests/project/delete-restore.spec.ts` |
|
||||
| Owner deletes a version stack and restores it from recently deleted | `tests/project/delete-restore.spec.ts` |
|
||||
| Owner creates a share link from a file context menu and lands on the share page | `tests/project/create-share-link.spec.ts` |
|
||||
| Owner protects a share with a password; guests must enter it to view | `tests/project/share-password.spec.ts` |
|
||||
| Owner creates a collection from the sidebar; the collection shows project files | `tests/project/create-collection.spec.ts` |
|
||||
@@ -103,6 +105,8 @@ apps/web/e2e/
|
||||
| Upload an image file, wait for transcode, and create a comment with draw | `tests/file/image-draw-comment.spec.ts` |
|
||||
| Upload a video file, wait for transcode, and create a comment with draw at a non-zero timestamp | `tests/file/video-draw-comment.spec.ts` |
|
||||
| Upload an audio file, wait for transcode, and create a comment at a non-zero timestamp | `tests/file/audio-timestamp-comment.spec.ts` |
|
||||
| Show a breathing poster preview and "Preparing..." while a video is still transcoding | `tests/file/processing-preview.spec.ts` |
|
||||
| Show a preparing circle before the poster is generated | `tests/file/processing-preview.spec.ts` |
|
||||
|
||||
## Conventions
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { expect, test } from '../../fixtures'
|
||||
import { fileCard } from '../../helpers/files'
|
||||
|
||||
// Uploaded as a binary file so no real transcode task races with the simulated mid-transcode
|
||||
// state we set up directly in the database.
|
||||
test.use({ fileOptions: { mediaType: 'binary' } })
|
||||
|
||||
test('shows the poster preview and "Preparing..." while a video is still transcoding', async ({
|
||||
file,
|
||||
prisma,
|
||||
}) => {
|
||||
const { page, projectId, fileId, fileName } = file
|
||||
|
||||
// Simulate a video that is mid-transcode: the poster/sprite preview already exists, but the
|
||||
// asset is still marked as processing.
|
||||
const assetDir = `files/e2e/${fileId}`
|
||||
await prisma.asset.update({
|
||||
where: { id: fileId },
|
||||
data: {
|
||||
status: 'processing',
|
||||
mediaType: 'video/mp4',
|
||||
media: {
|
||||
duration: 10,
|
||||
filesize: 0,
|
||||
frames: 300,
|
||||
proxyType: 'video',
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
sprite: { key: `${assetDir}/sprite.webp`, frames: 100, tileX: 10, tileY: 10 },
|
||||
poster: { key: `${assetDir}/poster.webp` },
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: {
|
||||
originalWidth: 1920,
|
||||
originalHeight: 1080,
|
||||
hasAudio: false,
|
||||
duration: 10,
|
||||
bitRate: 0,
|
||||
frameRate: 30,
|
||||
totalFrames: 300,
|
||||
startTimecode: '00:00:00:00',
|
||||
format: {},
|
||||
},
|
||||
original: { key: `${assetDir}/original.mp4`, filesizeInBytes: 0, codec: '' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
|
||||
const card = fileCard(page, fileName)
|
||||
await expect(card).toBeVisible()
|
||||
|
||||
// The preview (poster thumbnail used as the sprite scrubber base) is rendered instead of a
|
||||
// blank placeholder, and its opacity breathes while transcoding is in progress.
|
||||
await expect(card.locator('img[alt="Thumbnail"]')).toBeVisible()
|
||||
await expect(card.getByTestId('file-card-preview-media')).toHaveClass(/animate-pulse/)
|
||||
|
||||
// The creator row is replaced by a "Preparing..." label while transcoding.
|
||||
await expect(card.getByText(/Preparing|准备中/i)).toBeVisible()
|
||||
|
||||
// The duration badge is hidden until the asset is ready.
|
||||
await expect(card.getByText('00:10')).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('shows a preparing circle before the poster is generated', async ({ file, prisma }) => {
|
||||
const { page, projectId, fileId, fileName } = file
|
||||
|
||||
// Simulate an asset whose upload finished but whose poster does not exist yet.
|
||||
await prisma.asset.update({
|
||||
where: { id: fileId },
|
||||
data: { status: 'processing', mediaType: 'video/mp4' },
|
||||
})
|
||||
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
|
||||
const card = fileCard(page, fileName)
|
||||
await expect(card).toBeVisible()
|
||||
|
||||
// A size-breathing circle stands in until the poster is available, with a "Preparing..." label.
|
||||
await expect(card.getByTestId('file-card-preparing-circle')).toBeVisible()
|
||||
await expect(card.getByText(/Preparing|准备中/i)).toBeVisible()
|
||||
})
|
||||
@@ -1,4 +1,5 @@
|
||||
import { expect, test } from '../../fixtures'
|
||||
import { seedFile, seedFolder } from '../../helpers/assets'
|
||||
import { fileCard } from '../../helpers/files'
|
||||
|
||||
test('owner deletes a file, finds it in recently deleted, and restores it', async ({
|
||||
@@ -43,3 +44,121 @@ test('owner deletes a file, finds it in recently deleted, and restores it', asyn
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await expect(fileCard(page, fileName)).toBeVisible()
|
||||
})
|
||||
|
||||
test('owner deletes a folder and still sees its contents preview and countdown in recently deleted', async ({
|
||||
project,
|
||||
prisma,
|
||||
}) => {
|
||||
const { page, projectId, rootFolderId } = project
|
||||
const folderName = `e2e-deleted-folder-${Date.now()}`
|
||||
|
||||
const folder = await seedFolder(prisma, projectId, rootFolderId, folderName)
|
||||
await seedFile(prisma, projectId, folder.id, 'inside-1.png')
|
||||
await seedFile(prisma, projectId, folder.id, 'inside-2.png')
|
||||
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await expect(fileCard(page, folderName)).toBeVisible()
|
||||
|
||||
// Delete the folder through the context menu + confirmation dialog
|
||||
await fileCard(page, folderName).click({ button: 'right' })
|
||||
await page.getByRole('menuitem', { name: 'Delete' }).click()
|
||||
|
||||
const deleteDialog = page.getByRole('alertdialog')
|
||||
await expect(deleteDialog.getByText('Delete Asset?')).toBeVisible()
|
||||
await deleteDialog.getByRole('button', { name: 'Delete' }).click()
|
||||
await expect(fileCard(page, folderName)).not.toBeVisible()
|
||||
|
||||
// Navigate to the Recently Deleted view
|
||||
await page.getByText('Recently Deleted').click()
|
||||
await expect(page).toHaveURL(/\/recently-deleted/)
|
||||
|
||||
const deletedFolderCard = fileCard(page, folderName)
|
||||
await expect(deletedFolderCard).toBeVisible()
|
||||
// The folder still shows previews of the files that were deleted with it
|
||||
await expect(deletedFolderCard.getByTestId('folder-preview-grid')).toBeVisible()
|
||||
// And each item shows how many days are left before permanent deletion
|
||||
await expect(deletedFolderCard.getByTestId('folder-card-days-left')).toHaveText(/30\s*(d|天)/)
|
||||
})
|
||||
|
||||
test('owner deletes a version stack and restores it from recently deleted', async ({
|
||||
project,
|
||||
prisma,
|
||||
}) => {
|
||||
const { page, projectId, rootFolderId } = project
|
||||
const latestVersionName = `e2e-stack-latest-${Date.now()}.png`
|
||||
const olderVersionName = `e2e-stack-older-${Date.now()}.png`
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: `e2e-stack-${Date.now()}`,
|
||||
type: 'version_stack',
|
||||
status: 'processed',
|
||||
projectId,
|
||||
parentId: rootFolderId,
|
||||
fileCount: 2,
|
||||
sizeByte: 20,
|
||||
},
|
||||
})
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: latestVersionName,
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
sizeByte: 10,
|
||||
sortIndex: 'a0',
|
||||
projectId,
|
||||
parentId: stack.id,
|
||||
},
|
||||
})
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: olderVersionName,
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
sizeByte: 10,
|
||||
sortIndex: 'a1',
|
||||
projectId,
|
||||
parentId: stack.id,
|
||||
},
|
||||
})
|
||||
|
||||
// The stack card is labelled with its latest version's name
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await expect(fileCard(page, latestVersionName)).toBeVisible()
|
||||
|
||||
await fileCard(page, latestVersionName).click({ button: 'right' })
|
||||
await page.getByRole('menuitem', { name: 'Delete' }).click()
|
||||
|
||||
const deleteDialog = page.getByRole('alertdialog')
|
||||
await expect(deleteDialog.getByText('Delete Asset?')).toBeVisible()
|
||||
await deleteDialog.getByRole('button', { name: 'Delete' }).click()
|
||||
await expect(fileCard(page, latestVersionName)).not.toBeVisible()
|
||||
|
||||
// The whole stack is soft-deleted, including its versions
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const row = await prisma.asset.findUnique({ where: { id: stack.id } })
|
||||
return row?.isDeleted
|
||||
})
|
||||
.toBe(true)
|
||||
|
||||
// Restore it from the Recently Deleted view
|
||||
await page.getByText('Recently Deleted').click()
|
||||
await expect(page).toHaveURL(/\/recently-deleted/)
|
||||
await expect(fileCard(page, latestVersionName)).toBeVisible()
|
||||
|
||||
await fileCard(page, latestVersionName).click({ button: 'right' })
|
||||
await page.getByRole('menuitem', { name: 'Restore' }).click()
|
||||
await expect(fileCard(page, latestVersionName)).not.toBeVisible()
|
||||
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const row = await prisma.asset.findUnique({ where: { id: stack.id } })
|
||||
return row?.isDeleted
|
||||
})
|
||||
.toBe(false)
|
||||
|
||||
// Back at the project root the stack is visible again
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await expect(fileCard(page, latestVersionName)).toBeVisible()
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
|
||||
@@ -16,6 +16,7 @@ import { migrateLegacyAgentAvatars } from '@shumai/core/src/agent/migration'
|
||||
import { handleDaemonCommands } from '@shumai/core/src/utils/daemon'
|
||||
import { authService } from '@shumai/core/src/auth/auth'
|
||||
import { sandboxService } from '@shumai/core'
|
||||
import { notificationJobService } from '@shumai/core/src/notification/notification-job'
|
||||
|
||||
if (process.argv.includes('--check')) {
|
||||
console.log('✅ Web app evaluated successfully!')
|
||||
@@ -58,6 +59,7 @@ async function run() {
|
||||
await metadataService.syncSystemFields().catch(console.error)
|
||||
await migrateLegacyAgentAvatars().catch(console.error)
|
||||
assetService.startCleanupJob()
|
||||
notificationJobService.start()
|
||||
workflowService.start()
|
||||
if (process.env.WORKFLOW_EXECUTOR === 'temporal') {
|
||||
const args = process.argv.slice(2)
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
},
|
||||
"apps/agent": {
|
||||
"name": "@shumai/agent-app",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"bin": {
|
||||
"shumai-agent": "./src/index.ts",
|
||||
},
|
||||
@@ -45,7 +45,7 @@
|
||||
},
|
||||
"apps/cli": {
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"bin": {
|
||||
"shumai-cli": "./src/index.ts",
|
||||
},
|
||||
@@ -60,7 +60,7 @@
|
||||
},
|
||||
"apps/premiere-uxp": {
|
||||
"name": "@shumai/premiere-uxp",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"dependencies": {
|
||||
"@shumai/api": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
@@ -114,7 +114,7 @@
|
||||
},
|
||||
"apps/transcode": {
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"bin": {
|
||||
"shumai-transcode": "./src/index.ts",
|
||||
},
|
||||
@@ -126,7 +126,7 @@
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"dependencies": {
|
||||
"@shumai/agent": "workspace:*",
|
||||
"@shumai/api": "workspace:*",
|
||||
@@ -146,7 +146,7 @@
|
||||
},
|
||||
"packages/agent": {
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sandbox-runtime": "0.0.74",
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
@@ -171,7 +171,7 @@
|
||||
},
|
||||
"packages/api": {
|
||||
"name": "@shumai/api",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"dependencies": {
|
||||
"@hono/zod-validator": "0.7.6",
|
||||
"@shumai/core": "workspace:*",
|
||||
@@ -185,7 +185,7 @@
|
||||
},
|
||||
"packages/core": {
|
||||
"name": "@shumai/core",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"dependencies": {
|
||||
"@ai-sdk/alibaba": "2.0.38",
|
||||
"@ai-sdk/amazon-bedrock": "5.0.67",
|
||||
@@ -214,6 +214,8 @@
|
||||
"@shumai/db": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
"@sinclair/typebox": "0.34.52",
|
||||
"@temporalio/activity": "1.24.0",
|
||||
"@temporalio/workflow": "1.24.0",
|
||||
"adm-zip": "0.6.0",
|
||||
"ai": "7.0.84",
|
||||
"better-auth": "1.6.11",
|
||||
@@ -224,6 +226,7 @@
|
||||
"extract-zip": "2.0.1",
|
||||
"hono": "4.13.5",
|
||||
"jittered-fractional-indexing": "1.0.1",
|
||||
"nodemailer": "10.0.10",
|
||||
"pdfkit": "0.20.1",
|
||||
"pino": "10.3.1",
|
||||
"sharp": "0.35.4",
|
||||
@@ -237,12 +240,13 @@
|
||||
"@modelcontextprotocol/server": "2.0.0",
|
||||
"@types/adm-zip": "0.5.8",
|
||||
"@types/extract-zip": "2.0.3",
|
||||
"@types/nodemailer": "8.0.2",
|
||||
"@types/pdfkit": "0.17.6",
|
||||
},
|
||||
},
|
||||
"packages/db": {
|
||||
"name": "@shumai/db",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"@prisma/adapter-pg": "7.10.0",
|
||||
@@ -258,7 +262,7 @@
|
||||
},
|
||||
"packages/dtos": {
|
||||
"name": "@shumai/dtos",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"zod": "4.5.4",
|
||||
@@ -266,7 +270,7 @@
|
||||
},
|
||||
"packages/e2e": {
|
||||
"name": "@shumai/e2e",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"@google/genai": "2.19.0",
|
||||
@@ -281,11 +285,11 @@
|
||||
},
|
||||
"packages/tableprinter": {
|
||||
"name": "@shumai/tableprinter",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
},
|
||||
"packages/transcode": {
|
||||
"name": "@shumai/transcode",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"dependencies": {
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/db": "workspace:*",
|
||||
@@ -299,7 +303,7 @@
|
||||
},
|
||||
"packages/webui": {
|
||||
"name": "@shumai/webui",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "1.7.0",
|
||||
"@dnd-kit/abstract": "0.5.0",
|
||||
@@ -401,7 +405,7 @@
|
||||
},
|
||||
"packages/workflow-core": {
|
||||
"name": "@shumai/workflow-core",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"dependencies": {
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/db": "workspace:*",
|
||||
@@ -1563,6 +1567,8 @@
|
||||
|
||||
"@types/node": ["@types/node@25.9.1", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg=="],
|
||||
|
||||
"@types/nodemailer": ["@types/nodemailer@8.0.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA=="],
|
||||
|
||||
"@types/pdfkit": ["@types/pdfkit@0.17.6", "", { "dependencies": { "@types/node": "*" } }, "sha512-tIwzxk2uWKp0Cq9JIluQXJid77lYhF52EsIOwhsMF4iWLA6YneoBR1xVKYYdAysHuepUB0OX4tdwMiUDdGKmig=="],
|
||||
|
||||
"@types/pg": ["@types/pg@8.23.1", "", { "dependencies": { "@types/node": "*", "pg-protocol": "*", "pg-types": "^2.2.0" } }, "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A=="],
|
||||
@@ -2591,6 +2597,8 @@
|
||||
|
||||
"node-releases": ["node-releases@2.0.54", "", {}, "sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ=="],
|
||||
|
||||
"nodemailer": ["nodemailer@10.0.10", "", {}, "sha512-He9XskOFms62SyAKkLu8CcGcYHAo+BSHSsORI8s4PJH8qZgZY4L4lDfvyN0twvmbpyG+eGrxpyBlskj9d9rJ8A=="],
|
||||
|
||||
"normalize-path": ["normalize-path@3.0.0", "", {}, "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA=="],
|
||||
|
||||
"object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
|
||||
@@ -3239,6 +3247,10 @@
|
||||
|
||||
"@reduxjs/toolkit/reselect": ["reselect@5.3.0", "", {}, "sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg=="],
|
||||
|
||||
"@shumai/core/@temporalio/activity": ["@temporalio/activity@1.24.0", "", { "dependencies": { "@temporalio/client": "1.24.0", "@temporalio/common": "1.24.0" } }, "sha512-eBBho/r9XHe2KczYGzmaSp6e9+6c9ta/GGOBldIBr00D/cV34kJ76iAY3Ue1pQTaP7YaX3phMuOz07uUg/IKyA=="],
|
||||
|
||||
"@shumai/core/@temporalio/workflow": ["@temporalio/workflow@1.24.0", "", { "dependencies": { "@temporalio/common": "1.24.0", "@temporalio/proto": "1.24.0", "nexus-rpc": "^0.0.3" } }, "sha512-pIA9nxkDCCbBnNuMSffQ44HWHYe3zXFfrDpDLwzh/FUSx8uLbsBM8jwf5oUMf+5eV/qVW9PknZhOu9IFO4XnPA=="],
|
||||
|
||||
"@shumai/webui/@types/react-dom": ["@types/react-dom@19.2.5", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-fMPwH9v7r/pp43yUd2/Mbiex5KouJwwR3dzHkhLREUC6764VyDsqxhAxv6OFEYR1RhjOyD1naqba8ECDBe7ZQg=="],
|
||||
|
||||
"@spectrum-web-components/action-button/@spectrum-web-components/icon": ["@spectrum-web-components/icon@0.37.0", "", { "dependencies": { "@spectrum-web-components/base": "^0.37.0", "@spectrum-web-components/iconset": "^0.37.0" } }, "sha512-DZ1yOKHxNQygzIJ7u9akYComDnMmxuTzfmYxxt9sHdUXmc1NbMkCJqEaAG/LYsdb+hc4xWaDTT9SzArLKZ/btA=="],
|
||||
@@ -3489,6 +3501,14 @@
|
||||
|
||||
"@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="],
|
||||
|
||||
"@shumai/core/@temporalio/activity/@temporalio/client": ["@temporalio/client@1.24.0", "", { "dependencies": { "@grpc/grpc-js": "^1.12.4", "@temporalio/common": "1.24.0", "@temporalio/proto": "1.24.0", "abort-controller": "^3.0.0", "long": "^5.3.2", "nexus-rpc": "^0.0.3", "uuid": "^11.1.0" } }, "sha512-/GGg6ZYl+pN/bQEvq414CyjDvyM+MM1WsMzi/7SCYb3UlivVXx9nOmH/6BGx8OfYFayp11fkmfSh6rt7vW/ePQ=="],
|
||||
|
||||
"@shumai/core/@temporalio/activity/@temporalio/common": ["@temporalio/common@1.24.0", "", { "dependencies": { "@temporalio/proto": "1.24.0", "long": "^5.3.2", "ms": "3.0.0-canary.1", "nexus-rpc": "^0.0.3", "protobufjs": "^8.7.1" } }, "sha512-jXp77fXwynBcVNc/CaGMT33TVYnhcN26S959HDv7Q71oc0rN6d8RHWR5z0nRCDAu5CQwZQRRhVK0TRdyAiEg7Q=="],
|
||||
|
||||
"@shumai/core/@temporalio/workflow/@temporalio/common": ["@temporalio/common@1.24.0", "", { "dependencies": { "@temporalio/proto": "1.24.0", "long": "^5.3.2", "ms": "3.0.0-canary.1", "nexus-rpc": "^0.0.3", "protobufjs": "^8.7.1" } }, "sha512-jXp77fXwynBcVNc/CaGMT33TVYnhcN26S959HDv7Q71oc0rN6d8RHWR5z0nRCDAu5CQwZQRRhVK0TRdyAiEg7Q=="],
|
||||
|
||||
"@shumai/core/@temporalio/workflow/@temporalio/proto": ["@temporalio/proto@1.24.0", "", { "dependencies": { "long": "^5.3.2", "protobufjs": "^8.7.1" } }, "sha512-vhlhB9GpoyJx+78r3lDahHywpdri6LKx7kt7djLIw6XzHyb8FQTIi4lX8DSJBqKp3+HVfL1CLwiqO26KFRzg/g=="],
|
||||
|
||||
"@spectrum-web-components/action-button/@spectrum-web-components/icon/@spectrum-web-components/iconset": ["@spectrum-web-components/iconset@0.37.0", "", { "dependencies": { "@spectrum-web-components/base": "^0.37.0" } }, "sha512-s1TBjWeQtGdGf6n+r+aG2glv77IgR0pNs0HLusGyYt6jzWFkP276fE7Neqq/2XvG9a9zvAwngffnWS3td/Gtmg=="],
|
||||
|
||||
"@spectrum-web-components/action-group/@spectrum-web-components/icons-workflow/@spectrum-web-components/icon": ["@spectrum-web-components/icon@0.37.0", "", { "dependencies": { "@spectrum-web-components/base": "^0.37.0", "@spectrum-web-components/iconset": "^0.37.0" } }, "sha512-DZ1yOKHxNQygzIJ7u9akYComDnMmxuTzfmYxxt9sHdUXmc1NbMkCJqEaAG/LYsdb+hc4xWaDTT9SzArLKZ/btA=="],
|
||||
@@ -3599,6 +3619,20 @@
|
||||
|
||||
"@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="],
|
||||
|
||||
"@shumai/core/@temporalio/activity/@temporalio/client/@temporalio/proto": ["@temporalio/proto@1.24.0", "", { "dependencies": { "long": "^5.3.2", "protobufjs": "^8.7.1" } }, "sha512-vhlhB9GpoyJx+78r3lDahHywpdri6LKx7kt7djLIw6XzHyb8FQTIi4lX8DSJBqKp3+HVfL1CLwiqO26KFRzg/g=="],
|
||||
|
||||
"@shumai/core/@temporalio/activity/@temporalio/common/@temporalio/proto": ["@temporalio/proto@1.24.0", "", { "dependencies": { "long": "^5.3.2", "protobufjs": "^8.7.1" } }, "sha512-vhlhB9GpoyJx+78r3lDahHywpdri6LKx7kt7djLIw6XzHyb8FQTIi4lX8DSJBqKp3+HVfL1CLwiqO26KFRzg/g=="],
|
||||
|
||||
"@shumai/core/@temporalio/activity/@temporalio/common/ms": ["ms@3.0.0-canary.1", "", {}, "sha512-kh8ARjh8rMN7Du2igDRO9QJnqCb2xYTJxyQYK7vJJS4TvLLmsbyhiKpSW+t+y26gyOyMd0riphX0GeWKU3ky5g=="],
|
||||
|
||||
"@shumai/core/@temporalio/activity/@temporalio/common/protobufjs": ["protobufjs@8.8.0", "", { "dependencies": { "long": "^5.3.2" } }, "sha512-N3xhQ5yyBx3vQq4gubBfASzYhJGNzeDbjqBpu61g7UVylsN/qyffU96TKWD3GbbLOKF82VGNRNvv1+BFgE31Eg=="],
|
||||
|
||||
"@shumai/core/@temporalio/workflow/@temporalio/common/ms": ["ms@3.0.0-canary.1", "", {}, "sha512-kh8ARjh8rMN7Du2igDRO9QJnqCb2xYTJxyQYK7vJJS4TvLLmsbyhiKpSW+t+y26gyOyMd0riphX0GeWKU3ky5g=="],
|
||||
|
||||
"@shumai/core/@temporalio/workflow/@temporalio/common/protobufjs": ["protobufjs@8.8.0", "", { "dependencies": { "long": "^5.3.2" } }, "sha512-N3xhQ5yyBx3vQq4gubBfASzYhJGNzeDbjqBpu61g7UVylsN/qyffU96TKWD3GbbLOKF82VGNRNvv1+BFgE31Eg=="],
|
||||
|
||||
"@shumai/core/@temporalio/workflow/@temporalio/proto/protobufjs": ["protobufjs@8.8.0", "", { "dependencies": { "long": "^5.3.2" } }, "sha512-N3xhQ5yyBx3vQq4gubBfASzYhJGNzeDbjqBpu61g7UVylsN/qyffU96TKWD3GbbLOKF82VGNRNvv1+BFgE31Eg=="],
|
||||
|
||||
"@spectrum-web-components/action-group/@spectrum-web-components/icons-workflow/@spectrum-web-components/icon/@spectrum-web-components/iconset": ["@spectrum-web-components/iconset@0.37.0", "", { "dependencies": { "@spectrum-web-components/base": "^0.37.0" } }, "sha512-s1TBjWeQtGdGf6n+r+aG2glv77IgR0pNs0HLusGyYt6jzWFkP276fE7Neqq/2XvG9a9zvAwngffnWS3td/Gtmg=="],
|
||||
|
||||
"@spectrum-web-components/card/@spectrum-web-components/icons-workflow/@spectrum-web-components/icon/@spectrum-web-components/iconset": ["@spectrum-web-components/iconset@0.37.0", "", { "dependencies": { "@spectrum-web-components/base": "^0.37.0" } }, "sha512-s1TBjWeQtGdGf6n+r+aG2glv77IgR0pNs0HLusGyYt6jzWFkP276fE7Neqq/2XvG9a9zvAwngffnWS3td/Gtmg=="],
|
||||
@@ -3620,5 +3654,7 @@
|
||||
"readdir-glob/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
|
||||
|
||||
"@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/react-primitive/@radix-ui/react-slot/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="],
|
||||
|
||||
"@shumai/core/@temporalio/activity/@temporalio/client/@temporalio/proto/protobufjs": ["protobufjs@8.8.0", "", { "dependencies": { "long": "^5.3.2" } }, "sha512-N3xhQ5yyBx3vQq4gubBfASzYhJGNzeDbjqBpu61g7UVylsN/qyffU96TKWD3GbbLOKF82VGNRNvv1+BFgE31Eg=="],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,6 @@ services:
|
||||
POSTGRES_USER: shumai
|
||||
POSTGRES_PASSWORD: shumai_password
|
||||
POSTGRES_DB: shumai_db
|
||||
ports:
|
||||
- '5432:5432'
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/18/docker
|
||||
healthcheck:
|
||||
@@ -28,6 +26,11 @@ services:
|
||||
- '3000:3000'
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
# Hardware Acceleration (NVENC / QuickSync / VA-API / RKMPP)
|
||||
# Uncomment the extends section below for hardware acceleration:
|
||||
# extends:
|
||||
# file: hwaccel.transcoding.yaml
|
||||
# service: cpu # set to one of [nvenc, quicksync, rkmpp, vaapi, vaapi-wsl] for accelerated transcoding
|
||||
environment:
|
||||
# Database Configuration
|
||||
DATABASE_URL: postgres://shumai:shumai_password@shumai_postgres:5432/shumai_db?search_path=public&sslmode=disable
|
||||
|
||||
@@ -6,8 +6,6 @@ services:
|
||||
POSTGRES_USER: shumai
|
||||
POSTGRES_PASSWORD: shumai_password
|
||||
POSTGRES_DB: shumai_db
|
||||
ports:
|
||||
- '5432:5432'
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/18/docker
|
||||
healthcheck:
|
||||
@@ -28,6 +26,11 @@ services:
|
||||
- '3000:3000'
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
# Hardware Acceleration (NVENC / QuickSync / VA-API / RKMPP)
|
||||
# Uncomment the extends section below for hardware acceleration:
|
||||
# extends:
|
||||
# file: hwaccel.transcoding.yaml
|
||||
# service: cpu # set to one of [nvenc, quicksync, rkmpp, vaapi, vaapi-wsl] for accelerated transcoding
|
||||
environment:
|
||||
# Database Configuration
|
||||
DATABASE_URL: postgres://shumai:shumai_password@shumai_postgres:5432/shumai_db?search_path=public&sslmode=disable
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# Configurations for hardware-accelerated transcoding
|
||||
services:
|
||||
cpu: {}
|
||||
|
||||
nvenc:
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: 1
|
||||
capabilities:
|
||||
- gpu
|
||||
- compute
|
||||
- video
|
||||
|
||||
quicksync:
|
||||
devices:
|
||||
- /dev/dri:/dev/dri
|
||||
|
||||
rkmpp:
|
||||
security_opt: # enables full access to /sys and /proc, still far better than privileged: true
|
||||
- systempaths=unconfined
|
||||
- apparmor=unconfined
|
||||
group_add:
|
||||
- video
|
||||
devices:
|
||||
- /dev/rga:/dev/rga
|
||||
- /dev/dri:/dev/dri
|
||||
- /dev/dma_heap:/dev/dma_heap
|
||||
- /dev/mpp_service:/dev/mpp_service
|
||||
|
||||
vaapi:
|
||||
devices:
|
||||
- /dev/dri:/dev/dri
|
||||
|
||||
vaapi-wsl: # use this for VAAPI if running in WSL2
|
||||
devices:
|
||||
- /dev/dri:/dev/dri
|
||||
- /dev/dxg:/dev/dxg
|
||||
volumes:
|
||||
- /usr/lib/wsl:/usr/lib/wsl
|
||||
environment:
|
||||
- LIBVA_DRIVER_NAME=d3d12
|
||||
@@ -7,8 +7,6 @@ services:
|
||||
POSTGRES_USER: shumai
|
||||
POSTGRES_PASSWORD: shumai_password
|
||||
POSTGRES_DB: shumai_db
|
||||
ports:
|
||||
- '5432:5432'
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql
|
||||
healthcheck:
|
||||
|
||||
@@ -0,0 +1,835 @@
|
||||
---
|
||||
title: "Changelog"
|
||||
description: "Recent updates, new features, and improvements in Shumai"
|
||||
---
|
||||
|
||||
<Update label="v0.4.9" description="September 28, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **notification**: You can now receive notifications via email, with batched digest emails and configurable team-level SMTP settings
|
||||
- **transcode**: Add VA-API hardware acceleration support for Linux hosts and Docker environments with Intel and AMD GPUs, featuring automatic DRI render node discovery, variable bitrate control, and structured transcoding observability logs
|
||||
- **transcode**: Add automatic fallback to software transcoding (libx264) when hardware-accelerated video encoding encounters GPU resolution constraints or runtime driver errors
|
||||
- **docker**: Add modular hardware-accelerated transcoding presets matching Immich's compose configuration via `hwaccel.transcoding.yaml` with support for NVENC, QuickSync, RKMPP, and VA-API
|
||||
|
||||
### Fixed
|
||||
|
||||
### Changed
|
||||
|
||||
- **transcode**: Improve video poster selection using intelligent scene detection and color variance filtering to automatically skip black frames, fade-ins, and blank intros in favor of representative video content
|
||||
- **transcode**: Optimize video sprite generation for large and long videos using a concurrent fast-seek pool and image compositing, avoiding full-video decoding while preserving instant single-pass generation for short clips
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.4.8" description="September 24, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **transcode**: Add HDR video proxy support: HDR videos automatically generate HDR video proxies and preview videos preserving HDR color characteristics, tone-mapped SDR thumbnails and posters, and automatic HDR player playback on supported displays with hardware EDR acceleration
|
||||
- **docs**: Add a Changelog section to the documentation site so users can explore release notes and updates directly in Mintlify
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Only show the center play button and darkened tint on initial video open before playback starts; once played, pausing or scrubbing back to start keeps the video canvas clean and unobstructed for review
|
||||
- **transcode**: Fix an issue where videos with orientation or rotation metadata (such as smartphone vertical videos) were incorrectly displayed with stretched aspect ratios in the video player
|
||||
- **cli**: Only manage and check PID files in daemon mode, preventing stale PID files, crash-loop conflicts, or spurious process checks during normal foreground and Docker execution
|
||||
|
||||
### Changed
|
||||
|
||||
- **transcode**: Improve video proxy visual quality and disable B-frames for smoother frame-by-frame seeking and scrubbing
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.4.7" description="September 19, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **changelog**: Introduce Keep a Changelog support, historical release summaries, and automated release notes extraction
|
||||
- **release**: Automatically populate GitHub release bodies from CHANGELOG.md and promote unreleased notes during version bumps
|
||||
- **settings**: Add FFmpeg threads slider to team media processing settings
|
||||
- **asset**: Show previews of a folder's contents and a "days left" countdown for each item in Recently Deleted
|
||||
- **asset**: Show the poster and hover preview for a video in the file list while it is still transcoding, with a gently pulsing cover (or an animated waiting circle before the poster is ready), "Uploading..."/"Preparing..." labels, and the duration hidden until it is ready
|
||||
|
||||
### Fixed
|
||||
|
||||
- **asset**: Fix an issue where moving a video to trash while it was still transcoding could cause it to lose its trashed status
|
||||
- **transcode**: Immediately stop background video processing and transcoding when a file is permanently deleted from the trash
|
||||
- **asset**: Fix proxy download filename using original file extension instead of proxy extension
|
||||
- **asset**: Fix an issue where deleting or restoring a version stack from the file list did nothing
|
||||
- **webui**: Center breadcrumb file action popup menu on the chevron icon
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.4.6" description="September 17, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **comment**: Add emoji reaction support for comments ([#405](https://github.com/shumaiOne/shumai/pull/405))
|
||||
- **premiere-uxp**: Introduce Adobe Premiere Pro UXP plugin for Shumai ([#407](https://github.com/shumaiOne/shumai/pull/407))
|
||||
- **settings**: Add team appearance setting to hide agent features ([#411](https://github.com/shumaiOne/shumai/pull/411))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **premiere-uxp**: Preserve remote cloud storage presigned URLs in asset resolution ([#408](https://github.com/shumaiOne/shumai/pull/408))
|
||||
- **premiere-uxp**: Scope sequence links by server endpoint and surface sync errors ([#409](https://github.com/shumaiOne/shumai/pull/409))
|
||||
- **api**: Enforce SHUMAI_DEMO_MODE for API token and CLI requests ([#413](https://github.com/shumaiOne/shumai/pull/413))
|
||||
|
||||
### Documentation
|
||||
|
||||
- Add NLE export and Premiere Pro UXP plugin documentation ([#412](https://github.com/shumaiOne/shumai/pull/412))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.4.5" description="September 13, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **core**: Export comments to FCP, Premiere, Media Composer, and Resolve ([#400](https://github.com/shumaiOne/shumai/pull/400))
|
||||
- **webui**: Add NLE comments export and migrate export API to POST ([#401](https://github.com/shumaiOne/shumai/pull/401))
|
||||
- **webui**: Add space key quick preview for files and folders ([#402](https://github.com/shumaiOne/shumai/pull/402))
|
||||
- **webui**: Show comments count badge in file card preview area ([#403](https://github.com/shumaiOne/shumai/pull/403))
|
||||
- **agent**: Use deterministic storage keys for preset avatars ([#404](https://github.com/shumaiOne/shumai/pull/404))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.4.4" description="September 9, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **upload**: S3 multipart upload with offline resume and wake lock ([#391](https://github.com/shumaiOne/shumai/pull/391))
|
||||
- **transcode**: Optimize video operations using ffmpeg http range requests ([#393](https://github.com/shumaiOne/shumai/pull/393))
|
||||
- **agent**: Enable read_asset tool for autofill agent ([#396](https://github.com/shumaiOne/shumai/pull/396))
|
||||
- **sandbox**: Abstract SandboxService and hot-reload allowed domains ([#398](https://github.com/shumaiOne/shumai/pull/398))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **s3**: Stream downloadToFile and putObject to prevent OOM on large files ([#392](https://github.com/shumaiOne/shumai/pull/392))
|
||||
- **agent**: Pass agent thinkingLevel to session name generation ([#395](https://github.com/shumaiOne/shumai/pull/395))
|
||||
- **agent**: Restrict pageCount and duration recommendations to matching media types ([#397](https://github.com/shumaiOne/shumai/pull/397))
|
||||
- **transcode**: Co-locate screenshots and derived artifacts in asset storage directory ([#399](https://github.com/shumaiOne/shumai/pull/399))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.4.3" description="September 6, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **asset**: Record and display agent provenance on assets and audit logs ([#380](https://github.com/shumaiOne/shumai/pull/380))
|
||||
- **agent**: Store preset avatars as real files in s3 storage ([#381](https://github.com/shumaiOne/shumai/pull/381))
|
||||
- **agent**: Add built-in image and video generation tools and settings ([#382](https://github.com/shumaiOne/shumai/pull/382))
|
||||
- **media-generation**: Add gemini-omni-1.1-flash video model and redesign settings UI ([#383](https://github.com/shumaiOne/shumai/pull/383))
|
||||
- **settings**: Redesign image/video settings to provider dialog with model toggles ([#385](https://github.com/shumaiOne/shumai/pull/385))
|
||||
- **agent**: Add asset management tools and CLI commands ([#387](https://github.com/shumaiOne/shumai/pull/387))
|
||||
- **cli**: Control asset deletion via SHUMAI_ALLOW_DELETE env var ([#388](https://github.com/shumaiOne/shumai/pull/388))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Clamp file card creation info to 2 lines and show tooltip on hover ([#390](https://github.com/shumaiOne/shumai/pull/390))
|
||||
|
||||
### Documentation
|
||||
|
||||
- **agents**: Add documentation for image and video generation settings ([#389](https://github.com/shumaiOne/shumai/pull/389))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **deps**: Upgrade bun to 1.4.2 and update packages ([#384](https://github.com/shumaiOne/shumai/pull/384))
|
||||
- **i18n**: Update paraglide-js to 2.25.0 and stop checking in generated code ([#386](https://github.com/shumaiOne/shumai/pull/386))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.4.2" description="September 3, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **chat**: Support markups, attachments, and timestamps in agent 1-to-1 chat ([#368](https://github.com/shumaiOne/shumai/pull/368))
|
||||
- **agent**: Move thread metadata to structured context XML ([#373](https://github.com/shumaiOne/shumai/pull/373))
|
||||
- **agent**: Improve timestamp precision and proxy selection for video screenshots ([#374](https://github.com/shumaiOne/shumai/pull/374))
|
||||
- **agent**: Support dynamic annotationId resolution across chat and comments ([#375](https://github.com/shumaiOne/shumai/pull/375))
|
||||
- **agent**: Consolidate media tools into read_asset and add S3 key support to download_asset ([#376](https://github.com/shumaiOne/shumai/pull/376))
|
||||
- **provider**: Optimize provider and model configuration management ([#377](https://github.com/shumaiOne/shumai/pull/377))
|
||||
- **provider**: Add provider and model sync feature with vendored generator ([#378](https://github.com/shumaiOne/shumai/pull/378))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **agent**: Set empty details in asset tool results to avoid data duplication ([#370](https://github.com/shumaiOne/shumai/pull/370))
|
||||
- **webui**: Strip styles and preserve multiline text on paste in chat input ([#371](https://github.com/shumaiOne/shumai/pull/371))
|
||||
- **agent**: Hide main comment sessions in dashboard sessions list ([#372](https://github.com/shumaiOne/shumai/pull/372))
|
||||
|
||||
### Changed
|
||||
|
||||
- **webui**: Use semantic system colors in notification settings ([#379](https://github.com/shumaiOne/shumai/pull/379))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.4.1" description="August 30, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **webui**: Add manage versions option to file card context menu ([#364](https://github.com/shumaiOne/shumai/pull/364))
|
||||
- **agent**: Refactor message context into unified shumai_message ([#365](https://github.com/shumaiOne/shumai/pull/365))
|
||||
- **webui**: Redesign comment attachment display into compact rows ([#366](https://github.com/shumaiOne/shumai/pull/366))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **asset,webui**: Disallow dropping version stacks onto files and version stacks ([#363](https://github.com/shumaiOne/shumai/pull/363))
|
||||
- **webui**: Prevent empty folder flash during initial loading ([#367](https://github.com/shumaiOne/shumai/pull/367))
|
||||
|
||||
### Changed
|
||||
|
||||
- **agent**: Remove executeAgentToolWorkflow and invoke core services directly ([#362](https://github.com/shumaiOne/shumai/pull/362))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.4.0" description="August 28, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **transcode**: Add hardware-accelerated video transcoding support ([#352](https://github.com/shumaiOne/shumai/pull/352))
|
||||
- **webui**: Truncate long file names with 100ms hover tooltip ([#355](https://github.com/shumaiOne/shumai/pull/355))
|
||||
- **webui**: Add simplified mobile-friendly layout for file and share lists ([#356](https://github.com/shumaiOne/shumai/pull/356))
|
||||
- **webui**: Add mobile friendly file detail and public share view ([#359](https://github.com/shumaiOne/shumai/pull/359))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **transcode**: Apply team hardware acceleration and source bitrate capping to watermark transcoding ([#353](https://github.com/shumaiOne/shumai/pull/353))
|
||||
- **share**: Hide and soft-delete symlinks when target assets are trashed ([#354](https://github.com/shumaiOne/shumai/pull/354))
|
||||
- **webui**: Fix breadcrumb file dropdown trigger stretching and alignment ([#360](https://github.com/shumaiOne/shumai/pull/360))
|
||||
- **webui**: Align mobile comment cards and thread vertical indicator ([#361](https://github.com/shumaiOne/shumai/pull/361))
|
||||
|
||||
### Documentation
|
||||
|
||||
- Add SECURITY.md with a private disclosure path ([#357](https://github.com/shumaiOne/shumai/pull/357))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.3.11" description="August 25, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **auth**: Add admin password reset CLI command and reset password web UI ([#347](https://github.com/shumaiOne/shumai/pull/347))
|
||||
- **project**: Add recent viewed files section to project folder tree ([#348](https://github.com/shumaiOne/shumai/pull/348))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Prevent left carousel remounting and scroll jump on file selection ([#351](https://github.com/shumaiOne/shumai/pull/351))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.3.10" description="August 23, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **agentic kanban**: Phase 1 not-agentic kanban board ([#330](https://github.com/shumaiOne/shumai/pull/330))
|
||||
- **kanban**: Resolve latest version for linked version stack assets and update demo login text ([#342](https://github.com/shumaiOne/shumai/pull/342))
|
||||
- **kanban**: Update task status permissions, reporter defaults, and participant access ([#345](https://github.com/shumaiOne/shumai/pull/345))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **kanban**: Use true thumbnail and poster for task asset previews ([#343](https://github.com/shumaiOne/shumai/pull/343))
|
||||
- **webui**: Sidebar selection styling, kanban active state, pointer cursors, and owner dashboard ([#344](https://github.com/shumaiOne/shumai/pull/344))
|
||||
- **kanban**: Improve drag-drop to column bottom, remove empty drop line, and fix timeline alignment ([#346](https://github.com/shumaiOne/shumai/pull/346))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.3.9" description="August 18, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **agent**: Add permission controls for chat agents ([#313](https://github.com/shumaiOne/shumai/pull/313))
|
||||
- **authz**: Enforce project-aware roles for agent/skill/mcp permissions ([#314](https://github.com/shumaiOne/shumai/pull/314))
|
||||
- **webui**: Use project members for asset comment mentions ([#315](https://github.com/shumaiOne/shumai/pull/315))
|
||||
- **quota**: Add 2-level database-backed resource quota system ([#318](https://github.com/shumaiOne/shumai/pull/318))
|
||||
- **settings**: Reorganize settings into personal, team, and AI sections ([#324](https://github.com/shumaiOne/shumai/pull/324))
|
||||
- **quota**: Move usage monitoring to team dashboard ([#327](https://github.com/shumaiOne/shumai/pull/327))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Preserve selected chatbot agent preference on reload ([#323](https://github.com/shumaiOne/shumai/pull/323))
|
||||
- **quota**: Exclude agents from quota rules and usage records ([#325](https://github.com/shumaiOne/shumai/pull/325))
|
||||
|
||||
### Documentation
|
||||
|
||||
- **team-settings**: Add resource quotas documentation and update readme features ([#326](https://github.com/shumaiOne/shumai/pull/326))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.3.8" description="August 15, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **webui**: Replace legacy markdown editor with new lexical wysiwyg editor ([#308](https://github.com/shumaiOne/shumai/pull/308))
|
||||
- **agent**: Add nested agents.md support across backend and webui ([#309](https://github.com/shumaiOne/shumai/pull/309))
|
||||
- **webui**: Improve AGENTS.md editor placeholder and read-only notice ([#310](https://github.com/shumaiOne/shumai/pull/310))
|
||||
- **version-stack**: Add manage versions dialog and version removal ([#311](https://github.com/shumaiOne/shumai/pull/311))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **core**: Rename latest version child record on version stack rename ([#312](https://github.com/shumaiOne/shumai/pull/312))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.3.7" description="August 14, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **metadata**: Replace aiAutofill boolean with autofillSource enum ([#302](https://github.com/shumaiOne/shumai/pull/302))
|
||||
- **agent**: Type-safe CREATION_CONTEXT metadata on create_file/create_version ([#303](https://github.com/shumaiOne/shumai/pull/303))
|
||||
- **sandbox**: Default Network Sandbox to off and add settings toggle switch ([#304](https://github.com/shumaiOne/shumai/pull/304))
|
||||
- **webui**: Redesign select metadata fields and improve long text field widget ([#305](https://github.com/shumaiOne/shumai/pull/305))
|
||||
- **agent**: Support dynamic newOption in select and selectMulti metadata fields ([#306](https://github.com/shumaiOne/shumai/pull/306))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Fix select field height and multi-select overflow/interaction issues ([#307](https://github.com/shumaiOne/shumai/pull/307))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.3.6" description="August 12, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **mcp**: Add MCP server support with proxy tool and OAuth flow ([#289](https://github.com/shumaiOne/shumai/pull/289))
|
||||
- **mcp**: Support tool-level directTools array and 3-state UI configuration ([#297](https://github.com/shumaiOne/shumai/pull/297))
|
||||
- **webui**: Direct canvas PDF rendering with selectable text ([#299](https://github.com/shumaiOne/shumai/pull/299))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **agent**: Prevent agents from accessing disabled skills ([#292](https://github.com/shumaiOne/shumai/pull/292))
|
||||
- **agent**: Resolve version stack name and size in list_assets ([#296](https://github.com/shumaiOne/shumai/pull/296))
|
||||
- **webui**: Content-only pinch-zoom and two-finger pan in media viewers ([#298](https://github.com/shumaiOne/shumai/pull/298))
|
||||
- **i18n**: Update Chinese translation for dashboard to 仪表板 ([#301](https://github.com/shumaiOne/shumai/pull/301))
|
||||
|
||||
### Documentation
|
||||
|
||||
- **mcp**: Add MCP support documentation to README and docs ([#300](https://github.com/shumaiOne/shumai/pull/300))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.3.5" description="August 9, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **transcode**: Add Gotenberg support for Office, HTML, CSV, and Markdown PDF proxies ([#283](https://github.com/shumaiOne/shumai/pull/283))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Resolve upload card freeze for unsupported files ([#284](https://github.com/shumaiOne/shumai/pull/284))
|
||||
- **webui**: Exclude file extension when selecting file name during inline rename ([#285](https://github.com/shumaiOne/shumai/pull/285))
|
||||
- Use renamed asset name in download Content-Disposition ([#286](https://github.com/shumaiOne/shumai/pull/286))
|
||||
- **webui**: Batch download no longer flashes a tab per file ([#287](https://github.com/shumaiOne/shumai/pull/287))
|
||||
- **webui**: Enable rename and delete actions in file detail top bar breadcrumb ([#288](https://github.com/shumaiOne/shumai/pull/288))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.3.4" description="August 8, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **sharelink**: Add sharelink watermark support ([#270](https://github.com/shumaiOne/shumai/pull/270))
|
||||
- **webui**: Remove original-file display fallbacks, use proxies only ([#273](https://github.com/shumaiOne/shumai/pull/273))
|
||||
- **share**: Add allow download config to share links ([#275](https://github.com/shumaiOne/shumai/pull/275))
|
||||
- **transcode**: Update preview thumbnail resolution to 300p with max length constraint ([#281](https://github.com/shumaiOne/shumai/pull/281))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **share**: Resolve symlink asset downloads in public share pages ([#274](https://github.com/shumaiOne/shumai/pull/274))
|
||||
- **webui**: Persist project sorting and prevent full page flash ([#276](https://github.com/shumaiOne/shumai/pull/276))
|
||||
|
||||
### Documentation
|
||||
|
||||
- **share-links**: Document allow download and lazy watermark settings ([#278](https://github.com/shumaiOne/shumai/pull/278))
|
||||
- **agent**: Clarify create_file/create_version context param guidance ([#282](https://github.com/shumaiOne/shumai/pull/282))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **e2e**: Watermarked download-disabled share link coverage (image + video) ([#277](https://github.com/shumaiOne/shumai/pull/277))
|
||||
- **e2e**: Stabilize watermark share spec on Firefox ([#279](https://github.com/shumaiOne/shumai/pull/279))
|
||||
- Split e2e scripts into app and webui targets ([#280](https://github.com/shumaiOne/shumai/pull/280))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.3.3" description="August 5, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **agent**: Enable LLM API call retries in AgentHarness ([#250](https://github.com/shumaiOne/shumai/pull/250))
|
||||
- **audit**: Add audit log support for APIs and WebUI dashboard ([#251](https://github.com/shumaiOne/shumai/pull/251))
|
||||
- **webui**: Persist agent preference in localStorage ([#254](https://github.com/shumaiOne/shumai/pull/254))
|
||||
- **e2e**: Add file domain comment and draw tests ([#260](https://github.com/shumaiOne/shumai/pull/260))
|
||||
- **agent**: Restrict bash access for non-owner users ([#262](https://github.com/shumaiOne/shumai/pull/262))
|
||||
- **agent**: Allow create_file tool to create files directly from content ([#263](https://github.com/shumaiOne/shumai/pull/263))
|
||||
- **agent**: Propagate autofill context from chat to autofill workflow ([#264](https://github.com/shumaiOne/shumai/pull/264))
|
||||
- **webui**: Render select options in field creation mode and pick random option color ([#265](https://github.com/shumaiOne/shumai/pull/265))
|
||||
- **project**: Include team-scoped members in project member list and add 3-section dialog layout ([#267](https://github.com/shumaiOne/shumai/pull/267))
|
||||
- **webui**: Disable role dropdown for project-scoped members in team view ([#269](https://github.com/shumaiOne/shumai/pull/269))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Mention popup avatars, keyboard auto-scroll, and non-sticky section headers ([#256](https://github.com/shumaiOne/shumai/pull/256))
|
||||
- **webui**: Persist field order on drag and drop ([#266](https://github.com/shumaiOne/shumai/pull/266))
|
||||
|
||||
### Changed
|
||||
|
||||
- **agent**: Load models directly from database without pi fallback ([#253](https://github.com/shumaiOne/shumai/pull/253))
|
||||
- **core**: Replace generated provider files with pi-ai dynamic methods ([#255](https://github.com/shumaiOne/shumai/pull/255))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **core**: Add missing tests for methods introduced in 97069042 ([#252](https://github.com/shumaiOne/shumai/pull/252))
|
||||
- **e2e**: Add domain-based auth and project web app e2e tests ([#257](https://github.com/shumaiOne/shumai/pull/257))
|
||||
- **e2e**: Add file, share, and collection web app e2e tests ([#258](https://github.com/shumaiOne/shumai/pull/258))
|
||||
- **e2e**: Add project-level invite and file-move e2e tests ([#259](https://github.com/shumaiOne/shumai/pull/259))
|
||||
- **e2e**: Add search in file list and save-search-as-collection cases ([#261](https://github.com/shumaiOne/shumai/pull/261))
|
||||
- **e2e**: Add member permission change tests ([#268](https://github.com/shumaiOne/shumai/pull/268))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.3.2" description="July 30, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **agent**: Add output truncation and streaming limits to sandboxed bash tool ([#248](https://github.com/shumaiOne/shumai/pull/248))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **agent**: Download original document asset instead of pdf proxy ([#247](https://github.com/shumaiOne/shumai/pull/247))
|
||||
- **webui**: Persist chatbot sidebar input text across route navigation ([#249](https://github.com/shumaiOne/shumai/pull/249))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.3.1" description="July 30, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **transcode**: Trigger ai metadata autofill post transcode ([#234](https://github.com/shumaiOne/shumai/pull/234))
|
||||
- **dashboard**: Add agent sessions view for team owners ([#237](https://github.com/shumaiOne/shumai/pull/237))
|
||||
- **db**: Preserve agent sessions on asset deletion by setting onDelete to SetNull ([#240](https://github.com/shumaiOne/shumai/pull/240))
|
||||
- **agent**: Add download_asset tool and prompt instructions ([#242](https://github.com/shumaiOne/shumai/pull/242))
|
||||
- **db**: Update Asset.sizeByte and AiUsage token fields to BigInt ([#244](https://github.com/shumaiOne/shumai/pull/244))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **agent**: Include select option labels and field name in autofill schema ([#235](https://github.com/shumaiOne/shumai/pull/235))
|
||||
- **agent**: Scope agent comment sessions to thread sessions anchored at root comments ([#239](https://github.com/shumaiOne/shumai/pull/239))
|
||||
- **agent**: Disable tools for session naming and make naming non-blocking ([#241](https://github.com/shumaiOne/shumai/pull/241))
|
||||
- **webui**: Update file size formatting to SI decimal standard ([#245](https://github.com/shumaiOne/shumai/pull/245))
|
||||
- **s3**: Enforce property syntax in S3Service interface and fix ReadableStream handling in S3StorageService ([#246](https://github.com/shumaiOne/shumai/pull/246))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.3.0" description="July 28, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **file-browser**: Add copy name and path option to context menu ([#225](https://github.com/shumaiOne/shumai/pull/225))
|
||||
- **agent**: Inject user name and role into chat context ([#226](https://github.com/shumaiOne/shumai/pull/226))
|
||||
- **agent**: Refactor database session storage to normalized DAG entries and lazy thread sync ([#229](https://github.com/shumaiOne/shumai/pull/229))
|
||||
- **agent**: Support ENABLE_WEAKER_NESTED_SANDBOX environment variable ([#233](https://github.com/shumaiOne/shumai/pull/233))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **agent**: Ensure atomic appendEntry and persist leaf entries in DatabaseSessionStorage ([#224](https://github.com/shumaiOne/shumai/pull/224))
|
||||
- Sharp version mismatch bug ([#230](https://github.com/shumaiOne/shumai/pull/230))
|
||||
- **agent**: Resolve S3 MIME type detection and prompt parameter in image analysis ([#232](https://github.com/shumaiOne/shumai/pull/232))
|
||||
|
||||
### Changed
|
||||
|
||||
- **agent**: Remove implicit agent mention trigger in comment threads ([#227](https://github.com/shumaiOne/shumai/pull/227))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **workflow**: Add docker compose deployment verification job ([#231](https://github.com/shumaiOne/shumai/pull/231))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.2.3" description="July 25, 2026">
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Show right sidebar by default on file detail page ([#219](https://github.com/shumaiOne/shumai/pull/219))
|
||||
- **webui**: Refresh file list and detail when agent executes asset creation tools ([#220](https://github.com/shumaiOne/shumai/pull/220))
|
||||
- **webui**: Fix space key drag overlay and shift range selection for version stacks ([#221](https://github.com/shumaiOne/shumai/pull/221))
|
||||
- **transcode**: Handle timestamp rounding tolerance for screenshot annotations ([#223](https://github.com/shumaiOne/shumai/pull/223))
|
||||
|
||||
### Changed
|
||||
|
||||
- **e2e**: Split transcode workflow E2E tests into per-workflow test files ([#222](https://github.com/shumaiOne/shumai/pull/222))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.2.2" description="July 23, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **webui**: Integrate AI usage API into dashboard page ([#216](https://github.com/shumaiOne/shumai/pull/216))
|
||||
- **ai-usage**: Add team and member token usage tracking and APIs ([#215](https://github.com/shumaiOne/shumai/pull/215))
|
||||
- **transcode**: Add PSD support via ImageMagick and enforce sRGB conversion ([#217](https://github.com/shumaiOne/shumai/pull/217))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **search**: Fix buildSqlCondition date range, numeric metadata, and string parsing bugs ([#213](https://github.com/shumaiOne/shumai/pull/213))
|
||||
- **webui**: Prevent horizontal overflow in search dialog result rows ([#214](https://github.com/shumaiOne/shumai/pull/214))
|
||||
- **webui**: Invalidate upload tasks query when upload task starts and completes ([#218](https://github.com/shumaiOne/shumai/pull/218))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.2.1" description="July 22, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **skill**: Add team owner skill permission control ([#209](https://github.com/shumaiOne/shumai/pull/209))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **agent**: Handle non-builtin models in getModelFromDb and upgrade pi-ai ([#211](https://github.com/shumaiOne/shumai/pull/211))
|
||||
- **provider**: Preserve model ids on provider update ([#212](https://github.com/shumaiOne/shumai/pull/212))
|
||||
|
||||
### Changed
|
||||
|
||||
- **core**: Split generated providers into per-provider files ([#210](https://github.com/shumaiOne/shumai/pull/210))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.2.0" description="July 21, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **transcode**: Add PDF preview, sprite generation, and annotation support ([#193](https://github.com/shumaiOne/shumai/pull/193))
|
||||
- **web**: Register pdf.worker route in production ([#195](https://github.com/shumaiOne/shumai/pull/195))
|
||||
- **agent**: Add read_pdf_pages tool and PDF page context support ([#196](https://github.com/shumaiOne/shumai/pull/196))
|
||||
- **transcode**: Split monolithic transcodeMedia into focused workflows ([#197](https://github.com/shumaiOne/shumai/pull/197))
|
||||
- **transcode**: Add PDF proxy support for TXT and CSV files ([#199](https://github.com/shumaiOne/shumai/pull/199))
|
||||
- **asset**: Replace mediaType/mimeType logic with proxyType ([#200](https://github.com/shumaiOne/shumai/pull/200))
|
||||
- **docker**: Install fonts-noto-cjk in runner stage ([#202](https://github.com/shumaiOne/shumai/pull/202))
|
||||
- **transcode**: Add markdown file to pdf proxy support ([#203](https://github.com/shumaiOne/shumai/pull/203))
|
||||
- **chat**: Track context asset changes and update agent context ([#204](https://github.com/shumaiOne/shumai/pull/204))
|
||||
- **agent**: Refactor media tools to static injection with mandatory assetId and authz ([#208](https://github.com/shumaiOne/shumai/pull/208))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **transcode**: Mark pdfkit as external and extract for docker runtime ([#201](https://github.com/shumaiOne/shumai/pull/201))
|
||||
- **agent**: Include skill id in formatSkillsForPrompt ([#205](https://github.com/shumaiOne/shumai/pull/205))
|
||||
- **asset**: Exclude soft-deleted children from latestChildren preview ([#206](https://github.com/shumaiOne/shumai/pull/206))
|
||||
- **agent**: Pass latest version asset from version stack to prompt builder ([#207](https://github.com/shumaiOne/shumai/pull/207))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.1.10" description="July 16, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **workflow-e2e**: Add E2E tests for agentAutofillMedia workflow ([#188](https://github.com/shumaiOne/shumai/pull/188))
|
||||
- **comments**: Support comment deletion and video player shortcuts ([#191](https://github.com/shumaiOne/shumai/pull/191))
|
||||
- **agent**: Support disabling specific tools for agents ([#192](https://github.com/shumaiOne/shumai/pull/192))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **e2e**: Add E2E workflow tests for remaining agent and transcode services ([#189](https://github.com/shumaiOne/shumai/pull/189))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.1.9" description="July 14, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **e2e**: Set up fullstack app-level e2e test framework and signup test case ([#184](https://github.com/shumaiOne/shumai/pull/184))
|
||||
- **chat**: Chatbot UI ([#185](https://github.com/shumaiOne/shumai/pull/185))
|
||||
- **agent**: Support aborting agent execution ([#186](https://github.com/shumaiOne/shumai/pull/186))
|
||||
|
||||
### Changed
|
||||
|
||||
- **api/chat**: Remove direct Prisma query from API layer ([#187](https://github.com/shumaiOne/shumai/pull/187))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.1.8" description="July 10, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **chatbot**: Implement type-safe Chat APIs with compaction support ([#180](https://github.com/shumaiOne/shumai/pull/180))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Enable build splitting and code-split all page routes ([#183](https://github.com/shumaiOne/shumai/pull/183))
|
||||
|
||||
### Documentation
|
||||
|
||||
- **readme**: Clarify displayed file size represents original file size ([#182](https://github.com/shumaiOne/shumai/pull/182))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.1.7" description="July 6, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **audio**: Support frame-accurate audio playback, comments, and AI safeguards ([#175](https://github.com/shumaiOne/shumai/pull/175))
|
||||
- **i18n**: Localize members dialog, notifications, uploads, user menus, dates, and players ([#178](https://github.com/shumaiOne/shumai/pull/178))
|
||||
- **comments**: Allow marking comments as complete or incomplete ([#179](https://github.com/shumaiOne/shumai/pull/179))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **upload**: Resolve empty and generic MIME types in confirmFileUpload ([#176](https://github.com/shumaiOne/shumai/pull/176))
|
||||
|
||||
### Changed
|
||||
|
||||
- **webui**: Modularize file viewer components into registry-driven architecture ([#174](https://github.com/shumaiOne/shumai/pull/174))
|
||||
|
||||
### Documentation
|
||||
|
||||
- Improve documentation and examples for S3 compatible storage ([#177](https://github.com/shumaiOne/shumai/pull/177))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.1.6" description="July 4, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **file-browser**: Show video duration on file card preview ([#170](https://github.com/shumaiOne/shumai/pull/170))
|
||||
- **webui**: Compare versions view for version stacks ([#171](https://github.com/shumaiOne/shumai/pull/171))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Resolve conditional hooks and setState-in-render errors ([#167](https://github.com/shumaiOne/shumai/pull/167))
|
||||
- **webui**: Resolve video player total frames mismatch ([#172](https://github.com/shumaiOne/shumai/pull/172))
|
||||
- **version-stack**: Resolve correct latest version ID of version stack ([#173](https://github.com/shumaiOne/shumai/pull/173))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **webui**: Video player e2e framework + Safari playhead fix ([#166](https://github.com/shumaiOne/shumai/pull/166))
|
||||
- **webui**: Add frame-accurate comment seek roundtrip e2e ([#168](https://github.com/shumaiOne/shumai/pull/168))
|
||||
- **webui**: Verify video player restarts playback after end ([#169](https://github.com/shumaiOne/shumai/pull/169))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.1.5" description="July 2, 2026">
|
||||
|
||||
### Changed
|
||||
|
||||
- **storage**: Use original filenames for stored files ([#165](https://github.com/shumaiOne/shumai/pull/165))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **release**: Add Aliyun ACR push to release workflow ([#164](https://github.com/shumaiOne/shumai/pull/164))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.1.4" description="July 1, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **transcode**: Change video poster resolution to 480p ([#161](https://github.com/shumaiOne/shumai/pull/161))
|
||||
- **auth**: Allow setting user locale on signup ([#163](https://github.com/shumaiOne/shumai/pull/163))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Preserve video ended state by skipping playhead snap on ended ([#162](https://github.com/shumaiOne/shumai/pull/162))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.1.3" description="June 30, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **webui**: Add i18n support using paraglide-js ([#156](https://github.com/shumaiOne/shumai/pull/156))
|
||||
- **video**: Add frame-accurate video player, SMPTE timecodes, and format switcher ([#157](https://github.com/shumaiOne/shumai/pull/157))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Align video timeline duration and formatting with frameio ([#158](https://github.com/shumaiOne/shumai/pull/158))
|
||||
- **webui**: Fix missing left sidebar for nested folders ([#159](https://github.com/shumaiOne/shumai/pull/159))
|
||||
- **api**: Fix update team settings and make request schema type-safe ([#160](https://github.com/shumaiOne/shumai/pull/160))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.1.2" description="June 25, 2026">
|
||||
|
||||
### Changed
|
||||
|
||||
- **s3**: Remove automatic port appending to AWS_ENDPOINT_URL_S3 ([#155](https://github.com/shumaiOne/shumai/pull/155))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.1.1" description="June 23, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **docker**: Add root entrypoint with privilege dropping for data volumes ([#151](https://github.com/shumaiOne/shumai/pull/151))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.1.0" description="June 22, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **share**: Secure share info API and fix wrong password feedback ([#150](https://github.com/shumaiOne/shumai/pull/150))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Truncate long folder, collection, and share link names in sidebar ([#149](https://github.com/shumaiOne/shumai/pull/149))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.0.11" description="June 22, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **cli**: Add shumai-cli and token authentication ([#144](https://github.com/shumaiOne/shumai/pull/144))
|
||||
- **settings**: Use singular headers and remove collapse/counters for single agent types ([#145](https://github.com/shumaiOne/shumai/pull/145))
|
||||
- **folders**: Auto expand folder tree in left sidebar on navigation ([#146](https://github.com/shumaiOne/shumai/pull/146))
|
||||
- **metadata**: Add single user and multiple user custom fields ([#147](https://github.com/shumaiOne/shumai/pull/147))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **cli**: Rename npm package to @shumai-one/shumai-cli ([#148](https://github.com/shumaiOne/shumai/pull/148))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.0.10" description="June 21, 2026">
|
||||
|
||||
### Changed
|
||||
|
||||
- **web**: Dynamically register production HTML bundle routes ([#142](https://github.com/shumaiOne/shumai/pull/142))
|
||||
|
||||
### Documentation
|
||||
|
||||
- **readme**: Polish structure, correct grammar, and add dependencies table ([#143](https://github.com/shumaiOne/shumai/pull/143))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.0.9" description="June 20, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **webui**: Show app version in avatar menu ([#139](https://github.com/shumaiOne/shumai/pull/139))
|
||||
- **cli**: Add background daemonization and subcommands ([#141](https://github.com/shumaiOne/shumai/pull/141))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- **release**: Add smoke tests to local release stage ([#140](https://github.com/shumaiOne/shumai/pull/140))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.0.8" description="June 19, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **api**: Implement read-only mode for reviewers ([#122](https://github.com/shumaiOne/shumai/pull/122))
|
||||
- **server**: Allow customizing server port via SHUMAI_SERVER_PORT ([#124](https://github.com/shumaiOne/shumai/pull/124))
|
||||
- **embedding**: Defer embedding workflow, use transcoded assets, and execute chunks in separate activities ([#125](https://github.com/shumaiOne/shumai/pull/125))
|
||||
- **webui**: Add external drag-and-drop file and folder upload support ([#126](https://github.com/shumaiOne/shumai/pull/126))
|
||||
- **agent**: Implement overlapping video chunks for semantic search ([#127](https://github.com/shumaiOne/shumai/pull/127))
|
||||
- **webui**: Support jumping to video timestamp from search results ([#128](https://github.com/shumaiOne/shumai/pull/128))
|
||||
- **auth**: Add demo mode support ([#131](https://github.com/shumaiOne/shumai/pull/131))
|
||||
- **auth**: Refine demo mode support ([#132](https://github.com/shumaiOne/shumai/pull/132))
|
||||
- **webui**: Default right sidebar to collapsed for new users ([#133](https://github.com/shumaiOne/shumai/pull/133))
|
||||
- **webui**: Use Shadcn Switch in toggle field and Rating component in search filter panel ([#137](https://github.com/shumaiOne/shumai/pull/137))
|
||||
- **upload**: Track byte-level progress with XMLHttpRequest ([#138](https://github.com/shumaiOne/shumai/pull/138))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **transcode**: Handle high-precision FPS using rational fractions ([#123](https://github.com/shumaiOne/shumai/pull/123))
|
||||
- **db**: Automatically update project updatedAt on asset modification ([#129](https://github.com/shumaiOne/shumai/pull/129))
|
||||
- **webui**: Use system colors for fields and improve search filter select options ([#130](https://github.com/shumaiOne/shumai/pull/130))
|
||||
- **search**: Fix hasAny and hasNone operators on metadata filter ([#134](https://github.com/shumaiOne/shumai/pull/134))
|
||||
- **webui**: Resolve folder tree sync, search dialog reset, and sidebar actions issues ([#136](https://github.com/shumaiOne/shumai/pull/136))
|
||||
|
||||
### Changed
|
||||
|
||||
- **webui**: Fix search dialog layout height, scroll areas, and restrict filter toggle click ([#135](https://github.com/shumaiOne/shumai/pull/135))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.0.7" description="June 17, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **workflow**: Configure transcode and agent concurrency via environment variables ([#116](https://github.com/shumaiOne/shumai/pull/116))
|
||||
- **webui**: Replace hardcoded colors with system tokens ([#119](https://github.com/shumaiOne/shumai/pull/119))
|
||||
- **webui**: Replace native overflow with shadcn ScrollArea in settings ([#120](https://github.com/shumaiOne/shumai/pull/120))
|
||||
- **api**: Use enum for API protocol in provider config ([#121](https://github.com/shumaiOne/shumai/pull/121))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **webui**: Reload video player and reset state when switching assets ([#114](https://github.com/shumaiOne/shumai/pull/114))
|
||||
|
||||
### Changed
|
||||
|
||||
- **transcode**: Relocate TranscodeService to core and flatten API package ([#115](https://github.com/shumaiOne/shumai/pull/115))
|
||||
|
||||
### Documentation
|
||||
|
||||
- Improve and restructure shumai documentation ([#118](https://github.com/shumaiOne/shumai/pull/118))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.0.6" description="June 15, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **sandbox**: Add pending domains support for network sandbox ([#109](https://github.com/shumaiOne/shumai/pull/109))
|
||||
- **webui**: Always show right sidebar and implement left vertical carousel ([#111](https://github.com/shumaiOne/shumai/pull/111))
|
||||
|
||||
### Fixed
|
||||
|
||||
- **build**: Propagate termination signals to active child process in wrappers ([#102](https://github.com/shumaiOne/shumai/pull/102))
|
||||
- **transcode**: Make deterministic transcode activity failures non-retryable in Temporal ([#104](https://github.com/shumaiOne/shumai/pull/104))
|
||||
- **player**: Implement seekbar dragging and match hover highlight color ([#108](https://github.com/shumaiOne/shumai/pull/108))
|
||||
- **webui**: Avoid refetching all pages on file/folder reorder ([#112](https://github.com/shumaiOne/shumai/pull/112))
|
||||
- **webui**: Force video-player mime type to video/mp4 ([#113](https://github.com/shumaiOne/shumai/pull/113))
|
||||
|
||||
### Changed
|
||||
|
||||
- **webui**: Use system color design tokens in video player components ([#106](https://github.com/shumaiOne/shumai/pull/106))
|
||||
- **webui**: Use requestAnimationFrame for smooth video progress bar updates ([#107](https://github.com/shumaiOne/shumai/pull/107))
|
||||
- **webui**: Fetch agents in mention input list dynamically ([#110](https://github.com/shumaiOne/shumai/pull/110))
|
||||
|
||||
### Documentation
|
||||
|
||||
- **readme**: Add comprehensive README.md ([#103](https://github.com/shumaiOne/shumai/pull/103))
|
||||
- **readme**: Improve remote deployment and temporal execution instructions ([#105](https://github.com/shumaiOne/shumai/pull/105))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.0.5" description="June 13, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **npm**: Auto deploy database migrations on package start ([#101](https://github.com/shumaiOne/shumai/pull/101))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.0.4" description="June 12, 2026">
|
||||
|
||||
### Fixed
|
||||
|
||||
- **cli/docker**: Resolve global CLI external dependencies and fix Docker 404 error ([#100](https://github.com/shumaiOne/shumai/pull/100))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.0.3" description="June 12, 2026">
|
||||
|
||||
### Fixed
|
||||
|
||||
- **cli**: Resolve platform binary path resolution under nested node_modules ([#99](https://github.com/shumaiOne/shumai/pull/99))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.0.2" description="June 12, 2026">
|
||||
|
||||
### Fixed
|
||||
|
||||
- **npm**: Add repository metadata to package.json for provenance verification ([#98](https://github.com/shumaiOne/shumai/pull/98))
|
||||
|
||||
### Maintenance
|
||||
|
||||
- Add release-npm.yaml workflow ([#97](https://github.com/shumaiOne/shumai/pull/97))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.0.1" description="June 12, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- Initial release of Shumai
|
||||
|
||||
</Update>
|
||||
@@ -24,12 +24,13 @@ Shumai is configured via environment variables. You can define these variables i
|
||||
|
||||
---
|
||||
|
||||
## Authentication Config
|
||||
## Authentication & Application 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) |
|
||||
| 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 and notification email links fallback. | `http://localhost:3000` (respects `SHUMAI_SERVER_PORT` fallback) |
|
||||
| `APP_URL` | The public URL of the web application. Used for notification email deep links (falls back to `BETTER_AUTH_URL`). | `https://shumai.example.com` |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
---
|
||||
title: Hardware Transcoding
|
||||
description: Accelerate video transcoding and reduce CPU load with GPU hardware acceleration.
|
||||
---
|
||||
|
||||
High-resolution camera recordings, phone videos, and animation media files require proxy transcoding to play smoothly in web browsers. Shumai transcodes these assets in the background, generating a universal `180p` proxy for instant scrubbing alongside full-resolution preview streams.
|
||||
|
||||
Hardware-accelerated transcoding allows you to offload video encoding to a dedicated or integrated GPU, dramatically speeding up processing and freeing host CPU cores for other services.
|
||||
|
||||
Shumai includes a built-in usability probe that tests hardware encoders at startup, alongside automatic runtime fallback during video processing. If GPU drivers or device nodes are unavailable, or if a hardware encoder encounters hardware limits (such as resolution or dimension constraints on certain GPUs) or runtime driver errors, Shumai seamlessly falls back to software encoding (`libx264`) without failing user tasks.
|
||||
|
||||
---
|
||||
|
||||
## Supported Backends
|
||||
|
||||
| Backend | Hardware Platform | Container Driver / Devices |
|
||||
| :-------------- | :--------------------------------- | :----------------------------------------------- |
|
||||
| **`nvenc`** | NVIDIA GPUs | NVIDIA Container Toolkit (`gpu, compute, video`) |
|
||||
| **`quicksync`** | Intel Integrated & Arc GPUs | `/dev/dri` render nodes |
|
||||
| **`vaapi`** | AMD & Intel GPUs | `/dev/dri` render nodes |
|
||||
| **`rkmpp`** | Rockchip ARM SoCs (e.g. RK3588) | `/dev/rga`, `/dev/dri`, `/dev/mpp_service` |
|
||||
| **`vaapi-wsl`** | Windows Subsystem for Linux (WSL2) | `/dev/dri`, `/dev/dxg`, `/usr/lib/wsl` |
|
||||
|
||||
---
|
||||
|
||||
## Limitations
|
||||
|
||||
- The instructions on this page focus on **Docker Compose**. Other container orchestrators (such as Kubernetes or Podman) require equivalent device passthrough configurations.
|
||||
- **Docker Desktop on macOS** runs inside a Linux virtual machine and does not support Apple Silicon VideoToolbox passthrough. (VideoToolbox hardware acceleration is supported when running Shumai natively via NPM or from source).
|
||||
- Hardware transcoding produces slightly different bitrate characteristics compared to software encoding. Shumai uses adaptive variable bitrate (VBR) rate control tailored to web streaming to maintain visual fidelity.
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
### NVENC (NVIDIA)
|
||||
|
||||
1. Ensure the official NVIDIA graphics driver is installed on the host:
|
||||
```bash
|
||||
nvidia-smi
|
||||
```
|
||||
2. Install the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html) on the host and restart Docker:
|
||||
```bash
|
||||
sudo apt-get install -y nvidia-container-toolkit
|
||||
sudo nvidia-ctk runtime configure --runtime=docker
|
||||
sudo systemctl restart docker
|
||||
```
|
||||
|
||||
### QuickSync & VA-API (Intel / AMD)
|
||||
|
||||
1. Verify that the Linux kernel has initialized the Direct Rendering Infrastructure (DRI) render node:
|
||||
```bash
|
||||
ls -la /dev/dri
|
||||
```
|
||||
You should see `card0` and `renderD128` (or similar).
|
||||
2. Shumai's Docker image automatically adjusts group permissions on container startup so the non-root application user can access host `/dev/dri` devices without permission errors.
|
||||
|
||||
### WSL2 (Windows)
|
||||
|
||||
- Ensure you are running Windows 11 with WSL2 and have installed the appropriate GPU drivers on the Windows host.
|
||||
- Use the `vaapi-wsl` preset which maps `/dev/dxg` and `/usr/lib/wsl` into the container.
|
||||
|
||||
---
|
||||
|
||||
## Setup with Docker Compose
|
||||
|
||||
Shumai uses a modular `hwaccel.transcoding.yaml` companion file to configure hardware devices.
|
||||
|
||||
### Step 1: Download Configuration Files
|
||||
|
||||
In your Shumai deployment directory, download the companion `hwaccel.transcoding.yaml` alongside `docker-compose.yaml`:
|
||||
|
||||
```bash
|
||||
# Global / Official
|
||||
curl -o hwaccel.transcoding.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/hwaccel.transcoding.yaml
|
||||
|
||||
# Accelerated Mirror (Mainland China)
|
||||
curl -o hwaccel.transcoding.yaml https://gh-proxy.com/https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/hwaccel.transcoding.yaml
|
||||
```
|
||||
|
||||
### Step 2: Enable Hardware Acceleration in Docker Compose
|
||||
|
||||
Open `docker-compose.yaml` (or `docker-compose-aliyun.yaml`), find the commented `extends` block under the `shumai` service, and uncomment it:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
shumai:
|
||||
# ...
|
||||
# Hardware Acceleration (NVENC / QuickSync / VA-API / RKMPP)
|
||||
extends:
|
||||
file: hwaccel.transcoding.yaml
|
||||
service: nvenc # set to one of [nvenc, quicksync, rkmpp, vaapi, vaapi-wsl]
|
||||
```
|
||||
|
||||
Replace `nvenc` with your target backend:
|
||||
|
||||
- `nvenc` for NVIDIA GPUs
|
||||
- `quicksync` for Intel Quick Sync
|
||||
- `vaapi` for AMD or Intel VA-API
|
||||
- `rkmpp` for Rockchip SoCs
|
||||
- `vaapi-wsl` for WSL2 on Windows
|
||||
|
||||
### Step 3: Start the Stack
|
||||
|
||||
Restart or recreate the Shumai container:
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Single Compose File Setup (Unraid / Portainer)
|
||||
|
||||
If your environment or container manager does not support multi-file `extends`, you can inline the hardware configuration directly into the `shumai` service in `docker-compose.yaml`:
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="NVIDIA NVENC">
|
||||
```yaml
|
||||
services:
|
||||
shumai:
|
||||
# ...
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: 1
|
||||
capabilities:
|
||||
- gpu
|
||||
- compute
|
||||
- video
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Intel QuickSync / AMD VA-API">
|
||||
```yaml services: shumai: # ... devices: - /dev/dri:/dev/dri ```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="WSL2 (Windows)">
|
||||
```yaml services: shumai: # ... devices: - /dev/dri:/dev/dri - /dev/dxg:/dev/dxg volumes: -
|
||||
/usr/lib/wsl:/usr/lib/wsl environment: - LIBVA_DRIVER_NAME=d3d12 ```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Rockchip RKMPP">
|
||||
```yaml
|
||||
services:
|
||||
shumai:
|
||||
# ...
|
||||
security_opt:
|
||||
- systempaths=unconfined
|
||||
- apparmor=unconfined
|
||||
group_add:
|
||||
- video
|
||||
devices:
|
||||
- /dev/rga:/dev/rga
|
||||
- /dev/dri:/dev/dri
|
||||
- /dev/dma_heap:/dev/dma_heap
|
||||
- /dev/mpp_service:/dev/mpp_service
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
---
|
||||
|
||||
## Web UI Settings
|
||||
|
||||
In the Shumai Web UI, navigate to **Team Settings** > **Transcoding Settings**.
|
||||
|
||||
- **Auto (Recommended)**: Shumai automatically probes candidate hardware encoders in optimal order (`h264_nvenc` → `h264_vaapi` → `h264_qsv` → `h264_amf` → `libx264`). If hardware acceleration is unavailable, it gracefully uses software encoding.
|
||||
- **Explicit Encoder**: You can pin the transcode pipeline to a specific encoder (e.g. `NVENC`, `Quick Sync`, `VA-API`).
|
||||
- **Off**: Forces CPU software encoding (`libx264`) for all video jobs.
|
||||
|
||||
---
|
||||
|
||||
## Verification & Monitoring
|
||||
|
||||
### Check Transcode Logs
|
||||
|
||||
When video transcoding begins on an uploaded asset, Shumai writes a structured log indicating the chosen encoder:
|
||||
|
||||
```bash
|
||||
docker compose logs -f shumai
|
||||
```
|
||||
|
||||
Look for the `Starting video transcoding` log entry:
|
||||
|
||||
```json
|
||||
{
|
||||
"level": 30,
|
||||
"time": 1790414665096,
|
||||
"encoder": "h264_nvenc",
|
||||
"hardwareAcceleration": "auto",
|
||||
"inputFile": "/tmp/transcode-.../video.mp4",
|
||||
"outputFile": "/tmp/transcode-.../video-180p.mp4",
|
||||
"msg": "Starting video transcoding"
|
||||
}
|
||||
```
|
||||
|
||||
If hardware acceleration was successfully initialized, `encoder` will show `h264_nvenc`, `h264_vaapi`, or `h264_qsv`.
|
||||
|
||||
### Monitor GPU Utilization
|
||||
|
||||
While transcoding a video, you can observe hardware utilization on the host:
|
||||
|
||||
- **NVIDIA**:
|
||||
```bash
|
||||
nvidia-smi
|
||||
# or
|
||||
nvtop
|
||||
```
|
||||
- **Intel**:
|
||||
```bash
|
||||
sudo intel_gpu_top
|
||||
```
|
||||
- **AMD**:
|
||||
```bash
|
||||
sudo radeontop
|
||||
```
|
||||
+14
-1
@@ -12,6 +12,14 @@
|
||||
"light": "#F5B895",
|
||||
"dark": "#A8384D"
|
||||
},
|
||||
"navbar": {
|
||||
"links": [
|
||||
{
|
||||
"label": "Changelog",
|
||||
"href": "/changelog"
|
||||
}
|
||||
]
|
||||
},
|
||||
"navigation": {
|
||||
"groups": [
|
||||
{
|
||||
@@ -57,16 +65,21 @@
|
||||
"pages": [
|
||||
"using-shumai/transcode-settings",
|
||||
"using-shumai/quotas-settings",
|
||||
"using-shumai/email-notifications",
|
||||
"using-shumai/password-reset"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Configuration",
|
||||
"pages": ["configuration/env-variables"]
|
||||
"pages": ["configuration/env-variables", "configuration/hardware-transcoding"]
|
||||
},
|
||||
{
|
||||
"group": "Temporal Deployment",
|
||||
"pages": ["configuration/temporal"]
|
||||
},
|
||||
{
|
||||
"group": "Releases",
|
||||
"pages": ["changelog"]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -12,9 +12,14 @@ We support three installation options. For most administrators, **Docker Compose
|
||||
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
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> **Hardware Acceleration:** By default, the standard Compose stack uses CPU-based software transcoding. If your server has a dedicated or integrated GPU (NVIDIA, Intel, AMD, or Rockchip), see the [Hardware Transcoding Guide](/configuration/hardware-transcoding) to enable GPU acceleration via the companion `hwaccel.transcoding.yaml`.
|
||||
|
||||
2. **Start the Services**:
|
||||
```bash
|
||||
docker compose up -d
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
---
|
||||
title: Email Notifications
|
||||
description: Configure team SMTP settings, deliver batched activity digest emails, and send test emails.
|
||||
---
|
||||
|
||||
Shumai includes a built-in email notification system that delivers updates on team activities—such as comments, mentions, new asset uploads, status changes, and Kanban tasks—directly to team members' inboxes.
|
||||
|
||||
To prevent inbox clutter and notification fatigue, Shumai does not send emails for every single action individually. Instead, a background delivery service aggregates pending notifications and sends periodic, batched digest emails with inline thumbnails and deep links.
|
||||
|
||||
---
|
||||
|
||||
## Configuring SMTP Settings
|
||||
|
||||
Email notification settings are managed at the team level by **Team Owners**.
|
||||
|
||||
To configure outgoing mail:
|
||||
|
||||
1. Click on **Team Settings** in the sidebar.
|
||||
2. Select the **Email Notifications** tab.
|
||||
3. Turn on the **Enable Email Notifications** switch.
|
||||
4. Fill in your SMTP server credentials and sender information.
|
||||
5. Click **Save** or **Save and Send Test Email**.
|
||||
|
||||
### SMTP Server Settings
|
||||
|
||||
| Field | Description | Example / Default |
|
||||
| :---------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------- |
|
||||
| **SMTP Host** | The hostname or IP address of your outgoing SMTP server. | `smtp.example.com` or `smtp.sendgrid.net` |
|
||||
| **SMTP Port** | The port used to connect to your SMTP server. | `587` (default, STARTTLS), `465` (SSL/TLS), or `25` |
|
||||
| **Username** | The username or API key required to authenticate with the SMTP server. | `user@example.com` or `apikey` |
|
||||
| **Password** | The authentication password or API secret. | `••••••••` |
|
||||
| **SSL / TLS (SMTPS)** | Connect directly using SSL/TLS encryption. Typically required when connecting over port `465`. | `Disabled` (default) |
|
||||
| **Ignore Certificate Errors** | Allows connections with self-signed, invalid, or unverified TLS certificates. Useful for local testing (e.g. Mailpit, MailHog) or private corporate relays. | `Disabled` (default) |
|
||||
|
||||
> [!TIP]
|
||||
> **Password Retention**: When updating existing email settings, you can leave the password input blank to keep the currently stored password. For security, stored passwords are never returned in cleartext to the client.
|
||||
|
||||
### Sender Information
|
||||
|
||||
| Field | Description | Example / Default |
|
||||
| :----------- | :-------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------- |
|
||||
| **From** | The sender name and email address that will appear in the `From` header. Ensure your SMTP provider is authorized to send on behalf of this address. | `Shumai <noreply@example.com>` |
|
||||
| **Reply-To** | _(Optional)_ An email address to receive replies if members respond directly to a notification email. | `support@example.com` |
|
||||
|
||||
---
|
||||
|
||||
## Testing SMTP Delivery
|
||||
|
||||
Before relying on email delivery, you can verify your configuration and credentials directly from the settings page:
|
||||
|
||||
1. Click **Save and Send Test Email**.
|
||||
2. In the **Send Test Email** modal, verify or adjust the sender `From` address.
|
||||
3. Click **Send Test Email**.
|
||||
|
||||
Shumai will perform an active handshake verification (`transport.verify()`) against your SMTP server and dispatch a styled test message to the email address of the currently logged-in administrator.
|
||||
|
||||
If the handshake or delivery fails (for example, due to an invalid password, blocked outbound port, or rejected sender address), an error toast is displayed with the exact message returned by the SMTP server.
|
||||
|
||||
---
|
||||
|
||||
## Delivery Architecture & Digest Batching
|
||||
|
||||
Shumai uses an asynchronous, batched architecture for email delivery:
|
||||
|
||||
```
|
||||
[ Team Activity ]
|
||||
(Comments, Uploads, Mentions, Kanban)
|
||||
│
|
||||
▼
|
||||
[ Database Queue ] (status: pending)
|
||||
│
|
||||
▼ (Every 3 minutes)
|
||||
[ Notification Background Job ]
|
||||
│
|
||||
├─ Filter recipients (check user preferences & project scope)
|
||||
├─ Exclude self-actions and AI agents
|
||||
├─ Group & collapse items (clusters > 3 summarized)
|
||||
├─ Fetch avatars & thumbnails as inline CID attachments
|
||||
│
|
||||
▼
|
||||
[ Nodemailer Transport ] ──> SMTP Server ──> [ Member Inboxes ]
|
||||
```
|
||||
|
||||
### 1. Periodic Background Delivery
|
||||
|
||||
Notifications are queued in PostgreSQL with a `pending` status. A background job runs periodically every **3 minutes**, acquiring pending notifications using atomic queue locking (`FOR UPDATE SKIP LOCKED`). This ensures safe delivery without duplicate emails even when multiple server instances run concurrently.
|
||||
|
||||
### 2. Digest Bundling
|
||||
|
||||
Rather than sending an email immediately for each action, all notifications collected for a recipient during the 3-minute window are combined into a single digest email. This keeps team communication organized and eliminates inbox spam during heavy collaboration sessions.
|
||||
|
||||
### 3. Smart Activity Collapsing
|
||||
|
||||
When an event cluster contains a high volume of items (for example, when an editor uploads dozens of video clips at once), Shumai automatically groups and collapses the items:
|
||||
|
||||
- If **3 or fewer** items are in a group, each item is displayed with its individual thumbnail and details.
|
||||
- If **more than 3** items are uploaded together, Shumai summarizes them into a single concise notification (e.g., _"Alice uploaded 12 new files to Project Alpha"_) with a preview of the first three file names.
|
||||
|
||||
### 4. Inline CID Attachments
|
||||
|
||||
Avatars and video/image asset thumbnails are retrieved from storage and embedded directly into the email as inline MIME attachments (`cid:...`).
|
||||
|
||||
Unlike external image links, inline CID attachments:
|
||||
|
||||
- Display immediately in desktop and mobile email clients (such as Apple Mail, Gmail, and Outlook) without being blocked by "show remote content" security warnings.
|
||||
- Do not require publicly accessible S3 URLs or reverse-proxy authentication to render.
|
||||
|
||||
### 5. Deep Linking
|
||||
|
||||
Every notification card in the email includes deep-linking action buttons (such as **View Asset**, **View Project**, or **View Task**) that navigate members straight to the corresponding resource in Shumai.
|
||||
|
||||
To ensure links point to your public domain instead of `localhost`, configure the `APP_URL` or `BETTER_AUTH_URL` environment variable on your Shumai server:
|
||||
|
||||
```bash
|
||||
APP_URL=https://shumai.example.com
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Member Preferences & Filtering
|
||||
|
||||
Email delivery respects team permissions and member choices:
|
||||
|
||||
- **Personal Preferences**: Team members can independently choose which types of activities they receive by opening **Team Settings > Notifications**. If a user disables notifications for a category (e.g. general comments or status updates), Shumai will not include those items in their email digests.
|
||||
- **Self-Action Suppression**: Members never receive notification emails for their own comments, uploads, or task updates (unless they explicitly enable the **Your Uploads** preference to be notified when their own media transcoding completes).
|
||||
- **Project Scope**: Members whose access is restricted to specific projects only receive email digests for activities within those assigned projects, unless they are explicitly `@mentioned`.
|
||||
- **AI Agents**: Automated AI agent accounts are automatically excluded from receiving email notifications.
|
||||
@@ -44,3 +44,11 @@ If you want to mute a specific project entirely (except for direct `@mentions` w
|
||||
- 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.
|
||||
|
||||
---
|
||||
|
||||
## Email Notifications
|
||||
|
||||
In addition to in-app notifications, Team Owners can configure outgoing SMTP settings to deliver batched activity digest emails to team members. The email delivery engine honors each member's individual notification preferences configured above.
|
||||
|
||||
See the [Email Notifications Guide](/using-shumai/email-notifications) for full SMTP setup instructions, test email workflows, and delivery architecture details.
|
||||
|
||||
@@ -34,3 +34,9 @@ Team Owners can select how the transcoding engine handles uploaded files. Shumai
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## Hardware Acceleration
|
||||
|
||||
To offload encoding workloads to GPUs (NVIDIA NVENC, Intel QuickSync, AMD/Intel VA-API, or Rockchip RKMPP), Shumai supports hardware-accelerated transcoding. See the [Hardware Transcoding Guide](/configuration/hardware-transcoding) for Docker Compose configuration, GPU passthrough, and driver prerequisites.
|
||||
|
||||
+5
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "shumai",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"repository": {
|
||||
@@ -38,7 +38,10 @@
|
||||
"release:local": "bun run scripts/release-local.ts",
|
||||
"release:patch": "bun run scripts/release.ts patch",
|
||||
"release:minor": "bun run scripts/release.ts minor",
|
||||
"release:major": "bun run scripts/release.ts major"
|
||||
"release:major": "bun run scripts/release.ts major",
|
||||
"changelog:extract": "bun run scripts/extract-changelog.ts",
|
||||
"docs:changelog": "bun run scripts/generate-docs-changelog.ts",
|
||||
"docs:changelog:check": "bun run scripts/generate-docs-changelog.ts --check"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "10.0.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/api",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -2,27 +2,34 @@ import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import notificationRoute from './notification'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { emailService } from '@shumai/core/src/notification/email'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
|
||||
const mockUser = { id: 'user1', name: 'Test User', email: 'test@example.com' }
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
authMiddleware: async (
|
||||
c: Context<{ Variables: { user: { id: string; name: string } } }>,
|
||||
next: Next,
|
||||
) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
authMiddleware: async (c: Context<{ Variables: { user: typeof mockUser } }>, next: Next) => {
|
||||
c.set('user', mockUser)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz')
|
||||
vi.mock('@shumai/core/src/notification/notification')
|
||||
vi.mock('@shumai/core/src/notification/email', () => ({
|
||||
emailService: {
|
||||
getEmailSettings: vi.fn(),
|
||||
updateEmailSettings: vi.fn(),
|
||||
sendTestEmail: vi.fn(),
|
||||
},
|
||||
}))
|
||||
vi.mock('@shumai/core/src/user-metadata/user-metadata')
|
||||
|
||||
describe('notification api', () => {
|
||||
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
|
||||
const app = new Hono<{ Variables: { user: typeof mockUser } }>()
|
||||
.use('*', async (c, next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
c.set('user', mockUser)
|
||||
await next()
|
||||
})
|
||||
.route('/', notificationRoute)
|
||||
@@ -155,4 +162,100 @@ describe('notification api', () => {
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/notifications/email - requires admin and returns settings', async () => {
|
||||
const mockSettings = {
|
||||
enabled: true,
|
||||
host: 'smtp.example.com',
|
||||
port: 587,
|
||||
username: 'user',
|
||||
password: 'secret-password',
|
||||
smtps: true,
|
||||
ignoreCert: false,
|
||||
from: 'noreply@example.com',
|
||||
replyTo: '',
|
||||
}
|
||||
vi.mocked(emailService.getEmailSettings).mockResolvedValue(mockSettings)
|
||||
|
||||
const res = await app.request('/teams/t1/notifications/email')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json).toEqual(mockSettings)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.objectContaining({ id: 'user1' }),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
expect(emailService.getEmailSettings).toHaveBeenCalledWith('t1')
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/notifications/email - requires admin and updates settings', async () => {
|
||||
const updateInput = {
|
||||
enabled: true,
|
||||
host: 'mail.example.com',
|
||||
port: 465,
|
||||
username: 'user',
|
||||
password: 'new-password',
|
||||
smtps: true,
|
||||
ignoreCert: false,
|
||||
from: 'shumai@example.com',
|
||||
replyTo: 'support@example.com',
|
||||
}
|
||||
vi.mocked(emailService.updateEmailSettings).mockResolvedValue(updateInput)
|
||||
|
||||
const res = await app.request('/teams/t1/notifications/email', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(updateInput),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json).toEqual(updateInput)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.objectContaining({ id: 'user1' }),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
expect(emailService.updateEmailSettings).toHaveBeenCalledWith('t1', updateInput)
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/notifications/email/test - requires admin and sends test email', async () => {
|
||||
const testReq = {
|
||||
host: 'smtp.example.com',
|
||||
port: 587,
|
||||
from: 'noreply@example.com',
|
||||
}
|
||||
vi.mocked(emailService.sendTestEmail).mockResolvedValue({
|
||||
success: true,
|
||||
messageId: '<test-msg-id@example.com>',
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/notifications/email/test', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(testReq),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json).toEqual({
|
||||
success: true,
|
||||
messageId: '<test-msg-id@example.com>',
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.objectContaining({ id: 'user1' }),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
expect(emailService.sendTestEmail).toHaveBeenCalledWith(
|
||||
't1',
|
||||
expect.objectContaining({ id: 'user1', email: 'test@example.com' }),
|
||||
testReq,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { emailService } from '@shumai/core/src/notification/email'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import {
|
||||
listNotificationsRequestSchema,
|
||||
markNotificationReadRequestSchema,
|
||||
notificationSettingsSchema,
|
||||
updateEmailNotificationSettingsSchema,
|
||||
testEmailRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
@@ -109,5 +112,57 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
return c.json({ success: true })
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/notifications/email', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const settings = await emailService.getEmailSettings(teamId)
|
||||
return c.json(settings)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/notifications/email',
|
||||
zValidator('json', updateEmailNotificationSettingsSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const settings = await emailService.updateEmailSettings(teamId, req)
|
||||
return c.json(settings)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/teams/:teamId/notifications/email/test',
|
||||
zValidator('json', testEmailRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const result = await emailService.sendTestEmail(teamId, user, req)
|
||||
return c.json(result)
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
|
||||
@@ -55,6 +55,7 @@ async function applyWatermarkToAssetMedia(
|
||||
width: vt.width ?? 0,
|
||||
height: vt.height ?? 0,
|
||||
size: 0,
|
||||
hdr: vt.hdr,
|
||||
})),
|
||||
)
|
||||
: []
|
||||
|
||||
@@ -418,6 +418,51 @@ describe('Share API', () => {
|
||||
expect(body.media.imageTranscodes).toEqual([])
|
||||
})
|
||||
|
||||
test('serves watermarked transcodes with hdr flags preserved when watermark enabled and completed', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithWatermark)
|
||||
vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(
|
||||
new Map([
|
||||
[
|
||||
'file1',
|
||||
watermarkMediaInfo({
|
||||
videoTranscodes: [
|
||||
{ key: 'files/watermarked-1080p.mp4', width: 1920, height: 1080, hdr: false },
|
||||
{ key: 'files/watermarked-1080p-hdr.mp4', width: 1920, height: 1080, hdr: true },
|
||||
],
|
||||
}),
|
||||
],
|
||||
]),
|
||||
)
|
||||
|
||||
const res = await app.request('/shares/share1/files/file1', {
|
||||
method: 'GET',
|
||||
headers: { 'x-share-password': 'pass' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.media.videoTranscodes).toEqual([
|
||||
{
|
||||
id: 'files/watermarked-1080p.mp4',
|
||||
url: 'http://s3/presigned',
|
||||
key: 'files/watermarked-1080p.mp4',
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
size: 0,
|
||||
hdr: false,
|
||||
},
|
||||
{
|
||||
id: 'files/watermarked-1080p-hdr.mp4',
|
||||
url: 'http://s3/presigned',
|
||||
key: 'files/watermarked-1080p-hdr.mp4',
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
size: 0,
|
||||
hdr: true,
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
test('serves empty transcode arrays while watermark transcoding is in flight', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithWatermark)
|
||||
vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map())
|
||||
|
||||
@@ -223,6 +223,27 @@ describe('team api', () => {
|
||||
expect(mockGetSettings).toHaveBeenCalledWith('t1')
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/settings does not return emailNotification to readers', async () => {
|
||||
mockGetSettings.mockResolvedValue({
|
||||
semanticSearchEnabled: false,
|
||||
transcode: { videoStrategy: 'best_match', hardwareAcceleration: 'off', threads: 0 },
|
||||
appearance: { hideAgent: false },
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/settings')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.emailNotification).toBeUndefined()
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/settings updates settings', async () => {
|
||||
mockUpdateSettings.mockResolvedValue({ transcode: { videoStrategy: 'all' } })
|
||||
|
||||
@@ -260,6 +281,44 @@ describe('team api', () => {
|
||||
expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'transcode.hardwareAcceleration', 'auto')
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/settings updates transcode.threads', async () => {
|
||||
mockUpdateSettings.mockResolvedValue({ transcode: { threads: 8 } })
|
||||
|
||||
const res = await app.request('/teams/t1/settings', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key: 'transcode.threads', value: 8 }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.transcode.threads).toBe(8)
|
||||
expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'transcode.threads', 8)
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/settings rejects invalid transcode.threads', async () => {
|
||||
const resNegative = await app.request('/teams/t1/settings', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key: 'transcode.threads', value: -1 }),
|
||||
})
|
||||
expect(resNegative.status).toBe(400)
|
||||
|
||||
const resTooLarge = await app.request('/teams/t1/settings', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key: 'transcode.threads', value: 33 }),
|
||||
})
|
||||
expect(resTooLarge.status).toBe(400)
|
||||
|
||||
const resFloat = await app.request('/teams/t1/settings', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key: 'transcode.threads', value: 4.5 }),
|
||||
})
|
||||
expect(resFloat.status).toBe(400)
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/settings updates appearance.hideAgent', async () => {
|
||||
mockUpdateSettings.mockResolvedValue({ appearance: { hideAgent: true } })
|
||||
|
||||
|
||||
@@ -105,15 +105,17 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
await uploadService.confirmFileUpload(user.id, taskId, req)
|
||||
|
||||
if (!req.errorMessage) {
|
||||
const context = await assetService.getAssetContext(req.fileId)
|
||||
|
||||
await notificationService.create({
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
teamId: teamId,
|
||||
projectId: context.projectId,
|
||||
creatorId: user.id,
|
||||
assetId: req.fileId,
|
||||
taskId: taskId,
|
||||
})
|
||||
|
||||
const context = await assetService.getAssetContext(req.fileId)
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.file_create,
|
||||
teamId: teamId,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/core",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
@@ -33,6 +33,8 @@
|
||||
"@shumai/db": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
"@sinclair/typebox": "0.34.52",
|
||||
"@temporalio/activity": "1.24.0",
|
||||
"@temporalio/workflow": "1.24.0",
|
||||
"adm-zip": "0.6.0",
|
||||
"ai": "7.0.84",
|
||||
"better-auth": "1.6.11",
|
||||
@@ -43,6 +45,7 @@
|
||||
"extract-zip": "2.0.1",
|
||||
"hono": "4.13.5",
|
||||
"jittered-fractional-indexing": "1.0.1",
|
||||
"nodemailer": "10.0.10",
|
||||
"pdfkit": "0.20.1",
|
||||
"pino": "10.3.1",
|
||||
"sharp": "0.35.4",
|
||||
@@ -56,6 +59,7 @@
|
||||
"@modelcontextprotocol/server": "2.0.0",
|
||||
"@types/adm-zip": "0.5.8",
|
||||
"@types/extract-zip": "2.0.3",
|
||||
"@types/nodemailer": "8.0.2",
|
||||
"@types/pdfkit": "0.17.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,13 +3,14 @@ import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
|
||||
import { AssetType, AssetStatus, Prisma } from '@shumai/db'
|
||||
import { AssetType, AssetStatus, Prisma, WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { AssetService } from './asset'
|
||||
|
||||
import { ensureJpegInStorage } from '@shumai/core/src/s3/preview-converter'
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
s3Service: {
|
||||
@@ -2529,6 +2530,209 @@ describe('AssetService', () => {
|
||||
expect(updatedEntry?.sessionId).toBe(session.id)
|
||||
})
|
||||
})
|
||||
|
||||
describe('listChildren with showDeleted', () => {
|
||||
const createImageFile = async (params: {
|
||||
name: string
|
||||
projectId: string
|
||||
parentId: string
|
||||
creatorId: string
|
||||
thumbnailKey: string
|
||||
duration?: number
|
||||
sortIndex?: string
|
||||
}) => {
|
||||
return prisma.asset.create({
|
||||
data: {
|
||||
name: params.name,
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
isDeleted: true,
|
||||
projectId: params.projectId,
|
||||
parentId: params.parentId,
|
||||
creatorId: params.creatorId,
|
||||
sizeByte: 100,
|
||||
sortIndex: params.sortIndex,
|
||||
mediaType: 'image/png',
|
||||
media: {
|
||||
duration: 0,
|
||||
filesize: 0,
|
||||
frames: 0,
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
finishedAt: new Date(0).toISOString(),
|
||||
metadata:
|
||||
params.duration === undefined
|
||||
? null
|
||||
: {
|
||||
originalHeight: 0,
|
||||
originalWidth: 0,
|
||||
hasAudio: false,
|
||||
duration: params.duration,
|
||||
bitRate: 0,
|
||||
frameRate: 0,
|
||||
totalFrames: 0,
|
||||
startTimecode: '00:00:00:00',
|
||||
format: null,
|
||||
},
|
||||
original: null,
|
||||
proxyType: 'image',
|
||||
thumbnail: {
|
||||
key: params.thumbnailKey,
|
||||
width: 0,
|
||||
height: 0,
|
||||
quality: 0,
|
||||
format: 'png',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
it('returns previews for children of a folder trashed via deleteAssets', async () => {
|
||||
const { project, user, assets } = await setupBasicAssets()
|
||||
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Trashed Folder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: assets.root.id,
|
||||
creatorId: user.id,
|
||||
},
|
||||
})
|
||||
|
||||
await createImageFile({
|
||||
name: 'inside-1.png',
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
creatorId: user.id,
|
||||
thumbnailKey: 'thumb-1',
|
||||
})
|
||||
await createImageFile({
|
||||
name: 'inside-2.png',
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
creatorId: user.id,
|
||||
thumbnailKey: 'thumb-2',
|
||||
})
|
||||
|
||||
await assetService.deleteAssets([folder.id])
|
||||
|
||||
const result = await assetService.listChildren({
|
||||
projectId: project.id,
|
||||
showDeleted: true,
|
||||
assetType: 'folder',
|
||||
})
|
||||
|
||||
expect(result.data).toHaveLength(1)
|
||||
expect(result.data[0].id).toBe(folder.id)
|
||||
expect(result.data[0].deletedAt).not.toBeNull()
|
||||
expect(result.data[0].latestChildren).toHaveLength(2)
|
||||
expect(result.data[0].latestChildren?.every((c) => c.preview?.thumbnailUrl)).toBe(true)
|
||||
})
|
||||
|
||||
it('resolves the latest deleted version for a trashed version stack child', async () => {
|
||||
const { project, user, assets } = await setupBasicAssets()
|
||||
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Trashed Folder With Stack',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: assets.root.id,
|
||||
creatorId: user.id,
|
||||
},
|
||||
})
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'clip',
|
||||
type: AssetType.version_stack,
|
||||
status: AssetStatus.processed,
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
creatorId: user.id,
|
||||
},
|
||||
})
|
||||
|
||||
await createImageFile({
|
||||
name: 'clip-v1.png',
|
||||
projectId: project.id,
|
||||
parentId: stack.id,
|
||||
creatorId: user.id,
|
||||
thumbnailKey: 'v1-thumb',
|
||||
duration: 11,
|
||||
sortIndex: 'a1',
|
||||
})
|
||||
await createImageFile({
|
||||
name: 'clip-v2.png',
|
||||
projectId: project.id,
|
||||
parentId: stack.id,
|
||||
creatorId: user.id,
|
||||
thumbnailKey: 'v2-thumb',
|
||||
duration: 42,
|
||||
sortIndex: 'a0',
|
||||
})
|
||||
|
||||
await assetService.deleteAssets([folder.id])
|
||||
|
||||
const result = await assetService.listChildren({
|
||||
projectId: project.id,
|
||||
showDeleted: true,
|
||||
assetType: 'folder',
|
||||
})
|
||||
|
||||
const previews = result.data[0].latestChildren ?? []
|
||||
expect(previews).toHaveLength(1)
|
||||
// The latest version (lowest sortIndex) must be the one used for the preview
|
||||
expect(previews[0].preview?.duration).toBe(42)
|
||||
expect(previews[0].preview?.thumbnailUrl).toBeDefined()
|
||||
})
|
||||
|
||||
it('still hides soft-deleted children when browsing a folder normally', async () => {
|
||||
const { project, user, assets } = await setupBasicAssets()
|
||||
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Active Folder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: assets.root.id,
|
||||
creatorId: user.id,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'active.png',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
isDeleted: false,
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
creatorId: user.id,
|
||||
},
|
||||
})
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'deleted.png',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
isDeleted: true,
|
||||
deletedAt: new Date(),
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
creatorId: user.id,
|
||||
},
|
||||
})
|
||||
|
||||
const folderInfo = await assetService.getAsset({ assetId: folder.id })
|
||||
expect(folderInfo.latestChildren).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('AssetService — natural sort by name', () => {
|
||||
@@ -3004,6 +3208,65 @@ describe('AssetService — natural sort by name', () => {
|
||||
|
||||
await expect(assetService.emptyTrash(project.id)).resolves.not.toThrow()
|
||||
})
|
||||
|
||||
it('should purge trashed assets whose status was processed, cancel their in-flight tasks, and delete WorkflowTasks', async () => {
|
||||
const cancelSpy = vi.spyOn(workflowService, 'cancel').mockResolvedValue(undefined)
|
||||
|
||||
const team = await prisma.team.create({ data: { name: 'Purge Task Team' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Purge Task Project', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'root',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Test User Purge', email: `test-purge-${Date.now()}@example.com` },
|
||||
})
|
||||
|
||||
// Asset was deleted, but status was set to 'processed' by background activity
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'skewed-status.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
isDeleted: true,
|
||||
deletedAt: new Date(),
|
||||
project: { connect: { id: project.id } },
|
||||
parent: { connect: { id: rootFolder.id } },
|
||||
creator: { connect: { id: user.id } },
|
||||
storageKey: { create: { key: 'files/skewed-status/raw.mp4' } },
|
||||
},
|
||||
})
|
||||
|
||||
// In-flight task for this asset
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: file.id,
|
||||
type: WorkflowTaskType.transcode_video,
|
||||
status: WorkflowTaskStatus.processing,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.emptyTrash(project.id)
|
||||
|
||||
// Asset should be deleted from DB
|
||||
const assetInDb = await prisma.asset.findUnique({ where: { id: file.id } })
|
||||
expect(assetInDb).toBeNull()
|
||||
|
||||
// Task should be cancelled
|
||||
expect(cancelSpy).toHaveBeenCalledWith(task.id)
|
||||
|
||||
// WorkflowTask should be deleted from DB
|
||||
const taskInDb = await prisma.workflowTask.findUnique({ where: { id: task.id } })
|
||||
expect(taskInDb).toBeNull()
|
||||
|
||||
cancelSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
describe('expireTrashedAssets', () => {
|
||||
@@ -3116,7 +3379,53 @@ describe('AssetService — natural sort by name', () => {
|
||||
'files/01TESTULID000000000000000/test-720p.mp4',
|
||||
'GET',
|
||||
true,
|
||||
'test.mp4',
|
||||
'test-720p.mp4',
|
||||
)
|
||||
})
|
||||
|
||||
it('downloading video proxy for test.mov should use proxy filename with mp4 extension instead of test.mov', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.mov',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
storageKey: {
|
||||
create: { key: 'files/01TESTULID000000000000000/test.mov' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.getDownloadUrl(asset.id, 'files/01TESTULID000000000000000/test-1080p.mp4')
|
||||
|
||||
expect(s3Service.presign).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'files/01TESTULID000000000000000/test-1080p.mp4',
|
||||
'GET',
|
||||
true,
|
||||
'test-1080p.mp4',
|
||||
)
|
||||
})
|
||||
|
||||
it('downloading proxy for a renamed asset should preserve new stem with proxy resolution and extension', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'awesome.mov',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
storageKey: {
|
||||
create: { key: 'files/01TESTULID000000000000000/test.mov' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.getDownloadUrl(asset.id, 'files/01TESTULID000000000000000/test-1080p.mp4')
|
||||
|
||||
expect(s3Service.presign).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'files/01TESTULID000000000000000/test-1080p.mp4',
|
||||
'GET',
|
||||
true,
|
||||
'awesome-1080p.mp4',
|
||||
)
|
||||
})
|
||||
|
||||
@@ -4858,4 +5167,88 @@ describe('AssetService — natural sort by name', () => {
|
||||
expect(stackInfo?.commentsCount).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('restoreAssets with in-flight transcoding', () => {
|
||||
it('should restore asset with status "processing" if a transcode task is still active', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Restore Transcode Team' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Restore Transcode Project', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'root',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'transcoding-video.mp4',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
parentId: rootFolder.id,
|
||||
status: AssetStatus.trashed,
|
||||
isDeleted: true,
|
||||
deletedAt: new Date(),
|
||||
},
|
||||
})
|
||||
|
||||
// Create an active transcode task
|
||||
await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: file.id,
|
||||
type: WorkflowTaskType.transcode_video,
|
||||
status: WorkflowTaskStatus.processing,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.restoreAssets([file.id])
|
||||
|
||||
const restored = await prisma.asset.findUnique({ where: { id: file.id } })
|
||||
expect(restored?.isDeleted).toBe(false)
|
||||
expect(restored?.status).toBe(AssetStatus.processing)
|
||||
})
|
||||
|
||||
it('should restore asset with status "processed" if no active transcode task exists', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Restore Completed Team' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Restore Completed Project', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'root',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'completed-video.mp4',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
parentId: rootFolder.id,
|
||||
status: AssetStatus.trashed,
|
||||
isDeleted: true,
|
||||
deletedAt: new Date(),
|
||||
},
|
||||
})
|
||||
|
||||
// Completed transcode task
|
||||
await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: file.id,
|
||||
type: WorkflowTaskType.transcode_video,
|
||||
status: WorkflowTaskStatus.completed,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.restoreAssets([file.id])
|
||||
|
||||
const restored = await prisma.asset.findUnique({ where: { id: file.id } })
|
||||
expect(restored?.isDeleted).toBe(false)
|
||||
expect(restored?.status).toBe(AssetStatus.processed)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { cancelWorkflowTask, prisma } from '@shumai/db'
|
||||
import {
|
||||
AncestorFolder,
|
||||
AssetInfo,
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
ListRecentsRequest,
|
||||
CommentExportFormat,
|
||||
PreviewFormat,
|
||||
TRASH_RETENTION_DAYS,
|
||||
} from '@shumai/dtos'
|
||||
import {
|
||||
exportCommentsToFormat,
|
||||
@@ -28,7 +29,15 @@ import {
|
||||
type ExportOptions,
|
||||
type ExportResult,
|
||||
} from './comments-export'
|
||||
import { type Asset, AssetStatus, AssetType, Prisma, type StorageKey } from '@shumai/db'
|
||||
import {
|
||||
type Asset,
|
||||
AssetStatus,
|
||||
AssetType,
|
||||
Prisma,
|
||||
type StorageKey,
|
||||
WorkflowTaskStatus,
|
||||
WorkflowTaskType,
|
||||
} from '@shumai/db'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { PaginatedData, paginateQuery, PaginationParams } from '@shumai/core/src/pagination'
|
||||
@@ -46,6 +55,8 @@ import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/perm
|
||||
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
import path from 'path'
|
||||
import { stemFromKey } from '@shumai/core/src/utils/filename'
|
||||
|
||||
export const assetInclude = {
|
||||
creator: true,
|
||||
@@ -88,6 +99,31 @@ export type AssetWithIncludes = Prisma.AssetGetPayload<{
|
||||
include: typeof assetInclude
|
||||
}>
|
||||
|
||||
/**
|
||||
* Same shape as {@link assetInclude}, but keeps soft-deleted children.
|
||||
*
|
||||
* The "Recently Deleted" view needs this because deleting a folder soft-deletes
|
||||
* all of its descendants by cascade, so filtering out deleted children leaves
|
||||
* the folder card with no previews of what was inside it.
|
||||
*/
|
||||
export const assetIncludeIncludingDeletedChildren = {
|
||||
...assetInclude,
|
||||
target: {
|
||||
...assetInclude.target,
|
||||
include: {
|
||||
...assetInclude.target.include,
|
||||
children: {
|
||||
...assetInclude.target.include.children,
|
||||
where: {},
|
||||
},
|
||||
},
|
||||
},
|
||||
children: {
|
||||
...assetInclude.children,
|
||||
where: {},
|
||||
},
|
||||
} as const
|
||||
|
||||
type CommentWithIncludes = Prisma.AssetCommentGetPayload<{
|
||||
include: {
|
||||
creator: true
|
||||
@@ -688,7 +724,7 @@ export class AssetService {
|
||||
throw new Error('ProjectID is required when ShowDeleted is true')
|
||||
}
|
||||
const thirtyDaysAgo = new Date()
|
||||
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)
|
||||
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - TRASH_RETENTION_DAYS)
|
||||
|
||||
where = {
|
||||
projectId: req.projectId,
|
||||
@@ -741,11 +777,13 @@ export class AssetService {
|
||||
break
|
||||
}
|
||||
|
||||
const include = req.showDeleted ? assetIncludeIncludingDeletedChildren : assetInclude
|
||||
|
||||
const { data: assets, pageInfo } = await paginateQuery(
|
||||
async (skip, take) => {
|
||||
return this.prismaClient.asset.findMany({
|
||||
where,
|
||||
include: assetInclude,
|
||||
include,
|
||||
orderBy,
|
||||
skip,
|
||||
take,
|
||||
@@ -755,7 +793,9 @@ export class AssetService {
|
||||
req,
|
||||
)
|
||||
|
||||
const infos = await this.toAssetInfos(assets)
|
||||
const infos = await this.toAssetInfos(assets, undefined, {
|
||||
includeDeletedChildren: req.showDeleted,
|
||||
})
|
||||
|
||||
return { data: infos, pageInfo }
|
||||
}
|
||||
@@ -1341,7 +1381,7 @@ export class AssetService {
|
||||
private async cascadeStatusToPendingPurge(rootIds: string[]): Promise<void> {
|
||||
if (rootIds.length === 0) return
|
||||
|
||||
await this.prismaClient.$executeRaw`
|
||||
const rows = await this.prismaClient.$queryRaw<{ id: string }[]>`
|
||||
WITH RECURSIVE descendant AS (
|
||||
SELECT id FROM assets WHERE id = ANY(${rootIds})
|
||||
UNION ALL
|
||||
@@ -1356,15 +1396,35 @@ export class AssetService {
|
||||
WHERE s.type = 'symlink' AND s.target_id IN (SELECT id FROM all_purging_targets)
|
||||
)
|
||||
UPDATE assets SET status = 'pending_purge', updated_at = NOW()
|
||||
WHERE id IN (SELECT id FROM all_purging_targets) OR id IN (SELECT id FROM all_affected_symlinks);
|
||||
WHERE id IN (SELECT id FROM all_purging_targets) OR id IN (SELECT id FROM all_affected_symlinks)
|
||||
RETURNING id;
|
||||
`
|
||||
|
||||
const affectedIds = rows.map((r) => r.id)
|
||||
if (affectedIds.length > 0) {
|
||||
const inFlightTasks = await this.prismaClient.workflowTask.findMany({
|
||||
where: {
|
||||
assetId: { in: affectedIds },
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
for (const task of inFlightTasks) {
|
||||
try {
|
||||
logger.info({ taskId: task.id }, 'Cancelling in-flight workflow task for purging asset')
|
||||
await cancelWorkflowTask(task.id)
|
||||
} catch (err) {
|
||||
logger.warn({ taskId: task.id, err }, 'Failed to cancel workflow task during purge')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async emptyTrash(projectId: string): Promise<void> {
|
||||
const trashedRoots = await this.prismaClient.asset.findMany({
|
||||
where: {
|
||||
projectId,
|
||||
status: 'trashed',
|
||||
isDeleted: true,
|
||||
},
|
||||
select: { id: true },
|
||||
@@ -1411,14 +1471,14 @@ export class AssetService {
|
||||
* Cascade the 'pending_purge' status to all their descendants.
|
||||
*/
|
||||
private async expireTrashedAssets() {
|
||||
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
|
||||
const thirtyDaysAgo = new Date(Date.now() - TRASH_RETENTION_DAYS * 24 * 60 * 60 * 1000)
|
||||
|
||||
// Find up to 100 expired roots, ordered by oldest first to avoid starvation
|
||||
const expiredRoots = await this.prismaClient.asset.findMany({
|
||||
where: {
|
||||
status: 'trashed',
|
||||
deletedAt: { lt: thirtyDaysAgo },
|
||||
isDeleted: true,
|
||||
status: { not: AssetStatus.pending_purge },
|
||||
deletedAt: { lt: thirtyDaysAgo },
|
||||
},
|
||||
orderBy: { deletedAt: 'asc' },
|
||||
select: { id: true },
|
||||
@@ -1433,6 +1493,35 @@ export class AssetService {
|
||||
* Stage 2: Delete DB records for assets marked as 'pending_purge'.
|
||||
*/
|
||||
private async purgePendingAssets() {
|
||||
const pendingAssets = await this.prismaClient.asset.findMany({
|
||||
where: { status: AssetStatus.pending_purge },
|
||||
select: { id: true },
|
||||
})
|
||||
const pendingAssetIds = pendingAssets.map((a) => a.id)
|
||||
|
||||
if (pendingAssetIds.length > 0) {
|
||||
const inFlightTasks = await this.prismaClient.workflowTask.findMany({
|
||||
where: {
|
||||
assetId: { in: pendingAssetIds },
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
for (const task of inFlightTasks) {
|
||||
try {
|
||||
logger.info({ taskId: task.id }, 'Cancelling in-flight workflow task before purge')
|
||||
await cancelWorkflowTask(task.id)
|
||||
} catch (err) {
|
||||
logger.warn({ taskId: task.id, err }, 'Failed to cancel workflow task during purge')
|
||||
}
|
||||
}
|
||||
|
||||
await this.prismaClient.workflowTask.deleteMany({
|
||||
where: { assetId: { in: pendingAssetIds } },
|
||||
})
|
||||
}
|
||||
|
||||
const { count } = await this.prismaClient.asset.deleteMany({
|
||||
where: { status: AssetStatus.pending_purge },
|
||||
})
|
||||
@@ -1575,11 +1664,30 @@ export class AssetService {
|
||||
}
|
||||
}
|
||||
|
||||
const activeTask = await tx.workflowTask.findFirst({
|
||||
where: {
|
||||
assetId: a.id,
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
type: {
|
||||
in: [
|
||||
WorkflowTaskType.transcode,
|
||||
WorkflowTaskType.transcode_video,
|
||||
WorkflowTaskType.transcode_image,
|
||||
WorkflowTaskType.transcode_pdf,
|
||||
WorkflowTaskType.transcode_pdf_pages,
|
||||
WorkflowTaskType.transcode_screenshot,
|
||||
WorkflowTaskType.transcode_image_annotation,
|
||||
WorkflowTaskType.transcode_watermark,
|
||||
],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await tx.asset.update({
|
||||
where: { id: a.id },
|
||||
data: {
|
||||
isDeleted: false,
|
||||
status: 'processed',
|
||||
status: activeTask ? AssetStatus.processing : AssetStatus.processed,
|
||||
deletedAt: null,
|
||||
},
|
||||
})
|
||||
@@ -2045,7 +2153,9 @@ export class AssetService {
|
||||
async toAssetInfos(
|
||||
assets: AssetWithIncludes[],
|
||||
previewFormat?: PreviewFormat,
|
||||
options?: { includeDeletedChildren?: boolean },
|
||||
): Promise<AssetInfo[]> {
|
||||
const includeDeletedChildren = options?.includeDeletedChildren ?? false
|
||||
const stackIds = new Set<string>()
|
||||
|
||||
for (const a of assets) {
|
||||
@@ -2076,7 +2186,10 @@ export class AssetService {
|
||||
const versionsMap = new Map<string, AssetWithIncludes['children'][0][]>()
|
||||
if (stackIds.size > 0) {
|
||||
const allVersions = await this.prismaClient.asset.findMany({
|
||||
where: { parentId: { in: Array.from(stackIds) }, isDeleted: false },
|
||||
where: {
|
||||
parentId: { in: Array.from(stackIds) },
|
||||
...(includeDeletedChildren ? {} : { isDeleted: false }),
|
||||
},
|
||||
include: {
|
||||
creator: true,
|
||||
agent: { include: { user: true } },
|
||||
@@ -2202,7 +2315,7 @@ export class AssetService {
|
||||
folderForPreview.children
|
||||
) {
|
||||
for (const child of folderForPreview.children) {
|
||||
if (child.isDeleted) continue
|
||||
if (!includeDeletedChildren && child.isDeleted) continue
|
||||
let previewAsset = child as Asset
|
||||
let mediaType = child.mediaType
|
||||
|
||||
@@ -2594,6 +2707,7 @@ export class AssetService {
|
||||
|
||||
let storageKey = asset.storageKey.key
|
||||
let assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
|
||||
let targetName = asset.name
|
||||
|
||||
if (!key.startsWith(assetDir) && asset.parentId) {
|
||||
// Check if requested key belongs to another version in the same version stack
|
||||
@@ -2603,11 +2717,14 @@ export class AssetService {
|
||||
isDeleted: false,
|
||||
storageKey: { key: { startsWith: key.substring(0, key.lastIndexOf('/') + 1) } },
|
||||
},
|
||||
select: { storageKey: { select: { key: true } } },
|
||||
select: { name: true, storageKey: { select: { key: true } } },
|
||||
})
|
||||
if (sibling?.storageKey?.key) {
|
||||
storageKey = sibling.storageKey.key
|
||||
assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
|
||||
if (sibling.name) {
|
||||
targetName = sibling.name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2615,13 +2732,35 @@ export class AssetService {
|
||||
throw new Error('Key does not belong to this asset')
|
||||
}
|
||||
|
||||
return s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
key,
|
||||
'GET',
|
||||
true,
|
||||
asset.name ?? undefined,
|
||||
)
|
||||
let downloadFilename: string | undefined
|
||||
if (key === storageKey) {
|
||||
downloadFilename = targetName ?? undefined
|
||||
} else {
|
||||
const keyBasename = path.posix.basename(key)
|
||||
const originalStem = stemFromKey(storageKey)
|
||||
const assetStem = targetName ? stemFromKey(targetName) : originalStem
|
||||
|
||||
if (
|
||||
originalStem &&
|
||||
assetStem &&
|
||||
originalStem !== assetStem &&
|
||||
keyBasename.startsWith(originalStem + '-')
|
||||
) {
|
||||
downloadFilename = assetStem + keyBasename.slice(originalStem.length)
|
||||
} else if (
|
||||
originalStem &&
|
||||
assetStem &&
|
||||
originalStem !== assetStem &&
|
||||
keyBasename.startsWith('watermark-' + originalStem + '-')
|
||||
) {
|
||||
downloadFilename =
|
||||
'watermark-' + assetStem + keyBasename.slice(('watermark-' + originalStem).length)
|
||||
} else {
|
||||
downloadFilename = keyBasename
|
||||
}
|
||||
}
|
||||
|
||||
return s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET', true, downloadFilename)
|
||||
}
|
||||
|
||||
async toPreviewInfo(
|
||||
|
||||
@@ -5,7 +5,7 @@ export * from './authz/authz'
|
||||
export * from './collection/collection'
|
||||
export * from './invite/invite'
|
||||
export * from './metadata/metadata'
|
||||
export * from './notification/notification'
|
||||
export * from './notification/index'
|
||||
export * from './project/project'
|
||||
export * from './provider/provider'
|
||||
export * from './s3/s3'
|
||||
|
||||
@@ -0,0 +1,700 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import nodemailer from 'nodemailer'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { NotificationType } from '@shumai/db'
|
||||
import { emailService, DEFAULT_EMAIL_SETTINGS } from './email'
|
||||
|
||||
const mockSendMail = vi.fn().mockResolvedValue({ messageId: '<mock-msg-id@shumai.test>' })
|
||||
const mockVerify = vi.fn().mockResolvedValue(true)
|
||||
const mockClose = vi.fn()
|
||||
|
||||
vi.mock('nodemailer', () => ({
|
||||
default: {
|
||||
createTransport: vi.fn(() => ({
|
||||
sendMail: mockSendMail,
|
||||
verify: mockVerify,
|
||||
close: mockClose,
|
||||
})),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('EmailService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockSendMail.mockResolvedValue({ messageId: '<mock-msg-id@shumai.test>' })
|
||||
mockVerify.mockResolvedValue(true)
|
||||
})
|
||||
|
||||
describe('getEmailSettings', () => {
|
||||
it('returns default settings when team settings are not set', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Team Alpha' } })
|
||||
const settings = await emailService.getEmailSettings(team.id)
|
||||
|
||||
expect(settings).toEqual(DEFAULT_EMAIL_SETTINGS)
|
||||
expect(settings.enabled).toBe(false)
|
||||
expect(settings.port).toBe(587)
|
||||
})
|
||||
|
||||
it('returns saved email settings when configured', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Team Beta',
|
||||
settings: {
|
||||
emailNotification: {
|
||||
enabled: true,
|
||||
host: 'smtp.beta.test',
|
||||
port: 465,
|
||||
username: 'beta_user',
|
||||
password: 'secret_password',
|
||||
smtps: true,
|
||||
ignoreCert: false,
|
||||
from: 'beta@shumai.test',
|
||||
replyTo: 'reply@shumai.test',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const settings = await emailService.getEmailSettings(team.id)
|
||||
expect(settings.enabled).toBe(true)
|
||||
expect(settings.host).toBe('smtp.beta.test')
|
||||
expect(settings.port).toBe(465)
|
||||
expect(settings.password).toBe('secret_password')
|
||||
})
|
||||
|
||||
it('throws 404 if team does not exist', async () => {
|
||||
await expect(emailService.getEmailSettings('non-existent-team-id')).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('updateEmailSettings', () => {
|
||||
it('updates email settings and saves to team.settings', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Team Gamma' } })
|
||||
|
||||
const updated = await emailService.updateEmailSettings(team.id, {
|
||||
enabled: true,
|
||||
host: 'smtp.gamma.test',
|
||||
port: 587,
|
||||
username: 'gamma',
|
||||
password: 'gamma_password',
|
||||
smtps: false,
|
||||
ignoreCert: true,
|
||||
from: 'gamma@shumai.test',
|
||||
replyTo: '',
|
||||
})
|
||||
|
||||
expect(updated.enabled).toBe(true)
|
||||
expect(updated.host).toBe('smtp.gamma.test')
|
||||
expect(updated.password).toBe('gamma_password')
|
||||
expect(updated.ignoreCert).toBe(true)
|
||||
|
||||
const reloaded = await prisma.team.findUnique({ where: { id: team.id } })
|
||||
expect(reloaded?.settings?.emailNotification?.host).toBe('smtp.gamma.test')
|
||||
})
|
||||
|
||||
it('preserves existing password if empty string or undefined is provided in update', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Team Delta',
|
||||
settings: {
|
||||
emailNotification: {
|
||||
enabled: true,
|
||||
host: 'smtp.delta.test',
|
||||
port: 587,
|
||||
username: 'delta',
|
||||
password: 'original_super_secret',
|
||||
smtps: false,
|
||||
ignoreCert: false,
|
||||
from: 'delta@shumai.test',
|
||||
replyTo: '',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const updated = await emailService.updateEmailSettings(team.id, {
|
||||
enabled: true,
|
||||
host: 'smtp.delta-updated.test',
|
||||
port: 587,
|
||||
username: 'delta_new',
|
||||
password: '', // Empty password should retain existing
|
||||
smtps: true,
|
||||
ignoreCert: false,
|
||||
from: 'delta@shumai.test',
|
||||
})
|
||||
|
||||
expect(updated.host).toBe('smtp.delta-updated.test')
|
||||
expect(updated.password).toBe('original_super_secret')
|
||||
|
||||
const reloaded = await prisma.team.findUnique({ where: { id: team.id } })
|
||||
expect(reloaded?.settings?.emailNotification?.password).toBe('original_super_secret')
|
||||
})
|
||||
})
|
||||
|
||||
describe('sendMail and verifySmtp', () => {
|
||||
it('verifySmtp calls transport.verify and closes transport', async () => {
|
||||
const config = { ...DEFAULT_EMAIL_SETTINGS, host: 'smtp.test' }
|
||||
const ok = await emailService.verifySmtp(config)
|
||||
|
||||
expect(ok).toBe(true)
|
||||
expect(mockVerify).toHaveBeenCalled()
|
||||
expect(mockClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('sendMail sends email using nodemailer transport', async () => {
|
||||
const config = { ...DEFAULT_EMAIL_SETTINGS, host: 'smtp.test', from: 'shumai@test.com' }
|
||||
const res = await emailService.sendMail(config, {
|
||||
to: 'user@test.com',
|
||||
subject: 'Hello',
|
||||
html: '<p>Hello World</p>',
|
||||
text: 'Hello World',
|
||||
})
|
||||
|
||||
expect(res.messageId).toBe('<mock-msg-id@shumai.test>')
|
||||
expect(mockSendMail).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
from: 'shumai@test.com',
|
||||
to: 'user@test.com',
|
||||
subject: 'Hello',
|
||||
}),
|
||||
)
|
||||
expect(mockClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('sendMail forwards attachments to nodemailer transport', async () => {
|
||||
const config = { ...DEFAULT_EMAIL_SETTINGS, host: 'smtp.test', from: 'shumai@test.com' }
|
||||
const attachments = [
|
||||
{
|
||||
filename: 'avatar.png',
|
||||
content: Buffer.from('image-data'),
|
||||
cid: 'avatar-123@shumai.internal',
|
||||
contentType: 'image/png',
|
||||
},
|
||||
]
|
||||
await emailService.sendMail(config, {
|
||||
to: 'user@test.com',
|
||||
subject: 'Hello',
|
||||
html: '<img src="cid:avatar-123@shumai.internal" />',
|
||||
text: 'Hello',
|
||||
attachments,
|
||||
})
|
||||
|
||||
expect(mockSendMail).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
attachments,
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('sendTestEmail', () => {
|
||||
it('sends test email to the current admin user', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Test Team',
|
||||
settings: {
|
||||
emailNotification: {
|
||||
enabled: true,
|
||||
host: 'smtp.test.com',
|
||||
port: 587,
|
||||
username: 'user',
|
||||
password: 'pw',
|
||||
smtps: false,
|
||||
ignoreCert: false,
|
||||
from: 'sender@test.com',
|
||||
replyTo: '',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const currentUser = { id: 'admin1', email: 'admin@shumai.test', name: 'Admin' }
|
||||
const result = await emailService.sendTestEmail(team.id, currentUser)
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(result.messageId).toBe('<mock-msg-id@shumai.test>')
|
||||
expect(mockVerify).toHaveBeenCalled()
|
||||
expect(mockSendMail).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
to: 'admin@shumai.test',
|
||||
subject: 'Test email from Shumai',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('allows overriding settings with input draft', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team 2' } })
|
||||
const currentUser = { id: 'admin2', email: 'admin2@shumai.test', name: 'Admin 2' }
|
||||
|
||||
const result = await emailService.sendTestEmail(team.id, currentUser, {
|
||||
host: 'smtp.draft.com',
|
||||
from: 'draft@test.com',
|
||||
password: 'draft-password',
|
||||
})
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(nodemailer.createTransport).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
host: 'smtp.draft.com',
|
||||
}),
|
||||
)
|
||||
expect(mockSendMail).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
from: 'draft@test.com',
|
||||
to: 'admin2@shumai.test',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('throws error when host is missing', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Empty Host Team' } })
|
||||
const currentUser = { id: 'admin3', email: 'admin3@shumai.test', name: 'Admin 3' }
|
||||
|
||||
await expect(
|
||||
emailService.sendTestEmail(team.id, currentUser, { host: '', from: 'a@b.com' }),
|
||||
).rejects.toThrow('SMTP host is required')
|
||||
})
|
||||
|
||||
it('throws error when from address is missing', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Empty From Team' } })
|
||||
const currentUser = { id: 'admin4', email: 'admin4@shumai.test', name: 'Admin 4' }
|
||||
|
||||
await expect(
|
||||
emailService.sendTestEmail(team.id, currentUser, { host: 'smtp.test', from: '' }),
|
||||
).rejects.toThrow('From address is required')
|
||||
})
|
||||
|
||||
it('throws 400 when verify fails', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Failing Team' } })
|
||||
const currentUser = { id: 'admin5', email: 'admin5@shumai.test', name: 'Admin 5' }
|
||||
|
||||
mockVerify.mockRejectedValueOnce(new Error('Connection refused'))
|
||||
|
||||
await expect(
|
||||
emailService.sendTestEmail(team.id, currentUser, {
|
||||
host: 'smtp.down.com',
|
||||
from: 'admin@down.com',
|
||||
}),
|
||||
).rejects.toThrow('SMTP verification failed: Connection refused')
|
||||
})
|
||||
})
|
||||
|
||||
describe('renderNotificationEmail', () => {
|
||||
it('renders comment notification', () => {
|
||||
const rendered = emailService.renderNotificationEmail({
|
||||
type: NotificationType.comment_created,
|
||||
creatorName: 'Alice',
|
||||
teamName: 'Designers',
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
assetId: 'asset-1',
|
||||
assetName: 'logo.png',
|
||||
commentMessage: 'Please make it bigger',
|
||||
})
|
||||
|
||||
expect(rendered.subject).toContain('Alice commented on "logo.png"')
|
||||
expect(rendered.html).toContain('Please make it bigger')
|
||||
expect(rendered.html).toContain('logo.png')
|
||||
expect(rendered.text).toContain('Alice commented on "logo.png"')
|
||||
})
|
||||
|
||||
it('renders mention notification', () => {
|
||||
const rendered = emailService.renderNotificationEmail({
|
||||
type: NotificationType.mention,
|
||||
creatorName: 'Bob',
|
||||
teamName: 'Developers',
|
||||
teamId: 'team-2',
|
||||
projectId: 'proj-2',
|
||||
assetId: 'asset-2',
|
||||
assetName: 'architecture.pdf',
|
||||
commentMessage: 'Take a look at this',
|
||||
})
|
||||
|
||||
expect(rendered.subject).toContain('Bob mentioned you')
|
||||
expect(rendered.html).toContain('Bob mentioned you')
|
||||
expect(rendered.html).toContain('Take a look at this')
|
||||
})
|
||||
|
||||
it('replaces user mentions with user names instead of user ID in comment emails', () => {
|
||||
const rendered = emailService.renderNotificationEmail({
|
||||
type: NotificationType.comment_created,
|
||||
creatorName: 'Bob',
|
||||
teamName: 'Designers',
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
assetId: 'asset-1',
|
||||
assetName: 'logo.png',
|
||||
commentMessage: '<@kUFrm1W4fKLCaLpw2XQP1OPe0gKACJpy> nice',
|
||||
mentionedUserNames: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
kUFrm1W4fKLCaLpw2XQP1OPe0gKACJpy: 'Alice',
|
||||
},
|
||||
})
|
||||
|
||||
expect(rendered.html).toContain('@Alice nice')
|
||||
expect(rendered.html).not.toContain('<@kUFrm1W4fKLCaLpw2XQP1OPe0gKACJpy>')
|
||||
expect(rendered.text).toContain('@Alice nice')
|
||||
expect(rendered.text).not.toContain('<@kUFrm1W4fKLCaLpw2XQP1OPe0gKACJpy>')
|
||||
})
|
||||
|
||||
it('renders asset upload notification with project name, creator profile image, and upload time', () => {
|
||||
const rendered = emailService.renderNotificationEmail({
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'Charlie',
|
||||
creatorAvatarUrl: 'https://example.com/avatar.jpg',
|
||||
teamName: 'Media',
|
||||
teamId: 'team-3',
|
||||
projectName: 'Marketing Campaign',
|
||||
projectId: 'proj-3',
|
||||
assetId: 'asset-3',
|
||||
assetName: 'video.mp4',
|
||||
fileCount: 1,
|
||||
uploadTime: new Date('2026-09-27T15:20:00Z'),
|
||||
})
|
||||
|
||||
expect(rendered.subject).toContain('Charlie uploaded "video.mp4" to Marketing Campaign')
|
||||
expect(rendered.html).toContain('Marketing Campaign')
|
||||
expect(rendered.html).toContain('https://example.com/avatar.jpg')
|
||||
expect(rendered.html).toContain('Sep 27, 2026')
|
||||
expect(rendered.text).toContain('Marketing Campaign')
|
||||
expect(rendered.text).toContain('Sep 27, 2026')
|
||||
})
|
||||
|
||||
it('renders single file uploaded notification', () => {
|
||||
const rendered = emailService.renderNotificationEmail({
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'Charlie',
|
||||
teamName: 'Media',
|
||||
teamId: 'team-3',
|
||||
projectId: 'proj-3',
|
||||
assetId: 'asset-3',
|
||||
assetName: 'video.mp4',
|
||||
fileCount: 1,
|
||||
})
|
||||
|
||||
expect(rendered.subject).toContain('Charlie uploaded "video.mp4"')
|
||||
expect(rendered.html).toContain('video.mp4')
|
||||
})
|
||||
|
||||
it('renders consolidated batch file upload notification', () => {
|
||||
const rendered = emailService.renderNotificationEmail({
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'Charlie',
|
||||
teamName: 'Media',
|
||||
teamId: 'team-3',
|
||||
projectName: 'Videos',
|
||||
projectId: 'proj-3',
|
||||
fileCount: 5,
|
||||
fileNames: ['img1.png', 'img2.png', 'img3.png', 'img4.png', 'img5.png'],
|
||||
})
|
||||
|
||||
expect(rendered.subject).toContain('Charlie uploaded 5 files to Videos')
|
||||
expect(rendered.html).toContain('img1.png')
|
||||
expect(rendered.html).toContain('and 2 more')
|
||||
})
|
||||
|
||||
it('renders user joined team notification', () => {
|
||||
const rendered = emailService.renderNotificationEmail({
|
||||
type: NotificationType.new_user_join_team,
|
||||
creatorName: 'Dave',
|
||||
teamName: 'Acme Corp',
|
||||
teamId: 'team-4',
|
||||
})
|
||||
|
||||
expect(rendered.subject).toContain('Dave joined Acme Corp')
|
||||
expect(rendered.html).toContain('Dave is now a member of Acme Corp')
|
||||
})
|
||||
|
||||
it('renders kanban task notifications', () => {
|
||||
const created = emailService.renderNotificationEmail({
|
||||
type: NotificationType.kanban_task_created,
|
||||
creatorName: 'Eva',
|
||||
teamName: 'Engineering',
|
||||
teamId: 'team-5',
|
||||
kanbanTaskId: 'kt-1',
|
||||
kanbanTaskTitle: 'Fix login bug',
|
||||
})
|
||||
expect(created.subject).toContain('Eva created task "Fix login bug"')
|
||||
|
||||
const assigned = emailService.renderNotificationEmail({
|
||||
type: NotificationType.kanban_task_assigned,
|
||||
creatorName: 'Frank',
|
||||
teamName: 'Engineering',
|
||||
teamId: 'team-5',
|
||||
kanbanTaskId: 'kt-2',
|
||||
kanbanTaskTitle: 'Design DB schema',
|
||||
})
|
||||
expect(assigned.subject).toContain('Frank assigned you to task "Design DB schema"')
|
||||
|
||||
const status = emailService.renderNotificationEmail({
|
||||
type: NotificationType.kanban_task_status_updated,
|
||||
creatorName: 'Grace',
|
||||
teamName: 'Engineering',
|
||||
teamId: 'team-5',
|
||||
kanbanTaskId: 'kt-3',
|
||||
kanbanTaskTitle: 'Refactor auth',
|
||||
commentMessage: 'Moved to In Progress',
|
||||
})
|
||||
expect(status.subject).toContain('Grace updated status of task "Refactor auth"')
|
||||
expect(status.html).toContain('Moved to In Progress')
|
||||
})
|
||||
|
||||
it('generates correct action links without team id for project and asset URLs', () => {
|
||||
const baseUrl = emailService.getBaseUrl()
|
||||
|
||||
// Project link
|
||||
const projectEmail = emailService.renderNotificationEmail({
|
||||
type: NotificationType.new_user_join_project,
|
||||
creatorName: 'Alice',
|
||||
teamName: 'Designers',
|
||||
teamId: '01KY2A7DRK2N0MECBDHTGAVV84',
|
||||
projectName: 'Project Alpha',
|
||||
projectId: '01KY2ANCA1SXGSPR63NVVD07EJ',
|
||||
})
|
||||
expect(projectEmail.html).toContain(`href="${baseUrl}/projects/01KY2ANCA1SXGSPR63NVVD07EJ"`)
|
||||
expect(projectEmail.html).not.toContain(
|
||||
'/teams/01KY2A7DRK2N0MECBDHTGAVV84/projects/01KY2ANCA1SXGSPR63NVVD07EJ',
|
||||
)
|
||||
|
||||
// Asset link
|
||||
const assetEmail = emailService.renderNotificationEmail({
|
||||
type: NotificationType.comment_created,
|
||||
creatorName: 'Alice',
|
||||
teamName: 'Designers',
|
||||
teamId: '01KY2A7DRK2N0MECBDHTGAVV84',
|
||||
projectName: 'Project Alpha',
|
||||
projectId: '01KY2ANCA1SXGSPR63NVVD07EJ',
|
||||
assetId: '01KY2ASSET1234567890ABCDEF',
|
||||
assetName: 'logo.png',
|
||||
commentMessage: 'Looks good',
|
||||
})
|
||||
expect(assetEmail.html).toContain(
|
||||
`href="${baseUrl}/projects/01KY2ANCA1SXGSPR63NVVD07EJ/files/01KY2ASSET1234567890ABCDEF"`,
|
||||
)
|
||||
expect(assetEmail.html).not.toContain('/teams/')
|
||||
})
|
||||
})
|
||||
|
||||
describe('renderBatchedNotificationEmail', () => {
|
||||
it('renders single notification with specific subject and detailed row', () => {
|
||||
const rendered = emailService.renderBatchedNotificationEmail({
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
recipientName: 'Bob',
|
||||
items: [
|
||||
{
|
||||
id: 'n-1',
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'Alice',
|
||||
creatorAvatarUrl: 'https://example.com/alice.png',
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
projectId: 'p-1',
|
||||
projectName: 'Website Redesign',
|
||||
assetId: 'a-1',
|
||||
assetName: 'hero.png',
|
||||
assetThumbnailUrl: 'https://example.com/hero-thumb.png',
|
||||
createdAt: new Date('2026-09-27T10:00:00Z'),
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
expect(rendered.subject).toBe('[Shumai] Alice uploaded "hero.png" to Website Redesign')
|
||||
expect(rendered.html).toContain('Alice')
|
||||
expect(rendered.html).toContain('Uploaded "hero.png" to Website Redesign')
|
||||
expect(rendered.html).toContain('https://example.com/hero-thumb.png')
|
||||
expect(rendered.html).toContain('https://example.com/alice.png')
|
||||
expect(rendered.text).toContain('Alice: Uploaded "hero.png" to Website Redesign')
|
||||
})
|
||||
|
||||
it('renders detailed rows with thumbnail when event count <= 3', () => {
|
||||
const rendered = emailService.renderBatchedNotificationEmail({
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
recipientName: 'Bob',
|
||||
items: [
|
||||
{
|
||||
id: 'n-1',
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'Alice',
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
projectId: 'p-1',
|
||||
projectName: 'Website Redesign',
|
||||
assetId: 'a-1',
|
||||
assetName: 'img1.png',
|
||||
assetThumbnailUrl: 'https://example.com/img1.png',
|
||||
createdAt: new Date('2026-09-27T10:00:00Z'),
|
||||
},
|
||||
{
|
||||
id: 'n-2',
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'Alice',
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
projectId: 'p-1',
|
||||
projectName: 'Website Redesign',
|
||||
assetId: 'a-2',
|
||||
assetName: 'img2.png',
|
||||
createdAt: new Date('2026-09-27T10:01:00Z'),
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
expect(rendered.subject).toBe('[Shumai] 2 new notifications')
|
||||
expect(rendered.html).toContain('You have 2 new updates:')
|
||||
expect(rendered.html).not.toContain('in <strong>Designers</strong>')
|
||||
expect(rendered.html).toContain('Open Shumai')
|
||||
expect(rendered.html).not.toContain('Open Designers')
|
||||
expect(rendered.html).not.toContain('Team: Designers')
|
||||
expect(rendered.text).toContain('You have 2 new update(s):')
|
||||
expect(rendered.text).toContain('Open Shumai:')
|
||||
expect(rendered.text).not.toContain('Team: Designers')
|
||||
expect(rendered.html).toContain('img1.png')
|
||||
expect(rendered.html).toContain('img2.png')
|
||||
// img1 has thumbnail, img2 does not
|
||||
expect(rendered.html).toContain('https://example.com/img1.png')
|
||||
expect(rendered.text).toContain('img1.png')
|
||||
expect(rendered.text).toContain('img2.png')
|
||||
})
|
||||
|
||||
it('collapses events into one summary row and omits thumbnails when count > 3', () => {
|
||||
const items = Array.from({ length: 5 }, (_, i) => ({
|
||||
id: `n-${i}`,
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'Alice',
|
||||
creatorAvatarUrl: 'https://example.com/alice.png',
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
projectId: 'p-1',
|
||||
projectName: 'Website Redesign',
|
||||
assetId: `a-${i}`,
|
||||
assetName: `photo_${i}.png`,
|
||||
assetThumbnailUrl: `https://example.com/thumb_${i}.png`,
|
||||
createdAt: new Date(`2026-09-27T10:0${i}:00Z`),
|
||||
}))
|
||||
|
||||
const rendered = emailService.renderBatchedNotificationEmail({
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
recipientName: 'Bob',
|
||||
items,
|
||||
})
|
||||
|
||||
expect(rendered.subject).toBe('[Shumai] 5 new notifications')
|
||||
expect(rendered.html).toContain('Alice uploaded 5 assets to Website Redesign')
|
||||
// Thumbnails must be omitted for collapsed groups (> 3)
|
||||
expect(rendered.html).not.toContain('https://example.com/thumb_')
|
||||
expect(rendered.text).toContain('Alice uploaded 5 assets to Website Redesign')
|
||||
})
|
||||
|
||||
it('batches mixed events in 1 email, collapsing groups > 3 while showing <= 3 in detail', () => {
|
||||
// 4 comments by UserB in Project Alpha (> 3)
|
||||
const commentItems = Array.from({ length: 4 }, (_, i) => ({
|
||||
id: `c-${i}`,
|
||||
type: NotificationType.comment_created,
|
||||
creatorName: 'UserB',
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
projectId: 'p-1',
|
||||
projectName: 'Project Alpha',
|
||||
assetId: `a-${i}`,
|
||||
assetName: `asset_${i}`,
|
||||
commentMessage: `Comment number ${i}`,
|
||||
createdAt: new Date(`2026-09-27T11:0${i}:00Z`),
|
||||
}))
|
||||
|
||||
// 1 upload by UserC in Project Alpha (<= 3)
|
||||
const uploadItem = {
|
||||
id: 'u-1',
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'UserC',
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
projectId: 'p-1',
|
||||
projectName: 'Project Alpha',
|
||||
assetId: 'a-upload',
|
||||
assetName: 'diagram.png',
|
||||
assetThumbnailUrl: 'https://example.com/diagram.png',
|
||||
createdAt: new Date('2026-09-27T11:05:00Z'),
|
||||
}
|
||||
|
||||
const rendered = emailService.renderBatchedNotificationEmail({
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
recipientName: 'Alice',
|
||||
items: [...commentItems, uploadItem],
|
||||
})
|
||||
|
||||
expect(rendered.subject).toBe('[Shumai] 5 new notifications')
|
||||
// Collapsed comment group
|
||||
expect(rendered.html).toContain('UserB left 4 comments in Project Alpha')
|
||||
// Detailed upload item with thumbnail
|
||||
expect(rendered.html).toContain('UserC')
|
||||
expect(rendered.html).toContain('diagram.png')
|
||||
expect(rendered.html).toContain('https://example.com/diagram.png')
|
||||
})
|
||||
|
||||
it('generates correct project action links in batched notification emails', () => {
|
||||
const baseUrl = emailService.getBaseUrl()
|
||||
|
||||
const rendered = emailService.renderBatchedNotificationEmail({
|
||||
teamId: '01KY2A7DRK2N0MECBDHTGAVV84',
|
||||
teamName: 'Designers',
|
||||
recipientName: 'Bob',
|
||||
items: [
|
||||
{
|
||||
id: 'n-1',
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'Alice',
|
||||
teamId: '01KY2A7DRK2N0MECBDHTGAVV84',
|
||||
teamName: 'Designers',
|
||||
projectId: '01KY2ANCA1SXGSPR63NVVD07EJ',
|
||||
projectName: 'Project Alpha',
|
||||
assetId: '01KY2ASSET1234567890ABCDEF',
|
||||
assetName: 'hero.png',
|
||||
createdAt: new Date('2026-09-27T10:00:00Z'),
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
expect(rendered.html).toContain(
|
||||
`href="${baseUrl}/projects/01KY2ANCA1SXGSPR63NVVD07EJ/files/01KY2ASSET1234567890ABCDEF"`,
|
||||
)
|
||||
expect(rendered.html).not.toContain(
|
||||
'/teams/01KY2A7DRK2N0MECBDHTGAVV84/projects/01KY2ANCA1SXGSPR63NVVD07EJ',
|
||||
)
|
||||
|
||||
// Test collapsed group (>3 items)
|
||||
const collapsedItems = Array.from({ length: 4 }, (_, i) => ({
|
||||
id: `n-${i}`,
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'Alice',
|
||||
teamId: '01KY2A7DRK2N0MECBDHTGAVV84',
|
||||
teamName: 'Designers',
|
||||
projectId: '01KY2ANCA1SXGSPR63NVVD07EJ',
|
||||
projectName: 'Project Alpha',
|
||||
assetId: `asset-${i}`,
|
||||
assetName: `file_${i}.png`,
|
||||
createdAt: new Date('2026-09-27T10:00:00Z'),
|
||||
}))
|
||||
|
||||
const renderedCollapsed = emailService.renderBatchedNotificationEmail({
|
||||
teamId: '01KY2A7DRK2N0MECBDHTGAVV84',
|
||||
teamName: 'Designers',
|
||||
recipientName: 'Bob',
|
||||
items: collapsedItems,
|
||||
})
|
||||
|
||||
expect(renderedCollapsed.html).toContain(
|
||||
`href="${baseUrl}/projects/01KY2ANCA1SXGSPR63NVVD07EJ"`,
|
||||
)
|
||||
expect(renderedCollapsed.html).not.toContain(
|
||||
'/teams/01KY2A7DRK2N0MECBDHTGAVV84/projects/01KY2ANCA1SXGSPR63NVVD07EJ',
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,912 @@
|
||||
import nodemailer, { type Transporter } from 'nodemailer'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { prisma, NotificationType } from '@shumai/db'
|
||||
import type { EmailNotificationSettings, UpdateEmailNotificationSettings } from '@shumai/dtos'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
|
||||
export interface EmailAttachment {
|
||||
filename: string
|
||||
content?: Buffer | string
|
||||
path?: string
|
||||
cid?: string
|
||||
contentType?: string
|
||||
}
|
||||
|
||||
export interface SendMailOptions {
|
||||
to: string
|
||||
subject: string
|
||||
html: string
|
||||
text: string
|
||||
attachments?: EmailAttachment[]
|
||||
}
|
||||
|
||||
export interface NotificationEmailContext {
|
||||
type: NotificationType
|
||||
creatorName: string
|
||||
creatorAvatarUrl?: string
|
||||
teamName: string
|
||||
teamId: string
|
||||
projectName?: string
|
||||
projectId?: string
|
||||
assetName?: string
|
||||
assetId?: string
|
||||
kanbanTaskTitle?: string
|
||||
kanbanTaskId?: string
|
||||
commentMessage?: string
|
||||
mentionedUserNames?: Record<string, string>
|
||||
fileCount?: number
|
||||
fileNames?: string[]
|
||||
uploadTime?: string | Date
|
||||
}
|
||||
|
||||
export interface BatchedNotificationItem {
|
||||
id: string
|
||||
type: NotificationType
|
||||
creatorName: string
|
||||
creatorAvatarUrl?: string
|
||||
teamId: string
|
||||
teamName: string
|
||||
projectId?: string
|
||||
projectName?: string
|
||||
assetId?: string
|
||||
assetName?: string
|
||||
assetThumbnailUrl?: string
|
||||
kanbanTaskId?: string
|
||||
kanbanTaskTitle?: string
|
||||
commentMessage?: string
|
||||
mentionedUserNames?: Record<string, string>
|
||||
uploadTime?: string | Date
|
||||
createdAt: Date
|
||||
}
|
||||
|
||||
export interface BatchedEmailContext {
|
||||
teamId: string
|
||||
teamName: string
|
||||
recipientName: string
|
||||
items: BatchedNotificationItem[]
|
||||
}
|
||||
|
||||
export function getNotificationBatchGroupKey(item: BatchedNotificationItem): string {
|
||||
return `${item.type}_${item.creatorName || ''}_${item.projectId || ''}_${item.teamId}`
|
||||
}
|
||||
|
||||
export const DEFAULT_EMAIL_SETTINGS: EmailNotificationSettings = {
|
||||
enabled: false,
|
||||
host: '',
|
||||
port: 587,
|
||||
username: '',
|
||||
password: '',
|
||||
smtps: false,
|
||||
ignoreCert: false,
|
||||
from: '',
|
||||
replyTo: '',
|
||||
}
|
||||
|
||||
export class EmailService {
|
||||
getBaseUrl(): string {
|
||||
const raw =
|
||||
process.env.APP_URL ||
|
||||
process.env.BETTER_AUTH_URL ||
|
||||
`http://localhost:${process.env.SHUMAI_SERVER_PORT || '3000'}`
|
||||
return raw.replace(/\/+$/, '')
|
||||
}
|
||||
|
||||
createTransport(config: EmailNotificationSettings): Transporter {
|
||||
return nodemailer.createTransport({
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
secure: config.smtps,
|
||||
tls: {
|
||||
rejectUnauthorized: !config.ignoreCert,
|
||||
},
|
||||
auth:
|
||||
config.username || config.password
|
||||
? {
|
||||
user: config.username,
|
||||
pass: config.password,
|
||||
}
|
||||
: undefined,
|
||||
connectionTimeout: 10000,
|
||||
})
|
||||
}
|
||||
|
||||
async verifySmtp(config: EmailNotificationSettings): Promise<boolean> {
|
||||
const transport = this.createTransport(config)
|
||||
try {
|
||||
await transport.verify()
|
||||
return true
|
||||
} finally {
|
||||
transport.close()
|
||||
}
|
||||
}
|
||||
|
||||
async sendMail(
|
||||
config: EmailNotificationSettings,
|
||||
options: SendMailOptions,
|
||||
): Promise<{ messageId: string }> {
|
||||
const transport = this.createTransport(config)
|
||||
try {
|
||||
logger.debug(
|
||||
{ to: options.to, from: config.from, subject: options.subject },
|
||||
'Sending email via nodemailer',
|
||||
)
|
||||
const info = await transport.sendMail({
|
||||
from: config.from,
|
||||
replyTo: config.replyTo || config.from,
|
||||
to: options.to,
|
||||
subject: options.subject,
|
||||
html: options.html,
|
||||
text: options.text,
|
||||
attachments: options.attachments,
|
||||
})
|
||||
logger.info({ messageId: info.messageId, to: options.to }, 'Email sent successfully')
|
||||
return { messageId: info.messageId }
|
||||
} finally {
|
||||
transport.close()
|
||||
}
|
||||
}
|
||||
|
||||
async getEmailSettings(teamId: string): Promise<EmailNotificationSettings> {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: { settings: true },
|
||||
})
|
||||
if (!team) {
|
||||
throw new HTTPException(404, { message: 'Team not found' })
|
||||
}
|
||||
|
||||
const saved = team.settings?.emailNotification
|
||||
return {
|
||||
enabled: saved?.enabled ?? DEFAULT_EMAIL_SETTINGS.enabled,
|
||||
host: saved?.host ?? DEFAULT_EMAIL_SETTINGS.host,
|
||||
port: saved?.port ?? DEFAULT_EMAIL_SETTINGS.port,
|
||||
username: saved?.username ?? DEFAULT_EMAIL_SETTINGS.username,
|
||||
password: saved?.password ?? DEFAULT_EMAIL_SETTINGS.password,
|
||||
smtps: saved?.smtps ?? DEFAULT_EMAIL_SETTINGS.smtps,
|
||||
ignoreCert: saved?.ignoreCert ?? DEFAULT_EMAIL_SETTINGS.ignoreCert,
|
||||
from: saved?.from ?? DEFAULT_EMAIL_SETTINGS.from,
|
||||
replyTo: saved?.replyTo ?? DEFAULT_EMAIL_SETTINGS.replyTo,
|
||||
}
|
||||
}
|
||||
|
||||
async updateEmailSettings(
|
||||
teamId: string,
|
||||
input: UpdateEmailNotificationSettings,
|
||||
): Promise<EmailNotificationSettings> {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: { settings: true },
|
||||
})
|
||||
if (!team) {
|
||||
throw new HTTPException(404, { message: 'Team not found' })
|
||||
}
|
||||
|
||||
const currentSettings = (team.settings || {}) as PrismaJson.Settings
|
||||
const existingEmailConfig = currentSettings.emailNotification
|
||||
|
||||
// If password is not provided or empty, retain existing password
|
||||
const password =
|
||||
input.password !== undefined && input.password !== ''
|
||||
? input.password
|
||||
: existingEmailConfig?.password || ''
|
||||
|
||||
const updatedEmailConfig: PrismaJson.EmailNotificationSettings = {
|
||||
enabled: input.enabled,
|
||||
host: input.host,
|
||||
port: input.port,
|
||||
username: input.username || '',
|
||||
password,
|
||||
smtps: input.smtps,
|
||||
ignoreCert: input.ignoreCert,
|
||||
from: input.from,
|
||||
replyTo: input.replyTo || '',
|
||||
}
|
||||
|
||||
currentSettings.emailNotification = updatedEmailConfig
|
||||
|
||||
const updatedTeam = await prisma.team.update({
|
||||
where: { id: teamId },
|
||||
data: { settings: currentSettings as PrismaJson.Settings },
|
||||
select: { settings: true },
|
||||
})
|
||||
|
||||
return updatedTeam.settings?.emailNotification as EmailNotificationSettings
|
||||
}
|
||||
|
||||
async sendTestEmail(
|
||||
teamId: string,
|
||||
currentUser: { id: string; email: string; name: string },
|
||||
overrides?: Partial<EmailNotificationSettings>,
|
||||
): Promise<{ success: boolean; messageId: string }> {
|
||||
const saved = await this.getEmailSettings(teamId)
|
||||
const effectiveConfig: EmailNotificationSettings = {
|
||||
...saved,
|
||||
...overrides,
|
||||
// If override password is empty, fall back to saved
|
||||
password:
|
||||
overrides?.password !== undefined && overrides.password !== ''
|
||||
? overrides.password
|
||||
: saved.password,
|
||||
}
|
||||
|
||||
if (!effectiveConfig.host) {
|
||||
throw new HTTPException(400, { message: 'SMTP host is required' })
|
||||
}
|
||||
if (!effectiveConfig.from) {
|
||||
throw new HTTPException(400, { message: 'From address is required' })
|
||||
}
|
||||
|
||||
try {
|
||||
await this.verifySmtp(effectiveConfig)
|
||||
} catch (err) {
|
||||
const errMsg = err instanceof Error ? err.message : String(err)
|
||||
logger.warn({ teamId, err: errMsg }, 'SMTP verification failed during test email')
|
||||
throw new HTTPException(400, { message: `SMTP verification failed: ${errMsg}` })
|
||||
}
|
||||
|
||||
const baseUrl = this.getBaseUrl()
|
||||
const subject = 'Test email from Shumai'
|
||||
const html = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Test Email from Shumai</title>
|
||||
<style>
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f9fafb; margin: 0; padding: 24px; color: #111827; }
|
||||
.container { max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 8px; border: 1px solid #e5e7eb; padding: 32px; }
|
||||
.header { font-size: 20px; font-weight: 700; margin-bottom: 16px; color: #111827; }
|
||||
.content { font-size: 14px; line-height: 1.6; color: #4b5563; margin-bottom: 24px; }
|
||||
.badge { display: inline-block; background-color: #ecfdf5; color: #065f46; font-size: 12px; font-weight: 600; padding: 4px 10px; border-radius: 9999px; margin-bottom: 16px; }
|
||||
.footer { font-size: 12px; color: #9ca3af; border-top: 1px solid #f3f4f6; padding-top: 16px; margin-top: 24px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">Shumai Notification System</div>
|
||||
<div class="badge">SMTP Verified</div>
|
||||
<div class="content">
|
||||
<p>Hello ${escapeHtml(currentUser.name || 'Admin')},</p>
|
||||
<p>This is a test email confirming that your SMTP server settings are correctly configured for team notifications in Shumai.</p>
|
||||
<p>Notifications for new comments, mentions, uploads, and Kanban tasks will now be delivered via this email service.</p>
|
||||
</div>
|
||||
<div class="footer">
|
||||
Sent from Shumai at <a href="${baseUrl}" style="color: #6366f1; text-decoration: none;">${baseUrl}</a>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`.trim()
|
||||
|
||||
const text = `
|
||||
Shumai Notification System - Test Email
|
||||
|
||||
Hello ${currentUser.name || 'Admin'},
|
||||
|
||||
This is a test email confirming that your SMTP server settings are correctly configured for team notifications in Shumai.
|
||||
|
||||
Sent from Shumai at ${baseUrl}
|
||||
`.trim()
|
||||
|
||||
try {
|
||||
const res = await this.sendMail(effectiveConfig, {
|
||||
to: currentUser.email,
|
||||
subject,
|
||||
html,
|
||||
text,
|
||||
})
|
||||
return { success: true, messageId: res.messageId }
|
||||
} catch (err) {
|
||||
const errMsg = err instanceof Error ? err.message : String(err)
|
||||
logger.error({ teamId, err: errMsg }, 'Failed to send test email')
|
||||
throw new HTTPException(400, { message: `Failed to send test email: ${errMsg}` })
|
||||
}
|
||||
}
|
||||
|
||||
renderNotificationEmail(ctx: NotificationEmailContext): {
|
||||
subject: string
|
||||
html: string
|
||||
text: string
|
||||
} {
|
||||
const baseUrl = this.getBaseUrl()
|
||||
let actionUrl = baseUrl
|
||||
let actionText = 'View in Shumai'
|
||||
|
||||
if (ctx.projectId && ctx.assetId) {
|
||||
actionUrl = `${baseUrl}/projects/${ctx.projectId}/files/${ctx.assetId}`
|
||||
actionText = 'View Asset'
|
||||
} else if (ctx.projectId) {
|
||||
actionUrl = `${baseUrl}/projects/${ctx.projectId}`
|
||||
actionText = 'View Project'
|
||||
} else if (ctx.teamId && ctx.kanbanTaskId) {
|
||||
actionUrl = `${baseUrl}/teams/${ctx.teamId}/kanban?taskId=${ctx.kanbanTaskId}`
|
||||
actionText = 'View Task'
|
||||
} else if (ctx.teamId) {
|
||||
actionUrl = `${baseUrl}/teams/${ctx.teamId}`
|
||||
actionText = 'Open Shumai'
|
||||
}
|
||||
|
||||
let subject = '[Shumai] Notification'
|
||||
let headline = 'You have a new notification'
|
||||
let detail = ''
|
||||
|
||||
const actor = ctx.creatorName || 'Someone'
|
||||
const actorInitial = (actor.trim()[0] || 'U').toUpperCase()
|
||||
const formattedUploadTime = formatUploadTime(ctx.uploadTime)
|
||||
|
||||
let commentMessage = ctx.commentMessage
|
||||
if (commentMessage) {
|
||||
commentMessage = commentMessage.replace(/<@([^>]+)>/g, (match, uid) => {
|
||||
const name = ctx.mentionedUserNames?.[uid]
|
||||
return name ? `@${name}` : `@${uid}`
|
||||
})
|
||||
}
|
||||
|
||||
switch (ctx.type) {
|
||||
case NotificationType.comment_created: {
|
||||
const target = ctx.assetName ? `"${ctx.assetName}"` : 'an asset'
|
||||
subject = `[Shumai] ${actor} commented on ${target}`
|
||||
headline = `${actor} left a comment`
|
||||
detail = commentMessage ? `"${commentMessage}"` : `New comment on ${target}`
|
||||
break
|
||||
}
|
||||
case NotificationType.reply_created: {
|
||||
const target = ctx.assetName ? `"${ctx.assetName}"` : 'an asset'
|
||||
subject = `[Shumai] ${actor} replied to your comment on ${target}`
|
||||
headline = `${actor} replied to your comment`
|
||||
detail = commentMessage ? `"${commentMessage}"` : `Reply on ${target}`
|
||||
break
|
||||
}
|
||||
case NotificationType.mention: {
|
||||
subject = `[Shumai] ${actor} mentioned you`
|
||||
headline = `${actor} mentioned you`
|
||||
detail = commentMessage ? `"${commentMessage}"` : 'You were mentioned in a comment'
|
||||
break
|
||||
}
|
||||
case NotificationType.successful_file_uploaded: {
|
||||
const target = ctx.assetName ? `"${ctx.assetName}"` : 'a file'
|
||||
const projectInfo = ctx.projectName ? ` to ${ctx.projectName}` : ''
|
||||
if (ctx.fileCount && ctx.fileCount > 1) {
|
||||
subject = `[Shumai] ${actor} uploaded ${ctx.fileCount} files${projectInfo}`
|
||||
headline = `${actor} uploaded ${ctx.fileCount} new files${projectInfo}`
|
||||
let filesSummary: string
|
||||
if (ctx.fileNames && ctx.fileNames.length > 0) {
|
||||
const previewList = ctx.fileNames.slice(0, 3).join(', ')
|
||||
const remaining = ctx.fileNames.length - 3
|
||||
filesSummary = remaining > 0 ? `${previewList}, and ${remaining} more` : previewList
|
||||
} else {
|
||||
filesSummary = `${ctx.fileCount} new files were uploaded`
|
||||
}
|
||||
const details: string[] = []
|
||||
if (ctx.projectName) details.push(`Project: ${ctx.projectName}`)
|
||||
if (formattedUploadTime) details.push(`Uploaded at: ${formattedUploadTime}`)
|
||||
details.push(`Files: ${filesSummary}`)
|
||||
detail = details.join('\n')
|
||||
} else {
|
||||
subject = `[Shumai] ${actor} uploaded ${target}${projectInfo}`
|
||||
headline = `${actor} uploaded ${target}${projectInfo}`
|
||||
const details: string[] = []
|
||||
if (ctx.assetName) details.push(`Asset: ${ctx.assetName}`)
|
||||
if (ctx.projectName) details.push(`Project: ${ctx.projectName}`)
|
||||
if (formattedUploadTime) details.push(`Uploaded at: ${formattedUploadTime}`)
|
||||
detail = details.join('\n')
|
||||
}
|
||||
break
|
||||
}
|
||||
case NotificationType.metadata_field_updated_status: {
|
||||
const target = ctx.assetName ? `"${ctx.assetName}"` : 'an asset'
|
||||
subject = `[Shumai] ${actor} updated status of ${target}`
|
||||
headline = `${actor} updated status of ${target}`
|
||||
detail = `Status update on ${target}`
|
||||
break
|
||||
}
|
||||
case NotificationType.new_user_join_team: {
|
||||
subject = `[Shumai] ${actor} joined ${ctx.teamName}`
|
||||
headline = `${actor} joined the team`
|
||||
detail = `${actor} is now a member of ${ctx.teamName}`
|
||||
break
|
||||
}
|
||||
case NotificationType.new_user_join_project: {
|
||||
const project = ctx.projectName || 'a project'
|
||||
subject = `[Shumai] ${actor} joined project ${project}`
|
||||
headline = `${actor} joined project ${project}`
|
||||
detail = `${actor} is now a member of ${project}`
|
||||
break
|
||||
}
|
||||
case NotificationType.kanban_task_created: {
|
||||
const task = ctx.kanbanTaskTitle ? `"${ctx.kanbanTaskTitle}"` : 'a task'
|
||||
subject = `[Shumai] ${actor} created task ${task}`
|
||||
headline = `${actor} created task ${task}`
|
||||
detail = commentMessage || `Task ${task} was created`
|
||||
break
|
||||
}
|
||||
case NotificationType.kanban_task_assigned: {
|
||||
const task = ctx.kanbanTaskTitle ? `"${ctx.kanbanTaskTitle}"` : 'a task'
|
||||
subject = `[Shumai] ${actor} assigned you to task ${task}`
|
||||
headline = `${actor} assigned you to task ${task}`
|
||||
detail = `You have been assigned to ${task}`
|
||||
break
|
||||
}
|
||||
case NotificationType.kanban_task_status_updated: {
|
||||
const task = ctx.kanbanTaskTitle ? `"${ctx.kanbanTaskTitle}"` : 'a task'
|
||||
subject = `[Shumai] ${actor} updated status of task ${task}`
|
||||
headline = `${actor} updated status of ${task}`
|
||||
detail = commentMessage || `Status changed for ${task}`
|
||||
break
|
||||
}
|
||||
case NotificationType.kanban_task_updated: {
|
||||
const task = ctx.kanbanTaskTitle ? `"${ctx.kanbanTaskTitle}"` : 'a task'
|
||||
subject = `[Shumai] ${actor} updated task ${task}`
|
||||
headline = `${actor} updated task ${task}`
|
||||
detail = commentMessage || `Task ${task} was updated`
|
||||
break
|
||||
}
|
||||
case NotificationType.kanban_task_deleted: {
|
||||
const task = ctx.kanbanTaskTitle ? `"${ctx.kanbanTaskTitle}"` : 'a task'
|
||||
subject = `[Shumai] ${actor} deleted task ${task}`
|
||||
headline = `${actor} deleted task ${task}`
|
||||
detail = `Task ${task} was deleted`
|
||||
break
|
||||
}
|
||||
case NotificationType.kanban_task_comment_created: {
|
||||
const task = ctx.kanbanTaskTitle ? `"${ctx.kanbanTaskTitle}"` : 'a task'
|
||||
subject = `[Shumai] ${actor} commented on task ${task}`
|
||||
headline = `${actor} commented on task ${task}`
|
||||
detail = commentMessage ? `"${commentMessage}"` : `New comment on ${task}`
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const avatarHtml = ctx.creatorAvatarUrl
|
||||
? `<img src="${escapeHtml(ctx.creatorAvatarUrl)}" alt="${escapeHtml(actor)}" width="36" height="36" style="width: 36px; height: 36px; border-radius: 50%; object-fit: cover; display: block; border: 1px solid #e5e7eb;" />`
|
||||
: `<table cellpadding="0" cellspacing="0" border="0" style="width: 36px; height: 36px; border-radius: 50%; background-color: #4f46e5; text-align: center;"><tr><td style="color: #ffffff; font-weight: 600; font-size: 14px; text-align: center; vertical-align: middle;">${escapeHtml(actorInitial)}</td></tr></table>`
|
||||
|
||||
const html = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>${escapeHtml(subject)}</title>
|
||||
<style>
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f9fafb; margin: 0; padding: 24px; color: #111827; }
|
||||
.container { max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 8px; border: 1px solid #e5e7eb; padding: 32px; }
|
||||
.header { font-size: 18px; font-weight: 700; margin-bottom: 8px; color: #111827; }
|
||||
.content { font-size: 14px; line-height: 1.6; color: #374151; margin-bottom: 24px; }
|
||||
.detail-box { background-color: #f3f4f6; border-left: 4px solid #4f46e5; padding: 12px 16px; border-radius: 4px; margin: 16px 0; font-size: 14px; color: #1f2937; white-space: pre-wrap; }
|
||||
.btn { display: inline-block; background-color: #4f46e5; color: #ffffff !important; padding: 10px 20px; border-radius: 6px; text-decoration: none; font-size: 14px; font-weight: 500; margin-top: 12px; }
|
||||
.footer { font-size: 12px; color: #9ca3af; border-top: 1px solid #f3f4f6; padding-top: 16px; margin-top: 24px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<table cellpadding="0" cellspacing="0" border="0" style="margin-bottom: 16px;">
|
||||
<tr>
|
||||
<td style="vertical-align: middle; padding-right: 12px; width: 36px;">
|
||||
${avatarHtml}
|
||||
</td>
|
||||
<td style="vertical-align: middle;">
|
||||
<div style="font-weight: 600; font-size: 15px; color: #111827; line-height: 1.2;">${escapeHtml(actor)}</div>
|
||||
${formattedUploadTime ? `<div style="font-size: 12px; color: #6b7280; margin-top: 2px;">Uploaded at ${escapeHtml(formattedUploadTime)}</div>` : ''}
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<div class="header">${escapeHtml(headline)}</div>
|
||||
<div class="content">
|
||||
${detail ? `<div class="detail-box">${escapeHtml(detail)}</div>` : ''}
|
||||
<a href="${actionUrl}" class="btn">${escapeHtml(actionText)}</a>
|
||||
</div>
|
||||
<div class="footer">
|
||||
Sent from <a href="${baseUrl}" style="color: #6366f1; text-decoration: none;">Shumai</a>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`.trim()
|
||||
|
||||
const text = `
|
||||
${subject}
|
||||
|
||||
${headline}
|
||||
${formattedUploadTime ? `Uploaded at: ${formattedUploadTime}\n` : ''}${detail ? `\n${detail}\n` : ''}
|
||||
${actionText}: ${actionUrl}
|
||||
Sent from Shumai at ${baseUrl}
|
||||
`.trim()
|
||||
|
||||
return { subject, html, text }
|
||||
}
|
||||
|
||||
renderBatchedNotificationEmail(ctx: BatchedEmailContext): {
|
||||
subject: string
|
||||
html: string
|
||||
text: string
|
||||
} {
|
||||
const baseUrl = this.getBaseUrl()
|
||||
const teamUrl = `${baseUrl}/teams/${ctx.teamId}`
|
||||
|
||||
if (ctx.items.length === 0) {
|
||||
return {
|
||||
subject: `[Shumai] Notifications`,
|
||||
html: `<p>No new notifications.</p>`,
|
||||
text: `No new notifications.`,
|
||||
}
|
||||
}
|
||||
|
||||
// Determine subject
|
||||
let subject = `[Shumai] ${ctx.items.length} new notifications`
|
||||
if (ctx.items.length === 1) {
|
||||
const single = ctx.items[0]
|
||||
const actor = single.creatorName || 'Someone'
|
||||
const target = single.assetName ? `"${single.assetName}"` : 'a file'
|
||||
const projectInfo = single.projectName ? ` to ${single.projectName}` : ''
|
||||
switch (single.type) {
|
||||
case NotificationType.successful_file_uploaded:
|
||||
subject = `[Shumai] ${actor} uploaded ${target}${projectInfo}`
|
||||
break
|
||||
case NotificationType.comment_created:
|
||||
subject = `[Shumai] ${actor} commented on ${target}`
|
||||
break
|
||||
case NotificationType.reply_created:
|
||||
subject = `[Shumai] ${actor} replied to your comment on ${target}`
|
||||
break
|
||||
case NotificationType.mention:
|
||||
subject = `[Shumai] ${actor} mentioned you`
|
||||
break
|
||||
case NotificationType.kanban_task_assigned: {
|
||||
const task = single.kanbanTaskTitle ? `"${single.kanbanTaskTitle}"` : 'a task'
|
||||
subject = `[Shumai] ${actor} assigned you to task ${task}`
|
||||
break
|
||||
}
|
||||
case NotificationType.kanban_task_created: {
|
||||
const task = single.kanbanTaskTitle ? `"${single.kanbanTaskTitle}"` : 'a task'
|
||||
subject = `[Shumai] ${actor} created task ${task}`
|
||||
break
|
||||
}
|
||||
default:
|
||||
subject = `[Shumai] 1 new notification`
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Group items: same type + actor + project
|
||||
const groups = new Map<string, BatchedNotificationItem[]>()
|
||||
for (const item of ctx.items) {
|
||||
const key = getNotificationBatchGroupKey(item)
|
||||
const list = groups.get(key)
|
||||
if (list) {
|
||||
list.push(item)
|
||||
} else {
|
||||
groups.set(key, [item])
|
||||
}
|
||||
}
|
||||
|
||||
const htmlRows: string[] = []
|
||||
const textRows: string[] = []
|
||||
|
||||
for (const [, cluster] of groups) {
|
||||
const first = cluster[0]
|
||||
const actor = first.creatorName || 'Someone'
|
||||
const avatarHtml = renderAvatarHtml(actor, first.creatorAvatarUrl)
|
||||
|
||||
if (cluster.length <= 3) {
|
||||
// Render detailed individual rows
|
||||
for (const item of cluster) {
|
||||
const action = getItemAction(baseUrl, item)
|
||||
const timeStr = formatUploadTime(item.uploadTime || item.createdAt)
|
||||
const detail = getNotificationItemDetail(item)
|
||||
|
||||
const thumbHtml = item.assetThumbnailUrl
|
||||
? `<div style="margin-top: 8px;"><img src="${escapeHtml(item.assetThumbnailUrl)}" alt="${escapeHtml(item.assetName || 'Thumbnail')}" width="140" style="max-width: 140px; max-height: 90px; border-radius: 6px; border: 1px solid #e5e7eb; object-fit: cover; display: block;" /></div>`
|
||||
: ''
|
||||
|
||||
htmlRows.push(
|
||||
`
|
||||
<div style="padding: 16px 0; border-bottom: 1px solid #f3f4f6;">
|
||||
<table cellpadding="0" cellspacing="0" border="0" style="width: 100%;">
|
||||
<tr>
|
||||
<td style="vertical-align: top; width: 44px; padding-right: 12px;">
|
||||
${avatarHtml}
|
||||
</td>
|
||||
<td style="vertical-align: top;">
|
||||
<div style="font-weight: 600; font-size: 14px; color: #111827;">${escapeHtml(actor)}</div>
|
||||
<div style="font-size: 13px; color: #374151; margin-top: 2px;">${escapeHtml(detail.headline)}</div>
|
||||
${timeStr ? `<div style="font-size: 12px; color: #6b7280; margin-top: 2px;">${escapeHtml(timeStr)}</div>` : ''}
|
||||
${detail.message ? `<div style="background-color: #f9fafb; border-left: 3px solid #6366f1; padding: 8px 12px; border-radius: 4px; font-size: 13px; color: #4b5563; margin-top: 6px; white-space: pre-wrap;">${escapeHtml(detail.message)}</div>` : ''}
|
||||
${thumbHtml}
|
||||
<div style="margin-top: 8px;">
|
||||
<a href="${action.url}" style="display: inline-block; font-size: 12px; font-weight: 500; color: #4f46e5; text-decoration: none;">${escapeHtml(action.text)} →</a>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
`.trim(),
|
||||
)
|
||||
|
||||
textRows.push(
|
||||
`- ${actor}: ${detail.headline}${timeStr ? ` (${timeStr})` : ''}${detail.message ? `\n "${detail.message}"` : ''}\n Link: ${action.url}`,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// Grouped summary row (count > 3, NO thumbnails)
|
||||
const count = cluster.length
|
||||
let summaryHeadline = `${actor} triggered ${count} updates`
|
||||
const projectName = first.projectName
|
||||
|
||||
switch (first.type) {
|
||||
case NotificationType.successful_file_uploaded:
|
||||
summaryHeadline = `${actor} uploaded ${count} assets${projectName ? ` to ${projectName}` : ''}`
|
||||
break
|
||||
case NotificationType.comment_created:
|
||||
summaryHeadline = `${actor} left ${count} comments${projectName ? ` in ${projectName}` : ''}`
|
||||
break
|
||||
case NotificationType.reply_created:
|
||||
summaryHeadline = `${actor} replied ${count} times to your comments`
|
||||
break
|
||||
case NotificationType.mention:
|
||||
summaryHeadline = `${actor} mentioned you ${count} times`
|
||||
break
|
||||
case NotificationType.metadata_field_updated_status:
|
||||
summaryHeadline = `${actor} updated status of ${count} assets`
|
||||
break
|
||||
case NotificationType.kanban_task_created:
|
||||
summaryHeadline = `${actor} created ${count} tasks${projectName ? ` in ${projectName}` : ''}`
|
||||
break
|
||||
case NotificationType.kanban_task_assigned:
|
||||
summaryHeadline = `${actor} assigned you to ${count} tasks`
|
||||
break
|
||||
case NotificationType.kanban_task_status_updated:
|
||||
summaryHeadline = `${actor} updated status of ${count} tasks`
|
||||
break
|
||||
case NotificationType.kanban_task_updated:
|
||||
summaryHeadline = `${actor} updated ${count} tasks`
|
||||
break
|
||||
case NotificationType.kanban_task_comment_created:
|
||||
summaryHeadline = `${actor} commented on ${count} tasks`
|
||||
break
|
||||
}
|
||||
|
||||
const latestTime = cluster.reduce((latest, it) => {
|
||||
const t = new Date(it.uploadTime || it.createdAt).getTime()
|
||||
return t > latest ? t : latest
|
||||
}, 0)
|
||||
const timeStr = latestTime > 0 ? formatUploadTime(new Date(latestTime)) : undefined
|
||||
const targetUrl = first.projectId ? `${baseUrl}/projects/${first.projectId}` : teamUrl
|
||||
|
||||
htmlRows.push(
|
||||
`
|
||||
<div style="padding: 16px 0; border-bottom: 1px solid #f3f4f6;">
|
||||
<table cellpadding="0" cellspacing="0" border="0" style="width: 100%;">
|
||||
<tr>
|
||||
<td style="vertical-align: top; width: 44px; padding-right: 12px;">
|
||||
${avatarHtml}
|
||||
</td>
|
||||
<td style="vertical-align: top;">
|
||||
<div style="font-weight: 600; font-size: 14px; color: #111827;">${escapeHtml(summaryHeadline)}</div>
|
||||
${timeStr ? `<div style="font-size: 12px; color: #6b7280; margin-top: 2px;">Latest activity: ${escapeHtml(timeStr)}</div>` : ''}
|
||||
<div style="margin-top: 8px;">
|
||||
<a href="${targetUrl}" style="display: inline-block; font-size: 12px; font-weight: 500; color: #4f46e5; text-decoration: none;">View Project →</a>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
`.trim(),
|
||||
)
|
||||
|
||||
textRows.push(
|
||||
`- ${summaryHeadline}${timeStr ? ` (Latest: ${timeStr})` : ''}\n Link: ${targetUrl}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const html = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>${escapeHtml(subject)}</title>
|
||||
<style>
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f9fafb; margin: 0; padding: 24px; color: #111827; }
|
||||
.container { max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 8px; border: 1px solid #e5e7eb; padding: 32px; }
|
||||
.header { font-size: 18px; font-weight: 700; color: #111827; }
|
||||
.subtitle { font-size: 14px; color: #6b7280; margin-top: 4px; margin-bottom: 20px; }
|
||||
.btn { display: inline-block; background-color: #4f46e5; color: #ffffff !important; padding: 10px 20px; border-radius: 6px; text-decoration: none; font-size: 14px; font-weight: 500; margin-top: 20px; }
|
||||
.footer { font-size: 12px; color: #9ca3af; border-top: 1px solid #f3f4f6; padding-top: 16px; margin-top: 24px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">Shumai Notifications</div>
|
||||
<div class="subtitle">You have ${ctx.items.length} new update${ctx.items.length > 1 ? 's' : ''}:</div>
|
||||
<div>
|
||||
${htmlRows.join('\n')}
|
||||
</div>
|
||||
<div style="text-align: center; margin-top: 20px;">
|
||||
<a href="${teamUrl}" class="btn">Open Shumai</a>
|
||||
</div>
|
||||
<div class="footer">
|
||||
Sent from <a href="${baseUrl}" style="color: #6366f1; text-decoration: none;">Shumai</a>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`.trim()
|
||||
|
||||
const text = `
|
||||
Shumai Notifications
|
||||
|
||||
You have ${ctx.items.length} new update(s):
|
||||
|
||||
${textRows.join('\n\n')}
|
||||
|
||||
Open Shumai: ${teamUrl}
|
||||
Sent from Shumai at ${baseUrl}
|
||||
`.trim()
|
||||
|
||||
return { subject, html, text }
|
||||
}
|
||||
}
|
||||
|
||||
function getNotificationItemDetail(item: BatchedNotificationItem): {
|
||||
headline: string
|
||||
message?: string
|
||||
} {
|
||||
const actor = item.creatorName || 'Someone'
|
||||
const asset = item.assetName ? `"${item.assetName}"` : 'an asset'
|
||||
const task = item.kanbanTaskTitle ? `"${item.kanbanTaskTitle}"` : 'a task'
|
||||
const project = item.projectName ? ` in ${item.projectName}` : ''
|
||||
|
||||
let commentMessage = item.commentMessage
|
||||
if (commentMessage && item.mentionedUserNames) {
|
||||
commentMessage = commentMessage.replace(/<@([^>]+)>/g, (match, uid) => {
|
||||
const name = item.mentionedUserNames?.[uid]
|
||||
return name ? `@${name}` : `@${uid}`
|
||||
})
|
||||
}
|
||||
|
||||
switch (item.type) {
|
||||
case NotificationType.successful_file_uploaded:
|
||||
return {
|
||||
headline: `Uploaded ${asset}${item.projectName ? ` to ${item.projectName}` : ''}`,
|
||||
}
|
||||
case NotificationType.comment_created:
|
||||
return {
|
||||
headline: `Commented on ${asset}${project}`,
|
||||
message: commentMessage,
|
||||
}
|
||||
case NotificationType.reply_created:
|
||||
return {
|
||||
headline: `Replied to your comment on ${asset}${project}`,
|
||||
message: commentMessage,
|
||||
}
|
||||
case NotificationType.mention:
|
||||
return {
|
||||
headline: `Mentioned you on ${item.kanbanTaskTitle ? `task ${task}` : asset}${project}`,
|
||||
message: commentMessage,
|
||||
}
|
||||
case NotificationType.metadata_field_updated_status:
|
||||
return {
|
||||
headline: `Updated status of ${asset}${project}`,
|
||||
}
|
||||
case NotificationType.kanban_task_created:
|
||||
return {
|
||||
headline: `Created task ${task}${project}`,
|
||||
message: commentMessage,
|
||||
}
|
||||
case NotificationType.kanban_task_assigned:
|
||||
return {
|
||||
headline: `Assigned you to task ${task}${project}`,
|
||||
}
|
||||
case NotificationType.kanban_task_status_updated:
|
||||
return {
|
||||
headline: `Updated status of task ${task}${project}`,
|
||||
message: commentMessage,
|
||||
}
|
||||
case NotificationType.kanban_task_updated:
|
||||
return {
|
||||
headline: `Updated task ${task}${project}`,
|
||||
message: commentMessage,
|
||||
}
|
||||
case NotificationType.kanban_task_deleted:
|
||||
return {
|
||||
headline: `Deleted task ${task}${project}`,
|
||||
}
|
||||
case NotificationType.kanban_task_comment_created:
|
||||
return {
|
||||
headline: `Commented on task ${task}${project}`,
|
||||
message: commentMessage,
|
||||
}
|
||||
case NotificationType.new_user_join_team:
|
||||
return {
|
||||
headline: `Joined the team ${item.teamName}`,
|
||||
}
|
||||
case NotificationType.new_user_join_project:
|
||||
return {
|
||||
headline: `Joined project ${item.projectName || 'a project'}`,
|
||||
}
|
||||
default:
|
||||
return {
|
||||
headline: `New activity from ${actor}`,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getItemAction(
|
||||
baseUrl: string,
|
||||
item: BatchedNotificationItem,
|
||||
): { url: string; text: string } {
|
||||
if (item.projectId && item.assetId) {
|
||||
return {
|
||||
url: `${baseUrl}/projects/${item.projectId}/files/${item.assetId}`,
|
||||
text: 'View Asset',
|
||||
}
|
||||
} else if (item.projectId) {
|
||||
return {
|
||||
url: `${baseUrl}/projects/${item.projectId}`,
|
||||
text: 'View Project',
|
||||
}
|
||||
} else if (item.teamId && item.kanbanTaskId) {
|
||||
return {
|
||||
url: `${baseUrl}/teams/${item.teamId}/kanban?taskId=${item.kanbanTaskId}`,
|
||||
text: 'View Task',
|
||||
}
|
||||
} else if (item.teamId) {
|
||||
return {
|
||||
url: `${baseUrl}/teams/${item.teamId}`,
|
||||
text: 'Open Shumai',
|
||||
}
|
||||
}
|
||||
return { url: baseUrl, text: 'Open Shumai' }
|
||||
}
|
||||
|
||||
function renderAvatarHtml(actor: string, avatarUrl?: string): string {
|
||||
const actorInitial = (actor.trim()[0] || 'U').toUpperCase()
|
||||
if (avatarUrl) {
|
||||
return `<img src="${escapeHtml(avatarUrl)}" alt="${escapeHtml(actor)}" width="36" height="36" style="width: 36px; height: 36px; border-radius: 50%; object-fit: cover; display: block; border: 1px solid #e5e7eb;" />`
|
||||
}
|
||||
return `<table cellpadding="0" cellspacing="0" border="0" style="width: 36px; height: 36px; border-radius: 50%; background-color: #4f46e5; text-align: center;"><tr><td style="color: #ffffff; font-weight: 600; font-size: 14px; text-align: center; vertical-align: middle;">${escapeHtml(actorInitial)}</td></tr></table>`
|
||||
}
|
||||
|
||||
function formatUploadTime(time: string | Date | undefined): string | undefined {
|
||||
if (!time) return undefined
|
||||
if (time instanceof Date) {
|
||||
if (isNaN(time.getTime())) return undefined
|
||||
return (
|
||||
new Intl.DateTimeFormat('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: '2-digit',
|
||||
hour12: true,
|
||||
timeZone: 'UTC',
|
||||
}).format(time) + ' UTC'
|
||||
)
|
||||
}
|
||||
const parsed = new Date(time)
|
||||
if (!isNaN(parsed.getTime())) {
|
||||
return (
|
||||
new Intl.DateTimeFormat('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: '2-digit',
|
||||
hour12: true,
|
||||
timeZone: 'UTC',
|
||||
}).format(parsed) + ' UTC'
|
||||
)
|
||||
}
|
||||
return time
|
||||
}
|
||||
|
||||
function escapeHtml(str: string): string {
|
||||
return str
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
export const emailService = new EmailService()
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from './notification'
|
||||
export * from './email'
|
||||
export * from './notification-job'
|
||||
@@ -0,0 +1,576 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { prisma, NotificationType, NotificationEmailStatus } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { emailService, type EmailAttachment } from './email'
|
||||
import { notificationJobService } from './notification-job'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
|
||||
describe('NotificationJobService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let sendMailSpy: ReturnType<typeof vi.spyOn>
|
||||
|
||||
beforeEach(() => {
|
||||
sendMailSpy = vi
|
||||
.spyOn(emailService, 'sendMail')
|
||||
.mockResolvedValue({ messageId: '<mock-id@shumai.test>' })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
sendMailSpy.mockRestore()
|
||||
notificationJobService.stop()
|
||||
})
|
||||
|
||||
async function createTeamWithEmail(name = 'Email Team') {
|
||||
return prisma.team.create({
|
||||
data: {
|
||||
name,
|
||||
settings: {
|
||||
emailNotification: {
|
||||
enabled: true,
|
||||
host: 'smtp.test.com',
|
||||
port: 587,
|
||||
username: 'user',
|
||||
password: 'pw',
|
||||
smtps: false,
|
||||
ignoreCert: false,
|
||||
from: 'noreply@test.com',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
it('picks up pending notifications, sends batched email, and marks them processed', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: { name: 'Alice', email: 'alice@test.com', password: 'p' },
|
||||
})
|
||||
const recipient = await prisma.user.create({
|
||||
data: { name: 'Bob', email: 'bob@test.com', password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: recipient.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Alpha Project', teamId: team.id },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'design.png',
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
project: { connect: { id: project.id } },
|
||||
},
|
||||
})
|
||||
|
||||
// Create 2 pending notifications
|
||||
const n1 = await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
assetId: asset.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
const n2 = await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.comment_created,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
assetId: asset.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
const processedCount = await notificationJobService.processPendingNotifications(500)
|
||||
expect(processedCount).toBe(2)
|
||||
|
||||
// Verify Bob received exactly 1 batched email containing both items
|
||||
expect(sendMailSpy).toHaveBeenCalledTimes(1)
|
||||
expect(sendMailSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ host: 'smtp.test.com' }),
|
||||
expect.objectContaining({
|
||||
to: 'bob@test.com',
|
||||
subject: '[Shumai] 2 new notifications',
|
||||
}),
|
||||
)
|
||||
|
||||
// Verify notifications are marked processed in DB
|
||||
const updated1 = await prisma.notification.findUnique({ where: { id: n1.id } })
|
||||
const updated2 = await prisma.notification.findUnique({ where: { id: n2.id } })
|
||||
expect(updated1?.emailStatus).toBe(NotificationEmailStatus.processed)
|
||||
expect(updated2?.emailStatus).toBe(NotificationEmailStatus.processed)
|
||||
})
|
||||
|
||||
it('skips already processed notifications', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: { name: 'Alice', email: 'alice2@test.com', password: 'p' },
|
||||
})
|
||||
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.comment_created,
|
||||
teamId: team.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.processed,
|
||||
},
|
||||
})
|
||||
|
||||
const processedCount = await notificationJobService.processPendingNotifications(500)
|
||||
expect(processedCount).toBe(0)
|
||||
expect(sendMailSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('marks notifications processed without sending email if team SMTP is disabled', async () => {
|
||||
// Team without emailNotification configured
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'No Email Team' },
|
||||
})
|
||||
const sender = await prisma.user.create({
|
||||
data: { name: 'Alice', email: 'alice3@test.com', password: 'p' },
|
||||
})
|
||||
|
||||
const notif = await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.new_user_join_team,
|
||||
teamId: team.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
const processedCount = await notificationJobService.processPendingNotifications(500)
|
||||
expect(processedCount).toBe(1)
|
||||
expect(sendMailSpy).not.toHaveBeenCalled()
|
||||
|
||||
const updated = await prisma.notification.findUnique({ where: { id: notif.id } })
|
||||
expect(updated?.emailStatus).toBe(NotificationEmailStatus.processed)
|
||||
})
|
||||
|
||||
it('excludes the actor from receiving notification about their own action', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const alice = await prisma.user.create({
|
||||
data: { name: 'Alice', email: 'alice-self@test.com', password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: alice.id, role: 'editor' },
|
||||
})
|
||||
|
||||
// Alice is the creator and only member
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.comment_created,
|
||||
teamId: team.id,
|
||||
creatorId: alice.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await notificationJobService.processPendingNotifications(500)
|
||||
// Alice should not receive an email for her own comment
|
||||
expect(sendMailSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('excludes AI agent users from receiving email notifications', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: { name: 'Alice', email: 'alice-agent-test@test.com', password: 'p' },
|
||||
})
|
||||
const agentUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'AutoAgent',
|
||||
email: 'agent-bot@shumai.ai',
|
||||
password: 'p',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: agentUser.id, role: 'editor' },
|
||||
})
|
||||
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.new_user_join_team,
|
||||
teamId: team.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await notificationJobService.processPendingNotifications(500)
|
||||
expect(sendMailSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('respects user notification preferences', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: { name: 'Alice', email: 'alice-pref@test.com', password: 'p' },
|
||||
})
|
||||
const bob = await prisma.user.create({
|
||||
data: { name: 'Bob', email: 'bob-pref@test.com', password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: bob.id, role: 'editor' },
|
||||
})
|
||||
|
||||
// Bob disabled comments in his notification settings
|
||||
await userMetadataService.upsertMetadata(bob.id, team.id, 'notification_settings', {
|
||||
comments: false,
|
||||
replies: true,
|
||||
mentions: true,
|
||||
yourUploads: false,
|
||||
otherUploads: true,
|
||||
statusUpdates: true,
|
||||
kanbanTasks: true,
|
||||
kanbanComments: true,
|
||||
})
|
||||
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.comment_created,
|
||||
teamId: team.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await notificationJobService.processPendingNotifications(500)
|
||||
expect(sendMailSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('filters notifications by project scope for project-scoped members', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: { name: 'Alice', email: 'alice-scope@test.com', password: 'p' },
|
||||
})
|
||||
const project1 = await prisma.project.create({
|
||||
data: { name: 'Project 1', teamId: team.id },
|
||||
})
|
||||
const project2 = await prisma.project.create({
|
||||
data: { name: 'Project 2', teamId: team.id },
|
||||
})
|
||||
|
||||
const bob = await prisma.user.create({
|
||||
data: { name: 'Bob', email: 'bob-scope@test.com', password: 'p' },
|
||||
})
|
||||
const bobMember = await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: bob.id, role: 'editor', scope: 'project' },
|
||||
})
|
||||
// Bob only belongs to Project 1
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: project1.id, teamMemberId: bobMember.id, role: 'editor' },
|
||||
})
|
||||
|
||||
// Notification in Project 2
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
teamId: team.id,
|
||||
projectId: project2.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await notificationJobService.processPendingNotifications(500)
|
||||
// Bob should not receive notification for Project 2
|
||||
expect(sendMailSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('batches 5 uploads and 1 comment into 1 email with collapsed upload summary', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: { name: 'UserB', email: 'userb@test.com', password: 'p' },
|
||||
})
|
||||
const recipient = await prisma.user.create({
|
||||
data: { name: 'Recipient', email: 'recip@test.com', password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: recipient.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Project Alpha', teamId: team.id },
|
||||
})
|
||||
|
||||
// 5 uploads by UserB in Project Alpha
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: `img_${i}.png`,
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
project: { connect: { id: project.id } },
|
||||
},
|
||||
})
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
assetId: asset.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// 1 comment by UserB
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.comment_created,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
const count = await notificationJobService.processPendingNotifications(500)
|
||||
expect(count).toBe(6)
|
||||
|
||||
// Recipient receives exactly 1 email containing all 6 events
|
||||
expect(sendMailSpy).toHaveBeenCalledTimes(1)
|
||||
const call = sendMailSpy.mock.calls[0]
|
||||
expect(call[1].to).toBe('recip@test.com')
|
||||
expect(call[1].subject).toBe('[Shumai] 6 new notifications')
|
||||
// Uploads collapsed into 1 row because count > 3
|
||||
expect(call[1].html).toContain('UserB uploaded 5 assets to Project Alpha')
|
||||
// Comment rendered as individual row
|
||||
expect(call[1].html).toContain('Commented on')
|
||||
})
|
||||
|
||||
it('embeds creator avatar and asset thumbnail as inline cid attachments', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Alice Artist',
|
||||
email: 'alice.artist@test.com',
|
||||
password: 'p',
|
||||
image: 'avatars/alice.png',
|
||||
},
|
||||
})
|
||||
const recipient = await prisma.user.create({
|
||||
data: { name: 'Bob Reviewer', email: 'bob.reviewer@test.com', password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: recipient.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Artwork Project', teamId: team.id },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'poster.png',
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
project: { connect: { id: project.id } },
|
||||
media: {
|
||||
thumbnail: { key: 'thumbnails/poster.jpg' },
|
||||
} as unknown as PrismaJson.MediaInfo,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
assetId: asset.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
const getObjectSpy = vi
|
||||
.spyOn(s3Service, 'getObject')
|
||||
.mockImplementation(async (_bucket, key) => {
|
||||
if (key === 'avatars/alice.png') {
|
||||
return { buffer: Buffer.from('alice-avatar-bytes'), contentType: 'image/png' }
|
||||
}
|
||||
if (key === 'thumbnails/poster.jpg') {
|
||||
return { buffer: Buffer.from('poster-thumb-bytes'), contentType: 'image/jpeg' }
|
||||
}
|
||||
throw new Error('Not found')
|
||||
})
|
||||
|
||||
try {
|
||||
const count = await notificationJobService.processPendingNotifications(500)
|
||||
expect(count).toBe(1)
|
||||
|
||||
expect(sendMailSpy).toHaveBeenCalledTimes(1)
|
||||
const call = sendMailSpy.mock.calls[0]
|
||||
const options = call[1]
|
||||
expect(options.to).toBe('bob.reviewer@test.com')
|
||||
|
||||
// Check attachments
|
||||
expect(options.attachments).toHaveLength(2)
|
||||
const avatarAtt = options.attachments.find((a: EmailAttachment) =>
|
||||
a.cid?.startsWith('avatar-'),
|
||||
)
|
||||
const thumbAtt = options.attachments.find((a: EmailAttachment) => a.cid?.startsWith('thumb-'))
|
||||
expect(avatarAtt).toBeDefined()
|
||||
expect(avatarAtt.content).toEqual(Buffer.from('alice-avatar-bytes'))
|
||||
expect(avatarAtt.cid).toBe(`avatar-${sender.id}@shumai.internal`)
|
||||
|
||||
expect(thumbAtt).toBeDefined()
|
||||
expect(thumbAtt.content).toEqual(Buffer.from('poster-thumb-bytes'))
|
||||
expect(thumbAtt.cid).toBe(`thumb-${asset.id}@shumai.internal`)
|
||||
|
||||
// Check HTML references the exact cid
|
||||
expect(options.html).toContain(`src="cid:${avatarAtt.cid}"`)
|
||||
expect(options.html).toContain(`src="cid:${thumbAtt.cid}"`)
|
||||
} finally {
|
||||
getObjectSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('omits thumbnail attachments when cluster has count > 3', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Bulk Uploader',
|
||||
email: 'bulk@test.com',
|
||||
password: 'p',
|
||||
image: 'avatars/bulk.png',
|
||||
},
|
||||
})
|
||||
const recipient = await prisma.user.create({
|
||||
data: { name: 'Recipient', email: 'bulk-recip@test.com', password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: recipient.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Bulk Project', teamId: team.id },
|
||||
})
|
||||
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: `bulk_${i}.png`,
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
project: { connect: { id: project.id } },
|
||||
media: {
|
||||
thumbnail: { key: `thumbnails/bulk_${i}.jpg` },
|
||||
} as unknown as PrismaJson.MediaInfo,
|
||||
},
|
||||
})
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
assetId: asset.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const getObjectSpy = vi
|
||||
.spyOn(s3Service, 'getObject')
|
||||
.mockImplementation(async (_bucket, key) => {
|
||||
if (key === 'avatars/bulk.png') {
|
||||
return { buffer: Buffer.from('bulk-avatar-bytes'), contentType: 'image/png' }
|
||||
}
|
||||
return { buffer: Buffer.from('thumb-bytes'), contentType: 'image/jpeg' }
|
||||
})
|
||||
|
||||
try {
|
||||
const count = await notificationJobService.processPendingNotifications(500)
|
||||
expect(count).toBe(4)
|
||||
|
||||
expect(sendMailSpy).toHaveBeenCalledTimes(1)
|
||||
const options = sendMailSpy.mock.calls[0][1]
|
||||
|
||||
// Count > 3, so only avatar attachment is included, NO thumbnail attachments!
|
||||
expect(options.attachments).toHaveLength(1)
|
||||
expect(options.attachments[0].cid).toBe(`avatar-${sender.id}@shumai.internal`)
|
||||
expect(options.html).toContain(`src="cid:avatar-${sender.id}@shumai.internal"`)
|
||||
expect(options.html).not.toContain('src="cid:thumb-')
|
||||
} finally {
|
||||
getObjectSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('gracefully handles missing images or S3 failure with fallback badge', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Broken Image User',
|
||||
email: 'broken@test.com',
|
||||
password: 'p',
|
||||
image: 'avatars/non-existent.png',
|
||||
},
|
||||
})
|
||||
const recipient = await prisma.user.create({
|
||||
data: { name: 'Recipient', email: 'broken-recip@test.com', password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: recipient.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Project', teamId: team.id },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'broken.png',
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
project: { connect: { id: project.id } },
|
||||
media: {
|
||||
thumbnail: { key: 'thumbnails/missing.jpg' },
|
||||
} as unknown as PrismaJson.MediaInfo,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
assetId: asset.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
const getObjectSpy = vi.spyOn(s3Service, 'getObject').mockRejectedValue(new Error('S3 error'))
|
||||
|
||||
try {
|
||||
const count = await notificationJobService.processPendingNotifications(500)
|
||||
expect(count).toBe(1)
|
||||
|
||||
expect(sendMailSpy).toHaveBeenCalledTimes(1)
|
||||
const options = sendMailSpy.mock.calls[0][1]
|
||||
|
||||
// No attachments because both avatar and thumb failed to load
|
||||
expect(options.attachments).toBeUndefined()
|
||||
// HTML falls back to letter badge "B" for "Broken Image User"
|
||||
expect(options.html).toContain('>B</td>')
|
||||
expect(options.html).not.toContain('<img')
|
||||
} finally {
|
||||
getObjectSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('starts and stops gracefully', () => {
|
||||
expect(() => {
|
||||
notificationJobService.start(100000, 100000)
|
||||
notificationJobService.stop()
|
||||
}).not.toThrow()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,496 @@
|
||||
import { prisma, NotificationType, NotificationEmailStatus } from '@shumai/db'
|
||||
import { emailService, getNotificationBatchGroupKey } from '@shumai/core/src/notification/email'
|
||||
import type { BatchedNotificationItem, EmailAttachment } from '@shumai/core/src/notification/email'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import type { NotificationSettings } from '@shumai/dtos'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
|
||||
function getExtensionFromMime(mime?: string): string {
|
||||
if (!mime) return 'jpg'
|
||||
if (mime.includes('png')) return 'png'
|
||||
if (mime.includes('webp')) return 'webp'
|
||||
if (mime.includes('gif')) return 'gif'
|
||||
if (mime.includes('svg')) return 'svg'
|
||||
return 'jpg'
|
||||
}
|
||||
|
||||
export class NotificationJobService {
|
||||
private isRunning = false
|
||||
private timer: NodeJS.Timeout | null = null
|
||||
private isProcessing = false
|
||||
|
||||
start(initialDelayMs = 5000, intervalMs = 3 * 60 * 1000): void {
|
||||
if (this.isRunning) return
|
||||
this.isRunning = true
|
||||
logger.info('Starting notification email background job')
|
||||
|
||||
const run = async () => {
|
||||
if (!this.isRunning) return
|
||||
try {
|
||||
await this.processPendingNotifications()
|
||||
} catch (err) {
|
||||
logger.error(
|
||||
{ err: err instanceof Error ? err.message : String(err) },
|
||||
'Error in notification email background job',
|
||||
)
|
||||
}
|
||||
|
||||
if (this.isRunning) {
|
||||
this.timer = setTimeout(run, intervalMs)
|
||||
}
|
||||
}
|
||||
|
||||
this.timer = setTimeout(run, initialDelayMs)
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.isRunning = false
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer)
|
||||
this.timer = null
|
||||
}
|
||||
logger.info('Stopped notification email background job')
|
||||
}
|
||||
|
||||
async processPendingNotifications(limit = 500): Promise<number> {
|
||||
if (this.isProcessing) {
|
||||
logger.debug('Notification job turn already in progress, skipping')
|
||||
return 0
|
||||
}
|
||||
|
||||
this.isProcessing = true
|
||||
let batchIds: string[] = []
|
||||
|
||||
try {
|
||||
// 1. Concurrency control: atomically lock up to limit pending notifications
|
||||
const locked = await prisma.$queryRaw<{ id: string }[]>`
|
||||
WITH candidates AS (
|
||||
SELECT id
|
||||
FROM notifications
|
||||
WHERE email_status = 'pending'::"NotificationEmailStatus"
|
||||
ORDER BY id ASC
|
||||
LIMIT ${limit}
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
UPDATE notifications
|
||||
SET email_status = 'processing'::"NotificationEmailStatus", updated_at = NOW()
|
||||
FROM candidates
|
||||
WHERE notifications.id = candidates.id
|
||||
RETURNING notifications.id;
|
||||
`
|
||||
|
||||
if (!locked || locked.length === 0) {
|
||||
return 0
|
||||
}
|
||||
|
||||
batchIds = locked.map((r) => r.id)
|
||||
logger.info({ count: batchIds.length }, 'Picked up pending notifications for processing')
|
||||
|
||||
// 2. Fetch full records with relations
|
||||
const notifications = await prisma.notification.findMany({
|
||||
where: { id: { in: batchIds } },
|
||||
include: {
|
||||
creator: { select: { id: true, name: true, image: true, type: true } },
|
||||
team: { select: { id: true, name: true } },
|
||||
project: { select: { id: true, name: true } },
|
||||
asset: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
media: true,
|
||||
projectId: true,
|
||||
createdAt: true,
|
||||
project: { select: { id: true, name: true } },
|
||||
},
|
||||
},
|
||||
user: { select: { id: true, name: true, email: true, type: true } },
|
||||
kanbanTask: { select: { id: true, title: true, projectId: true } },
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
|
||||
// 3. Group notifications by teamId
|
||||
const byTeam = new Map<string, typeof notifications>()
|
||||
for (const n of notifications) {
|
||||
const list = byTeam.get(n.teamId)
|
||||
if (list) {
|
||||
list.push(n)
|
||||
} else {
|
||||
byTeam.set(n.teamId, [n])
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Process each team
|
||||
for (const [teamId, teamNotifs] of byTeam) {
|
||||
const emailSettings = await emailService.getEmailSettings(teamId)
|
||||
if (!emailSettings.enabled || !emailSettings.host || !emailSettings.from) {
|
||||
logger.debug(
|
||||
{ teamId },
|
||||
'Team email notifications disabled or unconfigured, skipping delivery',
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
// Fetch team members excluding AI agents
|
||||
const members = await prisma.teamMember.findMany({
|
||||
where: {
|
||||
teamId,
|
||||
user: {
|
||||
type: { not: 'agent' },
|
||||
agent: null,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true, type: true } },
|
||||
projectMembers: { select: { projectId: true } },
|
||||
},
|
||||
})
|
||||
|
||||
const avatarCache = new Map<
|
||||
string,
|
||||
{ cidUrl: string; attachment: EmailAttachment } | null
|
||||
>()
|
||||
const thumbCache = new Map<string, { cidUrl: string; attachment: EmailAttachment } | null>()
|
||||
const cidAttachmentMap = new Map<string, EmailAttachment>()
|
||||
|
||||
const resolveAvatar = async (
|
||||
creatorId?: string | null,
|
||||
image?: string | null,
|
||||
): Promise<string | undefined> => {
|
||||
if (!image) return undefined
|
||||
if (creatorId && avatarCache.has(creatorId)) {
|
||||
const cached = avatarCache.get(creatorId)
|
||||
return cached ? cached.cidUrl : undefined
|
||||
}
|
||||
|
||||
const cid = `avatar-${creatorId || Math.random().toString(36).slice(2)}@shumai.internal`
|
||||
const cidUrl = `cid:${cid}`
|
||||
|
||||
try {
|
||||
if (image.startsWith('http://') || image.startsWith('https://')) {
|
||||
const res = await fetch(image, { signal: AbortSignal.timeout(5000) })
|
||||
if (res.ok) {
|
||||
const arrayBuffer = await res.arrayBuffer()
|
||||
const buffer = Buffer.from(arrayBuffer)
|
||||
const contentType = res.headers.get('content-type') || 'image/jpeg'
|
||||
const ext = getExtensionFromMime(contentType)
|
||||
const resolved = {
|
||||
cidUrl,
|
||||
attachment: {
|
||||
filename: `avatar-${creatorId || 'user'}.${ext}`,
|
||||
content: buffer,
|
||||
cid,
|
||||
contentType,
|
||||
},
|
||||
}
|
||||
if (creatorId) avatarCache.set(creatorId, resolved)
|
||||
cidAttachmentMap.set(cidUrl, resolved.attachment)
|
||||
return cidUrl
|
||||
}
|
||||
} else {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const obj = await s3Service.getObject(bucket, image)
|
||||
if (obj && obj.buffer && obj.buffer.length > 0) {
|
||||
const contentType = obj.contentType || 'image/jpeg'
|
||||
const ext = getExtensionFromMime(contentType)
|
||||
const resolved = {
|
||||
cidUrl,
|
||||
attachment: {
|
||||
filename: `avatar-${creatorId || 'user'}.${ext}`,
|
||||
content: obj.buffer,
|
||||
cid,
|
||||
contentType,
|
||||
},
|
||||
}
|
||||
if (creatorId) avatarCache.set(creatorId, resolved)
|
||||
cidAttachmentMap.set(cidUrl, resolved.attachment)
|
||||
return cidUrl
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.debug(
|
||||
{ err: err instanceof Error ? err.message : String(err), image, creatorId },
|
||||
'Failed to resolve avatar image for inline email attachment',
|
||||
)
|
||||
}
|
||||
|
||||
if (creatorId) avatarCache.set(creatorId, null)
|
||||
return undefined
|
||||
}
|
||||
|
||||
const resolveThumbnail = async (
|
||||
assetId?: string | null,
|
||||
media?: unknown,
|
||||
): Promise<string | undefined> => {
|
||||
if (!assetId || !media) return undefined
|
||||
if (thumbCache.has(assetId)) {
|
||||
const cached = thumbCache.get(assetId)
|
||||
return cached ? cached.cidUrl : undefined
|
||||
}
|
||||
|
||||
const m = media as PrismaJson.MediaInfo | null
|
||||
const key = m?.thumbnail?.key || m?.poster?.key
|
||||
if (!key) return undefined
|
||||
|
||||
const cid = `thumb-${assetId}@shumai.internal`
|
||||
const cidUrl = `cid:${cid}`
|
||||
|
||||
try {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const obj = await s3Service.getObject(bucket, key)
|
||||
if (obj && obj.buffer && obj.buffer.length > 0) {
|
||||
const contentType = obj.contentType || 'image/jpeg'
|
||||
const ext = getExtensionFromMime(contentType)
|
||||
const resolved = {
|
||||
cidUrl,
|
||||
attachment: {
|
||||
filename: `thumb-${assetId}.${ext}`,
|
||||
content: obj.buffer,
|
||||
cid,
|
||||
contentType,
|
||||
},
|
||||
}
|
||||
thumbCache.set(assetId, resolved)
|
||||
cidAttachmentMap.set(cidUrl, resolved.attachment)
|
||||
return cidUrl
|
||||
}
|
||||
} catch (err) {
|
||||
logger.debug(
|
||||
{ err: err instanceof Error ? err.message : String(err), assetId, key },
|
||||
'Failed to resolve thumbnail image for inline email attachment',
|
||||
)
|
||||
}
|
||||
|
||||
thumbCache.set(assetId, null)
|
||||
return undefined
|
||||
}
|
||||
|
||||
const userItemsMap = new Map<
|
||||
string,
|
||||
{ user: (typeof members)[0]['user']; items: BatchedNotificationItem[] }
|
||||
>()
|
||||
|
||||
for (const member of members) {
|
||||
if (!member.user.email) continue
|
||||
if (
|
||||
member.user.type === 'agent' ||
|
||||
member.user.email.endsWith('@shumai.ai') ||
|
||||
member.user.email.startsWith('agent-')
|
||||
) {
|
||||
continue
|
||||
}
|
||||
|
||||
const settingsMeta = await userMetadataService.getMetadata(
|
||||
member.userId,
|
||||
teamId,
|
||||
'notification_settings',
|
||||
)
|
||||
const settings: NotificationSettings = settingsMeta
|
||||
? (settingsMeta.value as NotificationSettings)
|
||||
: {
|
||||
comments: true,
|
||||
replies: true,
|
||||
mentions: true,
|
||||
yourUploads: false,
|
||||
otherUploads: true,
|
||||
statusUpdates: true,
|
||||
kanbanTasks: true,
|
||||
kanbanComments: true,
|
||||
}
|
||||
|
||||
for (const n of teamNotifs) {
|
||||
// Actor check (do not notify self unless it's their upload and yourUploads is enabled)
|
||||
if (n.creatorId === member.userId) {
|
||||
if (n.type !== NotificationType.successful_file_uploaded || !settings.yourUploads) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Targeted notification check
|
||||
if (n.userId && n.userId !== member.userId) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Project scope check
|
||||
if (member.scope === 'project' && n.projectId) {
|
||||
if (n.type !== NotificationType.mention && n.userId !== member.userId) {
|
||||
const inProject = member.projectMembers.some((pm) => pm.projectId === n.projectId)
|
||||
if (!inProject) continue
|
||||
}
|
||||
}
|
||||
|
||||
// Settings preference check
|
||||
let allowed = false
|
||||
switch (n.type) {
|
||||
case NotificationType.comment_created:
|
||||
allowed = settings.comments ?? true
|
||||
break
|
||||
case NotificationType.reply_created:
|
||||
allowed = settings.replies ?? true
|
||||
break
|
||||
case NotificationType.mention:
|
||||
allowed = settings.mentions ?? true
|
||||
break
|
||||
case NotificationType.successful_file_uploaded:
|
||||
allowed =
|
||||
member.userId === n.creatorId
|
||||
? (settings.yourUploads ?? false)
|
||||
: (settings.otherUploads ?? true)
|
||||
break
|
||||
case NotificationType.metadata_field_updated_status:
|
||||
allowed = settings.statusUpdates ?? true
|
||||
break
|
||||
case NotificationType.kanban_task_created:
|
||||
case NotificationType.kanban_task_assigned:
|
||||
case NotificationType.kanban_task_status_updated:
|
||||
case NotificationType.kanban_task_updated:
|
||||
case NotificationType.kanban_task_deleted:
|
||||
allowed = settings.kanbanTasks ?? true
|
||||
break
|
||||
case NotificationType.kanban_task_comment_created:
|
||||
allowed = settings.kanbanComments ?? true
|
||||
break
|
||||
case NotificationType.new_user_join_team:
|
||||
case NotificationType.new_user_join_project:
|
||||
allowed = true
|
||||
break
|
||||
default:
|
||||
allowed = true
|
||||
break
|
||||
}
|
||||
|
||||
if (!allowed) continue
|
||||
|
||||
const creatorAvatarUrl = await resolveAvatar(n.creatorId, n.creator?.image)
|
||||
const assetThumbnailUrl = await resolveThumbnail(n.assetId, n.asset?.media)
|
||||
|
||||
const item: BatchedNotificationItem = {
|
||||
id: n.id,
|
||||
type: n.type || NotificationType.successful_file_uploaded,
|
||||
creatorName: n.creator?.name || 'Someone',
|
||||
creatorAvatarUrl,
|
||||
teamId: n.teamId,
|
||||
teamName: n.team?.name || 'Team',
|
||||
projectId: n.projectId || n.asset?.projectId || undefined,
|
||||
projectName: n.project?.name || n.asset?.project?.name || undefined,
|
||||
assetId: n.assetId || undefined,
|
||||
assetName: n.asset?.name || undefined,
|
||||
assetThumbnailUrl,
|
||||
kanbanTaskId: n.kanbanTaskId || undefined,
|
||||
kanbanTaskTitle: n.kanbanTask?.title || undefined,
|
||||
uploadTime: n.asset?.createdAt || n.createdAt,
|
||||
createdAt: n.createdAt,
|
||||
}
|
||||
|
||||
let entry = userItemsMap.get(member.userId)
|
||||
if (!entry) {
|
||||
entry = { user: member.user, items: [] }
|
||||
userItemsMap.set(member.userId, entry)
|
||||
}
|
||||
entry.items.push(item)
|
||||
}
|
||||
}
|
||||
|
||||
// Deliver batched email to each user with pending items
|
||||
for (const [userId, { user, items }] of userItemsMap) {
|
||||
if (items.length === 0 || !user.email) continue
|
||||
try {
|
||||
const rendered = emailService.renderBatchedNotificationEmail({
|
||||
teamId,
|
||||
teamName: teamNotifs[0].team?.name || 'Team',
|
||||
recipientName: user.name || 'Member',
|
||||
items,
|
||||
})
|
||||
// Collect attachments for this email based on rendered items
|
||||
const attachmentsMap = new Map<string, EmailAttachment>()
|
||||
|
||||
// Group items exactly as renderBatchedNotificationEmail does
|
||||
const groups = new Map<string, BatchedNotificationItem[]>()
|
||||
for (const item of items) {
|
||||
const key = getNotificationBatchGroupKey(item)
|
||||
const list = groups.get(key)
|
||||
if (list) {
|
||||
list.push(item)
|
||||
} else {
|
||||
groups.set(key, [item])
|
||||
}
|
||||
}
|
||||
|
||||
for (const [, cluster] of groups) {
|
||||
const first = cluster[0]
|
||||
if (first.creatorAvatarUrl) {
|
||||
const att = cidAttachmentMap.get(first.creatorAvatarUrl)
|
||||
if (att?.cid) attachmentsMap.set(att.cid, att)
|
||||
}
|
||||
|
||||
if (cluster.length <= 3) {
|
||||
// Detailed rows: individual avatars and thumbnails are rendered
|
||||
for (const item of cluster) {
|
||||
if (item.creatorAvatarUrl) {
|
||||
const att = cidAttachmentMap.get(item.creatorAvatarUrl)
|
||||
if (att?.cid) attachmentsMap.set(att.cid, att)
|
||||
}
|
||||
if (item.assetThumbnailUrl) {
|
||||
const att = cidAttachmentMap.get(item.assetThumbnailUrl)
|
||||
if (att?.cid) attachmentsMap.set(att.cid, att)
|
||||
}
|
||||
}
|
||||
}
|
||||
// If cluster.length > 3, thumbnails are not rendered, so we do not attach them
|
||||
}
|
||||
|
||||
const attachments = Array.from(attachmentsMap.values())
|
||||
|
||||
await emailService.sendMail(emailSettings, {
|
||||
to: user.email,
|
||||
subject: rendered.subject,
|
||||
html: rendered.html,
|
||||
text: rendered.text,
|
||||
attachments: attachments.length > 0 ? attachments : undefined,
|
||||
})
|
||||
} catch (err) {
|
||||
logger.error(
|
||||
{
|
||||
userId,
|
||||
email: user.email,
|
||||
err: err instanceof Error ? err.message : String(err),
|
||||
},
|
||||
'Failed to deliver batched notification email to user',
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Update batch status to processed
|
||||
await prisma.notification.updateMany({
|
||||
where: { id: { in: batchIds } },
|
||||
data: { emailStatus: NotificationEmailStatus.processed },
|
||||
})
|
||||
|
||||
return batchIds.length
|
||||
} catch (err) {
|
||||
logger.error(
|
||||
{ err: err instanceof Error ? err.message : String(err), batchCount: batchIds.length },
|
||||
'Unexpected failure in processPendingNotifications',
|
||||
)
|
||||
if (batchIds.length > 0) {
|
||||
// Mark as processed so subsequent turns aren't permanently blocked
|
||||
await prisma.notification
|
||||
.updateMany({
|
||||
where: { id: { in: batchIds } },
|
||||
data: { emailStatus: NotificationEmailStatus.processed },
|
||||
})
|
||||
.catch((cleanErr) =>
|
||||
logger.error({ cleanErr }, 'Failed to mark notifications processed on error'),
|
||||
)
|
||||
}
|
||||
throw err
|
||||
} finally {
|
||||
this.isProcessing = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const notificationJobService = new NotificationJobService()
|
||||
@@ -2,6 +2,7 @@ import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { TeamSettingsResponse } from '@shumai/dtos'
|
||||
|
||||
describe('TeamService', () => {
|
||||
setupTestDbHooks()
|
||||
@@ -10,6 +11,7 @@ describe('TeamService', () => {
|
||||
const team = await teamService.ensureDefaultTeam()
|
||||
expect(team).toBeDefined()
|
||||
expect(team.name).toBe('Default Team')
|
||||
expect((team.settings as TeamSettingsResponse | null)?.transcode?.threads).toBe(0)
|
||||
})
|
||||
|
||||
it('should create team', async () => {
|
||||
@@ -363,7 +365,15 @@ describe('TeamService', () => {
|
||||
})
|
||||
|
||||
const settings = await teamService.getSettings(team.id)
|
||||
expect(settings).toEqual({ semanticSearchEnabled: false, appearance: { hideAgent: false } })
|
||||
expect(settings).toEqual({
|
||||
semanticSearchEnabled: false,
|
||||
transcode: {
|
||||
videoStrategy: 'best_match',
|
||||
hardwareAcceleration: 'off',
|
||||
threads: 0,
|
||||
},
|
||||
appearance: { hideAgent: false },
|
||||
})
|
||||
|
||||
await teamService.updateSettings(team.id, 'theme', 'dark')
|
||||
|
||||
@@ -371,17 +381,27 @@ describe('TeamService', () => {
|
||||
expect(newSettings).toEqual({
|
||||
theme: 'dark',
|
||||
semanticSearchEnabled: false,
|
||||
transcode: {
|
||||
videoStrategy: 'best_match',
|
||||
hardwareAcceleration: 'off',
|
||||
threads: 0,
|
||||
},
|
||||
appearance: { hideAgent: false },
|
||||
})
|
||||
|
||||
await teamService.updateSettings(team.id, 'transcode.videoStrategy', 'all')
|
||||
await teamService.updateSettings(team.id, 'transcode.hardwareAcceleration', 'auto')
|
||||
await teamService.updateSettings(team.id, 'transcode.threads', 4)
|
||||
await teamService.updateSettings(team.id, 'appearance.hideAgent', true)
|
||||
|
||||
const finalSettings = await teamService.getSettings(team.id)
|
||||
expect(finalSettings).toEqual({
|
||||
theme: 'dark',
|
||||
transcode: { videoStrategy: 'all', hardwareAcceleration: 'auto' },
|
||||
transcode: {
|
||||
videoStrategy: 'all',
|
||||
hardwareAcceleration: 'auto',
|
||||
threads: 4,
|
||||
},
|
||||
appearance: { hideAgent: true },
|
||||
semanticSearchEnabled: false,
|
||||
})
|
||||
@@ -501,4 +521,36 @@ describe('TeamService', () => {
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
it('should not leak emailNotification or credentials in getSettings', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Team With Credentials',
|
||||
settings: {
|
||||
transcode: {
|
||||
videoStrategy: 'best_match',
|
||||
hardwareAcceleration: 'off',
|
||||
threads: 4,
|
||||
},
|
||||
appearance: {
|
||||
hideAgent: true,
|
||||
},
|
||||
emailNotification: {
|
||||
enabled: true,
|
||||
host: 'smtp.secret.com',
|
||||
port: 587,
|
||||
password: 'super-secret-smtp-password',
|
||||
from: 'noreply@secret.com',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const settings = await teamService.getSettings(team.id)
|
||||
|
||||
expect(settings).toBeDefined()
|
||||
expect(settings.transcode?.threads).toBe(4)
|
||||
expect(settings.appearance?.hideAgent).toBe(true)
|
||||
expect((settings as Record<string, unknown>).emailNotification).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -33,7 +33,11 @@ export class TeamService {
|
||||
data: {
|
||||
name: 'Default Team',
|
||||
settings: {
|
||||
transcode: { videoStrategy: 'best_match', hardwareAcceleration: 'off' },
|
||||
transcode: {
|
||||
videoStrategy: 'best_match',
|
||||
hardwareAcceleration: 'off',
|
||||
threads: 0,
|
||||
},
|
||||
},
|
||||
sandbox: { create: {} },
|
||||
},
|
||||
@@ -294,13 +298,25 @@ export class TeamService {
|
||||
where: { id: teamId },
|
||||
})
|
||||
if (!team) throw new HTTPException(404, { message: 'team not found' })
|
||||
const settings = (team.settings || {}) as TeamSettingsResponse
|
||||
const rawSettings = { ...(team.settings || {}) } as PrismaJson.Settings & {
|
||||
[key: string]: unknown
|
||||
}
|
||||
delete rawSettings.emailNotification
|
||||
const settings = rawSettings as TeamSettingsResponse
|
||||
|
||||
const embeddingAgent = await prisma.agent.findFirst({
|
||||
where: { teamId, type: 'embedding', enabled: true },
|
||||
})
|
||||
settings.semanticSearchEnabled = !!embeddingAgent
|
||||
|
||||
if (!settings.transcode) {
|
||||
settings.transcode = {
|
||||
videoStrategy: 'best_match',
|
||||
hardwareAcceleration: 'off',
|
||||
threads: 0,
|
||||
}
|
||||
}
|
||||
|
||||
if (!settings.appearance) {
|
||||
settings.appearance = { hideAgent: false }
|
||||
} else if (settings.appearance.hideAgent === undefined) {
|
||||
@@ -332,6 +348,12 @@ export class TeamService {
|
||||
TeamSettingsResponse['transcode']
|
||||
>['hardwareAcceleration']
|
||||
delete settings['transcode.hardwareAcceleration']
|
||||
} else if (key === 'transcode.threads') {
|
||||
if (!settings.transcode) {
|
||||
settings.transcode = {}
|
||||
}
|
||||
settings.transcode.threads = Number(value)
|
||||
delete settings['transcode.threads']
|
||||
} else if (key === 'appearance.hideAgent') {
|
||||
if (!settings.appearance) {
|
||||
settings.appearance = {}
|
||||
@@ -342,12 +364,12 @@ export class TeamService {
|
||||
settings[key] = value
|
||||
}
|
||||
|
||||
const updated = await prisma.team.update({
|
||||
await prisma.team.update({
|
||||
where: { id: teamId },
|
||||
data: { settings: settings as unknown as PrismaJson.Settings },
|
||||
})
|
||||
|
||||
return (updated.settings || {}) as TeamSettingsResponse
|
||||
return this.getSettings(teamId)
|
||||
}
|
||||
|
||||
async getSandboxSettings(teamId: string): Promise<SandboxSettings> {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -195,6 +195,58 @@ describe('UploadService', () => {
|
||||
transcode: {
|
||||
videoStrategy: 'best_match',
|
||||
hardwareAcceleration: 'off',
|
||||
threads: 0,
|
||||
sprite: true,
|
||||
poster: true,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should pass custom transcode.threads from team settings to transcode task', async () => {
|
||||
await prisma.team.update({
|
||||
where: { id: teamId },
|
||||
data: {
|
||||
settings: {
|
||||
transcode: {
|
||||
videoStrategy: 'all',
|
||||
hardwareAcceleration: 'auto',
|
||||
threads: 12,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const task = await prisma.task.create({
|
||||
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'video-custom-threads.mp4',
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
where: { key: 'test-key-threads' },
|
||||
create: { key: 'test-key-threads' },
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id })
|
||||
|
||||
const workflowTask = await prisma.workflowTask.findFirst({
|
||||
where: { assetId: asset.id, type: WorkflowTaskType.transcode_video },
|
||||
})
|
||||
expect(workflowTask).toBeDefined()
|
||||
expect(workflowTask?.payload).toEqual({
|
||||
projectId: projectId,
|
||||
transcode: {
|
||||
videoStrategy: 'all',
|
||||
hardwareAcceleration: 'auto',
|
||||
threads: 12,
|
||||
sprite: true,
|
||||
poster: true,
|
||||
},
|
||||
|
||||
@@ -331,6 +331,7 @@ export class UploadService {
|
||||
})
|
||||
} else {
|
||||
const settings = team.settings as PrismaJson.Settings | null
|
||||
const threads = settings?.transcode?.threads ?? 0
|
||||
if (isVideo) {
|
||||
const strategy = settings?.transcode?.videoStrategy || 'best_match'
|
||||
const hardwareAcceleration = settings?.transcode?.hardwareAcceleration || 'off'
|
||||
@@ -338,12 +339,15 @@ export class UploadService {
|
||||
await new VideoTranscoder(tx as any, asset.id, team.id, projectId)
|
||||
.setStrategy(strategy)
|
||||
.setHardwareAcceleration(hardwareAcceleration)
|
||||
.setThreads(threads)
|
||||
.withSprite()
|
||||
.withPoster()
|
||||
.submit()
|
||||
} else if (isAudio) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await new VideoTranscoder(tx as any, asset.id, team.id, projectId).submit()
|
||||
await new VideoTranscoder(tx as any, asset.id, team.id, projectId)
|
||||
.setThreads(threads)
|
||||
.submit()
|
||||
} else if (isImage) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await new ImageTranscoder(tx as any, asset.id, team.id, projectId).withThumbnail().submit()
|
||||
|
||||
@@ -67,15 +67,26 @@ describe('handleDaemonCommands', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('runs the runFn on normal startup', async () => {
|
||||
it('runs the runFn on normal foreground startup without creating a PID file', async () => {
|
||||
process.argv = ['node', 'script.js']
|
||||
const runFn = vi.fn().mockResolvedValue(undefined)
|
||||
|
||||
await handleDaemonCommands(appName, runFn)
|
||||
|
||||
expect(runFn).toHaveBeenCalled()
|
||||
expect(existsSync(pidFile)).toBe(true)
|
||||
expect(readFileSync(pidFile, 'utf8').trim()).toBe(process.pid.toString())
|
||||
expect(existsSync(pidFile)).toBe(false)
|
||||
})
|
||||
|
||||
it('runs foreground startup even if a stale or conflicting PID file exists', async () => {
|
||||
process.argv = ['node', 'script.js']
|
||||
const runFn = vi.fn().mockResolvedValue(undefined)
|
||||
|
||||
mkdirSync(join(mockTempDir, '.shumai', 'pids'), { recursive: true })
|
||||
writeFileSync(pidFile, '12345')
|
||||
|
||||
await handleDaemonCommands(appName, runFn)
|
||||
|
||||
expect(runFn).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('stops the process if stop command is passed', async () => {
|
||||
@@ -122,4 +133,26 @@ describe('handleDaemonCommands', () => {
|
||||
expect(spawn).toHaveBeenCalled()
|
||||
expect(mockExit).toHaveBeenCalledWith(0)
|
||||
})
|
||||
|
||||
it('runs and manages PID file when running as a daemonized child', async () => {
|
||||
process.argv = ['node', 'script.js']
|
||||
const originalEnv = process.env.SHUMAI_DAEMONIZED
|
||||
process.env.SHUMAI_DAEMONIZED = 'true'
|
||||
|
||||
try {
|
||||
const runFn = vi.fn().mockResolvedValue(undefined)
|
||||
|
||||
await handleDaemonCommands(appName, runFn)
|
||||
|
||||
expect(runFn).toHaveBeenCalled()
|
||||
expect(existsSync(pidFile)).toBe(true)
|
||||
expect(readFileSync(pidFile, 'utf8').trim()).toBe(process.pid.toString())
|
||||
} finally {
|
||||
if (originalEnv !== undefined) {
|
||||
process.env.SHUMAI_DAEMONIZED = originalEnv
|
||||
} else {
|
||||
delete process.env.SHUMAI_DAEMONIZED
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -17,6 +17,9 @@ const PID_DIR = join(SHUMAI_DIR, 'pids')
|
||||
const LOG_DIR = join(SHUMAI_DIR, 'logs')
|
||||
|
||||
function isProcessRunning(pid: number): boolean {
|
||||
if (pid <= 1) {
|
||||
return false
|
||||
}
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
return true
|
||||
@@ -35,7 +38,7 @@ async function stopProcess(appName: string, pidFile: string): Promise<boolean> {
|
||||
}
|
||||
|
||||
const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10)
|
||||
if (isNaN(pid)) {
|
||||
if (isNaN(pid) || pid <= 1) {
|
||||
console.log(`Invalid PID found in ${pidFile}. Cleaning up file.`)
|
||||
try {
|
||||
unlinkSync(pidFile)
|
||||
@@ -180,18 +183,25 @@ export async function handleDaemonCommands(
|
||||
appName: string,
|
||||
runFn: () => Promise<void>,
|
||||
): Promise<void> {
|
||||
const pidFile = join(PID_DIR, `${appName}.pid`)
|
||||
const logFile = join(LOG_DIR, `${appName}.log`)
|
||||
|
||||
// Ensure directories exist
|
||||
mkdirSync(PID_DIR, { recursive: true })
|
||||
mkdirSync(LOG_DIR, { recursive: true })
|
||||
|
||||
const args = process.argv.slice(2)
|
||||
const isStop = args.includes('stop')
|
||||
const isRestart = args.includes('restart')
|
||||
const isLogs = args.includes('logs')
|
||||
const isDaemon = args.includes('-d') && process.env.SHUMAI_DAEMONIZED !== 'true'
|
||||
const isDaemonizedChild = process.env.SHUMAI_DAEMONIZED === 'true'
|
||||
|
||||
// Normal foreground startup: do not create, check, or track PID files
|
||||
if (!isStop && !isRestart && !isLogs && !isDaemon && !isDaemonizedChild) {
|
||||
await runFn()
|
||||
return
|
||||
}
|
||||
|
||||
const pidFile = join(PID_DIR, `${appName}.pid`)
|
||||
const logFile = join(LOG_DIR, `${appName}.log`)
|
||||
|
||||
// Ensure directories exist for daemon commands
|
||||
mkdirSync(PID_DIR, { recursive: true })
|
||||
mkdirSync(LOG_DIR, { recursive: true })
|
||||
|
||||
if (isStop) {
|
||||
await stopProcess(appName, pidFile)
|
||||
@@ -216,27 +226,7 @@ export async function handleDaemonCommands(
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
// Normal Startup logic: check if already running
|
||||
if (existsSync(pidFile)) {
|
||||
const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10)
|
||||
if (!isNaN(pid) && pid !== process.pid) {
|
||||
if (isProcessRunning(pid)) {
|
||||
console.error(
|
||||
`${appName} is already running (PID: ${pid}). Use '${appName} stop' or '${appName} restart'.`,
|
||||
)
|
||||
process.exit(1)
|
||||
} else {
|
||||
// Process is dead, clean up PID file
|
||||
try {
|
||||
unlinkSync(pidFile)
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Write the PID file
|
||||
// Daemonized child startup (SHUMAI_DAEMONIZED === 'true')
|
||||
writeFileSync(pidFile, process.pid.toString(), 'utf8')
|
||||
|
||||
const cleanPidFile = () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/db",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "NotificationEmailStatus" AS ENUM ('pending', 'processing', 'processed', 'failed');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "notifications" ADD COLUMN "email_status" "NotificationEmailStatus" NOT NULL DEFAULT 'pending';
|
||||
|
||||
-- Update legacy rows to processed
|
||||
UPDATE "notifications" SET "email_status" = 'processed';
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notifications_email_status_created_at_idx" ON "notifications"("email_status", "created_at");
|
||||
@@ -76,6 +76,13 @@ enum NotificationType {
|
||||
kanban_task_comment_created
|
||||
}
|
||||
|
||||
enum NotificationEmailStatus {
|
||||
pending
|
||||
processing
|
||||
processed
|
||||
failed
|
||||
}
|
||||
|
||||
enum ProjectMemberRole {
|
||||
owner
|
||||
editor
|
||||
@@ -776,9 +783,12 @@ model Notification {
|
||||
userId String? @map("user_id")
|
||||
user User? @relation("UserToNotification", fields: [userId], references: [id])
|
||||
|
||||
emailStatus NotificationEmailStatus @default(pending) @map("email_status")
|
||||
|
||||
readByMembers TeamMember? @relation("TeamMemberToLastReadNotification")
|
||||
|
||||
@@index([kanbanTaskId])
|
||||
@@index([emailStatus, createdAt])
|
||||
@@map("notifications")
|
||||
}
|
||||
|
||||
|
||||
@@ -538,6 +538,13 @@ export type EnumNotificationTypeNullableFilter<$PrismaModel = never> = {
|
||||
not?: Prisma.NestedEnumNotificationTypeNullableFilter<$PrismaModel> | $Enums.NotificationType | null
|
||||
}
|
||||
|
||||
export type EnumNotificationEmailStatusFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.NotificationEmailStatus | Prisma.EnumNotificationEmailStatusFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.NotificationEmailStatus[] | Prisma.ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel>
|
||||
notIn?: $Enums.NotificationEmailStatus[] | Prisma.ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedEnumNotificationEmailStatusFilter<$PrismaModel> | $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type EnumNotificationTypeNullableWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.NotificationType | Prisma.EnumNotificationTypeFieldRefInput<$PrismaModel> | null
|
||||
in?: $Enums.NotificationType[] | Prisma.ListEnumNotificationTypeFieldRefInput<$PrismaModel> | null
|
||||
@@ -548,6 +555,16 @@ export type EnumNotificationTypeNullableWithAggregatesFilter<$PrismaModel = neve
|
||||
_max?: Prisma.NestedEnumNotificationTypeNullableFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type EnumNotificationEmailStatusWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.NotificationEmailStatus | Prisma.EnumNotificationEmailStatusFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.NotificationEmailStatus[] | Prisma.ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel>
|
||||
notIn?: $Enums.NotificationEmailStatus[] | Prisma.ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedEnumNotificationEmailStatusWithAggregatesFilter<$PrismaModel> | $Enums.NotificationEmailStatus
|
||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_min?: Prisma.NestedEnumNotificationEmailStatusFilter<$PrismaModel>
|
||||
_max?: Prisma.NestedEnumNotificationEmailStatusFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type EnumTaskTypeNullableFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.TaskType | Prisma.EnumTaskTypeFieldRefInput<$PrismaModel> | null
|
||||
in?: $Enums.TaskType[] | Prisma.ListEnumTaskTypeFieldRefInput<$PrismaModel> | null
|
||||
@@ -1367,6 +1384,13 @@ export type NestedEnumNotificationTypeNullableFilter<$PrismaModel = never> = {
|
||||
not?: Prisma.NestedEnumNotificationTypeNullableFilter<$PrismaModel> | $Enums.NotificationType | null
|
||||
}
|
||||
|
||||
export type NestedEnumNotificationEmailStatusFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.NotificationEmailStatus | Prisma.EnumNotificationEmailStatusFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.NotificationEmailStatus[] | Prisma.ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel>
|
||||
notIn?: $Enums.NotificationEmailStatus[] | Prisma.ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedEnumNotificationEmailStatusFilter<$PrismaModel> | $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NestedEnumNotificationTypeNullableWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.NotificationType | Prisma.EnumNotificationTypeFieldRefInput<$PrismaModel> | null
|
||||
in?: $Enums.NotificationType[] | Prisma.ListEnumNotificationTypeFieldRefInput<$PrismaModel> | null
|
||||
@@ -1377,6 +1401,16 @@ export type NestedEnumNotificationTypeNullableWithAggregatesFilter<$PrismaModel
|
||||
_max?: Prisma.NestedEnumNotificationTypeNullableFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type NestedEnumNotificationEmailStatusWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.NotificationEmailStatus | Prisma.EnumNotificationEmailStatusFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.NotificationEmailStatus[] | Prisma.ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel>
|
||||
notIn?: $Enums.NotificationEmailStatus[] | Prisma.ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedEnumNotificationEmailStatusWithAggregatesFilter<$PrismaModel> | $Enums.NotificationEmailStatus
|
||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_min?: Prisma.NestedEnumNotificationEmailStatusFilter<$PrismaModel>
|
||||
_max?: Prisma.NestedEnumNotificationEmailStatusFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type NestedEnumTaskTypeNullableFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.TaskType | Prisma.EnumTaskTypeFieldRefInput<$PrismaModel> | null
|
||||
in?: $Enums.TaskType[] | Prisma.ListEnumTaskTypeFieldRefInput<$PrismaModel> | null
|
||||
|
||||
+10
@@ -87,6 +87,16 @@ export const NotificationType = {
|
||||
export type NotificationType = (typeof NotificationType)[keyof typeof NotificationType]
|
||||
|
||||
|
||||
export const NotificationEmailStatus = {
|
||||
pending: 'pending',
|
||||
processing: 'processing',
|
||||
processed: 'processed',
|
||||
failed: 'failed'
|
||||
} as const
|
||||
|
||||
export type NotificationEmailStatus = (typeof NotificationEmailStatus)[keyof typeof NotificationEmailStatus]
|
||||
|
||||
|
||||
export const ProjectMemberRole = {
|
||||
owner: 'owner',
|
||||
editor: 'editor',
|
||||
|
||||
+4
-4
File diff suppressed because one or more lines are too long
+16
-1
@@ -4724,7 +4724,8 @@ export const NotificationScalarFieldEnum = {
|
||||
assetId: 'assetId',
|
||||
taskId: 'taskId',
|
||||
kanbanTaskId: 'kanbanTaskId',
|
||||
userId: 'userId'
|
||||
userId: 'userId',
|
||||
emailStatus: 'emailStatus'
|
||||
} as const
|
||||
|
||||
export type NotificationScalarFieldEnum = (typeof NotificationScalarFieldEnum)[keyof typeof NotificationScalarFieldEnum]
|
||||
@@ -5421,6 +5422,20 @@ export type ListEnumNotificationTypeFieldRefInput<$PrismaModel> = FieldRefInputT
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'NotificationEmailStatus'
|
||||
*/
|
||||
export type EnumNotificationEmailStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'NotificationEmailStatus'>
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'NotificationEmailStatus[]'
|
||||
*/
|
||||
export type ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'NotificationEmailStatus[]'>
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'TaskType'
|
||||
*/
|
||||
|
||||
@@ -490,7 +490,8 @@ export const NotificationScalarFieldEnum = {
|
||||
assetId: 'assetId',
|
||||
taskId: 'taskId',
|
||||
kanbanTaskId: 'kanbanTaskId',
|
||||
userId: 'userId'
|
||||
userId: 'userId',
|
||||
emailStatus: 'emailStatus'
|
||||
} as const
|
||||
|
||||
export type NotificationScalarFieldEnum = (typeof NotificationScalarFieldEnum)[keyof typeof NotificationScalarFieldEnum]
|
||||
|
||||
+80
-1
@@ -38,6 +38,7 @@ export type NotificationMinAggregateOutputType = {
|
||||
taskId: string | null
|
||||
kanbanTaskId: string | null
|
||||
userId: string | null
|
||||
emailStatus: $Enums.NotificationEmailStatus | null
|
||||
}
|
||||
|
||||
export type NotificationMaxAggregateOutputType = {
|
||||
@@ -52,6 +53,7 @@ export type NotificationMaxAggregateOutputType = {
|
||||
taskId: string | null
|
||||
kanbanTaskId: string | null
|
||||
userId: string | null
|
||||
emailStatus: $Enums.NotificationEmailStatus | null
|
||||
}
|
||||
|
||||
export type NotificationCountAggregateOutputType = {
|
||||
@@ -66,6 +68,7 @@ export type NotificationCountAggregateOutputType = {
|
||||
taskId: number
|
||||
kanbanTaskId: number
|
||||
userId: number
|
||||
emailStatus: number
|
||||
_all: number
|
||||
}
|
||||
|
||||
@@ -82,6 +85,7 @@ export type NotificationMinAggregateInputType = {
|
||||
taskId?: true
|
||||
kanbanTaskId?: true
|
||||
userId?: true
|
||||
emailStatus?: true
|
||||
}
|
||||
|
||||
export type NotificationMaxAggregateInputType = {
|
||||
@@ -96,6 +100,7 @@ export type NotificationMaxAggregateInputType = {
|
||||
taskId?: true
|
||||
kanbanTaskId?: true
|
||||
userId?: true
|
||||
emailStatus?: true
|
||||
}
|
||||
|
||||
export type NotificationCountAggregateInputType = {
|
||||
@@ -110,6 +115,7 @@ export type NotificationCountAggregateInputType = {
|
||||
taskId?: true
|
||||
kanbanTaskId?: true
|
||||
userId?: true
|
||||
emailStatus?: true
|
||||
_all?: true
|
||||
}
|
||||
|
||||
@@ -197,6 +203,7 @@ export type NotificationGroupByOutputType = {
|
||||
taskId: string | null
|
||||
kanbanTaskId: string | null
|
||||
userId: string | null
|
||||
emailStatus: $Enums.NotificationEmailStatus
|
||||
_count: NotificationCountAggregateOutputType | null
|
||||
_min: NotificationMinAggregateOutputType | null
|
||||
_max: NotificationMaxAggregateOutputType | null
|
||||
@@ -232,6 +239,7 @@ export type NotificationWhereInput = {
|
||||
taskId?: Prisma.StringNullableFilter<"Notification"> | string | null
|
||||
kanbanTaskId?: Prisma.StringNullableFilter<"Notification"> | string | null
|
||||
userId?: Prisma.StringNullableFilter<"Notification"> | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFilter<"Notification"> | $Enums.NotificationEmailStatus
|
||||
team?: Prisma.XOR<Prisma.TeamScalarRelationFilter, Prisma.TeamWhereInput>
|
||||
project?: Prisma.XOR<Prisma.ProjectNullableScalarRelationFilter, Prisma.ProjectWhereInput> | null
|
||||
creator?: Prisma.XOR<Prisma.UserNullableScalarRelationFilter, Prisma.UserWhereInput> | null
|
||||
@@ -254,6 +262,7 @@ export type NotificationOrderByWithRelationInput = {
|
||||
taskId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
kanbanTaskId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
userId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
emailStatus?: Prisma.SortOrder
|
||||
team?: Prisma.TeamOrderByWithRelationInput
|
||||
project?: Prisma.ProjectOrderByWithRelationInput
|
||||
creator?: Prisma.UserOrderByWithRelationInput
|
||||
@@ -279,6 +288,7 @@ export type NotificationWhereUniqueInput = Prisma.AtLeast<{
|
||||
taskId?: Prisma.StringNullableFilter<"Notification"> | string | null
|
||||
kanbanTaskId?: Prisma.StringNullableFilter<"Notification"> | string | null
|
||||
userId?: Prisma.StringNullableFilter<"Notification"> | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFilter<"Notification"> | $Enums.NotificationEmailStatus
|
||||
team?: Prisma.XOR<Prisma.TeamScalarRelationFilter, Prisma.TeamWhereInput>
|
||||
project?: Prisma.XOR<Prisma.ProjectNullableScalarRelationFilter, Prisma.ProjectWhereInput> | null
|
||||
creator?: Prisma.XOR<Prisma.UserNullableScalarRelationFilter, Prisma.UserWhereInput> | null
|
||||
@@ -301,6 +311,7 @@ export type NotificationOrderByWithAggregationInput = {
|
||||
taskId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
kanbanTaskId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
userId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
emailStatus?: Prisma.SortOrder
|
||||
_count?: Prisma.NotificationCountOrderByAggregateInput
|
||||
_max?: Prisma.NotificationMaxOrderByAggregateInput
|
||||
_min?: Prisma.NotificationMinOrderByAggregateInput
|
||||
@@ -321,6 +332,7 @@ export type NotificationScalarWhereWithAggregatesInput = {
|
||||
taskId?: Prisma.StringNullableWithAggregatesFilter<"Notification"> | string | null
|
||||
kanbanTaskId?: Prisma.StringNullableWithAggregatesFilter<"Notification"> | string | null
|
||||
userId?: Prisma.StringNullableWithAggregatesFilter<"Notification"> | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusWithAggregatesFilter<"Notification"> | $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationCreateInput = {
|
||||
@@ -328,6 +340,7 @@ export type NotificationCreateInput = {
|
||||
type?: $Enums.NotificationType | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
team: Prisma.TeamCreateNestedOneWithoutNotificationsInput
|
||||
project?: Prisma.ProjectCreateNestedOneWithoutNotificationsInput
|
||||
creator?: Prisma.UserCreateNestedOneWithoutCreatedNotificationsInput
|
||||
@@ -350,6 +363,7 @@ export type NotificationUncheckedCreateInput = {
|
||||
taskId?: string | null
|
||||
kanbanTaskId?: string | null
|
||||
userId?: string | null
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
readByMembers?: Prisma.TeamMemberUncheckedCreateNestedOneWithoutLastReadNotificationInput
|
||||
}
|
||||
|
||||
@@ -358,6 +372,7 @@ export type NotificationUpdateInput = {
|
||||
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutNotificationsNestedInput
|
||||
project?: Prisma.ProjectUpdateOneWithoutNotificationsNestedInput
|
||||
creator?: Prisma.UserUpdateOneWithoutCreatedNotificationsNestedInput
|
||||
@@ -380,6 +395,7 @@ export type NotificationUncheckedUpdateInput = {
|
||||
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
readByMembers?: Prisma.TeamMemberUncheckedUpdateOneWithoutLastReadNotificationNestedInput
|
||||
}
|
||||
|
||||
@@ -395,6 +411,7 @@ export type NotificationCreateManyInput = {
|
||||
taskId?: string | null
|
||||
kanbanTaskId?: string | null
|
||||
userId?: string | null
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationUpdateManyMutationInput = {
|
||||
@@ -402,6 +419,7 @@ export type NotificationUpdateManyMutationInput = {
|
||||
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationUncheckedUpdateManyInput = {
|
||||
@@ -416,6 +434,7 @@ export type NotificationUncheckedUpdateManyInput = {
|
||||
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationListRelationFilter = {
|
||||
@@ -445,6 +464,7 @@ export type NotificationCountOrderByAggregateInput = {
|
||||
taskId?: Prisma.SortOrder
|
||||
kanbanTaskId?: Prisma.SortOrder
|
||||
userId?: Prisma.SortOrder
|
||||
emailStatus?: Prisma.SortOrder
|
||||
}
|
||||
|
||||
export type NotificationMaxOrderByAggregateInput = {
|
||||
@@ -459,6 +479,7 @@ export type NotificationMaxOrderByAggregateInput = {
|
||||
taskId?: Prisma.SortOrder
|
||||
kanbanTaskId?: Prisma.SortOrder
|
||||
userId?: Prisma.SortOrder
|
||||
emailStatus?: Prisma.SortOrder
|
||||
}
|
||||
|
||||
export type NotificationMinOrderByAggregateInput = {
|
||||
@@ -473,6 +494,7 @@ export type NotificationMinOrderByAggregateInput = {
|
||||
taskId?: Prisma.SortOrder
|
||||
kanbanTaskId?: Prisma.SortOrder
|
||||
userId?: Prisma.SortOrder
|
||||
emailStatus?: Prisma.SortOrder
|
||||
}
|
||||
|
||||
export type NotificationCreateNestedManyWithoutCreatorInput = {
|
||||
@@ -705,6 +727,10 @@ export type NullableEnumNotificationTypeFieldUpdateOperationsInput = {
|
||||
set?: $Enums.NotificationType | null
|
||||
}
|
||||
|
||||
export type EnumNotificationEmailStatusFieldUpdateOperationsInput = {
|
||||
set?: $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationCreateNestedManyWithoutTaskInput = {
|
||||
create?: Prisma.XOR<Prisma.NotificationCreateWithoutTaskInput, Prisma.NotificationUncheckedCreateWithoutTaskInput> | Prisma.NotificationCreateWithoutTaskInput[] | Prisma.NotificationUncheckedCreateWithoutTaskInput[]
|
||||
connectOrCreate?: Prisma.NotificationCreateOrConnectWithoutTaskInput | Prisma.NotificationCreateOrConnectWithoutTaskInput[]
|
||||
@@ -794,6 +820,7 @@ export type NotificationCreateWithoutCreatorInput = {
|
||||
type?: $Enums.NotificationType | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
team: Prisma.TeamCreateNestedOneWithoutNotificationsInput
|
||||
project?: Prisma.ProjectCreateNestedOneWithoutNotificationsInput
|
||||
asset?: Prisma.AssetCreateNestedOneWithoutNotificationsInput
|
||||
@@ -814,6 +841,7 @@ export type NotificationUncheckedCreateWithoutCreatorInput = {
|
||||
taskId?: string | null
|
||||
kanbanTaskId?: string | null
|
||||
userId?: string | null
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
readByMembers?: Prisma.TeamMemberUncheckedCreateNestedOneWithoutLastReadNotificationInput
|
||||
}
|
||||
|
||||
@@ -832,6 +860,7 @@ export type NotificationCreateWithoutUserInput = {
|
||||
type?: $Enums.NotificationType | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
team: Prisma.TeamCreateNestedOneWithoutNotificationsInput
|
||||
project?: Prisma.ProjectCreateNestedOneWithoutNotificationsInput
|
||||
creator?: Prisma.UserCreateNestedOneWithoutCreatedNotificationsInput
|
||||
@@ -852,6 +881,7 @@ export type NotificationUncheckedCreateWithoutUserInput = {
|
||||
assetId?: string | null
|
||||
taskId?: string | null
|
||||
kanbanTaskId?: string | null
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
readByMembers?: Prisma.TeamMemberUncheckedCreateNestedOneWithoutLastReadNotificationInput
|
||||
}
|
||||
|
||||
@@ -896,6 +926,7 @@ export type NotificationScalarWhereInput = {
|
||||
taskId?: Prisma.StringNullableFilter<"Notification"> | string | null
|
||||
kanbanTaskId?: Prisma.StringNullableFilter<"Notification"> | string | null
|
||||
userId?: Prisma.StringNullableFilter<"Notification"> | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFilter<"Notification"> | $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationUpsertWithWhereUniqueWithoutUserInput = {
|
||||
@@ -919,6 +950,7 @@ export type NotificationCreateWithoutTeamInput = {
|
||||
type?: $Enums.NotificationType | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
project?: Prisma.ProjectCreateNestedOneWithoutNotificationsInput
|
||||
creator?: Prisma.UserCreateNestedOneWithoutCreatedNotificationsInput
|
||||
asset?: Prisma.AssetCreateNestedOneWithoutNotificationsInput
|
||||
@@ -939,6 +971,7 @@ export type NotificationUncheckedCreateWithoutTeamInput = {
|
||||
taskId?: string | null
|
||||
kanbanTaskId?: string | null
|
||||
userId?: string | null
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
readByMembers?: Prisma.TeamMemberUncheckedCreateNestedOneWithoutLastReadNotificationInput
|
||||
}
|
||||
|
||||
@@ -973,6 +1006,7 @@ export type NotificationCreateWithoutReadByMembersInput = {
|
||||
type?: $Enums.NotificationType | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
team: Prisma.TeamCreateNestedOneWithoutNotificationsInput
|
||||
project?: Prisma.ProjectCreateNestedOneWithoutNotificationsInput
|
||||
creator?: Prisma.UserCreateNestedOneWithoutCreatedNotificationsInput
|
||||
@@ -994,6 +1028,7 @@ export type NotificationUncheckedCreateWithoutReadByMembersInput = {
|
||||
taskId?: string | null
|
||||
kanbanTaskId?: string | null
|
||||
userId?: string | null
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationCreateOrConnectWithoutReadByMembersInput = {
|
||||
@@ -1017,6 +1052,7 @@ export type NotificationUpdateWithoutReadByMembersInput = {
|
||||
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutNotificationsNestedInput
|
||||
project?: Prisma.ProjectUpdateOneWithoutNotificationsNestedInput
|
||||
creator?: Prisma.UserUpdateOneWithoutCreatedNotificationsNestedInput
|
||||
@@ -1038,6 +1074,7 @@ export type NotificationUncheckedUpdateWithoutReadByMembersInput = {
|
||||
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationCreateWithoutProjectInput = {
|
||||
@@ -1045,6 +1082,7 @@ export type NotificationCreateWithoutProjectInput = {
|
||||
type?: $Enums.NotificationType | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
team: Prisma.TeamCreateNestedOneWithoutNotificationsInput
|
||||
creator?: Prisma.UserCreateNestedOneWithoutCreatedNotificationsInput
|
||||
asset?: Prisma.AssetCreateNestedOneWithoutNotificationsInput
|
||||
@@ -1065,6 +1103,7 @@ export type NotificationUncheckedCreateWithoutProjectInput = {
|
||||
taskId?: string | null
|
||||
kanbanTaskId?: string | null
|
||||
userId?: string | null
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
readByMembers?: Prisma.TeamMemberUncheckedCreateNestedOneWithoutLastReadNotificationInput
|
||||
}
|
||||
|
||||
@@ -1099,6 +1138,7 @@ export type NotificationCreateWithoutAssetInput = {
|
||||
type?: $Enums.NotificationType | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
team: Prisma.TeamCreateNestedOneWithoutNotificationsInput
|
||||
project?: Prisma.ProjectCreateNestedOneWithoutNotificationsInput
|
||||
creator?: Prisma.UserCreateNestedOneWithoutCreatedNotificationsInput
|
||||
@@ -1119,6 +1159,7 @@ export type NotificationUncheckedCreateWithoutAssetInput = {
|
||||
taskId?: string | null
|
||||
kanbanTaskId?: string | null
|
||||
userId?: string | null
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
readByMembers?: Prisma.TeamMemberUncheckedCreateNestedOneWithoutLastReadNotificationInput
|
||||
}
|
||||
|
||||
@@ -1153,6 +1194,7 @@ export type NotificationCreateWithoutTaskInput = {
|
||||
type?: $Enums.NotificationType | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
team: Prisma.TeamCreateNestedOneWithoutNotificationsInput
|
||||
project?: Prisma.ProjectCreateNestedOneWithoutNotificationsInput
|
||||
creator?: Prisma.UserCreateNestedOneWithoutCreatedNotificationsInput
|
||||
@@ -1173,6 +1215,7 @@ export type NotificationUncheckedCreateWithoutTaskInput = {
|
||||
assetId?: string | null
|
||||
kanbanTaskId?: string | null
|
||||
userId?: string | null
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
readByMembers?: Prisma.TeamMemberUncheckedCreateNestedOneWithoutLastReadNotificationInput
|
||||
}
|
||||
|
||||
@@ -1207,6 +1250,7 @@ export type NotificationCreateWithoutKanbanTaskInput = {
|
||||
type?: $Enums.NotificationType | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
team: Prisma.TeamCreateNestedOneWithoutNotificationsInput
|
||||
project?: Prisma.ProjectCreateNestedOneWithoutNotificationsInput
|
||||
creator?: Prisma.UserCreateNestedOneWithoutCreatedNotificationsInput
|
||||
@@ -1227,6 +1271,7 @@ export type NotificationUncheckedCreateWithoutKanbanTaskInput = {
|
||||
assetId?: string | null
|
||||
taskId?: string | null
|
||||
userId?: string | null
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
readByMembers?: Prisma.TeamMemberUncheckedCreateNestedOneWithoutLastReadNotificationInput
|
||||
}
|
||||
|
||||
@@ -1267,6 +1312,7 @@ export type NotificationCreateManyCreatorInput = {
|
||||
taskId?: string | null
|
||||
kanbanTaskId?: string | null
|
||||
userId?: string | null
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationCreateManyUserInput = {
|
||||
@@ -1280,6 +1326,7 @@ export type NotificationCreateManyUserInput = {
|
||||
assetId?: string | null
|
||||
taskId?: string | null
|
||||
kanbanTaskId?: string | null
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationUpdateWithoutCreatorInput = {
|
||||
@@ -1287,6 +1334,7 @@ export type NotificationUpdateWithoutCreatorInput = {
|
||||
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutNotificationsNestedInput
|
||||
project?: Prisma.ProjectUpdateOneWithoutNotificationsNestedInput
|
||||
asset?: Prisma.AssetUpdateOneWithoutNotificationsNestedInput
|
||||
@@ -1307,6 +1355,7 @@ export type NotificationUncheckedUpdateWithoutCreatorInput = {
|
||||
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
readByMembers?: Prisma.TeamMemberUncheckedUpdateOneWithoutLastReadNotificationNestedInput
|
||||
}
|
||||
|
||||
@@ -1321,6 +1370,7 @@ export type NotificationUncheckedUpdateManyWithoutCreatorInput = {
|
||||
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationUpdateWithoutUserInput = {
|
||||
@@ -1328,6 +1378,7 @@ export type NotificationUpdateWithoutUserInput = {
|
||||
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutNotificationsNestedInput
|
||||
project?: Prisma.ProjectUpdateOneWithoutNotificationsNestedInput
|
||||
creator?: Prisma.UserUpdateOneWithoutCreatedNotificationsNestedInput
|
||||
@@ -1348,6 +1399,7 @@ export type NotificationUncheckedUpdateWithoutUserInput = {
|
||||
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
readByMembers?: Prisma.TeamMemberUncheckedUpdateOneWithoutLastReadNotificationNestedInput
|
||||
}
|
||||
|
||||
@@ -1362,6 +1414,7 @@ export type NotificationUncheckedUpdateManyWithoutUserInput = {
|
||||
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationCreateManyTeamInput = {
|
||||
@@ -1375,6 +1428,7 @@ export type NotificationCreateManyTeamInput = {
|
||||
taskId?: string | null
|
||||
kanbanTaskId?: string | null
|
||||
userId?: string | null
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationUpdateWithoutTeamInput = {
|
||||
@@ -1382,6 +1436,7 @@ export type NotificationUpdateWithoutTeamInput = {
|
||||
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
project?: Prisma.ProjectUpdateOneWithoutNotificationsNestedInput
|
||||
creator?: Prisma.UserUpdateOneWithoutCreatedNotificationsNestedInput
|
||||
asset?: Prisma.AssetUpdateOneWithoutNotificationsNestedInput
|
||||
@@ -1402,6 +1457,7 @@ export type NotificationUncheckedUpdateWithoutTeamInput = {
|
||||
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
readByMembers?: Prisma.TeamMemberUncheckedUpdateOneWithoutLastReadNotificationNestedInput
|
||||
}
|
||||
|
||||
@@ -1416,6 +1472,7 @@ export type NotificationUncheckedUpdateManyWithoutTeamInput = {
|
||||
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationCreateManyProjectInput = {
|
||||
@@ -1429,6 +1486,7 @@ export type NotificationCreateManyProjectInput = {
|
||||
taskId?: string | null
|
||||
kanbanTaskId?: string | null
|
||||
userId?: string | null
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationUpdateWithoutProjectInput = {
|
||||
@@ -1436,6 +1494,7 @@ export type NotificationUpdateWithoutProjectInput = {
|
||||
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutNotificationsNestedInput
|
||||
creator?: Prisma.UserUpdateOneWithoutCreatedNotificationsNestedInput
|
||||
asset?: Prisma.AssetUpdateOneWithoutNotificationsNestedInput
|
||||
@@ -1456,6 +1515,7 @@ export type NotificationUncheckedUpdateWithoutProjectInput = {
|
||||
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
readByMembers?: Prisma.TeamMemberUncheckedUpdateOneWithoutLastReadNotificationNestedInput
|
||||
}
|
||||
|
||||
@@ -1470,6 +1530,7 @@ export type NotificationUncheckedUpdateManyWithoutProjectInput = {
|
||||
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationCreateManyAssetInput = {
|
||||
@@ -1483,6 +1544,7 @@ export type NotificationCreateManyAssetInput = {
|
||||
taskId?: string | null
|
||||
kanbanTaskId?: string | null
|
||||
userId?: string | null
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationUpdateWithoutAssetInput = {
|
||||
@@ -1490,6 +1552,7 @@ export type NotificationUpdateWithoutAssetInput = {
|
||||
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutNotificationsNestedInput
|
||||
project?: Prisma.ProjectUpdateOneWithoutNotificationsNestedInput
|
||||
creator?: Prisma.UserUpdateOneWithoutCreatedNotificationsNestedInput
|
||||
@@ -1510,6 +1573,7 @@ export type NotificationUncheckedUpdateWithoutAssetInput = {
|
||||
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
readByMembers?: Prisma.TeamMemberUncheckedUpdateOneWithoutLastReadNotificationNestedInput
|
||||
}
|
||||
|
||||
@@ -1524,6 +1588,7 @@ export type NotificationUncheckedUpdateManyWithoutAssetInput = {
|
||||
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationCreateManyTaskInput = {
|
||||
@@ -1537,6 +1602,7 @@ export type NotificationCreateManyTaskInput = {
|
||||
assetId?: string | null
|
||||
kanbanTaskId?: string | null
|
||||
userId?: string | null
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationUpdateWithoutTaskInput = {
|
||||
@@ -1544,6 +1610,7 @@ export type NotificationUpdateWithoutTaskInput = {
|
||||
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutNotificationsNestedInput
|
||||
project?: Prisma.ProjectUpdateOneWithoutNotificationsNestedInput
|
||||
creator?: Prisma.UserUpdateOneWithoutCreatedNotificationsNestedInput
|
||||
@@ -1564,6 +1631,7 @@ export type NotificationUncheckedUpdateWithoutTaskInput = {
|
||||
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
readByMembers?: Prisma.TeamMemberUncheckedUpdateOneWithoutLastReadNotificationNestedInput
|
||||
}
|
||||
|
||||
@@ -1578,6 +1646,7 @@ export type NotificationUncheckedUpdateManyWithoutTaskInput = {
|
||||
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationCreateManyKanbanTaskInput = {
|
||||
@@ -1591,6 +1660,7 @@ export type NotificationCreateManyKanbanTaskInput = {
|
||||
assetId?: string | null
|
||||
taskId?: string | null
|
||||
userId?: string | null
|
||||
emailStatus?: $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
export type NotificationUpdateWithoutKanbanTaskInput = {
|
||||
@@ -1598,6 +1668,7 @@ export type NotificationUpdateWithoutKanbanTaskInput = {
|
||||
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutNotificationsNestedInput
|
||||
project?: Prisma.ProjectUpdateOneWithoutNotificationsNestedInput
|
||||
creator?: Prisma.UserUpdateOneWithoutCreatedNotificationsNestedInput
|
||||
@@ -1618,6 +1689,7 @@ export type NotificationUncheckedUpdateWithoutKanbanTaskInput = {
|
||||
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
readByMembers?: Prisma.TeamMemberUncheckedUpdateOneWithoutLastReadNotificationNestedInput
|
||||
}
|
||||
|
||||
@@ -1632,6 +1704,7 @@ export type NotificationUncheckedUpdateManyWithoutKanbanTaskInput = {
|
||||
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
|
||||
}
|
||||
|
||||
|
||||
@@ -1648,6 +1721,7 @@ export type NotificationSelect<ExtArgs extends runtime.Types.Extensions.Internal
|
||||
taskId?: boolean
|
||||
kanbanTaskId?: boolean
|
||||
userId?: boolean
|
||||
emailStatus?: boolean
|
||||
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
|
||||
project?: boolean | Prisma.Notification$projectArgs<ExtArgs>
|
||||
creator?: boolean | Prisma.Notification$creatorArgs<ExtArgs>
|
||||
@@ -1670,6 +1744,7 @@ export type NotificationSelectCreateManyAndReturn<ExtArgs extends runtime.Types.
|
||||
taskId?: boolean
|
||||
kanbanTaskId?: boolean
|
||||
userId?: boolean
|
||||
emailStatus?: boolean
|
||||
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
|
||||
project?: boolean | Prisma.Notification$projectArgs<ExtArgs>
|
||||
creator?: boolean | Prisma.Notification$creatorArgs<ExtArgs>
|
||||
@@ -1691,6 +1766,7 @@ export type NotificationSelectUpdateManyAndReturn<ExtArgs extends runtime.Types.
|
||||
taskId?: boolean
|
||||
kanbanTaskId?: boolean
|
||||
userId?: boolean
|
||||
emailStatus?: boolean
|
||||
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
|
||||
project?: boolean | Prisma.Notification$projectArgs<ExtArgs>
|
||||
creator?: boolean | Prisma.Notification$creatorArgs<ExtArgs>
|
||||
@@ -1712,9 +1788,10 @@ export type NotificationSelectScalar = {
|
||||
taskId?: boolean
|
||||
kanbanTaskId?: boolean
|
||||
userId?: boolean
|
||||
emailStatus?: boolean
|
||||
}
|
||||
|
||||
export type NotificationOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "type" | "createdAt" | "updatedAt" | "teamId" | "projectId" | "creatorId" | "assetId" | "taskId" | "kanbanTaskId" | "userId", ExtArgs["result"]["notification"]>
|
||||
export type NotificationOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "type" | "createdAt" | "updatedAt" | "teamId" | "projectId" | "creatorId" | "assetId" | "taskId" | "kanbanTaskId" | "userId" | "emailStatus", ExtArgs["result"]["notification"]>
|
||||
export type NotificationInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
|
||||
project?: boolean | Prisma.Notification$projectArgs<ExtArgs>
|
||||
@@ -1768,6 +1845,7 @@ export type $NotificationPayload<ExtArgs extends runtime.Types.Extensions.Intern
|
||||
taskId: string | null
|
||||
kanbanTaskId: string | null
|
||||
userId: string | null
|
||||
emailStatus: $Enums.NotificationEmailStatus
|
||||
}, ExtArgs["result"]["notification"]>
|
||||
composites: {}
|
||||
}
|
||||
@@ -2210,6 +2288,7 @@ export interface NotificationFieldRefs {
|
||||
readonly taskId: Prisma.FieldRef<"Notification", 'String'>
|
||||
readonly kanbanTaskId: Prisma.FieldRef<"Notification", 'String'>
|
||||
readonly userId: Prisma.FieldRef<"Notification", 'String'>
|
||||
readonly emailStatus: Prisma.FieldRef<"Notification", 'NotificationEmailStatus'>
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -18,6 +18,20 @@ export function registerWorkflowTrigger(cb: WorkflowTriggerCallback) {
|
||||
onWorkflowTaskCreated = cb
|
||||
}
|
||||
|
||||
// Global callback for workflow task cancellation (decouples db/core packages from workflow engine)
|
||||
type WorkflowCancelCallback = (taskId: string) => Promise<void>
|
||||
let onWorkflowTaskCancelled: WorkflowCancelCallback | null = null
|
||||
|
||||
export function registerWorkflowCancel(cb: WorkflowCancelCallback) {
|
||||
onWorkflowTaskCancelled = cb
|
||||
}
|
||||
|
||||
export async function cancelWorkflowTask(taskId: string): Promise<void> {
|
||||
if (onWorkflowTaskCancelled) {
|
||||
await onWorkflowTaskCancelled(taskId)
|
||||
}
|
||||
}
|
||||
|
||||
const isTest = process.env.NODE_ENV === 'test'
|
||||
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
|
||||
@@ -50,6 +50,7 @@ declare global {
|
||||
// ----------------------------------------------------------------------
|
||||
export type VideoTranscodeStrategy = 'best_match' | 'all'
|
||||
export type HardwareAcceleration = 'off' | 'auto'
|
||||
export type HdrType = 'pq' | 'hlg' | 'dovi_p5' | 'dovi_p8' | 'sdr'
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Collection Filter
|
||||
@@ -59,6 +60,7 @@ declare global {
|
||||
export interface TranscodeSettings {
|
||||
videoStrategy: VideoTranscodeStrategy
|
||||
hardwareAcceleration?: HardwareAcceleration
|
||||
threads?: number
|
||||
}
|
||||
|
||||
export interface MediaProviderConfig {
|
||||
@@ -83,10 +85,23 @@ declare global {
|
||||
hideAgent?: boolean
|
||||
}
|
||||
|
||||
export interface EmailNotificationSettings {
|
||||
enabled: boolean
|
||||
host?: string
|
||||
port?: number
|
||||
username?: string
|
||||
password?: string
|
||||
smtps?: boolean
|
||||
ignoreCert?: boolean
|
||||
from?: string
|
||||
replyTo?: string
|
||||
}
|
||||
|
||||
export interface Settings {
|
||||
transcode: TranscodeSettings
|
||||
transcode?: TranscodeSettings
|
||||
mediaGeneration?: MediaGenerationSettings
|
||||
appearance?: AppearanceSettings
|
||||
emailNotification?: EmailNotificationSettings
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -103,6 +118,7 @@ declare global {
|
||||
width: number
|
||||
height: number
|
||||
resolution?: string
|
||||
hdr?: boolean
|
||||
}
|
||||
|
||||
export interface ImageTranscode {
|
||||
@@ -129,6 +145,7 @@ declare global {
|
||||
export interface Metadata {
|
||||
originalHeight: number
|
||||
originalWidth: number
|
||||
rotation?: number
|
||||
hasAudio: boolean
|
||||
duration: number
|
||||
bitRate: number
|
||||
@@ -141,6 +158,12 @@ declare global {
|
||||
audioChannels?: number
|
||||
audioSampleRate?: number
|
||||
audioBitDepth?: number
|
||||
colorTransfer?: string
|
||||
colorPrimaries?: string
|
||||
colorSpace?: string
|
||||
isHdr?: boolean
|
||||
hdrType?: HdrType
|
||||
dvProfile?: number
|
||||
format: unknown
|
||||
}
|
||||
|
||||
@@ -314,6 +337,7 @@ declare global {
|
||||
export interface TaskSpec {
|
||||
videoStrategy?: VideoTranscodeStrategy
|
||||
hardwareAcceleration?: HardwareAcceleration
|
||||
threads?: number
|
||||
thumbnail?: boolean
|
||||
sprite?: boolean
|
||||
poster?: boolean
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/dtos",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { z } from 'zod'
|
||||
import { paginationPageInfoSchema, paginationParamsSchema } from './pagination'
|
||||
|
||||
/**
|
||||
* Number of days a soft-deleted asset is kept before it is permanently purged.
|
||||
* Shared between the backend retention logic and the WebUI countdown labels.
|
||||
*/
|
||||
export const TRASH_RETENTION_DAYS = 30
|
||||
|
||||
export const assetInfoPaginatedListSchema = z.object({
|
||||
data: z.array(z.lazy(() => assetInfoSchema)),
|
||||
pageInfo: paginationPageInfoSchema,
|
||||
@@ -12,6 +18,7 @@ export const previewInfoSchema = z.object({
|
||||
thumbnailUrl: z.string().optional(),
|
||||
originalHeight: z.number().optional(),
|
||||
originalWidth: z.number().optional(),
|
||||
rotation: z.number().optional(),
|
||||
spriteUrl: z.string().optional(),
|
||||
duration: z.number().optional(),
|
||||
pageCount: z.number().optional(),
|
||||
@@ -54,6 +61,7 @@ export const mediaMetadataSchema = z.object({
|
||||
duration: z.number().optional(),
|
||||
originalWidth: z.number().optional(),
|
||||
originalHeight: z.number().optional(),
|
||||
rotation: z.number().optional(),
|
||||
frameRate: z.number().optional(),
|
||||
totalFrames: z.number().optional(),
|
||||
startTimecode: z.string().optional(),
|
||||
@@ -97,6 +105,7 @@ export const assetInfoSchema = z.object({
|
||||
width: z.number(),
|
||||
height: z.number(),
|
||||
size: z.number(),
|
||||
hdr: z.boolean().optional(),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
@@ -329,6 +338,7 @@ export interface VideoTranscode {
|
||||
width: number
|
||||
height: number
|
||||
size: number
|
||||
hdr?: boolean
|
||||
}
|
||||
|
||||
export const postAttachmentRequestSchema = z.object({
|
||||
|
||||
@@ -99,3 +99,51 @@ export const notificationSettingsSchema = z.object({
|
||||
})
|
||||
|
||||
export type NotificationSettings = z.infer<typeof notificationSettingsSchema>
|
||||
|
||||
export const emailNotificationSettingsSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
host: z.string().default(''),
|
||||
port: z.number().int().min(1).max(65535).default(587),
|
||||
username: z.string().optional(),
|
||||
password: z.string().optional(),
|
||||
smtps: z.boolean().default(false),
|
||||
ignoreCert: z.boolean().default(false),
|
||||
from: z.string().default(''),
|
||||
replyTo: z.string().optional(),
|
||||
})
|
||||
|
||||
export type EmailNotificationSettings = z.infer<typeof emailNotificationSettingsSchema>
|
||||
|
||||
export const updateEmailNotificationSettingsSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
host: z.string().default(''),
|
||||
port: z.number().int().min(1).max(65535).default(587),
|
||||
username: z.string().optional(),
|
||||
password: z.string().optional(),
|
||||
smtps: z.boolean().default(false),
|
||||
ignoreCert: z.boolean().default(false),
|
||||
from: z.string().default(''),
|
||||
replyTo: z.string().optional(),
|
||||
})
|
||||
|
||||
export type UpdateEmailNotificationSettings = z.input<typeof updateEmailNotificationSettingsSchema>
|
||||
|
||||
export const testEmailRequestSchema = z.object({
|
||||
host: z.string().optional(),
|
||||
port: z.number().int().min(1).max(65535).optional(),
|
||||
username: z.string().optional(),
|
||||
password: z.string().optional(),
|
||||
smtps: z.boolean().optional(),
|
||||
ignoreCert: z.boolean().optional(),
|
||||
from: z.string().optional(),
|
||||
replyTo: z.string().optional(),
|
||||
})
|
||||
|
||||
export type TestEmailRequest = z.infer<typeof testEmailRequestSchema>
|
||||
|
||||
export const testEmailResponseSchema = z.object({
|
||||
success: z.boolean(),
|
||||
messageId: z.string(),
|
||||
})
|
||||
|
||||
export type TestEmailResponse = z.infer<typeof testEmailResponseSchema>
|
||||
|
||||
@@ -89,6 +89,10 @@ export const updateTeamSettingsRequestSchema = z.union([
|
||||
key: z.literal('transcode.hardwareAcceleration'),
|
||||
value: z.nativeEnum(HardwareAcceleration),
|
||||
}),
|
||||
z.object({
|
||||
key: z.literal('transcode.threads'),
|
||||
value: z.number().int().min(0).max(32),
|
||||
}),
|
||||
z.object({
|
||||
key: z.literal('appearance.hideAgent'),
|
||||
value: z.boolean(),
|
||||
@@ -104,6 +108,7 @@ export interface TeamSettingsResponse {
|
||||
transcode?: {
|
||||
videoStrategy?: VideoTranscodeStrategy
|
||||
hardwareAcceleration?: HardwareAcceleration
|
||||
threads?: number
|
||||
}
|
||||
appearance?: TeamAppearanceSettings
|
||||
semanticSearchEnabled?: boolean
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/e2e",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/tableprinter",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -63,6 +63,7 @@ vi.mock('@shumai/core/src/transcode/transcode', async (importOriginal) => {
|
||||
transcodeAudio: vi.fn(),
|
||||
transcodeImage: vi.fn(),
|
||||
generateSprite: vi.fn(),
|
||||
generatePoster: vi.fn(),
|
||||
generatePdfSprite: vi.fn().mockResolvedValue({
|
||||
pageCount: 10,
|
||||
originalWidth: 800,
|
||||
@@ -75,6 +76,7 @@ vi.mock('@shumai/core/src/transcode/transcode', async (importOriginal) => {
|
||||
takeScreenshots: vi.fn(),
|
||||
overlayAnnotations: vi.fn(),
|
||||
renderPdfPages: vi.fn(),
|
||||
getAvailableFilters: vi.fn().mockResolvedValue(new Set(['zscale', 'tonemap'])),
|
||||
},
|
||||
}
|
||||
})
|
||||
@@ -184,6 +186,7 @@ describe('Transcode Activities', () => {
|
||||
audioChannels: 2,
|
||||
audioSampleRate: 48000,
|
||||
audioBitDepth: 16,
|
||||
rotation: -90,
|
||||
mimeType: 'video/mp4',
|
||||
})
|
||||
|
||||
@@ -197,6 +200,7 @@ describe('Transcode Activities', () => {
|
||||
expect(transcodeService.getVideoInfo).toHaveBeenCalledWith('/tmp/v.mp4')
|
||||
expect(result.duration).toBe(10)
|
||||
expect(result.metadata?.originalWidth).toBe(1920)
|
||||
expect(result.metadata?.rotation).toBe(-90)
|
||||
expect(result.metadata?.videoBitRate).toBe(850000)
|
||||
expect(result.metadata?.videoCodec).toBe('Advanced Video Coding')
|
||||
expect(result.metadata?.audioCodec).toBe('MPEG-4 Audio')
|
||||
@@ -205,7 +209,10 @@ describe('Transcode Activities', () => {
|
||||
expect(result.metadata?.audioBitDepth).toBe(16)
|
||||
expect(metadataService.updateAssetMetadata).toHaveBeenCalledWith(
|
||||
asset.id,
|
||||
expect.arrayContaining([{ key: 'file_type', value: 'video' }]),
|
||||
expect.arrayContaining([
|
||||
{ key: 'file_type', value: 'video' },
|
||||
{ key: 'rotation', value: -90 },
|
||||
]),
|
||||
true,
|
||||
)
|
||||
})
|
||||
@@ -595,6 +602,83 @@ describe('Transcode Activities', () => {
|
||||
expect(updated?.hasJpegPreview).toBe(false)
|
||||
expect(s3Service.putObject).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should throw non-retryable ApplicationFailure and not upload when asset is pending_purge in updateAssetMediaActivity', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'purging.mp4',
|
||||
storageKey: { create: { key: 'purging.mp4' } },
|
||||
status: 'pending_purge',
|
||||
type: 'file',
|
||||
},
|
||||
})
|
||||
|
||||
const putObjectSpy = vi.mocked(s3Service.putObject)
|
||||
putObjectSpy.mockClear()
|
||||
|
||||
await expect(
|
||||
updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo: { duration: 100 } as unknown as PrismaJson.MediaInfo,
|
||||
}),
|
||||
).rejects.toThrow('Asset not found, has no key, or is being purged')
|
||||
|
||||
expect(putObjectSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should tolerate missing or deleted asset without throwing P2025 in updateAssetMediaActivity', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'deleted-during-update.mp4',
|
||||
storageKey: { create: { key: 'deleted-during-update.mp4' } },
|
||||
status: 'uploaded',
|
||||
type: 'file',
|
||||
},
|
||||
})
|
||||
|
||||
const putObjectSpy = vi.mocked(s3Service.putObject)
|
||||
putObjectSpy.mockClear()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
putObjectSpy.mockImplementationOnce(async (): Promise<any> => {
|
||||
await prisma.asset.delete({ where: { id: asset.id } })
|
||||
return {}
|
||||
})
|
||||
|
||||
await expect(
|
||||
updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo: { duration: 100 } as unknown as PrismaJson.MediaInfo,
|
||||
}),
|
||||
).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('should throw non-retryable ApplicationFailure and not upload when asset is pending_purge in transcodeVideoActivity', async () => {
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'purging-video.mp4',
|
||||
storageKey: { create: { key: 'purging-video.mp4' } },
|
||||
status: 'pending_purge',
|
||||
type: 'file',
|
||||
},
|
||||
})
|
||||
|
||||
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
|
||||
const putObjectSpy = vi.mocked(s3Service.putObject)
|
||||
putObjectSpy.mockClear()
|
||||
|
||||
await expect(
|
||||
transcodeVideoActivity({
|
||||
assetKey: 'purging-video.mp4',
|
||||
filePath: '/tmp/purging-video.mp4',
|
||||
videoSpec: { resolution: '720p', width: 1280, height: 720 },
|
||||
duration: 10,
|
||||
originalFps: 30,
|
||||
}),
|
||||
).rejects.toThrow('Asset or storage key has been purged or is pending purge')
|
||||
|
||||
expect(putObjectSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should call transcodeService.transcodeVideo', async () => {
|
||||
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
|
||||
|
||||
@@ -606,6 +690,7 @@ describe('Transcode Activities', () => {
|
||||
originalFps: 30,
|
||||
hardwareAcceleration: 'auto',
|
||||
sourceVideoBitrate: 600_000,
|
||||
threads: 8,
|
||||
})
|
||||
|
||||
expect(transcodeService.transcodeVideo).toHaveBeenCalledWith(
|
||||
@@ -613,6 +698,38 @@ describe('Transcode Activities', () => {
|
||||
inputFile: '/tmp/v.mp4',
|
||||
hardwareAcceleration: 'auto',
|
||||
sourceVideoBitrate: 600_000,
|
||||
threads: 8,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('transcodeVideoActivity appends -hdr.mp4 suffix and forwards HDR metadata', async () => {
|
||||
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
|
||||
|
||||
const result = await transcodeVideoActivity({
|
||||
assetKey: 'files/asset-1/video.mp4',
|
||||
filePath: '/tmp/video.mp4',
|
||||
videoSpec: { resolution: '1080p', width: 1920, height: 1080, hdr: true },
|
||||
duration: 10,
|
||||
originalFps: 30,
|
||||
sourceIsHdr: true,
|
||||
sourceHdrType: 'pq',
|
||||
sourceColorTransfer: 'smpte2084',
|
||||
sourceColorPrimaries: 'bt2020',
|
||||
sourceColorSpace: 'bt2020nc',
|
||||
})
|
||||
|
||||
expect(result.key).toBe('files/asset-1/video-1080p-hdr.mp4')
|
||||
expect(result.hdr).toBe(true)
|
||||
expect(transcodeService.transcodeVideo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
inputFile: '/tmp/video.mp4',
|
||||
hdr: true,
|
||||
sourceIsHdr: true,
|
||||
sourceHdrType: 'pq',
|
||||
sourceColorTransfer: 'smpte2084',
|
||||
sourceColorPrimaries: 'bt2020',
|
||||
sourceColorSpace: 'bt2020nc',
|
||||
}),
|
||||
)
|
||||
})
|
||||
@@ -731,6 +848,26 @@ describe('Transcode Activities', () => {
|
||||
).rejects.toThrowError(/Video transcoding failed/)
|
||||
})
|
||||
|
||||
it('should throw non-retryable ApplicationFailure when transcodeVideoActivity is cancelled', async () => {
|
||||
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
|
||||
const abortError = new Error('The operation was aborted')
|
||||
abortError.name = 'AbortError'
|
||||
vi.mocked(transcodeService.transcodeVideo).mockRejectedValue(abortError)
|
||||
|
||||
const promise = transcodeVideoActivity({
|
||||
assetKey: 'v.mp4',
|
||||
filePath: '/tmp/v.mp4',
|
||||
videoSpec: { resolution: '720p', width: 1280, height: 720 },
|
||||
duration: 10,
|
||||
originalFps: 30,
|
||||
})
|
||||
|
||||
await expect(promise).rejects.toThrowError(/Video transcoding cancelled/)
|
||||
await expect(promise).rejects.toMatchObject({
|
||||
nonRetryable: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw non-retryable ApplicationFailure when transcodeImageActivity fails with sharp error', async () => {
|
||||
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
|
||||
vi.mocked(transcodeService.transcodeImage).mockRejectedValue(new Error('sharp failed'))
|
||||
@@ -774,6 +911,44 @@ describe('Transcode Activities', () => {
|
||||
).rejects.toThrowError(/Sprite\/Poster generation failed/)
|
||||
})
|
||||
|
||||
it('generateSpriteActivity forwards HDR options to transcodeService.generateSprite', async () => {
|
||||
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
|
||||
vi.mocked(transcodeService.generateSprite).mockImplementation(
|
||||
async (_in, spriteOut, posterOut) => {
|
||||
fs.writeFileSync(spriteOut, Buffer.from('fake-sprite'))
|
||||
fs.writeFileSync(posterOut, Buffer.from('fake-poster'))
|
||||
},
|
||||
)
|
||||
|
||||
await generateSpriteActivity({
|
||||
assetKey: 'files/asset-1/video.mp4',
|
||||
filePath: '/tmp/video.mp4',
|
||||
mediaInfo: {
|
||||
duration: 10,
|
||||
metadata: {
|
||||
isHdr: true,
|
||||
hdrType: 'pq',
|
||||
colorTransfer: 'smpte2084',
|
||||
},
|
||||
} as unknown as PrismaJson.MediaInfo,
|
||||
spriteSpec: { key: 'files/asset-1/sprite.webp', frames: 100, tileX: 10, tileY: 10 },
|
||||
posterSpec: { key: 'files/asset-1/poster.webp' },
|
||||
})
|
||||
|
||||
expect(transcodeService.generateSprite).toHaveBeenCalledWith(
|
||||
'/tmp/video.mp4',
|
||||
expect.any(String),
|
||||
expect.any(String),
|
||||
10,
|
||||
undefined,
|
||||
{
|
||||
isHdr: true,
|
||||
hdrType: 'pq',
|
||||
colorTransfer: 'smpte2084',
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
it('should throw non-retryable ApplicationFailure when takeScreenshotsActivity fails with error', async () => {
|
||||
vi.mocked(transcodeService.takeScreenshots).mockRejectedValue(new Error('FFmpeg failed'))
|
||||
|
||||
@@ -953,23 +1128,12 @@ describe('Transcode Activities', () => {
|
||||
expect(child_process.execFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should extract poster upfront at t=0 and upload to S3', async () => {
|
||||
it('should extract poster upfront and upload to S3', async () => {
|
||||
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
|
||||
vi.mocked(s3Service.resolveInput).mockResolvedValue('https://mock-r2.com/video.mp4')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(child_process.execFile as any).mockImplementation(
|
||||
(
|
||||
file: string,
|
||||
args: string[],
|
||||
cb: (err: Error | null, result: { stdout: string; stderr: string }) => void,
|
||||
) => {
|
||||
if (file === 'ffmpeg') {
|
||||
const outPath = args[args.length - 1]
|
||||
fs.writeFileSync(outPath, 'fake-poster-bytes')
|
||||
}
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
},
|
||||
)
|
||||
vi.mocked(transcodeService.generatePoster).mockImplementation(async (_in, posterOut) => {
|
||||
fs.writeFileSync(posterOut, Buffer.from('fake-poster-bytes'))
|
||||
})
|
||||
|
||||
const res = await extractPosterActivity({
|
||||
assetKey: 'video.mp4',
|
||||
@@ -978,19 +1142,15 @@ describe('Transcode Activities', () => {
|
||||
|
||||
expect(res.poster.key).toBe('files/asset-1/poster.webp')
|
||||
expect(s3Service.resolveInput).toHaveBeenCalledWith('shumai', 'video.mp4')
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining([
|
||||
'-ss',
|
||||
'0',
|
||||
'-i',
|
||||
'https://mock-r2.com/video.mp4',
|
||||
'-vframes',
|
||||
'1',
|
||||
'-c:v',
|
||||
'libwebp',
|
||||
]),
|
||||
expect.any(Function),
|
||||
expect(transcodeService.generatePoster).toHaveBeenCalledWith(
|
||||
'https://mock-r2.com/video.mp4',
|
||||
expect.stringContaining('poster.webp'),
|
||||
{
|
||||
isHdr: undefined,
|
||||
hdrType: undefined,
|
||||
colorTransfer: undefined,
|
||||
signal: undefined,
|
||||
},
|
||||
)
|
||||
expect(s3Service.putObject).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
@@ -1001,6 +1161,104 @@ describe('Transcode Activities', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('extractPosterActivity applies tone mapping filter when isHdr is true', async () => {
|
||||
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
|
||||
vi.mocked(s3Service.resolveInput).mockResolvedValue('https://mock-r2.com/video.mp4')
|
||||
vi.mocked(transcodeService.generatePoster).mockImplementation(async (_in, posterOut) => {
|
||||
fs.writeFileSync(posterOut, Buffer.from('fake-poster-bytes'))
|
||||
})
|
||||
|
||||
await extractPosterActivity({
|
||||
assetKey: 'video.mp4',
|
||||
posterSpec: { key: 'files/asset-1/poster.webp' },
|
||||
isHdr: true,
|
||||
hdrType: 'pq',
|
||||
colorTransfer: 'smpte2084',
|
||||
})
|
||||
|
||||
expect(transcodeService.generatePoster).toHaveBeenCalledWith(
|
||||
'https://mock-r2.com/video.mp4',
|
||||
expect.stringContaining('poster.webp'),
|
||||
{
|
||||
isHdr: true,
|
||||
hdrType: 'pq',
|
||||
colorTransfer: 'smpte2084',
|
||||
signal: undefined,
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
it('should throw non-retryable ApplicationFailure when poster extraction is cancelled with aborted signal', async () => {
|
||||
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
|
||||
const controller = new AbortController()
|
||||
controller.abort()
|
||||
|
||||
await expect(
|
||||
extractPosterActivity({
|
||||
assetKey: 'video.mp4',
|
||||
posterSpec: { key: 'files/asset-1/poster.webp' },
|
||||
signal: controller.signal,
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
message: 'Poster extraction cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw non-retryable ApplicationFailure when poster extraction ffmpeg execution is aborted', async () => {
|
||||
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
|
||||
vi.mocked(s3Service.resolveInput).mockResolvedValue('https://mock-r2.com/video.mp4')
|
||||
const controller = new AbortController()
|
||||
|
||||
const abortErr = new Error('The operation was aborted')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(abortErr as any).code = 'ABORT_ERR'
|
||||
vi.mocked(transcodeService.generatePoster).mockRejectedValue(abortErr)
|
||||
|
||||
await expect(
|
||||
extractPosterActivity({
|
||||
assetKey: 'video.mp4',
|
||||
posterSpec: { key: 'files/asset-1/poster.webp' },
|
||||
signal: controller.signal,
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
message: 'Poster extraction cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw non-retryable ApplicationFailure and not upload when asset is pending_purge before poster upload', async () => {
|
||||
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
|
||||
vi.mocked(s3Service.resolveInput).mockResolvedValue('https://mock-r2.com/video.mp4')
|
||||
const putObjectSpy = vi.mocked(s3Service.putObject)
|
||||
putObjectSpy.mockClear()
|
||||
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'purging-poster.mp4',
|
||||
storageKey: { create: { key: 'purging-poster.mp4' } },
|
||||
status: 'pending_purge',
|
||||
type: 'file',
|
||||
},
|
||||
})
|
||||
|
||||
vi.mocked(transcodeService.generatePoster).mockImplementation(async (_in, posterOut) => {
|
||||
fs.writeFileSync(posterOut, Buffer.from('fake-poster-bytes'))
|
||||
})
|
||||
|
||||
await expect(
|
||||
extractPosterActivity({
|
||||
assetKey: 'purging-poster.mp4',
|
||||
posterSpec: { key: 'files/asset-1/poster.webp' },
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
message: 'Asset or storage key has been purged or is pending purge',
|
||||
nonRetryable: true,
|
||||
})
|
||||
|
||||
expect(putObjectSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should delete S3 object successfully', async () => {
|
||||
await deleteS3ObjectActivity({ key: 'files/test-key.mp4' })
|
||||
expect(s3Service.deleteObject).toHaveBeenCalledWith('shumai', 'files/test-key.mp4')
|
||||
@@ -1013,12 +1271,14 @@ describe('Transcode Activities', () => {
|
||||
const res = await transcodeAudioActivity({
|
||||
assetKey: 'files/proj-123/a.wav',
|
||||
filePath: '/tmp/a.wav',
|
||||
threads: 4,
|
||||
})
|
||||
|
||||
expect(transcodeService.transcodeAudio).toHaveBeenCalledWith({
|
||||
inputFile: '/tmp/a.wav',
|
||||
outputFile: expect.stringContaining('a-audio-proxy.mp4'),
|
||||
bitrate: '128k',
|
||||
threads: 4,
|
||||
})
|
||||
|
||||
expect(s3Service.putObject).toHaveBeenCalledWith(
|
||||
@@ -1247,5 +1507,56 @@ describe('Transcode Activities', () => {
|
||||
})
|
||||
expect(task).toBeNull()
|
||||
})
|
||||
|
||||
it('should create ai_metadata_autofill task when asset is in trash (isDeleted: true)', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Test User Trashed Autofill', email: 'test-trashed-autofill@test.com' },
|
||||
})
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Test Team Trashed Autofill' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: user.id, role: 'owner' },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Test Project Trashed Autofill', teamId: team.id },
|
||||
})
|
||||
const autofillAgent = await prisma.agent.create({
|
||||
data: {
|
||||
id: user.id,
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
teamId: team.id,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: { provider: 'test', model: 'test' } as any,
|
||||
},
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'trashed-video.mp4',
|
||||
mediaType: 'video/mp4',
|
||||
type: 'file',
|
||||
status: 'trashed',
|
||||
isDeleted: true,
|
||||
projectId: project.id,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
media: { proxyType: 'video' } as any,
|
||||
},
|
||||
})
|
||||
|
||||
await createAutofillTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.findFirst({
|
||||
where: { assetId: asset.id, type: 'ai_metadata_autofill' },
|
||||
})
|
||||
expect(task).toBeDefined()
|
||||
expect(task?.status).toBe('pending')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((task?.payload as any)?.agent?.agentId).toBe(autofillAgent.id)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { prisma, WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
|
||||
import { AssetStatus, prisma, WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { transcodeService } from '@shumai/core/src/transcode/transcode'
|
||||
import { transcodeService, type HdrType } from '@shumai/core/src/transcode/transcode'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { getDerivedArtifactDirectory, stemFromKey } from '@shumai/core/src/utils/filename'
|
||||
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
|
||||
@@ -12,7 +12,17 @@ import {
|
||||
isMarkdownDocument,
|
||||
isOfficeDocument,
|
||||
} from '@shumai/core/src/utils/mime'
|
||||
import { ApplicationFailure } from '@temporalio/activity'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { ApplicationFailure, Context } from '@temporalio/activity'
|
||||
import { getLocalTaskAbortSignal } from '@shumai/workflow-core'
|
||||
|
||||
function getActivityCancellationSignal(taskId?: string): AbortSignal | undefined {
|
||||
try {
|
||||
return Context.current().cancellationSignal
|
||||
} catch {
|
||||
return getLocalTaskAbortSignal(taskId)
|
||||
}
|
||||
}
|
||||
import * as path from 'path'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
@@ -47,6 +57,24 @@ function getErrorDetails(err: unknown): { code?: string; message: string; name?:
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureAssetNotPurging(assetKey: string): Promise<void> {
|
||||
const sk = await prisma.storageKey.findUnique({
|
||||
where: { key: assetKey },
|
||||
include: { assets: { select: { id: true, status: true } } },
|
||||
})
|
||||
if (
|
||||
sk &&
|
||||
(sk.status === 'purging' ||
|
||||
sk.assets.length === 0 ||
|
||||
sk.assets.every((a) => a.status === AssetStatus.pending_purge))
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Asset or storage key has been purged or is pending purge',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function getMediaInfoActivity(params: {
|
||||
filePath: string
|
||||
assetId: string
|
||||
@@ -114,6 +142,13 @@ export async function getMediaInfoActivity(params: {
|
||||
audioChannels: info.audioChannels,
|
||||
audioSampleRate: info.audioSampleRate,
|
||||
audioBitDepth: info.audioBitDepth,
|
||||
colorTransfer: info.colorTransfer,
|
||||
colorPrimaries: info.colorPrimaries,
|
||||
colorSpace: info.colorSpace,
|
||||
isHdr: info.isHdr,
|
||||
hdrType: info.hdrType,
|
||||
dvProfile: info.dvProfile,
|
||||
rotation: info.rotation,
|
||||
format: {},
|
||||
}
|
||||
metadataUpdates.push(
|
||||
@@ -123,6 +158,12 @@ export async function getMediaInfoActivity(params: {
|
||||
{ key: 'bitRate', value: info.bitRate / 1000 },
|
||||
{ key: 'frame_rate', value: info.frameRate },
|
||||
)
|
||||
if (info.rotation !== undefined)
|
||||
metadataUpdates.push({ key: 'rotation', value: info.rotation })
|
||||
if (info.isHdr !== undefined)
|
||||
metadataUpdates.push({ key: 'is_hdr', value: info.isHdr ? 1 : 0 })
|
||||
if (info.colorTransfer)
|
||||
metadataUpdates.push({ key: 'color_transfer', value: info.colorTransfer })
|
||||
if (info.videoCodec) metadataUpdates.push({ key: 'video_codec', value: info.videoCodec })
|
||||
if (info.audioCodec) metadataUpdates.push({ key: 'audio_codec', value: info.audioCodec })
|
||||
if (info.audioChannels !== undefined)
|
||||
@@ -216,6 +257,7 @@ export async function getMediaInfoActivity(params: {
|
||||
}
|
||||
|
||||
export interface VideoActivityParams {
|
||||
taskId?: string
|
||||
assetKey: string
|
||||
filePath: string
|
||||
videoSpec: PrismaJson.VideoTranscode
|
||||
@@ -223,6 +265,12 @@ export interface VideoActivityParams {
|
||||
originalFps: number
|
||||
hardwareAcceleration?: PrismaJson.HardwareAcceleration
|
||||
sourceVideoBitrate?: number
|
||||
threads?: number
|
||||
sourceIsHdr?: boolean
|
||||
sourceHdrType?: HdrType
|
||||
sourceColorTransfer?: string
|
||||
sourceColorPrimaries?: string
|
||||
sourceColorSpace?: string
|
||||
}
|
||||
|
||||
export async function transcodeVideoActivity(
|
||||
@@ -231,7 +279,16 @@ export async function transcodeVideoActivity(
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const stem = stemFromKey(params.assetKey)
|
||||
const res = params.videoSpec.resolution || `${params.videoSpec.height}p`
|
||||
const key = path.posix.join(path.posix.dirname(params.assetKey), `${stem}-${res}.mp4`)
|
||||
const suffix = params.videoSpec.hdr ? `${res}-hdr` : res
|
||||
const key = path.posix.join(path.posix.dirname(params.assetKey), `${stem}-${suffix}.mp4`)
|
||||
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
if (signal?.aborted) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Video transcoding cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
await s3Service.headObject(bucket, key)
|
||||
@@ -241,7 +298,7 @@ export async function transcodeVideoActivity(
|
||||
}
|
||||
|
||||
const tmpDir = path.dirname(params.filePath)
|
||||
const outputFile = path.join(tmpDir, `${stem}-${res}.mp4`)
|
||||
const outputFile = path.join(tmpDir, `${stem}-${suffix}.mp4`)
|
||||
|
||||
try {
|
||||
let targetFps: number | string = params.originalFps || 30
|
||||
@@ -267,10 +324,19 @@ export async function transcodeVideoActivity(
|
||||
disableAudio,
|
||||
hardwareAcceleration: params.hardwareAcceleration,
|
||||
sourceVideoBitrate: params.sourceVideoBitrate,
|
||||
threads: params.threads,
|
||||
signal,
|
||||
hdr: params.videoSpec.hdr,
|
||||
sourceIsHdr: params.sourceIsHdr,
|
||||
sourceHdrType: params.sourceHdrType,
|
||||
sourceColorTransfer: params.sourceColorTransfer,
|
||||
sourceColorPrimaries: params.sourceColorPrimaries,
|
||||
sourceColorSpace: params.sourceColorSpace,
|
||||
})
|
||||
|
||||
const stat = fs.statSync(outputFile)
|
||||
const stream = Bun.file(outputFile).stream()
|
||||
await ensureAssetNotPurging(params.assetKey)
|
||||
await s3Service.putObject(bucket, key, stream, stat.size, 'video/mp4')
|
||||
|
||||
return { ...params.videoSpec, key }
|
||||
@@ -278,6 +344,19 @@ export async function transcodeVideoActivity(
|
||||
const { code, message } = getErrorDetails(err)
|
||||
const lowerMsg = message.toLowerCase()
|
||||
|
||||
if (
|
||||
signal?.aborted ||
|
||||
code === 'ABORT_ERR' ||
|
||||
message.includes('aborted') ||
|
||||
lowerMsg.includes('abort')
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Video transcoding cancelled',
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
code === 'ENOENT' ||
|
||||
lowerMsg.includes('enoent') ||
|
||||
@@ -285,7 +364,9 @@ export async function transcodeVideoActivity(
|
||||
lowerMsg.includes('ffprobe') ||
|
||||
lowerMsg.includes('spawn') ||
|
||||
lowerMsg.includes('format') ||
|
||||
lowerMsg.includes('no video stream found')
|
||||
lowerMsg.includes('no video stream found') ||
|
||||
lowerMsg.includes('zscale') ||
|
||||
lowerMsg.includes('tonemap')
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Video transcoding failed: ${message}`,
|
||||
@@ -300,8 +381,10 @@ export async function transcodeVideoActivity(
|
||||
}
|
||||
|
||||
export interface AudioActivityParams {
|
||||
taskId?: string
|
||||
assetKey: string
|
||||
filePath: string
|
||||
threads?: number
|
||||
}
|
||||
|
||||
export async function transcodeAudioActivity(
|
||||
@@ -311,6 +394,14 @@ export async function transcodeAudioActivity(
|
||||
const stem = stemFromKey(params.assetKey)
|
||||
const key = path.posix.join(path.posix.dirname(params.assetKey), `${stem}-audio-proxy.mp4`)
|
||||
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
if (signal?.aborted) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Audio transcoding cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
await s3Service.headObject(bucket, key)
|
||||
return { width: 0, height: 0, key }
|
||||
@@ -326,10 +417,13 @@ export async function transcodeAudioActivity(
|
||||
inputFile: params.filePath,
|
||||
outputFile,
|
||||
bitrate: '128k',
|
||||
threads: params.threads,
|
||||
signal,
|
||||
})
|
||||
|
||||
const stat = fs.statSync(outputFile)
|
||||
const stream = Bun.file(outputFile).stream()
|
||||
await ensureAssetNotPurging(params.assetKey)
|
||||
await s3Service.putObject(bucket, key, stream, stat.size, 'video/mp4')
|
||||
|
||||
return { width: 0, height: 0, key }
|
||||
@@ -337,6 +431,19 @@ export async function transcodeAudioActivity(
|
||||
const { code, message } = getErrorDetails(err)
|
||||
const lowerMsg = message.toLowerCase()
|
||||
|
||||
if (
|
||||
signal?.aborted ||
|
||||
code === 'ABORT_ERR' ||
|
||||
message.includes('aborted') ||
|
||||
lowerMsg.includes('abort')
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Audio transcoding cancelled',
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
code === 'ENOENT' ||
|
||||
lowerMsg.includes('enoent') ||
|
||||
@@ -396,6 +503,7 @@ export async function transcodeImageActivity(
|
||||
},
|
||||
)
|
||||
const buffer = fs.readFileSync(outputFile)
|
||||
await ensureAssetNotPurging(params.assetKey)
|
||||
await s3Service.putObject(bucket, key, buffer, buffer.length, 'image/webp')
|
||||
|
||||
return { ...params.imageSpec, key }
|
||||
@@ -426,6 +534,7 @@ export async function transcodeImageActivity(
|
||||
}
|
||||
|
||||
export interface GenerateSpriteActivityParams {
|
||||
taskId?: string
|
||||
assetKey: string
|
||||
filePath: string
|
||||
mediaInfo: PrismaJson.MediaInfo
|
||||
@@ -435,6 +544,14 @@ export interface GenerateSpriteActivityParams {
|
||||
|
||||
export async function generateSpriteActivity(params: GenerateSpriteActivityParams) {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
if (signal?.aborted) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Sprite/Poster generation cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
await s3Service.headObject(bucket, params.spriteSpec.key)
|
||||
await s3Service.headObject(bucket, params.posterSpec.key)
|
||||
@@ -453,6 +570,7 @@ export async function generateSpriteActivity(params: GenerateSpriteActivityParam
|
||||
params.filePath,
|
||||
spriteFile,
|
||||
posterFile,
|
||||
signal,
|
||||
)
|
||||
if (params.mediaInfo && params.mediaInfo.metadata) {
|
||||
params.mediaInfo.metadata.totalFrames = pdfRes.pageCount
|
||||
@@ -466,10 +584,17 @@ export async function generateSpriteActivity(params: GenerateSpriteActivityParam
|
||||
spriteFile,
|
||||
posterFile,
|
||||
params.mediaInfo.duration,
|
||||
signal,
|
||||
{
|
||||
isHdr: params.mediaInfo.metadata?.isHdr,
|
||||
hdrType: params.mediaInfo.metadata?.hdrType,
|
||||
colorTransfer: params.mediaInfo.metadata?.colorTransfer,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const spriteBuffer = fs.readFileSync(spriteFile)
|
||||
await ensureAssetNotPurging(params.assetKey)
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
params.spriteSpec.key,
|
||||
@@ -492,13 +617,28 @@ export async function generateSpriteActivity(params: GenerateSpriteActivityParam
|
||||
const { code, message } = getErrorDetails(err)
|
||||
const lowerMsg = message.toLowerCase()
|
||||
|
||||
if (
|
||||
signal?.aborted ||
|
||||
code === 'ABORT_ERR' ||
|
||||
message.includes('aborted') ||
|
||||
lowerMsg.includes('abort')
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Sprite/Poster generation cancelled',
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
code === 'ENOENT' ||
|
||||
lowerMsg.includes('enoent') ||
|
||||
lowerMsg.includes('ffmpeg') ||
|
||||
lowerMsg.includes('ffprobe') ||
|
||||
lowerMsg.includes('spawn') ||
|
||||
lowerMsg.includes('format')
|
||||
lowerMsg.includes('format') ||
|
||||
lowerMsg.includes('zscale') ||
|
||||
lowerMsg.includes('tonemap')
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Sprite/Poster generation failed: ${message}`,
|
||||
@@ -606,6 +746,7 @@ export async function generatePdfProxyActivity(
|
||||
|
||||
const stat = fs.statSync(pdfFilePath)
|
||||
const stream = Bun.file(pdfFilePath).stream()
|
||||
await ensureAssetNotPurging(params.assetKey)
|
||||
await s3Service.putObject(bucket, pdfProxyKey, stream, stat.size, 'application/pdf')
|
||||
|
||||
return { pdfProxyKey, pdfFilePath }
|
||||
@@ -664,9 +805,9 @@ export async function updateAssetMediaActivity(params: UpdateAssetMediaActivityP
|
||||
include: { storageKey: true },
|
||||
})
|
||||
const key = asset?.storageKey?.key
|
||||
if (!asset || !key) {
|
||||
if (!asset || !key || asset.status === AssetStatus.pending_purge) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Asset not found or has no key',
|
||||
message: 'Asset not found, has no key, or is being purged',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
@@ -675,14 +816,24 @@ export async function updateAssetMediaActivity(params: UpdateAssetMediaActivityP
|
||||
const buffer = Buffer.from(JSON.stringify(params.mediaInfo))
|
||||
await s3Service.putObject(bucket, infoKey, buffer, buffer.length, 'application/json')
|
||||
|
||||
await prisma.asset.update({
|
||||
where: { id: params.assetId },
|
||||
const { count } = await prisma.asset.updateMany({
|
||||
where: {
|
||||
id: params.assetId,
|
||||
status: { not: AssetStatus.pending_purge },
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
data: { media: params.mediaInfo as any, hasJpegPreview: false },
|
||||
})
|
||||
if (count === 0) {
|
||||
logger.info(
|
||||
{ assetId: params.assetId },
|
||||
'[updateAssetMediaActivity] Asset was deleted or pending purge before media update completed',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function takeScreenshotsActivity(params: {
|
||||
taskId?: string
|
||||
assetKey: string
|
||||
assetId: string
|
||||
start: number
|
||||
@@ -691,11 +842,33 @@ export async function takeScreenshotsActivity(params: {
|
||||
commentTimestamp?: number | null
|
||||
annotations?: PrismaJson.AnnotationList | null
|
||||
}): Promise<Array<{ key: string; timestamp: number }>> {
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
if (signal?.aborted) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Screenshot extraction cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
return await transcodeService.takeScreenshots(params)
|
||||
return await transcodeService.takeScreenshots({ ...params, signal })
|
||||
} catch (err) {
|
||||
const { code, message } = getErrorDetails(err)
|
||||
const lowerMsg = message.toLowerCase()
|
||||
|
||||
if (
|
||||
signal?.aborted ||
|
||||
code === 'ABORT_ERR' ||
|
||||
message.includes('aborted') ||
|
||||
lowerMsg.includes('abort')
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Screenshot extraction cancelled',
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
code === 'ENOENT' ||
|
||||
lowerMsg.includes('enoent') ||
|
||||
@@ -716,11 +889,24 @@ export async function takeScreenshotsActivity(params: {
|
||||
export interface ExtractPosterActivityParams {
|
||||
assetKey: string
|
||||
posterSpec: PrismaJson.PosterInfo
|
||||
taskId?: string
|
||||
signal?: AbortSignal
|
||||
isHdr?: boolean
|
||||
hdrType?: HdrType
|
||||
colorTransfer?: string
|
||||
}
|
||||
|
||||
export async function extractPosterActivity(
|
||||
params: ExtractPosterActivityParams,
|
||||
): Promise<{ poster: PrismaJson.PosterInfo }> {
|
||||
const signal = params.signal || getActivityCancellationSignal(params.taskId)
|
||||
if (signal?.aborted) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Poster extraction cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
try {
|
||||
await s3Service.headObject(bucket, params.posterSpec.key)
|
||||
@@ -734,29 +920,15 @@ export async function extractPosterActivity(
|
||||
|
||||
try {
|
||||
const inputSource = await s3Service.resolveInput(bucket, params.assetKey)
|
||||
const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://')
|
||||
|
||||
const args = [
|
||||
...(isRemote
|
||||
? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5']
|
||||
: []),
|
||||
'-ss',
|
||||
'0',
|
||||
'-i',
|
||||
inputSource,
|
||||
'-vframes',
|
||||
'1',
|
||||
'-vf',
|
||||
'scale=-2:300:force_original_aspect_ratio=decrease',
|
||||
'-c:v',
|
||||
'libwebp',
|
||||
'-q:v',
|
||||
'75',
|
||||
posterFile,
|
||||
]
|
||||
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
||||
await transcodeService.generatePoster(inputSource, posterFile, {
|
||||
isHdr: params.isHdr,
|
||||
hdrType: params.hdrType,
|
||||
colorTransfer: params.colorTransfer,
|
||||
signal,
|
||||
})
|
||||
|
||||
const posterBuffer = fs.readFileSync(posterFile)
|
||||
await ensureAssetNotPurging(params.assetKey)
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
params.posterSpec.key,
|
||||
@@ -769,12 +941,28 @@ export async function extractPosterActivity(
|
||||
} catch (err) {
|
||||
const { code, message } = getErrorDetails(err)
|
||||
const lowerMsg = message.toLowerCase()
|
||||
|
||||
if (
|
||||
signal?.aborted ||
|
||||
code === 'ABORT_ERR' ||
|
||||
message.includes('aborted') ||
|
||||
lowerMsg.includes('abort')
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Poster extraction cancelled',
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
code === 'ENOENT' ||
|
||||
lowerMsg.includes('enoent') ||
|
||||
lowerMsg.includes('nosuchkey') ||
|
||||
lowerMsg.includes('ffmpeg') ||
|
||||
lowerMsg.includes('sharp')
|
||||
lowerMsg.includes('sharp') ||
|
||||
lowerMsg.includes('zscale') ||
|
||||
lowerMsg.includes('tonemap')
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Poster extraction failed: ${message}`,
|
||||
@@ -816,6 +1004,7 @@ export async function overlayAnnotationsActivity(params: {
|
||||
}
|
||||
|
||||
export async function renderPdfPagesActivity(params: {
|
||||
taskId?: string
|
||||
assetKey: string
|
||||
assetId: string
|
||||
start: number
|
||||
@@ -823,11 +1012,33 @@ export async function renderPdfPagesActivity(params: {
|
||||
commentTimestamp?: number | null
|
||||
annotations?: PrismaJson.AnnotationList | null
|
||||
}): Promise<Array<{ key: string; page: number }>> {
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
if (signal?.aborted) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'PDF page rendering cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
return await transcodeService.renderPdfPages(params)
|
||||
return await transcodeService.renderPdfPages({ ...params, signal })
|
||||
} catch (err) {
|
||||
const { code, message } = getErrorDetails(err)
|
||||
const lowerMsg = message.toLowerCase()
|
||||
|
||||
if (
|
||||
signal?.aborted ||
|
||||
code === 'ABORT_ERR' ||
|
||||
message.includes('aborted') ||
|
||||
lowerMsg.includes('abort')
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'PDF page rendering cancelled',
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
code === 'ENOENT' ||
|
||||
lowerMsg.includes('enoent') ||
|
||||
@@ -933,7 +1144,7 @@ export async function createAutofillTaskIfEnabledActivity(
|
||||
project: true,
|
||||
},
|
||||
})
|
||||
if (!asset || (asset.type !== 'file' && asset.type !== 'version_stack') || asset.isDeleted) {
|
||||
if (!asset || (asset.type !== 'file' && asset.type !== 'version_stack')) {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -352,6 +352,7 @@ describe('Watermark Activities', () => {
|
||||
transcode: {
|
||||
videoStrategy: 'best_match',
|
||||
hardwareAcceleration: 'auto',
|
||||
threads: 6,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -398,11 +399,131 @@ describe('Watermark Activities', () => {
|
||||
hardwareAcceleration: 'auto',
|
||||
sourceVideoBitrate: 1800000,
|
||||
disableAudio: true,
|
||||
threads: 6,
|
||||
}),
|
||||
)
|
||||
|
||||
fs.rmSync(outFilePath, { force: true })
|
||||
})
|
||||
|
||||
it('mirrors both SDR and HDR videoTranscodes preserving HDR flags and -hdr suffix', async () => {
|
||||
const assetKey = 'files/hdr-wm/video.mp4'
|
||||
const storageKey = await prisma.storageKey.create({ data: { key: assetKey } })
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'video.mp4',
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
storageKeyId: storageKey.id,
|
||||
mediaType: 'video/mp4',
|
||||
media: {
|
||||
duration: 10,
|
||||
filesize: 0,
|
||||
frames: 300,
|
||||
proxyType: 'video',
|
||||
imageTranscodes: [],
|
||||
videoPreview: { width: 1920, height: 1080 },
|
||||
finishedAt: new Date().toISOString(),
|
||||
original: {
|
||||
key: assetKey,
|
||||
filesizeInBytes: 0,
|
||||
codec: '',
|
||||
},
|
||||
metadata: {
|
||||
originalWidth: 1920,
|
||||
originalHeight: 1080,
|
||||
duration: 10,
|
||||
bitRate: 1000,
|
||||
frameRate: 30,
|
||||
totalFrames: 300,
|
||||
startTimecode: '00:00:00:00',
|
||||
hasAudio: true,
|
||||
format: {},
|
||||
isHdr: true,
|
||||
hdrType: 'pq',
|
||||
colorTransfer: 'smpte2084',
|
||||
},
|
||||
videoTranscodes: [
|
||||
{
|
||||
key: 'files/hdr-wm/video-1080p.mp4',
|
||||
resolution: '1080p',
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
hdr: false,
|
||||
},
|
||||
{
|
||||
key: 'files/hdr-wm/video-1080p-hdr.mp4',
|
||||
resolution: '1080p',
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
hdr: true,
|
||||
},
|
||||
],
|
||||
} as PrismaJson.MediaInfo,
|
||||
},
|
||||
})
|
||||
const config = await seedConfig()
|
||||
|
||||
vi.mocked(transcodeService.getVideoInfo).mockResolvedValue({
|
||||
originalWidth: 1920,
|
||||
originalHeight: 1080,
|
||||
duration: 10,
|
||||
bitRate: 1000,
|
||||
frameRate: 30,
|
||||
totalFrames: 300,
|
||||
startTimecode: '00:00:00:00',
|
||||
hasAudio: true,
|
||||
mimeType: 'video/mp4',
|
||||
isHdr: true,
|
||||
hdrType: 'pq',
|
||||
colorTransfer: 'smpte2084',
|
||||
})
|
||||
vi.mocked(s3Service.putObject).mockResolvedValue(undefined as never)
|
||||
|
||||
const sdrOut = path.join('/tmp', `video-watermark-${config.id}-1080p.mp4`)
|
||||
const hdrOut = path.join('/tmp', `video-watermark-${config.id}-1080p-hdr.mp4`)
|
||||
fs.writeFileSync(sdrOut, Buffer.from('fake sdr'))
|
||||
fs.writeFileSync(hdrOut, Buffer.from('fake hdr'))
|
||||
|
||||
const media = await transcodeWatermarkMediaActivity({
|
||||
assetId: asset.id,
|
||||
watermarkConfigId: config.id,
|
||||
})
|
||||
|
||||
expect(media.videoTranscodes).toHaveLength(2)
|
||||
expect(media.videoTranscodes?.[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
resolution: '1080p',
|
||||
hdr: false,
|
||||
key: expect.stringContaining(`video-watermark-${config.id}-1080p.mp4`),
|
||||
}),
|
||||
)
|
||||
expect(media.videoTranscodes?.[1]).toEqual(
|
||||
expect.objectContaining({
|
||||
resolution: '1080p',
|
||||
hdr: true,
|
||||
key: expect.stringContaining(`video-watermark-${config.id}-1080p-hdr.mp4`),
|
||||
}),
|
||||
)
|
||||
|
||||
expect(transcodeService.transcodeVideo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
outputFile: sdrOut,
|
||||
hdr: false,
|
||||
sourceIsHdr: true,
|
||||
}),
|
||||
)
|
||||
expect(transcodeService.transcodeVideo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
outputFile: hdrOut,
|
||||
hdr: true,
|
||||
sourceIsHdr: true,
|
||||
}),
|
||||
)
|
||||
|
||||
fs.rmSync(sdrOut, { force: true })
|
||||
fs.rmSync(hdrOut, { force: true })
|
||||
})
|
||||
})
|
||||
|
||||
describe('completeWatermarkFileActivity', () => {
|
||||
|
||||
@@ -150,6 +150,7 @@ export async function transcodeWatermarkMediaActivity(
|
||||
|
||||
const teamSettings = asset.project?.team?.settings as PrismaJson.Settings | null
|
||||
const hardwareAcceleration = teamSettings?.transcode?.hardwareAcceleration ?? 'off'
|
||||
const threads = teamSettings?.transcode?.threads ?? 0
|
||||
|
||||
// The config column is declared as PrismaJson.WatermarkConfigSpec, which is
|
||||
// structurally identical to the DTO type, so no cast is required.
|
||||
@@ -180,6 +181,12 @@ export async function transcodeWatermarkMediaActivity(
|
||||
let startTimecode = '00:00:00:00'
|
||||
let hasAudio = false
|
||||
let sourceVideoBitrate: number | undefined
|
||||
let colorTransfer: string | undefined
|
||||
let colorPrimaries: string | undefined
|
||||
let colorSpace: string | undefined
|
||||
let isHdr: boolean | undefined
|
||||
let hdrType: PrismaJson.HdrType | undefined
|
||||
let dvProfile: number | undefined
|
||||
|
||||
if (isVideo) {
|
||||
const info = await transcodeService.getVideoInfo(rawFilePath)
|
||||
@@ -193,6 +200,12 @@ export async function transcodeWatermarkMediaActivity(
|
||||
startTimecode = info.startTimecode || '00:00:00:00'
|
||||
hasAudio = info.hasAudio
|
||||
sourceVideoBitrate = info.videoBitRate || info.bitRate
|
||||
colorTransfer = info.colorTransfer
|
||||
colorPrimaries = info.colorPrimaries
|
||||
colorSpace = info.colorSpace
|
||||
isHdr = info.isHdr
|
||||
hdrType = info.hdrType
|
||||
dvProfile = info.dvProfile
|
||||
} else if (isImage) {
|
||||
const info = await transcodeService.getImageInfo(rawFilePath)
|
||||
originalWidth = info.originalWidth
|
||||
@@ -257,6 +270,12 @@ export async function transcodeWatermarkMediaActivity(
|
||||
totalFrames,
|
||||
startTimecode,
|
||||
hasAudio,
|
||||
colorTransfer: colorTransfer ?? originalMedia?.metadata?.colorTransfer,
|
||||
colorPrimaries: colorPrimaries ?? originalMedia?.metadata?.colorPrimaries,
|
||||
colorSpace: colorSpace ?? originalMedia?.metadata?.colorSpace,
|
||||
isHdr: isHdr ?? originalMedia?.metadata?.isHdr,
|
||||
hdrType: hdrType ?? originalMedia?.metadata?.hdrType,
|
||||
dvProfile: dvProfile ?? originalMedia?.metadata?.dvProfile,
|
||||
format: {},
|
||||
},
|
||||
original: {
|
||||
@@ -319,6 +338,8 @@ export async function transcodeWatermarkMediaActivity(
|
||||
const targetWidth = vt.width || originalWidth
|
||||
const targetHeight = vt.height || originalHeight
|
||||
const resolution = vt.resolution || `${targetHeight}p`
|
||||
const isVtHdr = Boolean(vt.hdr)
|
||||
const suffix = isVtHdr ? `${resolution}-hdr` : resolution
|
||||
|
||||
const svgString = generateWatermarkSvg(config, targetWidth, targetHeight, blockImagesMap)
|
||||
const overlayPngBuffer = await transcodeService.renderSvgToPng(svgString)
|
||||
@@ -326,7 +347,7 @@ export async function transcodeWatermarkMediaActivity(
|
||||
const overlayPngPath = path.join(tmpDir, `watermarkOverlay-${i}.png`)
|
||||
fs.writeFileSync(overlayPngPath, overlayPngBuffer)
|
||||
|
||||
const outFileName = `${stem}-watermark-${params.watermarkConfigId}-${resolution}.mp4`
|
||||
const outFileName = `${stem}-watermark-${params.watermarkConfigId}-${suffix}.mp4`
|
||||
const outFilePath = path.join(tmpDir, outFileName)
|
||||
|
||||
await transcodeService.transcodeVideo({
|
||||
@@ -338,6 +359,13 @@ export async function transcodeWatermarkMediaActivity(
|
||||
overlayFile: overlayPngPath,
|
||||
hardwareAcceleration,
|
||||
sourceVideoBitrate,
|
||||
threads,
|
||||
hdr: isVtHdr,
|
||||
sourceIsHdr: isHdr ?? originalMedia?.metadata?.isHdr,
|
||||
sourceHdrType: hdrType ?? originalMedia?.metadata?.hdrType,
|
||||
sourceColorTransfer: colorTransfer ?? originalMedia?.metadata?.colorTransfer,
|
||||
sourceColorPrimaries: colorPrimaries ?? originalMedia?.metadata?.colorPrimaries,
|
||||
sourceColorSpace: colorSpace ?? originalMedia?.metadata?.colorSpace,
|
||||
})
|
||||
|
||||
const stat = fs.statSync(outFilePath)
|
||||
@@ -357,6 +385,7 @@ export async function transcodeWatermarkMediaActivity(
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
resolution,
|
||||
hdr: isVtHdr,
|
||||
})
|
||||
}
|
||||
mediaInfo.filesize = totalSize
|
||||
|
||||
@@ -29,6 +29,13 @@ export class VideoTranscoder {
|
||||
return this
|
||||
}
|
||||
|
||||
setThreads(threads?: number): this {
|
||||
if (threads !== undefined) {
|
||||
this.spec.threads = threads
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
withSprite(): this {
|
||||
this.spec.sprite = true
|
||||
return this
|
||||
|
||||
@@ -16,9 +16,9 @@ export async function fetchAssetWithKey(workerQueue: string, assetId: string) {
|
||||
const { getAssetActivity } = getActivities()
|
||||
const asset = await executeActivity(workerQueue, getAssetActivity, assetId)
|
||||
const key = asset?.storageKey?.key
|
||||
if (!asset || !key) {
|
||||
if (!asset || !key || asset.status === 'pending_purge') {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Asset not found or has no key',
|
||||
message: 'Asset not found, has no key, or is being purged',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -88,6 +88,7 @@ describe('renderPdfPagesWorkflow', () => {
|
||||
await renderPdfPagesWorkflow(task)
|
||||
|
||||
expect(mockActivities.renderPdfPagesActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-pdf-pages',
|
||||
assetKey: 'doc.pdf',
|
||||
assetId: 'asset-pdf',
|
||||
start: 1,
|
||||
|
||||
@@ -21,6 +21,7 @@ export async function renderPdfPagesWorkflow(task: WorkflowTask): Promise<void>
|
||||
const pdfKey = (asset.media as PrismaJson.MediaInfo | null)?.pdfTranscode?.key || key
|
||||
|
||||
const pages = await executeActivity(workerQueue, renderPdfPagesActivity, {
|
||||
taskId: task.id,
|
||||
assetKey: pdfKey,
|
||||
assetId: asset.id,
|
||||
start: payload.pdfPages.start,
|
||||
|
||||
@@ -87,6 +87,7 @@ describe('takeVideoScreenshotsWorkflow', () => {
|
||||
await takeVideoScreenshotsWorkflow(task)
|
||||
|
||||
expect(mockActivities.takeScreenshotsActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-screenshot',
|
||||
assetKey: 'video.mp4',
|
||||
assetId: 'asset-video',
|
||||
start: 0,
|
||||
@@ -157,6 +158,7 @@ describe('takeVideoScreenshotsWorkflow', () => {
|
||||
await takeVideoScreenshotsWorkflow(task)
|
||||
|
||||
expect(mockActivities.takeScreenshotsActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-screenshot-proxy',
|
||||
assetKey: 'proxy-1080p.mp4',
|
||||
assetId: 'asset-video-proxy',
|
||||
start: 1.2345,
|
||||
@@ -166,4 +168,58 @@ describe('takeVideoScreenshotsWorkflow', () => {
|
||||
annotations: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('should prioritize SDR proxy over higher-resolution HDR proxy to avoid washed-out annotations', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-screenshot-sdr-prioritized',
|
||||
assetId: 'asset-video-hdr',
|
||||
type: WorkflowTaskType.transcode_screenshot,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
sessionId: null,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
screenshot: {
|
||||
start: 2.0,
|
||||
end: 2.0,
|
||||
count: 1,
|
||||
commentTimestamp: 2.0,
|
||||
annotations: [],
|
||||
},
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-video-hdr',
|
||||
storageKey: { key: 'raw-hdr.mp4' },
|
||||
mediaType: 'video/mp4',
|
||||
media: {
|
||||
videoTranscodes: [
|
||||
{ key: 'proxy-1080p-hdr.mp4', height: 1080, width: 1920, hdr: true },
|
||||
{ key: 'proxy-720p.mp4', height: 720, width: 1280, hdr: false },
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
mockActivities.takeScreenshotsActivity.mockResolvedValue([
|
||||
{ key: 'files/asset-video-hdr/screenshots/shot1.webp', timestamp: 2.0 },
|
||||
])
|
||||
|
||||
await takeVideoScreenshotsWorkflow(task)
|
||||
|
||||
expect(mockActivities.takeScreenshotsActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetKey: 'proxy-720p.mp4',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -23,7 +23,12 @@ export async function takeVideoScreenshotsWorkflow(task: WorkflowTask): Promise<
|
||||
if (mediaInfo.videoTranscodes && mediaInfo.videoTranscodes.length > 0) {
|
||||
const sorted = [...mediaInfo.videoTranscodes]
|
||||
.filter((t) => t.key)
|
||||
.sort((a, b) => (b.height || 0) - (a.height || 0))
|
||||
.sort((a, b) => {
|
||||
// Prioritize SDR over HDR to avoid washed out screenshots
|
||||
if (!a.hdr && b.hdr) return -1
|
||||
if (a.hdr && !b.hdr) return 1
|
||||
return (b.height || 0) - (a.height || 0)
|
||||
})
|
||||
if (sorted.length > 0 && sorted[0].key) {
|
||||
targetKey = sorted[0].key
|
||||
}
|
||||
@@ -33,6 +38,7 @@ export async function takeVideoScreenshotsWorkflow(task: WorkflowTask): Promise<
|
||||
const { takeScreenshotsActivity } = getActivities()
|
||||
|
||||
const screenshots = await executeActivity(workerQueue, takeScreenshotsActivity, {
|
||||
taskId: task.id,
|
||||
assetKey: targetKey,
|
||||
assetId: asset.id,
|
||||
start: payload.screenshot.start,
|
||||
|
||||
@@ -187,6 +187,7 @@ describe('transcodeVideoWorkflow', () => {
|
||||
transcode: {
|
||||
videoStrategy: 'best_match',
|
||||
hardwareAcceleration: 'auto',
|
||||
threads: 8,
|
||||
},
|
||||
},
|
||||
createdAt: new Date(),
|
||||
@@ -238,6 +239,7 @@ describe('transcodeVideoWorkflow', () => {
|
||||
filePath: '/tmp/video.mp4',
|
||||
hardwareAcceleration: 'auto',
|
||||
sourceVideoBitrate: 850000,
|
||||
threads: 8,
|
||||
}),
|
||||
)
|
||||
})
|
||||
@@ -252,7 +254,9 @@ describe('transcodeVideoWorkflow', () => {
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
transcode: {},
|
||||
transcode: {
|
||||
threads: 4,
|
||||
},
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
@@ -300,10 +304,13 @@ describe('transcodeVideoWorkflow', () => {
|
||||
|
||||
await transcodeVideoWorkflow(task)
|
||||
|
||||
expect(mockActivities.transcodeAudioActivity).toHaveBeenCalledWith({
|
||||
assetKey: 'audio.wav',
|
||||
filePath: '/tmp/video.mp4',
|
||||
})
|
||||
expect(mockActivities.transcodeAudioActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetKey: 'audio.wav',
|
||||
filePath: '/tmp/video.mp4',
|
||||
threads: 4,
|
||||
}),
|
||||
)
|
||||
|
||||
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-audio',
|
||||
@@ -385,6 +392,7 @@ describe('transcodeVideoWorkflow', () => {
|
||||
posterSpec: {
|
||||
key: 'files/asset-poster/poster.webp',
|
||||
},
|
||||
taskId: 'task-poster',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith({
|
||||
@@ -394,4 +402,304 @@ describe('transcodeVideoWorkflow', () => {
|
||||
}),
|
||||
})
|
||||
})
|
||||
|
||||
it('should persist poster/sprite before transcoding proxies so previews are available early', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-sprite',
|
||||
assetId: 'asset-sprite',
|
||||
type: WorkflowTaskType.transcode_video,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
sessionId: null,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
transcode: {
|
||||
poster: true,
|
||||
sprite: true,
|
||||
videoStrategy: 'best_match',
|
||||
},
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-sprite',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-sprite',
|
||||
storageKey: { key: 'files/asset-sprite/video.mp4' },
|
||||
mediaType: 'video/mp4',
|
||||
})
|
||||
|
||||
mockActivities.getMediaInfoActivity.mockResolvedValue({
|
||||
proxyType: 'video',
|
||||
metadata: {
|
||||
originalWidth: 1920,
|
||||
originalHeight: 1080,
|
||||
duration: 10,
|
||||
frameRate: 30,
|
||||
totalFrames: 300,
|
||||
startTimecode: '00:00:00:00',
|
||||
bitRate: 1000,
|
||||
hasAudio: false,
|
||||
format: {},
|
||||
},
|
||||
videoTranscodes: [],
|
||||
imageTranscodes: [],
|
||||
})
|
||||
|
||||
mockActivities.extractPosterActivity.mockResolvedValue({
|
||||
poster: { key: 'files/asset-sprite/poster.webp' },
|
||||
})
|
||||
mockActivities.generateSpriteActivity.mockResolvedValue({
|
||||
sprite: { key: 'files/asset-sprite/sprite.webp', frames: 100, tileX: 10, tileY: 10 },
|
||||
poster: { key: 'files/asset-sprite/poster.webp' },
|
||||
})
|
||||
mockActivities.transcodeVideoActivity.mockResolvedValue({
|
||||
key: 'files/asset-sprite/video-180p.mp4',
|
||||
width: 320,
|
||||
height: 180,
|
||||
})
|
||||
|
||||
// Capture a snapshot of the media payload at each commit: the workflow mutates the same
|
||||
// `mediaInfo` object in place, so the recorded mock call args would reflect the final state.
|
||||
const commitSnapshots: Array<{ sprite?: unknown; videoTranscodes: unknown[] }> = []
|
||||
mockActivities.updateAssetMediaActivity.mockImplementation(
|
||||
(params: { mediaInfo: { sprite?: unknown; videoTranscodes?: unknown[] } }) => {
|
||||
commitSnapshots.push({
|
||||
sprite: params.mediaInfo.sprite,
|
||||
videoTranscodes: [...(params.mediaInfo.videoTranscodes ?? [])],
|
||||
})
|
||||
return Promise.resolve()
|
||||
},
|
||||
)
|
||||
|
||||
await transcodeVideoWorkflow(task)
|
||||
|
||||
const spriteOrder = mockActivities.generateSpriteActivity.mock.invocationCallOrder[0]
|
||||
const firstProxyOrder = mockActivities.transcodeVideoActivity.mock.invocationCallOrder[0]
|
||||
|
||||
// Sprite generation must run before any proxy transcode.
|
||||
expect(spriteOrder).toBeLessThan(firstProxyOrder)
|
||||
|
||||
// The media commit that carries the sprite must land before the first proxy transcode too,
|
||||
// and must not yet contain any proxy transcodes.
|
||||
const spriteCommitIndex = commitSnapshots.findIndex((snapshot) => snapshot.sprite !== undefined)
|
||||
expect(spriteCommitIndex).toBeGreaterThanOrEqual(0)
|
||||
expect(commitSnapshots[spriteCommitIndex].videoTranscodes).toEqual([])
|
||||
|
||||
expect(
|
||||
mockActivities.updateAssetMediaActivity.mock.invocationCallOrder[spriteCommitIndex],
|
||||
).toBeLessThan(firstProxyOrder)
|
||||
})
|
||||
|
||||
it('should transcode only HDR proxies and HDR 180p preview when source is HDR', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-hdr',
|
||||
assetId: 'asset-hdr',
|
||||
type: WorkflowTaskType.transcode_video,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
sessionId: null,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
transcode: {
|
||||
videoStrategy: 'best_match',
|
||||
poster: true,
|
||||
},
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-hdr',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-hdr',
|
||||
storageKey: { key: 'hdr-video.mp4' },
|
||||
mediaType: 'video/mp4',
|
||||
})
|
||||
|
||||
mockActivities.getMediaInfoActivity.mockResolvedValue({
|
||||
proxyType: 'video',
|
||||
metadata: {
|
||||
originalWidth: 1920,
|
||||
originalHeight: 1080,
|
||||
duration: 10,
|
||||
frameRate: 30,
|
||||
totalFrames: 300,
|
||||
startTimecode: '00:00:00:00',
|
||||
bitRate: 1000,
|
||||
videoBitRate: 850000,
|
||||
hasAudio: false,
|
||||
format: {},
|
||||
isHdr: true,
|
||||
hdrType: 'pq',
|
||||
colorTransfer: 'smpte2084',
|
||||
colorPrimaries: 'bt2020',
|
||||
colorSpace: 'bt2020nc',
|
||||
},
|
||||
videoTranscodes: [],
|
||||
imageTranscodes: [],
|
||||
})
|
||||
|
||||
mockActivities.transcodeVideoActivity.mockImplementation(async (params) => {
|
||||
return {
|
||||
key: `files/asset-hdr/video-${params.videoSpec.resolution}${params.videoSpec.hdr ? '-hdr' : ''}.mp4`,
|
||||
width: params.videoSpec.width,
|
||||
height: params.videoSpec.height,
|
||||
resolution: params.videoSpec.resolution,
|
||||
hdr: params.videoSpec.hdr,
|
||||
}
|
||||
})
|
||||
|
||||
await transcodeVideoWorkflow(task)
|
||||
|
||||
// Poster extraction must use SDR tone mapping
|
||||
expect(mockActivities.extractPosterActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
isHdr: true,
|
||||
hdrType: 'pq',
|
||||
colorTransfer: 'smpte2084',
|
||||
}),
|
||||
)
|
||||
|
||||
// 180p preview must be generated as HDR (hdr: true)
|
||||
expect(mockActivities.transcodeVideoActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
videoSpec: expect.objectContaining({
|
||||
resolution: '180p',
|
||||
hdr: true,
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
// Main resolution (1080p) must be called as HDR (hdr: true)
|
||||
expect(mockActivities.transcodeVideoActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
videoSpec: expect.objectContaining({
|
||||
resolution: '1080p',
|
||||
hdr: true,
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
// No calls should have been made with hdr: false for HDR source
|
||||
const calls = mockActivities.transcodeVideoActivity.mock.calls
|
||||
const sdrCalls = calls.filter(
|
||||
(c: unknown[]) => (c[0] as { videoSpec: { hdr?: boolean } }).videoSpec.hdr === false,
|
||||
)
|
||||
expect(sdrCalls).toHaveLength(0)
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-hdr',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
})
|
||||
})
|
||||
|
||||
it('should transcode only SDR proxy and SDR 180p preview when source is SDR', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-sdr-source',
|
||||
assetId: 'asset-sdr-source',
|
||||
type: WorkflowTaskType.transcode_video,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
sessionId: null,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
transcode: {
|
||||
videoStrategy: 'best_match',
|
||||
poster: true,
|
||||
},
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-sdr-source',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-sdr-source',
|
||||
storageKey: { key: 'sdr-video.mp4' },
|
||||
mediaType: 'video/mp4',
|
||||
})
|
||||
|
||||
mockActivities.getMediaInfoActivity.mockResolvedValue({
|
||||
proxyType: 'video',
|
||||
metadata: {
|
||||
originalWidth: 1920,
|
||||
originalHeight: 1080,
|
||||
duration: 10,
|
||||
frameRate: 30,
|
||||
totalFrames: 300,
|
||||
startTimecode: '00:00:00:00',
|
||||
bitRate: 1000,
|
||||
videoBitRate: 850000,
|
||||
hasAudio: false,
|
||||
format: {},
|
||||
isHdr: false,
|
||||
},
|
||||
videoTranscodes: [],
|
||||
imageTranscodes: [],
|
||||
})
|
||||
|
||||
mockActivities.transcodeVideoActivity.mockImplementation(async (params) => {
|
||||
return {
|
||||
key: `files/asset-sdr-source/video-${params.videoSpec.resolution}.mp4`,
|
||||
width: params.videoSpec.width,
|
||||
height: params.videoSpec.height,
|
||||
resolution: params.videoSpec.resolution,
|
||||
hdr: params.videoSpec.hdr,
|
||||
}
|
||||
})
|
||||
|
||||
await transcodeVideoWorkflow(task)
|
||||
|
||||
// 180p preview must be generated as SDR (hdr: false)
|
||||
expect(mockActivities.transcodeVideoActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
videoSpec: expect.objectContaining({
|
||||
resolution: '180p',
|
||||
hdr: false,
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
// Main resolution (1080p) must be generated as SDR (hdr: false)
|
||||
expect(mockActivities.transcodeVideoActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
videoSpec: expect.objectContaining({
|
||||
resolution: '1080p',
|
||||
hdr: false,
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
// No calls should have been made with hdr: true for SDR source
|
||||
const calls = mockActivities.transcodeVideoActivity.mock.calls
|
||||
const hdrCalls = calls.filter(
|
||||
(c: unknown[]) => (c[0] as { videoSpec: { hdr?: boolean } }).videoSpec.hdr === true,
|
||||
)
|
||||
expect(hdrCalls).toHaveLength(0)
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-sdr-source',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -68,6 +68,10 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
const posterResult = await executeActivity(workerQueue, extractPosterActivity, {
|
||||
assetKey: key,
|
||||
posterSpec,
|
||||
taskId: task.id,
|
||||
isHdr: mediaInfo.metadata?.isHdr,
|
||||
hdrType: mediaInfo.metadata?.hdrType,
|
||||
colorTransfer: mediaInfo.metadata?.colorTransfer,
|
||||
})
|
||||
mediaInfo.poster = posterResult.poster
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
@@ -76,6 +80,43 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
})
|
||||
}
|
||||
|
||||
// Generate the sprite (and its poster fallback) before the expensive proxy transcodes so the
|
||||
// file list can show a poster/sprite preview while the asset is still processing.
|
||||
if (spec.sprite || (spec.poster && !mediaInfo.poster)) {
|
||||
const lastSlashIndex = key.lastIndexOf('/')
|
||||
const assetDir = lastSlashIndex === -1 ? '' : key.substring(0, lastSlashIndex)
|
||||
|
||||
const spriteSpec: PrismaJson.SpriteInfo = {
|
||||
key: assetDir ? `${assetDir}/sprite.webp` : 'sprite.webp',
|
||||
frames: 100,
|
||||
tileX: 10,
|
||||
tileY: 10,
|
||||
}
|
||||
const posterSpec: PrismaJson.PosterInfo = mediaInfo.poster || {
|
||||
key: assetDir ? `${assetDir}/poster.webp` : 'poster.webp',
|
||||
}
|
||||
|
||||
const spriteResult = await executeActivity(workerQueue, generateSpriteActivity, {
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
spriteSpec,
|
||||
posterSpec,
|
||||
mediaInfo,
|
||||
})
|
||||
if (spec.sprite) {
|
||||
mediaInfo.sprite = spriteResult.sprite
|
||||
}
|
||||
if (!mediaInfo.poster) {
|
||||
mediaInfo.poster = spriteResult.poster
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
}
|
||||
|
||||
const metadata = mediaInfo.metadata
|
||||
|
||||
if (mediaInfo.proxyType === 'video' && metadata) {
|
||||
@@ -91,13 +132,46 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
metadata.originalHeight,
|
||||
)
|
||||
|
||||
const isHdr = Boolean(metadata.isHdr)
|
||||
|
||||
if (res === '180p') {
|
||||
const videoSpec: PrismaJson.VideoTranscode = {
|
||||
resolution: res,
|
||||
width,
|
||||
height,
|
||||
hdr: isHdr,
|
||||
}
|
||||
|
||||
const videoTranscode = await executeActivity(workerQueue, transcodeVideoActivity, {
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
videoSpec,
|
||||
duration: metadata.duration,
|
||||
originalFps: metadata.frameRate,
|
||||
hardwareAcceleration: spec.hardwareAcceleration,
|
||||
sourceVideoBitrate: metadata.videoBitRate || metadata.bitRate,
|
||||
threads: spec.threads,
|
||||
sourceIsHdr: metadata.isHdr,
|
||||
sourceHdrType: metadata.hdrType,
|
||||
sourceColorTransfer: metadata.colorTransfer,
|
||||
sourceColorPrimaries: metadata.colorPrimaries,
|
||||
sourceColorSpace: metadata.colorSpace,
|
||||
})
|
||||
|
||||
mediaInfo.videoPreview = videoTranscode
|
||||
continue
|
||||
}
|
||||
|
||||
const videoSpec: PrismaJson.VideoTranscode = {
|
||||
resolution: res,
|
||||
width,
|
||||
height,
|
||||
hdr: isHdr,
|
||||
}
|
||||
|
||||
const videoTranscode = await executeActivity(workerQueue, transcodeVideoActivity, {
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
videoSpec,
|
||||
@@ -105,21 +179,25 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
originalFps: metadata.frameRate,
|
||||
hardwareAcceleration: spec.hardwareAcceleration,
|
||||
sourceVideoBitrate: metadata.videoBitRate || metadata.bitRate,
|
||||
threads: spec.threads,
|
||||
sourceIsHdr: metadata.isHdr,
|
||||
sourceHdrType: metadata.hdrType,
|
||||
sourceColorTransfer: metadata.colorTransfer,
|
||||
sourceColorPrimaries: metadata.colorPrimaries,
|
||||
sourceColorSpace: metadata.colorSpace,
|
||||
})
|
||||
|
||||
if (res === '180p') {
|
||||
mediaInfo.videoPreview = videoTranscode
|
||||
} else {
|
||||
mediaInfo.videoTranscodes.push(videoTranscode)
|
||||
}
|
||||
mediaInfo.videoTranscodes.push(videoTranscode)
|
||||
}
|
||||
}
|
||||
|
||||
const isAudio = mediaInfo.proxyType === 'audio'
|
||||
if (isAudio && metadata) {
|
||||
const audioTranscode = await executeActivity(workerQueue, transcodeAudioActivity, {
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
threads: spec.threads,
|
||||
})
|
||||
mediaInfo.videoTranscodes.push(audioTranscode)
|
||||
}
|
||||
@@ -133,35 +211,6 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
mediaInfo.thumbnail = thumbTranscode
|
||||
}
|
||||
|
||||
if (spec.sprite || (spec.poster && !mediaInfo.poster)) {
|
||||
const lastSlashIndex = key.lastIndexOf('/')
|
||||
const assetDir = lastSlashIndex === -1 ? '' : key.substring(0, lastSlashIndex)
|
||||
|
||||
const spriteSpec: PrismaJson.SpriteInfo = {
|
||||
key: assetDir ? `${assetDir}/sprite.webp` : 'sprite.webp',
|
||||
frames: 100,
|
||||
tileX: 10,
|
||||
tileY: 10,
|
||||
}
|
||||
const posterSpec: PrismaJson.PosterInfo = mediaInfo.poster || {
|
||||
key: assetDir ? `${assetDir}/poster.webp` : 'poster.webp',
|
||||
}
|
||||
|
||||
const spriteResult = await executeActivity(workerQueue, generateSpriteActivity, {
|
||||
assetKey: key,
|
||||
filePath,
|
||||
spriteSpec,
|
||||
posterSpec,
|
||||
mediaInfo,
|
||||
})
|
||||
if (spec.sprite) {
|
||||
mediaInfo.sprite = spriteResult.sprite
|
||||
}
|
||||
if (!mediaInfo.poster) {
|
||||
mediaInfo.poster = spriteResult.poster
|
||||
}
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
|
||||
@@ -144,4 +144,20 @@ describe('BreadcrumbNav component', () => {
|
||||
|
||||
expect(container.querySelector('.lucide-bot')).toBeNull()
|
||||
})
|
||||
|
||||
it('renders file actions dropdown trigger button and opens on click', () => {
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BreadcrumbNav
|
||||
{...baseProps}
|
||||
fileId="file-1"
|
||||
currentAsset={{ id: 'file-1', name: 'sample.mov', type: 'file', version: 1 }}
|
||||
allowDownload={true}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
const triggerButton = screen.getByRole('button', { name: 'sample.mov' })
|
||||
expect(triggerButton).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -84,6 +84,7 @@ interface BreadcrumbNavProps {
|
||||
key: string
|
||||
width: number
|
||||
height: number
|
||||
hdr?: boolean
|
||||
}>
|
||||
}
|
||||
versions?: Array<{
|
||||
@@ -133,6 +134,7 @@ export function BreadcrumbNav({
|
||||
const { openMobileMenu } = useDualSidebarStore()
|
||||
const [isManageVersionsOpen, setIsManageVersionsOpen] = useState(false)
|
||||
const [isLinkedTasksOpen, setIsLinkedTasksOpen] = useState(false)
|
||||
const [isFileMenuOpen, setIsFileMenuOpen] = useState(false)
|
||||
|
||||
const targetAssetId = fileId || currentAsset.id
|
||||
const isRecentlyDeleted = currentAsset.name === 'Recently Deleted'
|
||||
@@ -249,17 +251,32 @@ export function BreadcrumbNav({
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger className="flex items-center gap-1 truncate rounded px-2 py-1 text-sm font-medium text-foreground transition-colors hover:bg-accent hover:text-accent-foreground">
|
||||
<DropdownMenu modal={false} open={isFileMenuOpen} onOpenChange={setIsFileMenuOpen}>
|
||||
<div
|
||||
className="flex items-center gap-1 truncate rounded px-2 py-1 text-sm font-medium text-foreground transition-colors hover:bg-accent hover:text-accent-foreground cursor-pointer select-none"
|
||||
onClick={() => setIsFileMenuOpen((prev) => !prev)}
|
||||
>
|
||||
<span className="truncate">{currentAsset.name}</span>
|
||||
{currentAsset.version !== undefined && (
|
||||
<Badge variant="outline" className="px-1 py-0 text-xs shrink-0">
|
||||
v{currentAsset.version}
|
||||
</Badge>
|
||||
)}
|
||||
<ChevronDown className="h-4 w-4 shrink-0" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-56" align="start">
|
||||
<DropdownMenuTrigger
|
||||
asChild
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={currentAsset.name}
|
||||
className="flex items-center justify-center p-0.5 rounded shrink-0 focus:outline-none"
|
||||
>
|
||||
<ChevronDown className="h-4 w-4 shrink-0" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
</div>
|
||||
<DropdownMenuContent className="w-56" align="center">
|
||||
{allowDownload &&
|
||||
(hasVideoTranscodes ? (
|
||||
<DropdownMenuSub>
|
||||
@@ -278,13 +295,14 @@ export function BreadcrumbNav({
|
||||
else if (longSide >= 960) resolution = '540p'
|
||||
else if (longSide >= 640) resolution = '360p'
|
||||
else if (longSide >= 320) resolution = '180p'
|
||||
const label = t.hdr ? `${resolution} (HDR)` : resolution
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={resolution}
|
||||
key={t.key || `${resolution}-${t.hdr ? 'hdr' : 'sdr'}`}
|
||||
onClick={() => handleDownload(t.key)}
|
||||
className="flex items-center justify-between"
|
||||
>
|
||||
<span>{resolution}</span>
|
||||
<span>{label}</span>
|
||||
<span className="text-xs text-muted-foreground">MP4</span>
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
|
||||
@@ -19,7 +19,7 @@ interface CompareControlBarProps {
|
||||
onVolumeChange: (volume: number) => void
|
||||
onToggleMute: () => void
|
||||
onChangePlaybackRate: (rate: number) => void
|
||||
onChangeResolution: (resolution: string) => void
|
||||
onChangeResolution: (resolution: string, hdr?: boolean) => void
|
||||
onZoomIn: () => void
|
||||
onZoomOut: () => void
|
||||
onFit: () => void
|
||||
@@ -65,6 +65,7 @@ export function CompareControlBar({
|
||||
isFullScreen,
|
||||
showFrames: false,
|
||||
currentResolution: v.currentResolution,
|
||||
isCurrentHdr: v.isCurrentHdr,
|
||||
}
|
||||
|
||||
// The active-side asset carries the metadata used for timecode display and
|
||||
@@ -88,7 +89,7 @@ export function CompareControlBar({
|
||||
toggleMute={onToggleMute}
|
||||
handleVolumeChange={onVolumeChange}
|
||||
changePlaybackRate={onChangePlaybackRate}
|
||||
changeResolution={(res: DisplayTranscode) => onChangeResolution(res.resolution)}
|
||||
changeResolution={(res: DisplayTranscode) => onChangeResolution(res.resolution, res.hdr)}
|
||||
handleDownload={(key?: string) => onDownload(key)}
|
||||
toggleFullScreen={onToggleFullScreen}
|
||||
onZoomChange={(nz: number) => (nz >= activeState.zoom ? onZoomIn() : onZoomOut())}
|
||||
|
||||
@@ -213,7 +213,7 @@ export function CompareViewer({
|
||||
)
|
||||
|
||||
const handleChangeResolution = useCallback(
|
||||
(resolution: string) => getActive()?.changeResolution(resolution),
|
||||
(resolution: string, hdr?: boolean) => getActive()?.changeResolution(resolution, hdr),
|
||||
[getActive],
|
||||
)
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ export interface PaneReportedState {
|
||||
playbackRate: number
|
||||
isLooping: boolean
|
||||
currentResolution: string
|
||||
isCurrentHdr?: boolean
|
||||
resolutions: DisplayTranscode[]
|
||||
buffered: number
|
||||
}
|
||||
@@ -45,7 +46,7 @@ export interface ComparePaneHandle {
|
||||
setVolume: (volume: number) => void
|
||||
setPlaybackRate: (rate: number) => void
|
||||
toggleLoop: () => void
|
||||
changeResolution: (resolution: string) => void
|
||||
changeResolution: (resolution: string, hdr?: boolean) => void
|
||||
// Zoom / pan (image + video)
|
||||
zoomBy: (factor: number) => void
|
||||
fit: () => void
|
||||
|
||||
@@ -19,7 +19,6 @@ interface DrawingCanvasProps {
|
||||
imageUrl?: string
|
||||
/** A live canvas to draw instead of an image URL (e.g. a PDF.js page render). */
|
||||
canvasElement?: HTMLCanvasElement | null
|
||||
videoElement?: HTMLVideoElement
|
||||
annotations: Annotation[]
|
||||
scale: number
|
||||
offset: { x: number; y: number }
|
||||
@@ -40,7 +39,6 @@ const DrawingCanvas = ({
|
||||
mediaDimensions,
|
||||
imageUrl,
|
||||
canvasElement,
|
||||
videoElement,
|
||||
annotations,
|
||||
scale,
|
||||
offset,
|
||||
@@ -53,7 +51,7 @@ const DrawingCanvas = ({
|
||||
onAddAnnotation,
|
||||
}: DrawingCanvasProps) => {
|
||||
const [loadedImage] = useImage(imageUrl || '', 'anonymous')
|
||||
const imageRef = useRef<Konva.Image>(null)
|
||||
const mediaGroupRef = useRef<Konva.Group>(null)
|
||||
const isDragging = useRef(false)
|
||||
const lastPos = useRef({ x: 0, y: 0 })
|
||||
const startPointRef = useRef<{ x: number; y: number } | null>(null)
|
||||
@@ -66,27 +64,11 @@ const DrawingCanvas = ({
|
||||
// Force a redraw whenever the live canvas source is swapped, so the layer
|
||||
// picks up the new page raster (Konva redraws the source each batchDraw).
|
||||
useEffect(() => {
|
||||
if (canvasElement && imageRef.current) {
|
||||
imageRef.current.getLayer()?.batchDraw()
|
||||
if (canvasElement && mediaGroupRef.current) {
|
||||
mediaGroupRef.current.getLayer()?.batchDraw()
|
||||
}
|
||||
}, [canvasElement])
|
||||
|
||||
// Handle Video Redraw
|
||||
useEffect(() => {
|
||||
if (videoElement && imageRef.current) {
|
||||
const layer = imageRef.current.getLayer()
|
||||
if (!layer) return
|
||||
|
||||
const anim = new Konva.Animation(() => {
|
||||
// Force redraw to update video frame
|
||||
}, layer)
|
||||
anim.start()
|
||||
return () => {
|
||||
anim.stop()
|
||||
}
|
||||
}
|
||||
}, [videoElement])
|
||||
|
||||
// -- Helpers --
|
||||
const getRelativePointerPosition = (
|
||||
node: Konva.Node,
|
||||
@@ -217,7 +199,7 @@ const DrawingCanvas = ({
|
||||
const handleGlobalMove = (e: MouseEvent | TouchEvent) => {
|
||||
if (!isDragging.current) return
|
||||
|
||||
const stage = imageRef.current?.getStage()
|
||||
const stage = mediaGroupRef.current?.getStage()
|
||||
if (!stage) return
|
||||
const container = stage.container()
|
||||
const rect = container.getBoundingClientRect()
|
||||
@@ -255,11 +237,11 @@ const DrawingCanvas = ({
|
||||
if (activeDrawing) {
|
||||
if (tool === 'select') return
|
||||
|
||||
const pos = getRelativePointerPosition(imageRef.current!, true, stagePos)
|
||||
const pos = getRelativePointerPosition(mediaGroupRef.current!, true, stagePos)
|
||||
if (!pos || !startPointRef.current) return
|
||||
const start = startPointRef.current
|
||||
|
||||
const layer = imageRef.current?.getLayer()
|
||||
const layer = mediaGroupRef.current?.getLayer()
|
||||
|
||||
if (tool === 'freehand' && currentLineRef.current) {
|
||||
const newPoints = currentLineRef.current.points().concat([pos.x, pos.y])
|
||||
@@ -317,8 +299,8 @@ const DrawingCanvas = ({
|
||||
const stage = e.target.getStage()
|
||||
if (!stage) return
|
||||
|
||||
// Use imageRef to get coordinates relative to the image (handling zoom/pan)
|
||||
const pos = getRelativePointerPosition(imageRef.current!)
|
||||
// Use mediaGroupRef to get coordinates relative to the media (handling zoom/pan)
|
||||
const pos = getRelativePointerPosition(mediaGroupRef.current!)
|
||||
if (!pos) return
|
||||
|
||||
// Only start drawing if within media bounds
|
||||
@@ -334,7 +316,7 @@ const DrawingCanvas = ({
|
||||
isDragging.current = true
|
||||
startPointRef.current = pos
|
||||
|
||||
const layer = imageRef.current?.getLayer()
|
||||
const layer = mediaGroupRef.current?.getLayer()
|
||||
if (!layer) return
|
||||
|
||||
if (currentTool === 'freehand' && currentLineRef.current) {
|
||||
@@ -474,32 +456,35 @@ const DrawingCanvas = ({
|
||||
onTouchStart={handleMouseDown}
|
||||
>
|
||||
<Layer>
|
||||
<KonvaImage
|
||||
ref={imageRef}
|
||||
image={videoElement || canvasElement || loadedImage}
|
||||
width={mediaDimensions.width}
|
||||
height={mediaDimensions.height}
|
||||
/>
|
||||
{annotations.map(renderAnnotation)}
|
||||
<Group ref={mediaGroupRef} width={mediaDimensions.width} height={mediaDimensions.height}>
|
||||
{(canvasElement || loadedImage) && (
|
||||
<KonvaImage
|
||||
image={canvasElement || loadedImage}
|
||||
width={mediaDimensions.width}
|
||||
height={mediaDimensions.height}
|
||||
/>
|
||||
)}
|
||||
{annotations.map(renderAnnotation)}
|
||||
|
||||
{/* Draft Shapes */}
|
||||
<Group listening={false}>
|
||||
<Line
|
||||
ref={currentLineRef}
|
||||
strokeWidth={2.6 / scale}
|
||||
lineCap="round"
|
||||
lineJoin="round"
|
||||
visible={false}
|
||||
/>
|
||||
<Rect ref={currentRectRef} strokeWidth={2.6 / scale} visible={false} />
|
||||
<Arrow
|
||||
ref={currentArrowRef}
|
||||
points={[]}
|
||||
strokeWidth={2.6 / scale}
|
||||
pointerLength={10 / scale}
|
||||
pointerWidth={10 / scale}
|
||||
visible={false}
|
||||
/>
|
||||
{/* Draft Shapes */}
|
||||
<Group listening={false}>
|
||||
<Line
|
||||
ref={currentLineRef}
|
||||
strokeWidth={2.6 / scale}
|
||||
lineCap="round"
|
||||
lineJoin="round"
|
||||
visible={false}
|
||||
/>
|
||||
<Rect ref={currentRectRef} strokeWidth={2.6 / scale} visible={false} />
|
||||
<Arrow
|
||||
ref={currentArrowRef}
|
||||
points={[]}
|
||||
strokeWidth={2.6 / scale}
|
||||
pointerLength={10 / scale}
|
||||
pointerWidth={10 / scale}
|
||||
visible={false}
|
||||
/>
|
||||
</Group>
|
||||
</Group>
|
||||
</Layer>
|
||||
</Stage>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { FileBrowser } from './file-browser'
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
|
||||
@@ -126,6 +127,7 @@ describe('FileBrowser', () => {
|
||||
let queryClient: QueryClient
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
@@ -312,4 +314,56 @@ describe('FileBrowser', () => {
|
||||
expect(screen.getByTestId('folder-preview-icon')).toBeDefined()
|
||||
expect(screen.getAllByText('Linked Folder').length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
const mockVersionStack: AssetInfo = {
|
||||
id: 'stack-1',
|
||||
name: 'stacked_clip.mp4',
|
||||
type: 'version_stack',
|
||||
sizeByte: 0,
|
||||
fileCount: 2,
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-01T00:00:00Z',
|
||||
status: 'processed',
|
||||
} as AssetInfo
|
||||
|
||||
it('deletes a version stack through the delete dialog', async () => {
|
||||
renderComponent({ folders: [], files: [mockVersionStack] })
|
||||
|
||||
const card = screen.getByTestId('file-card')
|
||||
fireEvent.keyDown(within(card).getByRole('button', { name: '' }), {
|
||||
key: 'ArrowDown',
|
||||
code: 'ArrowDown',
|
||||
})
|
||||
fireEvent.click(await screen.findByRole('menuitem', { name: /^Delete$|^删除$/ }))
|
||||
|
||||
const dialog = await screen.findByRole('alertdialog')
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: /^Delete$|^删除$/ }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(vi.mocked(client.api.files.$delete)).toHaveBeenCalledWith({
|
||||
json: { ids: ['stack-1'] },
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
it('restores a version stack through the context action in recently deleted', async () => {
|
||||
renderComponent({
|
||||
folders: [],
|
||||
files: [mockVersionStack],
|
||||
isRecentlyDeleted: true,
|
||||
})
|
||||
|
||||
const card = screen.getByTestId('file-card')
|
||||
fireEvent.keyDown(within(card).getByRole('button', { name: '' }), {
|
||||
key: 'ArrowDown',
|
||||
code: 'ArrowDown',
|
||||
})
|
||||
fireEvent.click(await screen.findByRole('menuitem', { name: /^Restore$|^恢复$/ }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(vi.mocked(client.api.files.restore.$post)).toHaveBeenCalledWith({
|
||||
json: { ids: ['stack-1'] },
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -223,15 +223,16 @@ describe('FileCard', () => {
|
||||
|
||||
renderComponent({ item: itemWithComments })
|
||||
|
||||
const wrapper = screen.getByTestId('file-card-preview-badges')
|
||||
expect(wrapper.className).toContain('absolute')
|
||||
expect(wrapper.className).toContain('bottom-1')
|
||||
expect(wrapper.className).toContain('left-1')
|
||||
expect(wrapper.className).toContain('pointer-events-none')
|
||||
|
||||
const commentsBadge = screen.getByTestId('file-card-comments-count')
|
||||
expect(commentsBadge).toBeTruthy()
|
||||
expect(commentsBadge.textContent).toContain('5')
|
||||
expect(commentsBadge.className).toContain('absolute')
|
||||
expect(commentsBadge.className).toContain('bottom-1')
|
||||
expect(commentsBadge.className).toContain('left-1')
|
||||
expect(commentsBadge.className).toContain('bg-black/60')
|
||||
expect(commentsBadge.className).toContain('text-white')
|
||||
expect(commentsBadge.className).toContain('pointer-events-none')
|
||||
expect(commentsBadge.className).toContain('tabular-nums')
|
||||
})
|
||||
|
||||
@@ -253,4 +254,132 @@ describe('FileCard', () => {
|
||||
renderComponent({ item: itemNoComments })
|
||||
expect(screen.queryByTestId('file-card-comments-count')).toBeNull()
|
||||
})
|
||||
|
||||
it('renders the days-left badge in preview area for recently deleted items', () => {
|
||||
const deletedItem: AssetInfo = {
|
||||
...fileItem,
|
||||
deletedAt: new Date().toISOString(),
|
||||
} as AssetInfo
|
||||
|
||||
renderComponent({ item: deletedItem, isRecentlyDeleted: true })
|
||||
|
||||
const badge = screen.getByTestId('file-card-days-left')
|
||||
expect(badge.textContent).toMatch(/30\s*(d|天)/)
|
||||
})
|
||||
|
||||
it('places the comments badge to the right of the days-left badge', () => {
|
||||
const deletedItem: AssetInfo = {
|
||||
...fileItem,
|
||||
deletedAt: new Date().toISOString(),
|
||||
commentsCount: 3,
|
||||
} as AssetInfo
|
||||
|
||||
renderComponent({ item: deletedItem, isRecentlyDeleted: true })
|
||||
|
||||
const wrapper = screen.getByTestId('file-card-preview-badges')
|
||||
const order = Array.from(wrapper.children).map((child) => child.getAttribute('data-testid'))
|
||||
expect(order).toEqual(['file-card-days-left', 'file-card-comments-count'])
|
||||
})
|
||||
|
||||
it('does not render the days-left badge outside of recently deleted', () => {
|
||||
const deletedItem: AssetInfo = {
|
||||
...fileItem,
|
||||
deletedAt: new Date().toISOString(),
|
||||
} as AssetInfo
|
||||
|
||||
renderComponent({ item: deletedItem, isRecentlyDeleted: false })
|
||||
expect(screen.queryByTestId('file-card-days-left')).toBeNull()
|
||||
})
|
||||
|
||||
it('does not render the days-left badge when deletedAt is missing', () => {
|
||||
renderComponent({ item: fileItem, isRecentlyDeleted: true })
|
||||
expect(screen.queryByTestId('file-card-days-left')).toBeNull()
|
||||
})
|
||||
|
||||
it('breathes the preview and shows "Preparing..." in place of the creator while processing', () => {
|
||||
const processingItem: AssetInfo = {
|
||||
...fileItem,
|
||||
status: 'processing',
|
||||
creator: { id: 'u1', name: 'Alice' },
|
||||
preview: {
|
||||
proxyType: 'video',
|
||||
thumbnailUrl: 'https://example.com/poster.webp',
|
||||
spriteUrl: 'https://example.com/sprite.webp',
|
||||
originalWidth: 1920,
|
||||
originalHeight: 1080,
|
||||
duration: 10,
|
||||
},
|
||||
} as AssetInfo
|
||||
|
||||
renderComponent({ item: processingItem })
|
||||
|
||||
// The preview (sprite scrubber base thumbnail) is rendered and breathes instead of an overlay.
|
||||
const media = screen.getByTestId('file-card-preview-media')
|
||||
expect(media.className).toContain('animate-pulse')
|
||||
expect(screen.getByAltText('Thumbnail').getAttribute('src')).toBe(
|
||||
'https://example.com/poster.webp',
|
||||
)
|
||||
|
||||
// The creator row is replaced by the status label while processing.
|
||||
expect(screen.getByText(/Preparing|准备中/i)).toBeTruthy()
|
||||
expect(screen.queryByText(/Alice/i)).toBeNull()
|
||||
|
||||
// The duration badge is hidden until the asset is ready.
|
||||
expect(screen.queryByText('00:10')).toBeNull()
|
||||
})
|
||||
|
||||
it('shows "Uploading..." in place of the creator while uploading', () => {
|
||||
const uploadingItem: AssetInfo = {
|
||||
...fileItem,
|
||||
status: 'uploading',
|
||||
creator: { id: 'u1', name: 'Alice' },
|
||||
} as AssetInfo
|
||||
|
||||
renderComponent({ item: uploadingItem })
|
||||
|
||||
expect(screen.getByText(/Uploading|上传中/i)).toBeTruthy()
|
||||
expect(screen.queryByText(/Alice/i)).toBeNull()
|
||||
})
|
||||
|
||||
it('shows a preparing circle and "Preparing..." when processing without a preview yet', () => {
|
||||
const processingItem: AssetInfo = {
|
||||
...fileItem,
|
||||
status: 'processing',
|
||||
creator: { id: 'u1', name: 'Alice' },
|
||||
} as AssetInfo
|
||||
|
||||
renderComponent({ item: processingItem })
|
||||
|
||||
expect(screen.queryByTestId('file-card-preview-media')).toBeNull()
|
||||
const circle = screen.getByTestId('file-card-preparing-circle')
|
||||
expect(circle.tagName.toLowerCase()).toBe('svg')
|
||||
expect(circle.querySelector('circle')?.getAttribute('fill')).toBe('transparent')
|
||||
expect(screen.getByText(/Preparing|准备中/i)).toBeTruthy()
|
||||
expect(screen.queryByText(/Alice/i)).toBeNull()
|
||||
})
|
||||
|
||||
it('stops breathing the preview and shows the creator once processed', () => {
|
||||
const processedItem: AssetInfo = {
|
||||
...fileItem,
|
||||
status: 'processed',
|
||||
creator: { id: 'u1', name: 'Alice' },
|
||||
preview: {
|
||||
proxyType: 'video',
|
||||
thumbnailUrl: 'https://example.com/poster.webp',
|
||||
duration: 10,
|
||||
},
|
||||
} as AssetInfo
|
||||
|
||||
renderComponent({ item: processedItem })
|
||||
|
||||
const media = screen.getByTestId('file-card-preview-media')
|
||||
expect(media.className).not.toContain('animate-pulse')
|
||||
expect(screen.getByAltText('Preview').getAttribute('src')).toBe(
|
||||
'https://example.com/poster.webp',
|
||||
)
|
||||
expect(screen.getByText(/Alice/i)).toBeTruthy()
|
||||
|
||||
// The duration badge appears once processing is done.
|
||||
expect(screen.getByText('00:10')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -21,13 +21,13 @@ import {
|
||||
TooltipTrigger,
|
||||
} from '@/ui/components/ui/tooltip'
|
||||
import { ProgressCircle } from '@/ui/components/ui/progress-circle'
|
||||
import { Skeleton } from '@/ui/components/ui/skeleton'
|
||||
import { formatTimeAgo } from '@/ui/lib/time'
|
||||
import { formatTimeAgo, getTrashDaysLeft } from '@/ui/lib/time'
|
||||
import { selectFileNameWithoutExtension } from '@/ui/lib/rename-utils'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
import { useDraggable, useDroppable } from '@dnd-kit/react'
|
||||
import {
|
||||
Clock,
|
||||
Download,
|
||||
Edit,
|
||||
History,
|
||||
@@ -252,6 +252,57 @@ export function FileCard({
|
||||
})
|
||||
}, [displayItem.createdAt, displayItem.agent, displayItem.creator?.name])
|
||||
|
||||
const daysLeft = isRecentlyDeleted ? getTrashDaysLeft(displayItem.deletedAt) : null
|
||||
const daysLeftTooltip =
|
||||
daysLeft === null
|
||||
? ''
|
||||
: daysLeft === 1
|
||||
? m.n_days_left_singular({ count: daysLeft })
|
||||
: m.n_days_left_plural({ count: daysLeft })
|
||||
|
||||
// A preview (poster thumbnail and/or sprite) can be available before transcoding finishes,
|
||||
// since the poster/sprite are generated and persisted ahead of the proxy transcodes.
|
||||
const hasPreview = Boolean(displayItem.preview?.thumbnailUrl || displayItem.preview?.spriteUrl)
|
||||
const isProcessing = displayItem.status === 'processing' || displayItem.status === 'uploaded'
|
||||
|
||||
// While uploading/transcoding, the creator row is replaced by a short status label so the real
|
||||
// date/author only appears once the asset is ready.
|
||||
const statusText =
|
||||
displayItem.status === 'uploading'
|
||||
? m.uploading()
|
||||
: displayItem.status === 'uploaded' || displayItem.status === 'processing'
|
||||
? m.preparing()
|
||||
: null
|
||||
|
||||
const previewBadges =
|
||||
daysLeft !== null ||
|
||||
(typeof displayItem.commentsCount === 'number' && displayItem.commentsCount > 0) ? (
|
||||
<div
|
||||
data-testid="file-card-preview-badges"
|
||||
className="pointer-events-none absolute bottom-1 left-1 z-10 flex items-center gap-1"
|
||||
>
|
||||
{daysLeft !== null && (
|
||||
<span
|
||||
data-testid="file-card-days-left"
|
||||
title={daysLeftTooltip}
|
||||
className="flex items-center gap-1 rounded bg-black/60 px-1 py-0.5 text-xs font-medium tabular-nums text-white"
|
||||
>
|
||||
<Clock className="h-3.5 w-3.5" />
|
||||
<span>{m.days_left_short({ count: daysLeft })}</span>
|
||||
</span>
|
||||
)}
|
||||
{typeof displayItem.commentsCount === 'number' && displayItem.commentsCount > 0 && (
|
||||
<span
|
||||
data-testid="file-card-comments-count"
|
||||
className="flex items-center gap-1 rounded bg-black/60 px-1 py-0.5 text-xs font-medium tabular-nums text-white"
|
||||
>
|
||||
<MessageCircleMore className="h-3.5 w-3.5" />
|
||||
<span>{displayItem.commentsCount}</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
) : null
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
@@ -303,45 +354,48 @@ export function FileCard({
|
||||
</div>
|
||||
|
||||
<div className="relative aspect-square overflow-hidden bg-muted/30">
|
||||
{displayItem.status === 'uploading' ||
|
||||
displayItem.status === 'processing' ||
|
||||
displayItem.status === 'uploaded' ||
|
||||
displayItem.status === 'error' ? (
|
||||
{displayItem.status === 'uploading' ? (
|
||||
<div className="flex h-full w-full items-center justify-center bg-background/50">
|
||||
{displayItem.status !== 'error' && (
|
||||
<Skeleton className="absolute inset-0 h-full w-full" />
|
||||
)}
|
||||
{displayItem.status === 'uploading' ? (
|
||||
<ProgressCircle progress={uploadPercent} className="w-16 h-16 z-10" />
|
||||
) : (
|
||||
<span
|
||||
className={cn(
|
||||
'z-10 font-medium px-2 text-center text-sm',
|
||||
displayItem.status === 'error'
|
||||
? 'text-destructive font-semibold'
|
||||
: 'text-muted-foreground capitalize',
|
||||
)}
|
||||
>
|
||||
{displayItem.status === 'uploaded'
|
||||
? 'Processing'
|
||||
: displayItem.status === 'error'
|
||||
? 'Failed to upload'
|
||||
: displayItem.status}
|
||||
</span>
|
||||
)}
|
||||
<ProgressCircle progress={uploadPercent} className="w-16 h-16 z-10" />
|
||||
</div>
|
||||
) : hasPreview ? (
|
||||
<>
|
||||
<div
|
||||
data-testid="file-card-preview-media"
|
||||
className={cn('h-full w-full', isProcessing && 'animate-pulse')}
|
||||
>
|
||||
<FilePreview item={displayItem} showDuration={!isProcessing} />
|
||||
</div>
|
||||
{previewBadges}
|
||||
</>
|
||||
) : displayItem.status === 'error' ? (
|
||||
<div className="flex h-full w-full items-center justify-center bg-background/50">
|
||||
<span className="z-10 font-medium px-2 text-center text-sm text-destructive font-semibold">
|
||||
{m.failed_to_upload()}
|
||||
</span>
|
||||
</div>
|
||||
) : displayItem.status === 'processing' || displayItem.status === 'uploaded' ? (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
{/* Same geometry as the upload progress ring, but empty inside and no percentage. */}
|
||||
<svg
|
||||
viewBox="0 0 50 50"
|
||||
data-testid="file-card-preparing-circle"
|
||||
className="h-16 w-16 opacity-60 animate-preparing-breathe"
|
||||
>
|
||||
<circle
|
||||
cx="25"
|
||||
cy="25"
|
||||
r="20"
|
||||
className="stroke-muted-foreground"
|
||||
strokeWidth="4"
|
||||
fill="transparent"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<FilePreview item={displayItem} showDuration />
|
||||
{typeof displayItem.commentsCount === 'number' && displayItem.commentsCount > 0 && (
|
||||
<span
|
||||
data-testid="file-card-comments-count"
|
||||
className="pointer-events-none absolute bottom-1 left-1 z-10 flex items-center gap-1 rounded bg-black/60 px-1 py-0.5 text-xs font-medium tabular-nums text-white"
|
||||
>
|
||||
<MessageCircleMore className="h-3.5 w-3.5" />
|
||||
<span>{displayItem.commentsCount}</span>
|
||||
</span>
|
||||
)}
|
||||
{previewBadges}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
@@ -378,7 +432,7 @@ export function FileCard({
|
||||
>
|
||||
<TooltipTrigger asChild>
|
||||
<p ref={creatorRef} className="text-sm text-muted-foreground line-clamp-2 h-[2lh]">
|
||||
{creatorText}
|
||||
{statusText ?? creatorText}
|
||||
</p>
|
||||
</TooltipTrigger>
|
||||
{isCreatorTooltipOpen && (
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, render, screen } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { FolderCard } from './folder-card'
|
||||
|
||||
vi.mock('@dnd-kit/react', () => ({
|
||||
useDraggable: () => ({
|
||||
ref: vi.fn(),
|
||||
isDragging: false,
|
||||
}),
|
||||
useDroppable: () => ({
|
||||
ref: vi.fn(),
|
||||
isDropTarget: false,
|
||||
}),
|
||||
}))
|
||||
|
||||
describe('FolderCard', () => {
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
const folderItem: AssetInfo = {
|
||||
id: 'folder-123',
|
||||
name: 'regular_folder',
|
||||
type: 'folder',
|
||||
status: 'processed',
|
||||
fileCount: 2,
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-01T00:00:00Z',
|
||||
} as AssetInfo
|
||||
|
||||
const renderComponent = (props: Partial<React.ComponentProps<typeof FolderCard>> = {}) => {
|
||||
return render(
|
||||
<FolderCard
|
||||
item={folderItem}
|
||||
isSelected={false}
|
||||
isChecked={false}
|
||||
isEditing={false}
|
||||
onSelect={vi.fn()}
|
||||
onDoubleClick={vi.fn()}
|
||||
onContextMenu={vi.fn()}
|
||||
onDragStart={vi.fn()}
|
||||
onDrop={vi.fn()}
|
||||
onRename={vi.fn()}
|
||||
onFinishEditing={vi.fn()}
|
||||
{...props}
|
||||
/>,
|
||||
)
|
||||
}
|
||||
|
||||
it('renders previews for the children of a folder', () => {
|
||||
const itemWithChildren: AssetInfo = {
|
||||
...folderItem,
|
||||
latestChildren: [
|
||||
{ type: 'image', preview: { proxyType: 'image', thumbnailUrl: 'http://x/thumb-1.png' } },
|
||||
{ type: 'image', preview: { proxyType: 'image', thumbnailUrl: 'http://x/thumb-2.png' } },
|
||||
],
|
||||
} as AssetInfo
|
||||
|
||||
renderComponent({ item: itemWithChildren })
|
||||
|
||||
const previews = screen.getAllByAltText('Preview')
|
||||
expect(previews).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('renders the days-left badge in the preview area for recently deleted folders', () => {
|
||||
const deletedItem: AssetInfo = {
|
||||
...folderItem,
|
||||
deletedAt: new Date().toISOString(),
|
||||
latestChildren: [
|
||||
{ type: 'image', preview: { proxyType: 'image', thumbnailUrl: 'http://x/thumb-1.png' } },
|
||||
],
|
||||
} as AssetInfo
|
||||
|
||||
renderComponent({ item: deletedItem, isRecentlyDeleted: true })
|
||||
|
||||
const badge = screen.getByTestId('folder-card-days-left')
|
||||
expect(badge.textContent).toMatch(/30\s*(d|天)/)
|
||||
// The badge must not hide the preview of the deleted folder's content
|
||||
expect(screen.getAllByAltText('Preview')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('does not render the days-left badge outside of recently deleted', () => {
|
||||
const deletedItem: AssetInfo = {
|
||||
...folderItem,
|
||||
deletedAt: new Date().toISOString(),
|
||||
} as AssetInfo
|
||||
|
||||
renderComponent({ item: deletedItem, isRecentlyDeleted: false })
|
||||
expect(screen.queryByTestId('folder-card-days-left')).toBeNull()
|
||||
})
|
||||
|
||||
it('does not render the days-left badge when deletedAt is missing', () => {
|
||||
renderComponent({ item: folderItem, isRecentlyDeleted: true })
|
||||
expect(screen.queryByTestId('folder-card-days-left')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -11,7 +11,8 @@ import { cn } from '@/ui/lib/utils'
|
||||
import { useDraggable, useDroppable } from '@dnd-kit/react'
|
||||
import type { AssetInfo, ChildPreview } from '@shumai/dtos'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { Download, Edit, History, MoreHorizontal, Trash2 } from 'lucide-react'
|
||||
import { getTrashDaysLeft } from '@/ui/lib/time'
|
||||
import { Clock, Download, Edit, History, MoreHorizontal, Trash2 } from 'lucide-react'
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { DragState } from '../dnd-types'
|
||||
import { FilePreview } from './file-preview'
|
||||
@@ -230,6 +231,14 @@ export function FolderCard({
|
||||
.trim()
|
||||
}, [])
|
||||
|
||||
const daysLeft = isRecentlyDeleted ? getTrashDaysLeft(item.deletedAt) : null
|
||||
const daysLeftTooltip =
|
||||
daysLeft === null
|
||||
? ''
|
||||
: daysLeft === 1
|
||||
? m.n_days_left_singular({ count: daysLeft })
|
||||
: m.n_days_left_plural({ count: daysLeft })
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
@@ -333,7 +342,20 @@ export function FolderCard({
|
||||
</div>
|
||||
|
||||
{item.latestChildren && item.latestChildren.length > 0 && (
|
||||
<FolderPreviewGrid items={item.latestChildren} />
|
||||
<div data-testid="folder-preview-grid" className="h-full w-full">
|
||||
<FolderPreviewGrid items={item.latestChildren} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{daysLeft !== null && (
|
||||
<span
|
||||
data-testid="folder-card-days-left"
|
||||
title={daysLeftTooltip}
|
||||
className="pointer-events-none absolute bottom-1 left-1 z-10 flex items-center gap-1 rounded bg-black/60 px-1 py-0.5 text-xs font-medium tabular-nums text-white"
|
||||
>
|
||||
<Clock className="h-3.5 w-3.5" />
|
||||
<span>{m.days_left_short({ count: daysLeft })}</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -141,7 +141,9 @@ export function useFileActions({
|
||||
}
|
||||
|
||||
const confirmDelete = () => {
|
||||
const fileIds = itemsToDelete.filter((i) => i.type === 'file').map((i) => i.id!)
|
||||
const fileIds = itemsToDelete
|
||||
.filter((i) => i.type === 'file' || i.type === 'version_stack')
|
||||
.map((i) => i.id!)
|
||||
const folderIds = itemsToDelete.filter((i) => i.type === 'folder').map((i) => i.id!)
|
||||
|
||||
if (fileIds.length > 0) {
|
||||
@@ -183,7 +185,9 @@ export function useFileActions({
|
||||
}
|
||||
|
||||
const handleRestore = (items: AssetInfo[]) => {
|
||||
const fileIds = items.filter((i) => i.type === 'file').map((i) => i.id!)
|
||||
const fileIds = items
|
||||
.filter((i) => i.type === 'file' || i.type === 'version_stack')
|
||||
.map((i) => i.id!)
|
||||
const folderIds = items.filter((i) => i.type === 'folder').map((i) => i.id!)
|
||||
|
||||
if (fileIds.length > 0) {
|
||||
|
||||
@@ -145,6 +145,7 @@ export function MobileFileDetail({
|
||||
key: t.key,
|
||||
width: t.width,
|
||||
height: t.height,
|
||||
hdr: t.hdr,
|
||||
})),
|
||||
}
|
||||
}, [file.media])
|
||||
|
||||
@@ -46,6 +46,7 @@ export interface MobileFileHeaderProps {
|
||||
key: string
|
||||
width: number
|
||||
height: number
|
||||
hdr?: boolean
|
||||
}>
|
||||
}
|
||||
canEdit?: boolean
|
||||
@@ -245,13 +246,14 @@ export function MobileFileHeader({
|
||||
else if (longSide >= 960) resolution = '540p'
|
||||
else if (longSide >= 640) resolution = '360p'
|
||||
else if (longSide >= 320) resolution = '180p'
|
||||
const label = t.hdr ? `${resolution} (HDR)` : resolution
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={resolution}
|
||||
key={t.key || `${resolution}-${t.hdr ? 'hdr' : 'sdr'}`}
|
||||
onClick={() => handleDownload(t.key)}
|
||||
className="flex items-center justify-between text-xs cursor-pointer"
|
||||
>
|
||||
<span>{resolution}</span>
|
||||
<span>{label}</span>
|
||||
<span className="text-[10px] text-muted-foreground">MP4</span>
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user