Compare commits

..
5 Commits
Author SHA1 Message Date
Yiling-J d87fe43b0f feat(dashboard): add workflow tasks monitoring and stopping to team dashboard (#489)
* feat(dashboard): add workflow tasks monitoring and stopping to team dashboard

* fix(asset): retain workflow tasks on asset purge and mark active tasks as failed

* style(webui): add edge padding to audit logs and workflow tasks tables

* fix(workflow): atomically update asset status to failed when task is stopped

* fix(workflow): propagate cancellation errors, guard concurrent task stop, and localize UI

* docs(changelog): keep only added log for workflow tasks dashboard

* test(provider): mock upstream catalog api calls using saved fixtures

* feat(dashboard): show file name, size, and project name in workflow tasks list
2026-10-23 16:44:52 +08:00
Yiling-J 7a0ffca629 Add feedback invitation to README
Added a feedback section to encourage user engagement.
2026-10-22 20:39:56 +08:00
Yiling-J 5cf6d31794 chore(deps): upgrade bun to 1.4.4 and migrate to bun fmt (#488)
- Upgrade Bun to 1.4.4 across Dockerfiles, CI workflows, and release configurations.
- Update @types/bun and bun-types.
- Remove eslint-plugin-prettier and update format script to use native bun fmt.
- Configure .prettierignore to exclude packages/webui/public and minified files.
2026-10-22 20:25:54 +08:00
Yiling-J 0d5fe48a3a docs(docker): add guide for scaling transcoding workers horizontally (#486) 2026-10-21 12:45:09 +08:00
Yiling-J 19eed521ae fix(webui): prevent unwanted redirects to login on reset-password page (#487)
* fix(webui): allow reset-password route with token when stale auth exists

* fix(webui): prevent 401 redirect to login on reset-password page
2026-10-21 12:12:25 +08:00
46 changed files with 2604 additions and 125 deletions
+4 -4
View File
@@ -24,7 +24,7 @@ jobs:
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.2
bun-version: 1.4.4
- name: Install dependencies
run: bun install
@@ -81,7 +81,7 @@ jobs:
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.2
bun-version: 1.4.4
- name: Install dependencies
run: bun install
@@ -126,7 +126,7 @@ jobs:
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.2
bun-version: 1.4.4
- name: Install dependencies
run: bun install
@@ -163,7 +163,7 @@ jobs:
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.2
bun-version: 1.4.4
- name: Install dependencies
run: bun install
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.2
bun-version: 1.4.4
- name: Setup Node.js
uses: actions/setup-node@v6
+3
View File
@@ -9,3 +9,6 @@ packages/webui/paraglide
*.md
**/*.md
docs/changelog.mdx
packages/webui/public
**/*.min.*
+1 -1
View File
@@ -159,7 +159,7 @@ The project is a monorepo managed by **Bun Workspaces**. It follows a strictly d
We follow Bun's monorepo conventions for dependency management:
1. **Self-Contained Packages**: Every workspace package MUST declare its own runtime `dependencies` in its local `package.json`. Do not rely on dependencies being available via the root.
2. **Shared DevDependencies**: Common development tools (e.g., `typescript`, `eslint`, `vitest`, `prettier`, `prisma`) MUST be declared in the root `package.json` to ensure version consistency across the workspace.
2. **Shared DevDependencies**: Common development tools (e.g., `typescript`, `eslint`, `vitest`, `prisma`) MUST be declared in the root `package.json` to ensure version consistency across the workspace.
3. **Local DevDependencies**: Tools specific to a single package (e.g., `@vitejs/plugin-react` for `webui`) should be declared in that package's local `package.json`.
4. **Workspace Imports**: Use `workspace:*` for internal package dependencies.
5. **Clean Root**: The root `package.json` must not contain runtime `dependencies`. It is reserved for shared `devDependencies` and workspace-wide `scripts`.
+1 -3
View File
@@ -8,9 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
### Fixed
### Changed
* **dashboard**: Add Workflow Tasks section to the Team Dashboard allowing team owners to monitor background workflow jobs, inspect execution payloads and outputs, and stop in-flight tasks
## [0.6.0] - 2026-10-20
+2 -2
View File
@@ -1,6 +1,6 @@
#syntax=docker/dockerfile:1.7-labs
# Stage 1: Builder
FROM oven/bun:1.4.2 AS builder
FROM oven/bun:1.4.4 AS builder
WORKDIR /app
@@ -28,7 +28,7 @@ RUN bun run build.ts
RUN bun run scripts/extract-runtime-deps.ts
# Stage 2: Runner
FROM oven/bun:1.4.2 AS runner
FROM oven/bun:1.4.4 AS runner
# Install system dependencies and Jellyfin-FFmpeg (with VA-API support)
RUN apt-get update && apt-get install -y --no-install-recommends \
+2 -2
View File
@@ -1,6 +1,6 @@
#syntax=docker/dockerfile:1.7-labs
# Stage 1: Builder
FROM oven/bun:1.4.2 AS builder
FROM oven/bun:1.4.4 AS builder
WORKDIR /app
@@ -23,7 +23,7 @@ RUN bun run build.ts transcode
RUN bun run scripts/extract-runtime-deps.ts
# Stage 2: Runner
FROM oven/bun:1.4.2 AS runner
FROM oven/bun:1.4.4 AS runner
# Install transcoding system dependencies and Jellyfin-FFmpeg (with VA-API/hardware acceleration support)
RUN apt-get update && apt-get install -y --no-install-recommends \
+35 -1
View File
@@ -70,7 +70,9 @@ The ultimate goal is an **agentic Kanban**, where agents and team members can wo
> * **For Images:** Shumai generates a high-quality WebP proxy at the exact same resolution as your original file for optimized viewing.
> * **For Videos:** It generates at least one proxy video (depending on your transcoding settings), alongside a sprite image and a small preview video (capped at 1600 frames) to enable fast timeline scrubbing and lightning-quick previews.
---
Have feedback or ideas? [Share them with us](https://github.com/shumaiOne/shumai/issues/328), and if you find Shumai useful, please give us a ⭐ or recommend Shumai to someone who might find it useful, it really helps!
## Installation
@@ -142,6 +144,38 @@ Docker Compose is the fastest way to get Shumai running. You do not need to clon
```
6. Open your browser and access Shumai at `http://localhost:3000` (or `http://<your-server-ip>:3000` for remote deployments).
#### **Scaling Transcode Workers (Parallel Processing)**
By default, the Docker Compose deployment transcodes videos one-by-one. This is by design, as video transcoding is compute-intensive and can saturate available CPU or GPU resources.
However, when uploading large batches (e.g., 100+ videos at once) or massive raw camera files that take hours to process and block subsequent uploads, you can scale transcoding throughput across additional machines. Each machine still processes tasks sequentially, but adding more worker instances increases overall parallel capacity.
Shumai makes this seamless with a dedicated [`shumaione/shumai-transcode`](https://hub.docker.com/r/shumaione/shumai-transcode) Docker image:
1. **Connect**: Launch a temporary machine and ensure network access to your PostgreSQL database and storage backend (e.g., S3 or shared storage).
2. **Start the worker**: Run the container with matching database and storage credentials:
```bash
docker run -d --name shumai_transcode_worker \
-e DATABASE_URL="postgres://shumai:shumai_password@<postgres-host>:5432/shumai_db?sslmode=disable" \
-e STORAGE_BACKEND="s3" \
-e S3_BUCKET="your-bucket-name" \
-e AWS_ENDPOINT_URL_S3="https://s3.us-east-1.amazonaws.com" \
-e S3_ACCESS_KEY_ID="your-access-key-id" \
-e S3_SECRET_ACCESS_KEY="your-secret-access-key" \
shumaione/shumai-transcode:latest
```
The worker will automatically attach to the task queue and begin processing pending transcode jobs in parallel with your primary instance.
3. **Stop anytime**: Once the transcoding backlog finishes (or whenever you no longer need the extra compute), simply stop or remove the worker:
```bash
docker stop shumai_transcode_worker
```
There is no downtime or impact on the main Shumai application.
### Option 2: Run from Source (Development)
To set up Shumai locally for development:
+4 -15
View File
@@ -11,14 +11,13 @@
"@testcontainers/postgresql": "12.1.0",
"@testing-library/dom": "10.4.1",
"@testing-library/react": "16.3.3",
"@types/bun": "1.4.0",
"@types/bun": "1.4.3",
"@types/node": "25.9.1",
"bun-plugin-pino": "1.5.0",
"bun-plugin-tailwind": "0.1.2",
"bun-types": "1.4.0",
"bun-types": "1.4.3",
"eslint": "10.9.1",
"eslint-config-prettier": "10.1.8",
"eslint-plugin-prettier": "5.5.6",
"eslint-plugin-react": "7.37.5",
"globals": "17.11.0",
"happy-dom": "20.12.0",
@@ -882,8 +881,6 @@
"@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="],
"@pkgr/core": ["@pkgr/core@0.3.6", "", {}, "sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA=="],
"@playwright/test": ["@playwright/test@1.61.1", "", { "dependencies": { "playwright": "1.61.1" }, "bin": { "playwright": "cli.js" } }, "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig=="],
"@pondwader/socks5-server": ["@pondwader/socks5-server@1.0.10", "", {}, "sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg=="],
@@ -1428,7 +1425,7 @@
"@types/aria-query": ["@types/aria-query@5.0.4", "", {}, "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw=="],
"@types/bun": ["@types/bun@1.4.0", "", { "dependencies": { "bun-types": "1.4.0" } }, "sha512-K+lZULY23vRgK/CfTjFIV+tyifaNdSMlPh9j+6mQ/cLfpOznLyAuzgV/JQysyECpkBQLVMSyvjlr2fBUSA9wFQ=="],
"@types/bun": ["@types/bun@1.4.3", "", { "dependencies": { "bun-types": "1.4.3" } }, "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw=="],
"@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="],
@@ -1708,7 +1705,7 @@
"bun-plugin-tailwind": ["bun-plugin-tailwind@0.1.2", "", { "peerDependencies": { "bun": ">=1.0.0" } }, "sha512-41jNC1tZRSK3s1o7pTNrLuQG8kL/0vR/JgiTmZAJ1eHwe0w5j6HFPKeqEk0WAD13jfrUC7+ULuewFBBCoADPpg=="],
"bun-types": ["bun-types@1.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-iIKw23BspnQQYd3prITOBxeUsxBHnwzX6YJfGMuNOZzeNcMmVqzIIVGRm1l69ogaPQmb4wB6BN8mA5bE9YuC5Q=="],
"bun-types": ["bun-types@1.4.3", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg=="],
"byline": ["byline@5.0.0", "", {}, "sha512-s6webAy+R4SR8XVuJWt2V2rGvhnrhxN+9S15GNuTK3wKPOXFF6RNc+8ug2XhH+2s4f+uudG4kUVYmYOQWL2g0Q=="],
@@ -1942,8 +1939,6 @@
"eslint-config-prettier": ["eslint-config-prettier@10.1.8", "", { "peerDependencies": { "eslint": ">=7.0.0" }, "bin": { "eslint-config-prettier": "bin/cli.js" } }, "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w=="],
"eslint-plugin-prettier": ["eslint-plugin-prettier@5.5.6", "", { "dependencies": { "prettier-linter-helpers": "^1.0.1", "synckit": "^0.11.13" }, "peerDependencies": { "@types/eslint": ">=8.0.0", "eslint": ">=8.0.0", "eslint-config-prettier": ">= 7.0.0 <10.0.0 || >=10.1.0", "prettier": ">=3.0.0" }, "optionalPeers": ["@types/eslint", "eslint-config-prettier"] }, "sha512-ifetmTcxWfz+4qRW3pH/ujdTq2jQIj59AxJMIN26K5avYgU8dxycUETQonWiW+wPrYXA0j3Try0l1CnwVQtDqQ=="],
"eslint-plugin-react": ["eslint-plugin-react@7.37.5", "", { "dependencies": { "array-includes": "^3.1.8", "array.prototype.findlast": "^1.2.5", "array.prototype.flatmap": "^1.3.3", "array.prototype.tosorted": "^1.1.4", "doctrine": "^2.1.0", "es-iterator-helpers": "^1.2.1", "estraverse": "^5.3.0", "hasown": "^2.0.2", "jsx-ast-utils": "^2.4.1 || ^3.0.0", "minimatch": "^3.1.2", "object.entries": "^1.1.9", "object.fromentries": "^2.0.8", "object.values": "^1.2.1", "prop-types": "^15.8.1", "resolve": "^2.0.0-next.5", "semver": "^6.3.1", "string.prototype.matchall": "^4.0.12", "string.prototype.repeat": "^1.0.0" }, "peerDependencies": { "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7" } }, "sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA=="],
"eslint-scope": ["eslint-scope@9.1.2", "", { "dependencies": { "@types/esrecurse": "^4.3.1", "@types/estree": "^1.0.8", "esrecurse": "^4.3.0", "estraverse": "^5.2.0" } }, "sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ=="],
@@ -2000,8 +1995,6 @@
"fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
"fast-diff": ["fast-diff@1.3.0", "", {}, "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw=="],
"fast-fifo": ["fast-fifo@1.3.2", "", {}, "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="],
"fast-json-stable-stringify": ["fast-json-stable-stringify@2.1.0", "", {}, "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="],
@@ -2576,8 +2569,6 @@
"prettier": ["prettier@3.9.6", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g=="],
"prettier-linter-helpers": ["prettier-linter-helpers@1.0.1", "", { "dependencies": { "fast-diff": "^1.1.2" } }, "sha512-SxToR7P8Y2lWmv/kTzVLC1t/GDI2WGjMwNhLLE9qtH8Q13C+aEmuRlzDst4Up4s0Wc8sF2M+J57iB3cMLqftfg=="],
"pretty-format": ["pretty-format@27.5.1", "", { "dependencies": { "ansi-regex": "^5.0.1", "ansi-styles": "^5.0.0", "react-is": "^17.0.1" } }, "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ=="],
"prisma": ["prisma@7.10.0", "", { "dependencies": { "@prisma/config": "7.10.0", "@prisma/dev": "0.24.17", "@prisma/engines": "7.10.0", "@prisma/studio-core": "0.33.0", "mysql2": "3.15.3", "postgres": "3.4.7" }, "peerDependencies": { "better-sqlite3": ">=9.0.0", "typescript": ">=5.4.0" }, "optionalPeers": ["better-sqlite3", "typescript"], "bin": { "prisma": "build/index.js" } }, "sha512-o0ornyJOWgygVAzGCpr8PdXV8EJLHyVGDDUr/voBQt8Azzw8cYTByzzPGcA/m4tCkPcnJA8raEOv2CslsKhPEw=="],
@@ -2802,8 +2793,6 @@
"supports-preserve-symlinks-flag": ["supports-preserve-symlinks-flag@1.0.0", "", {}, "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w=="],
"synckit": ["synckit@0.11.13", "", { "dependencies": { "@pkgr/core": "^0.3.6" } }, "sha512-eNRKgb3z66Yp3D2CixVujOUvXLFUTij/zVnV8KRyvFdQwpz7I5DS8UfRkTeLzb64u+dkzDSdelE24izu+zSSUg=="],
"tabbable": ["tabbable@6.5.0", "", {}, "sha512-wieBHXygIm7OyQOu5hQlkk62/WyCFYGlWg7L6/ZCUZwx0o398Zkn4pVmMyfYhfMG8kGrj/Krt8eIk6UKC6VzwA=="],
"tailwind-merge": ["tailwind-merge@3.6.0", "", {}, "sha512-uxL7qAVQriqRQPAyK3pj66VqskWqoZ37PW94jwOTwNfq/z9oyu1V+eqrZqtR2+fCiXdYOZe/Modt8GtvqNzu+w=="],
+3 -4
View File
@@ -24,7 +24,7 @@
"test:e2e:workflow": "bun --bun vitest run -c packages/e2e/vitest.config.ts",
"test:e2e:install": "playwright install --with-deps",
"harness:dev": "bun run packages/webui/e2e/harness/serve.ts",
"format": "prettier --write .",
"format": "bun fmt",
"db:migrate": "bun run prisma migrate dev",
"db:deploy": "bun run prisma migrate deploy",
"db:generate": "cd packages/db && bunx prisma generate",
@@ -50,14 +50,13 @@
"@testcontainers/postgresql": "12.1.0",
"@testing-library/dom": "10.4.1",
"@testing-library/react": "16.3.3",
"@types/bun": "1.4.0",
"@types/bun": "1.4.3",
"@types/node": "25.9.1",
"bun-plugin-pino": "1.5.0",
"bun-plugin-tailwind": "0.1.2",
"bun-types": "1.4.0",
"bun-types": "1.4.3",
"eslint": "10.9.1",
"eslint-config-prettier": "10.1.8",
"eslint-plugin-prettier": "5.5.6",
"eslint-plugin-react": "7.37.5",
"globals": "17.11.0",
"happy-dom": "20.12.0",
+1 -7
View File
@@ -859,13 +859,7 @@ export const initializeAgentSessionActivity = defineStep(
name: att.asset.name,
type: att.asset.type,
mediaType: attProxyType as
| 'image'
| 'video'
| 'pdf'
| 'audio'
| '3d'
| 'other'
| undefined,
'image' | 'video' | 'pdf' | 'audio' | '3d' | 'other' | undefined,
mimeType: att.asset.mediaType || undefined,
})
}
@@ -34,8 +34,7 @@ export async function resolveAnnotationsById(
})
if (entry) {
const details = (entry.data as Record<string, unknown> | null)?.details as
| ShumaiMessageContext
| undefined
ShumaiMessageContext | undefined
const entryAssetId = entry.assetId || details?.currentAsset?.id
if (entryAssetId && entryAssetId !== assetId) {
throw new Error(
+2 -4
View File
@@ -355,8 +355,7 @@ export function createReadAssetTool(
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- transcode screenshot output
const output = completedTask.output as any
const screenshots = output?.screenshots as
| Array<{ key: string; timestamp: number }>
| undefined
Array<{ key: string; timestamp: number }> | undefined
if (!screenshots || screenshots.length === 0) {
throw new Error(
@@ -620,8 +619,7 @@ export function createReadAssetTool(
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- transcode screenshot output
const output = completedTask.output as any
const screenshots = output?.screenshots as
| Array<{ key: string; timestamp: number }>
| undefined
Array<{ key: string; timestamp: number }> | undefined
if (!screenshots || screenshots.length === 0) {
throw new Error('No screenshots were generated.')
+131
View File
@@ -68,6 +68,14 @@ vi.mock('@shumai/core/src/gotenberg/gotenberg', () => ({
},
}))
vi.mock('@shumai/core/src/workflowTask/workflowTask', () => ({
workflowTaskService: {
listWorkflowTasks: vi.fn(),
getBatchWorkflowTaskStatus: vi.fn(),
stopWorkflowTask: vi.fn(),
},
}))
describe('team api', () => {
const app = new Hono().use('*', authMiddleware).route('/', teamRoute)
let mockCreateTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
@@ -655,6 +663,129 @@ describe('team api', () => {
)
})
it('GET /teams/:teamId/workflow-tasks returns list of workflow tasks for team owner', async () => {
const { workflowTaskService } = await import('@shumai/core/src/workflowTask/workflowTask')
vi.mocked(workflowTaskService.listWorkflowTasks).mockResolvedValue({
nodes: [
{
id: 'task1',
uid: 'uid1',
teamId: 't1',
projectId: 'p1',
assetId: 'a1',
type: 'transcode_video' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
status: 'processing' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
payload: {},
output: null,
heartbeat: null,
inputTokens: 0,
outputTokens: 0,
model: null,
sessionId: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
],
pageInfo: {
hasNextPage: false,
endCursor: null,
},
total: 1,
})
const res = await app.request('/teams/t1/workflow-tasks')
expect(res.status).toBe(200)
const data = await res.json()
expect(data.nodes).toHaveLength(1)
expect(data.nodes[0].id).toBe('task1')
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
permission: Permission.Admin,
type: ResourceType.Team,
id: 't1',
}),
)
})
it('POST /teams/:teamId/workflow-tasks/batch-status returns batch task statuses', async () => {
const { workflowTaskService } = await import('@shumai/core/src/workflowTask/workflowTask')
vi.mocked(workflowTaskService.getBatchWorkflowTaskStatus).mockResolvedValue({
tasks: [
{
id: 'task1',
uid: 'uid1',
teamId: 't1',
projectId: 'p1',
assetId: 'a1',
type: 'transcode_video' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
status: 'completed' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
payload: {},
output: null,
heartbeat: null,
inputTokens: 0,
outputTokens: 0,
model: null,
sessionId: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
],
})
const res = await app.request('/teams/t1/workflow-tasks/batch-status', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ taskIds: ['task1'] }),
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.tasks).toHaveLength(1)
expect(data.tasks[0].status).toBe('completed')
})
it('POST /teams/:teamId/workflow-tasks/:taskId/stop stops task for team owner', async () => {
const { workflowTaskService } = await import('@shumai/core/src/workflowTask/workflowTask')
vi.mocked(workflowTaskService.stopWorkflowTask).mockResolvedValue({
success: true,
task: {
id: 'task1',
uid: 'uid1',
teamId: 't1',
projectId: 'p1',
assetId: 'a1',
type: 'transcode_video' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
status: 'failed' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
payload: {},
output: { error: 'Task was stopped by user' },
heartbeat: null,
inputTokens: 0,
outputTokens: 0,
model: null,
sessionId: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
})
const res = await app.request('/teams/t1/workflow-tasks/task1/stop', {
method: 'POST',
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.success).toBe(true)
expect(data.task.status).toBe('failed')
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
permission: Permission.Admin,
type: ResourceType.Team,
id: 't1',
}),
)
})
it('GET /teams/:teamId/turntable-settings returns turntable settings', async () => {
const { turntableService } = await import('@shumai/core/src/turntable/turntable')
vi.mocked(turntableService.getSettings).mockResolvedValue({
+71
View File
@@ -16,6 +16,8 @@ import {
updateTeamMemberRoleRequestSchema,
createApiTokenRequestSchema,
listAuditLogsQuerySchema,
listWorkflowTasksQuerySchema,
batchWorkflowTaskStatusSchema,
} from '@shumai/dtos'
import {
updateUserMetadataRequestSchema,
@@ -25,6 +27,7 @@ import {
import { apiTokenService } from '@shumai/core/src/user/api-token'
import { aiUsageService } from '@shumai/core/src/ai-usage/ai-usage'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { workflowTaskService } from '@shumai/core/src/workflowTask/workflowTask'
import { turntableService } from '@shumai/core/src/turntable/turntable'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { NotificationType } from '@shumai/db'
@@ -517,5 +520,73 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(logs)
})
.get(
'/teams/:teamId/workflow-tasks',
zValidator('query', listWorkflowTasksQuerySchema),
async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const query = c.req.valid('query')
await authzService.hasPermission({
user,
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
const tasks = await workflowTaskService.listWorkflowTasks({
teamId,
status: query.status,
types: query.types,
first: query.first,
after: query.after,
})
return c.json(tasks)
},
)
.post(
'/teams/:teamId/workflow-tasks/batch-status',
zValidator('json', batchWorkflowTaskStatusSchema),
async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
const result = await workflowTaskService.getBatchWorkflowTaskStatus({
teamId,
taskIds: req.taskIds,
})
return c.json(result)
},
)
.post('/teams/:teamId/workflow-tasks/:taskId/stop', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const taskId = c.req.param('taskId')
await authzService.hasPermission({
user,
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
const result = await workflowTaskService.stopWorkflowTask({
teamId,
taskId,
})
return c.json(result)
})
export default route
+6 -3
View File
@@ -3240,7 +3240,7 @@ 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 () => {
it('should purge trashed assets whose status was processed, cancel their in-flight tasks, and retain WorkflowTasks as failed', async () => {
const cancelSpy = vi.spyOn(workflowService, 'cancel').mockResolvedValue(undefined)
const team = await prisma.team.create({ data: { name: 'Purge Task Team' } })
@@ -3292,9 +3292,12 @@ describe('AssetService — natural sort by name', () => {
// Task should be cancelled
expect(cancelSpy).toHaveBeenCalledWith(task.id)
// WorkflowTask should be deleted from DB
// WorkflowTask should be retained in DB and marked as failed
const taskInDb = await prisma.workflowTask.findUnique({ where: { id: task.id } })
expect(taskInDb).toBeNull()
expect(taskInDb).not.toBeNull()
expect(taskInDb?.status).toBe(WorkflowTaskStatus.failed)
const output = taskInDb?.output as { error?: string }
expect(output?.error).toBe('Asset was purged')
cancelSpy.mockRestore()
})
+23 -19
View File
@@ -1419,6 +1419,17 @@ export class AssetService {
logger.warn({ taskId: task.id, err }, 'Failed to cancel workflow task during purge')
}
}
await this.prismaClient.workflowTask.updateMany({
where: {
assetId: { in: affectedIds },
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
data: {
status: WorkflowTaskStatus.failed,
output: { error: 'Asset was purged' },
},
})
}
}
@@ -1518,8 +1529,15 @@ export class AssetService {
}
}
await this.prismaClient.workflowTask.deleteMany({
where: { assetId: { in: pendingAssetIds } },
await this.prismaClient.workflowTask.updateMany({
where: {
assetId: { in: pendingAssetIds },
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
data: {
status: WorkflowTaskStatus.failed,
output: { error: 'Asset was purged' },
},
})
}
@@ -2408,12 +2426,7 @@ export class AssetService {
}
const proxyType = (media?.proxyType || null) as
| 'image'
| 'video'
| 'audio'
| 'pdf'
| '3d'
| null
'image' | 'video' | 'audio' | 'pdf' | '3d' | null
result.push({
id: a.id,
@@ -2780,12 +2793,7 @@ export class AssetService {
if (!asset.media) return null
const proxyType = (asset.media?.proxyType || null) as
| 'image'
| 'video'
| 'audio'
| 'pdf'
| '3d'
| null
'image' | 'video' | 'audio' | 'pdf' | '3d' | null
let rawThumbKey: string | undefined
if (proxyType === 'image' && asset.media.thumbnail?.key) {
@@ -2864,11 +2872,7 @@ export class AssetService {
'GET',
)
const attachmentProxyType = (a.asset.media?.proxyType || null) as
| 'image'
| 'video'
| 'audio'
| 'pdf'
| null
'image' | 'video' | 'audio' | 'pdf' | null
attachments.push({
id: a.id,
assetId: a.asset.id,
+1 -3
View File
@@ -90,9 +90,7 @@ export class GotenbergService {
})
if (versionRes.ok) {
const vData = (await versionRes.json().catch(() => null)) as
| { version?: string }
| string
| null
{ version?: string } | string | null
if (vData && typeof vData === 'object' && 'version' in vData) {
version = String(vData.version)
} else if (typeof vData === 'string') {
+1 -2
View File
@@ -68,8 +68,7 @@ export async function resolveIntegrationConfig<TKey extends keyof PrismaJson.Set
})
const teamSettings = team?.settings as PrismaJson.Settings | null
const serviceSettings = teamSettings?.[def.settingsKey] as
| { url?: string; username?: string; password?: string }
| undefined
{ url?: string; username?: string; password?: string } | undefined
if (serviceSettings?.url?.trim()) {
return {
+1 -3
View File
@@ -41,9 +41,7 @@ export interface ProxyServerInfo {
}
export type ConnectionOutcome =
| { status: 'connected' }
| { status: 'needs-auth' }
| { status: 'error'; message: string }
{ status: 'connected' } | { status: 'needs-auth' } | { status: 'error'; message: string }
export interface CallToolOutcome {
ok: boolean
+1 -2
View File
@@ -351,8 +351,7 @@ export class McpService {
instructions?: string | null
} = {}
const impl = connection.serverVersion as
| { name?: string; title?: string; description?: string }
| undefined
{ name?: string; title?: string; description?: string } | undefined
if (impl && typeof impl === 'object') {
const reportedName = impl.title ?? impl.name
if (typeof reportedName === 'string' && reportedName.trim() !== '') {
+33 -21
View File
@@ -43,24 +43,30 @@ export function getNextOptionColor(existingOptions: PrismaJson.SelectOption[] =
export class MetadataService {
constructor(private client: typeof prisma = prisma) {}
async syncSystemFields(): Promise<void> {
await this.client.$transaction(async (tx) => {
for (const field of systemFields) {
await tx.metadataField.upsert({
where: { key: field.key },
update: {
scope: field.scope,
readOnly: field.readOnly,
config: field.config,
},
create: {
key: field.key,
scope: field.scope,
readOnly: field.readOnly ?? false,
config: field.config,
},
})
}
})
await this.client.$transaction(
async (tx) => {
for (const field of systemFields) {
await tx.metadataField.upsert({
where: { key: field.key },
update: {
scope: field.scope,
readOnly: field.readOnly,
config: field.config,
},
create: {
key: field.key,
scope: field.scope,
readOnly: field.readOnly ?? false,
config: field.config,
},
})
}
},
{
maxWait: 10000,
timeout: 30000,
},
)
}
async createTeamField(
@@ -312,9 +318,15 @@ export class MetadataService {
reqs: UpdateAssetMetadataRequest[],
allowReadOnly = false,
): Promise<void> {
await this.client.$transaction(async (tx) => {
await this.updateAssetMetadataInternal(tx, assetId, reqs, allowReadOnly)
})
await this.client.$transaction(
async (tx) => {
await this.updateAssetMetadataInternal(tx, assetId, reqs, allowReadOnly)
},
{
maxWait: 10000,
timeout: 30000,
},
)
}
/**
@@ -0,0 +1,54 @@
{
"anthropic": {
"models": {
"claude-3-5-sonnet-20241022": {
"id": "claude-3-5-sonnet-20241022",
"name": "Claude 3.5 Sonnet",
"tool_call": true,
"reasoning": false,
"limit": {
"context": 200000,
"output": 8192
},
"cost": {
"input": 3,
"output": 15,
"cache_read": 0.3,
"cache_write": 3.75
}
}
}
},
"openai": {
"models": {
"gpt-4o": {
"id": "gpt-4o",
"name": "GPT-4o",
"tool_call": true,
"reasoning": false,
"limit": {
"context": 128000,
"output": 4096
},
"cost": {
"input": 2.5,
"output": 10
}
},
"gpt-4o-extra-new": {
"id": "gpt-4o-extra-new",
"name": "GPT-4o Extra New",
"tool_call": true,
"reasoning": false,
"limit": {
"context": 128000,
"output": 4096
},
"cost": {
"input": 2.5,
"output": 10
}
}
}
}
}
@@ -0,0 +1,7 @@
{
"data": [
{
"id": "meta/llama-3.1-70b-instruct"
}
]
}
@@ -0,0 +1,17 @@
{
"data": [
{
"id": "meta-llama/llama-3.1-8b-instruct",
"name": "Meta: Llama 3.1 8B Instruct",
"context_length": 131072,
"pricing": {
"prompt": "0.00000005",
"completion": "0.00000008"
},
"top_provider": {
"max_completion_tokens": 8192
},
"supported_parameters": ["tools"]
}
]
}
@@ -1141,8 +1141,7 @@ async function loadModelsDevData(): Promise<Model<any>[]> {
baseUrl: getBedrockBaseUrl(id),
reasoning: m.reasoning === true,
input: (m.modalities?.input?.includes('image') ? ['text', 'image'] : ['text']) as (
| 'text'
| 'image'
'text' | 'image'
)[],
cost: {
input: m.cost?.input || 0,
+44 -6
View File
@@ -8,6 +8,42 @@ import * as generateModelsModule from './generator/generate-models'
import { ProviderConfigSerializable, providerModelSchema } from '@shumai/dtos'
import { getBuiltinProvidersMap } from '@shumai/core/src/provider/builtin'
import { z } from 'zod'
import modelsDevFixture from './fixtures/models-dev.json'
import openRouterFixture from './fixtures/openrouter.json'
import nvidiaFixture from './fixtures/nvidia.json'
const originalFetch = globalThis.fetch
function setupCatalogFetchMock() {
return vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url
if (url.includes('models.dev')) {
return new Response(JSON.stringify(modelsDevFixture), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
if (url.includes('openrouter.ai')) {
return new Response(JSON.stringify(openRouterFixture), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
if (url.includes('nvidia')) {
return new Response(JSON.stringify(nvidiaFixture), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
if (url.includes('ai-gateway')) {
return new Response(JSON.stringify({ data: [] }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
return originalFetch(input)
})
}
type ProviderModel = z.infer<typeof providerModelSchema>
@@ -349,10 +385,9 @@ describe('ProviderService', () => {
expect((modelsAfterUpdate[1].config as { api: string }).api).toBe('anthropic-messages')
})
it(
'should check for updates and correctly segregate new vs existing providers',
{ timeout: 30000 },
async () => {
it('should check for updates and correctly segregate new vs existing providers', async () => {
const fetchSpy = setupCatalogFetchMock()
try {
// 1. Check updates with empty team: all discovered providers are new
const emptyTeam = await prisma.team.create({
data: { name: 'Empty Provider Team' },
@@ -368,6 +403,7 @@ describe('ProviderService', () => {
// 3. Check updates after init: existing providers should have isNewProvider: false
const afterInitCheck = await providerService.checkUpdates(teamWithBuiltins.id)
const existing = afterInitCheck.providers.find((p) => !p.isNewProvider)
expect(existing).toBeDefined()
if (existing) {
expect(existing.isNewProvider).toBe(false)
const dbModels = await providerService.listModelsByProvider(
@@ -381,8 +417,10 @@ describe('ProviderService', () => {
expect(dbModelIds.has(m.modelId)).toBe(false)
}
}
},
)
} finally {
fetchSpy.mockRestore()
}
})
it('should throw an error when upstream catalog fetch fails in checkUpdates', async () => {
const team = await teamService.ensureDefaultTeam()
@@ -0,0 +1,550 @@
import { describe, it, expect } from 'vitest'
import {
prisma,
WorkflowTaskStatus,
WorkflowTaskType,
AssetStatus,
registerWorkflowCancel,
} from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { HTTPException } from 'hono/http-exception'
import { workflowTaskService } from './workflowTask'
describe('WorkflowTaskService', () => {
setupTestDbHooks()
it('lists workflow tasks for a team with pagination and filters', async () => {
const team1 = await prisma.team.create({
data: { name: 'Workflow Team 1' },
})
const team2 = await prisma.team.create({
data: { name: 'Workflow Team 2' },
})
const project1 = await prisma.project.create({
data: { name: 'Project 1', teamId: team1.id },
})
const asset1 = await prisma.asset.create({
data: {
name: 'video1.mp4',
type: 'file',
sizeByte: 2048,
status: 'uploaded',
projectId: project1.id,
},
})
// Task 1: Team 1 direct
const task1 = await prisma.workflowTask.create({
data: {
assetId: asset1.id,
teamId: team1.id,
projectId: project1.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.completed,
},
})
// Task 2: Team 1 via project (teamId is null)
const task2 = await prisma.workflowTask.create({
data: {
assetId: asset1.id,
projectId: project1.id,
type: WorkflowTaskType.chat,
status: WorkflowTaskStatus.pending,
},
})
// Task 3: Team 2
await prisma.workflowTask.create({
data: {
assetId: 'other-asset',
teamId: team2.id,
type: WorkflowTaskType.transcode_image,
status: WorkflowTaskStatus.processing,
},
})
// 1. List all for Team 1
const listAll = await workflowTaskService.listWorkflowTasks({
teamId: team1.id,
})
expect(listAll.total).toBe(2)
expect(listAll.nodes).toHaveLength(2)
expect(listAll.nodes.map((n) => n.id)).toEqual([task2.id, task1.id]) // ordered by id desc
expect(listAll.nodes[0].fileName).toBe('video1.mp4')
expect(listAll.nodes[0].fileSize).toBe(2048)
expect(listAll.nodes[0].projectName).toBe('Project 1')
expect(listAll.nodes[0].projectId).toBe(project1.id)
expect(listAll.nodes[1].fileName).toBe('video1.mp4')
expect(listAll.nodes[1].fileSize).toBe(2048)
expect(listAll.nodes[1].projectName).toBe('Project 1')
// 2. Filter by status
const listPending = await workflowTaskService.listWorkflowTasks({
teamId: team1.id,
status: [WorkflowTaskStatus.pending],
})
expect(listPending.total).toBe(1)
expect(listPending.nodes[0].id).toBe(task2.id)
// 3. Filter by type
const listChat = await workflowTaskService.listWorkflowTasks({
teamId: team1.id,
types: [WorkflowTaskType.chat],
})
expect(listChat.total).toBe(1)
expect(listChat.nodes[0].id).toBe(task2.id)
// 4. Pagination
const page1 = await workflowTaskService.listWorkflowTasks({
teamId: team1.id,
first: 1,
})
expect(page1.nodes).toHaveLength(1)
expect(page1.nodes[0].id).toBe(task2.id)
expect(page1.pageInfo.hasNextPage).toBe(true)
const page2 = await workflowTaskService.listWorkflowTasks({
teamId: team1.id,
first: 1,
after: page1.pageInfo.endCursor!,
})
expect(page2.nodes).toHaveLength(1)
expect(page2.nodes[0].id).toBe(task1.id)
})
it('gets batch status for specific task IDs with team security', async () => {
const team1 = await prisma.team.create({
data: { name: 'Batch Team 1' },
})
const team2 = await prisma.team.create({
data: { name: 'Batch Team 2' },
})
const task1 = await prisma.workflowTask.create({
data: {
assetId: 'a1',
teamId: team1.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.processing,
},
})
const task2 = await prisma.workflowTask.create({
data: {
assetId: 'a2',
teamId: team2.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.processing,
},
})
// Query empty
const empty = await workflowTaskService.getBatchWorkflowTaskStatus({
teamId: team1.id,
taskIds: [],
})
expect(empty.tasks).toEqual([])
// Query both task1 and task2 under team1
const res = await workflowTaskService.getBatchWorkflowTaskStatus({
teamId: team1.id,
taskIds: [task1.id, task2.id],
})
// task2 should be excluded because it belongs to team2
expect(res.tasks).toHaveLength(1)
expect(res.tasks[0].id).toBe(task1.id)
expect(res.tasks[0].status).toBe(WorkflowTaskStatus.processing)
})
it('stops a pending or processing task successfully', async () => {
const team = await prisma.team.create({
data: { name: 'Stop Team' },
})
const pendingTask = await prisma.workflowTask.create({
data: {
assetId: 'asset-pending',
teamId: team.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.pending,
payload: { projectId: 'p1' },
},
})
const processingTask = await prisma.workflowTask.create({
data: {
assetId: 'asset-processing',
teamId: team.id,
type: WorkflowTaskType.ai_metadata_autofill,
status: WorkflowTaskStatus.processing,
},
})
// Stop pending task
const stopPendingRes = await workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: pendingTask.id,
})
expect(stopPendingRes.success).toBe(true)
expect(stopPendingRes.task.status).toBe(WorkflowTaskStatus.failed)
const pendingOutput = stopPendingRes.task.output as { error: string }
expect(pendingOutput.error).toBe('Task was stopped by user')
// Stop processing task
const stopProcessingRes = await workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: processingTask.id,
})
expect(stopProcessingRes.success).toBe(true)
expect(stopProcessingRes.task.status).toBe(WorkflowTaskStatus.failed)
})
it('updates associated asset status to failed atomically when task is stopped', async () => {
const team = await prisma.team.create({
data: { name: 'Asset Stop Team' },
})
const project = await prisma.project.create({
data: { name: 'Asset Stop Project', teamId: team.id },
})
// Asset 1: currently uploaded (e.g. pending transcode)
const asset1 = await prisma.asset.create({
data: {
name: 'pending-video.mp4',
type: 'file',
status: AssetStatus.uploaded,
projectId: project.id,
media: {
duration: 120,
filesize: 1000,
frames: 3000,
imageTranscodes: [],
videoTranscodes: [],
finishedAt: '',
metadata: null,
original: null,
},
},
})
const task1 = await prisma.workflowTask.create({
data: {
assetId: asset1.id,
teamId: team.id,
projectId: project.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.pending,
},
})
// Asset 2: already processed (media finished)
const asset2 = await prisma.asset.create({
data: {
name: 'completed-video.mp4',
type: 'file',
status: AssetStatus.processed,
projectId: project.id,
media: {
duration: 60,
filesize: 500,
frames: 1500,
imageTranscodes: [],
videoTranscodes: [],
finishedAt: '2026-01-01',
metadata: null,
original: null,
},
},
})
const task2 = await prisma.workflowTask.create({
data: {
assetId: asset2.id,
teamId: team.id,
projectId: project.id,
type: WorkflowTaskType.ai_metadata_autofill,
status: WorkflowTaskStatus.processing,
},
})
// Stop task 1 (pending transcode)
await workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: task1.id,
})
const updatedAsset1 = await prisma.asset.findUniqueOrThrow({
where: { id: asset1.id },
})
expect(updatedAsset1.status).toBe(AssetStatus.failed)
const media1 = updatedAsset1.media as PrismaJson.MediaInfo
expect(media1.duration).toBe(120) // preserved other json properties
expect(media1.filesize).toBe(1000)
expect(media1.error).toBe('Task was stopped by user')
// Stop task 2 (asset already processed)
await workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: task2.id,
})
const updatedAsset2 = await prisma.asset.findUniqueOrThrow({
where: { id: asset2.id },
})
// Must NOT be overwritten to failed
expect(updatedAsset2.status).toBe(AssetStatus.processed)
const media2 = updatedAsset2.media as PrismaJson.MediaInfo
expect(media2.duration).toBe(60)
expect(media2.error).toBeUndefined()
})
it('throws 400 when attempting to stop completed or failed task', async () => {
const team = await prisma.team.create({
data: { name: 'Stop Error Team' },
})
const completedTask = await prisma.workflowTask.create({
data: {
assetId: 'asset-completed',
teamId: team.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.completed,
},
})
await expect(
workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: completedTask.id,
}),
).rejects.toThrow(HTTPException)
})
it('throws 404 when stopping non-existent task and 403 when task belongs to other team', async () => {
const team1 = await prisma.team.create({
data: { name: 'Team 1' },
})
const team2 = await prisma.team.create({
data: { name: 'Team 2' },
})
const task2 = await prisma.workflowTask.create({
data: {
assetId: 'asset-team2',
teamId: team2.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.pending,
},
})
// Non-existent task
await expect(
workflowTaskService.stopWorkflowTask({
teamId: team1.id,
taskId: 'non-existent-task-id',
}),
).rejects.toThrow(HTTPException)
// Task belongs to team 2
await expect(
workflowTaskService.stopWorkflowTask({
teamId: team1.id,
taskId: task2.id,
}),
).rejects.toThrow(HTTPException)
})
it('throws 502 and does not modify task or asset when workflow cancellation fails', async () => {
const team = await prisma.team.create({
data: { name: 'Cancel Fail Team' },
})
const project = await prisma.project.create({
data: { name: 'Cancel Fail Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'fail-cancel.mp4',
type: 'file',
status: AssetStatus.processing,
projectId: project.id,
},
})
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
teamId: team.id,
projectId: project.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.processing,
},
})
registerWorkflowCancel(async () => {
throw new Error('DBOS connection failure')
})
try {
await expect(
workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: task.id,
}),
).rejects.toMatchObject({ status: 502 })
// Verify task status was NOT changed to failed
const currentTask = await prisma.workflowTask.findUniqueOrThrow({
where: { id: task.id },
})
expect(currentTask.status).toBe(WorkflowTaskStatus.processing)
// Verify asset status was NOT changed to failed
const currentAsset = await prisma.asset.findUniqueOrThrow({
where: { id: asset.id },
})
expect(currentAsset.status).toBe(AssetStatus.processing)
} finally {
registerWorkflowCancel(async () => {})
}
})
it('throws 409 and does not overwrite status when task completes during cancellation', async () => {
const team = await prisma.team.create({
data: { name: 'Race Team' },
})
const project = await prisma.project.create({
data: { name: 'Race Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'race.mp4',
type: 'file',
status: AssetStatus.processing,
projectId: project.id,
},
})
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
teamId: team.id,
projectId: project.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.processing,
},
})
// Simulate task completing in the background while cancelWorkflowTask is awaiting
registerWorkflowCancel(async () => {
await prisma.workflowTask.update({
where: { id: task.id },
data: { status: WorkflowTaskStatus.completed },
})
await prisma.asset.update({
where: { id: asset.id },
data: { status: AssetStatus.processed },
})
})
try {
await expect(
workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: task.id,
}),
).rejects.toMatchObject({ status: 409 })
// Verify task remains completed, not overwritten to failed
const currentTask = await prisma.workflowTask.findUniqueOrThrow({
where: { id: task.id },
})
expect(currentTask.status).toBe(WorkflowTaskStatus.completed)
// Verify asset remains processed, not overwritten to failed
const currentAsset = await prisma.asset.findUniqueOrThrow({
where: { id: asset.id },
})
expect(currentAsset.status).toBe(AssetStatus.processed)
} finally {
registerWorkflowCancel(async () => {})
}
})
it('enriches tasks with fileName, fileSize, and projectName, and handles purged assets gracefully', async () => {
const team = await prisma.team.create({
data: { name: 'Enrich Team' },
})
const project = await prisma.project.create({
data: { name: 'Enrich Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'sample_audio.mp3',
type: 'file',
sizeByte: 5242880,
status: 'uploaded',
projectId: project.id,
},
})
const taskWithAsset = await prisma.workflowTask.create({
data: {
assetId: asset.id,
teamId: team.id,
projectId: project.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.pending,
},
})
const taskWithPurgedAsset = await prisma.workflowTask.create({
data: {
assetId: 'purged-asset-id',
teamId: team.id,
type: WorkflowTaskType.transcode_image,
status: WorkflowTaskStatus.completed,
},
})
const listRes = await workflowTaskService.listWorkflowTasks({ teamId: team.id })
expect(listRes.total).toBe(2)
const foundActive = listRes.nodes.find((n) => n.id === taskWithAsset.id)
expect(foundActive).toBeDefined()
expect(foundActive?.fileName).toBe('sample_audio.mp3')
expect(foundActive?.fileSize).toBe(5242880)
expect(foundActive?.projectName).toBe('Enrich Project')
expect(foundActive?.projectId).toBe(project.id)
const foundPurged = listRes.nodes.find((n) => n.id === taskWithPurgedAsset.id)
expect(foundPurged).toBeDefined()
expect(foundPurged?.fileName).toBeNull()
expect(foundPurged?.fileSize).toBeNull()
expect(foundPurged?.projectName).toBeNull()
// Test batch status enrichment
const batchRes = await workflowTaskService.getBatchWorkflowTaskStatus({
teamId: team.id,
taskIds: [taskWithAsset.id, taskWithPurgedAsset.id],
})
expect(batchRes.tasks).toHaveLength(2)
const batchActive = batchRes.tasks.find((t) => t.id === taskWithAsset.id)
expect(batchActive?.fileName).toBe('sample_audio.mp3')
expect(batchActive?.fileSize).toBe(5242880)
expect(batchActive?.projectName).toBe('Enrich Project')
// Test stopWorkflowTask enrichment
const stopRes = await workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: taskWithAsset.id,
})
expect(stopRes.success).toBe(true)
expect(stopRes.task.fileName).toBe('sample_audio.mp3')
expect(stopRes.task.fileSize).toBe(5242880)
expect(stopRes.task.projectName).toBe('Enrich Project')
})
})
@@ -0,0 +1,330 @@
import {
prisma,
cancelWorkflowTask,
WorkflowTaskStatus,
type WorkflowTaskType,
type Prisma,
} from '@shumai/db'
import type { WorkflowTaskItem, ListWorkflowTasksResponse } from '@shumai/dtos'
import { paginateQuery } from '@shumai/core/src/pagination'
import { logger } from '@shumai/core/src/logger'
import { HTTPException } from 'hono/http-exception'
export interface ListWorkflowTasksParams {
teamId: string
status?: WorkflowTaskStatus[]
types?: WorkflowTaskType[]
first?: number
after?: string
}
export interface StopWorkflowTaskParams {
teamId: string
taskId: string
}
export interface GetBatchWorkflowTaskStatusParams {
teamId: string
taskIds: string[]
}
interface EnrichedMetadata {
fileName?: string | null
fileSize?: number | null
projectId?: string | null
projectName?: string | null
}
function mapToWorkflowTaskItem(
task: {
id: string
uid: string
teamId: string | null
projectId: string | null
assetId: string
type: WorkflowTaskType | null
status: WorkflowTaskStatus | null
payload: unknown
output: unknown
heartbeat: Date | null
inputTokens: number
outputTokens: number
model: string | null
sessionId: string | null
createdAt: Date
updatedAt: Date
},
extra?: EnrichedMetadata,
): WorkflowTaskItem {
return {
id: task.id,
uid: task.uid,
teamId: task.teamId,
projectId: extra?.projectId !== undefined ? extra.projectId : task.projectId,
projectName: extra?.projectName ?? null,
assetId: task.assetId,
fileName: extra?.fileName ?? null,
fileSize: extra?.fileSize ?? null,
type: task.type,
status: task.status,
payload: task.payload,
output: task.output,
heartbeat: task.heartbeat ? task.heartbeat.toISOString() : null,
inputTokens: task.inputTokens,
outputTokens: task.outputTokens,
model: task.model,
sessionId: task.sessionId,
createdAt: task.createdAt.toISOString(),
updatedAt: task.updatedAt.toISOString(),
}
}
export class WorkflowTaskService {
private async enrichWorkflowTasks<
T extends {
id: string
uid: string
teamId: string | null
projectId: string | null
assetId: string
type: WorkflowTaskType | null
status: WorkflowTaskStatus | null
payload: unknown
output: unknown
heartbeat: Date | null
inputTokens: number
outputTokens: number
model: string | null
sessionId: string | null
createdAt: Date
updatedAt: Date
},
>(tasks: T[]): Promise<WorkflowTaskItem[]> {
if (tasks.length === 0) {
return []
}
const assetIds = [...new Set(tasks.map((t) => t.assetId).filter(Boolean))]
const assets =
assetIds.length > 0
? await prisma.asset.findMany({
where: { id: { in: assetIds } },
select: { id: true, name: true, sizeByte: true, projectId: true },
})
: []
const assetMap = new Map(assets.map((a) => [a.id, a]))
const allProjectIds = [
...new Set(
[...tasks.map((t) => t.projectId), ...assets.map((a) => a.projectId)].filter(
(id): id is string => Boolean(id),
),
),
]
const projects =
allProjectIds.length > 0
? await prisma.project.findMany({
where: { id: { in: allProjectIds } },
select: { id: true, name: true },
})
: []
const projectMap = new Map(projects.map((p) => [p.id, p.name]))
return tasks.map((task) => {
const asset = assetMap.get(task.assetId)
const effectiveProjectId = task.projectId || asset?.projectId || null
const projectName = effectiveProjectId ? (projectMap.get(effectiveProjectId) ?? null) : null
const fileName = asset?.name ?? null
const fileSize = asset ? Number(asset.sizeByte) : null
return mapToWorkflowTaskItem(task, {
fileName,
fileSize,
projectId: effectiveProjectId,
projectName,
})
})
}
async listWorkflowTasks(params: ListWorkflowTasksParams): Promise<ListWorkflowTasksResponse> {
const teamProjects = await prisma.project.findMany({
where: { teamId: params.teamId },
select: { id: true },
})
const projectIds = teamProjects.map((p) => p.id)
const where: Prisma.WorkflowTaskWhereInput = {
OR: [
{ teamId: params.teamId },
...(projectIds.length > 0 ? [{ projectId: { in: projectIds } }] : []),
],
}
if (params.status && params.status.length > 0) {
where.status = { in: params.status }
}
if (params.types && params.types.length > 0) {
where.type = { in: params.types }
}
const result = await paginateQuery(
(skip, take) =>
prisma.workflowTask.findMany({
where,
orderBy: { id: 'desc' },
skip,
take,
}),
() => prisma.workflowTask.count({ where }),
{ first: params.first, after: params.after },
)
const nodes = await this.enrichWorkflowTasks(result.data)
return {
nodes,
pageInfo: {
hasNextPage: !!result.pageInfo.cursor,
endCursor: result.pageInfo.cursor || null,
},
total: result.pageInfo.total ?? 0,
}
}
async getBatchWorkflowTaskStatus(
params: GetBatchWorkflowTaskStatusParams,
): Promise<{ tasks: WorkflowTaskItem[] }> {
if (!params.taskIds || params.taskIds.length === 0) {
return { tasks: [] }
}
const teamProjects = await prisma.project.findMany({
where: { teamId: params.teamId },
select: { id: true },
})
const projectIds = teamProjects.map((p) => p.id)
const tasks = await prisma.workflowTask.findMany({
where: {
id: { in: params.taskIds },
OR: [
{ teamId: params.teamId },
...(projectIds.length > 0 ? [{ projectId: { in: projectIds } }] : []),
],
},
orderBy: { id: 'desc' },
})
const enriched = await this.enrichWorkflowTasks(tasks)
return { tasks: enriched }
}
async stopWorkflowTask(
params: StopWorkflowTaskParams,
): Promise<{ success: boolean; task: WorkflowTaskItem }> {
const task = await prisma.workflowTask.findUnique({
where: { id: params.taskId },
})
if (!task) {
throw new HTTPException(404, { message: 'Workflow task not found' })
}
// Verify task belongs to this team (either directly or via project)
let belongsToTeam = task.teamId === params.teamId
if (!belongsToTeam && task.projectId) {
const project = await prisma.project.findUnique({
where: { id: task.projectId },
select: { teamId: true },
})
if (project?.teamId === params.teamId) {
belongsToTeam = true
}
}
if (!belongsToTeam) {
throw new HTTPException(403, { message: 'Permission denied: Task does not belong to team' })
}
if (
task.status !== WorkflowTaskStatus.pending &&
task.status !== WorkflowTaskStatus.processing
) {
throw new HTTPException(400, {
message: `Only pending or processing tasks can be stopped. Current status: ${task.status}`,
})
}
// Notify workflow engine (DBOS) to cancel workflow execution
try {
await cancelWorkflowTask(task.id)
} catch (err) {
logger.error({ taskId: task.id, err }, 'Failed to cancel workflow task in workflow engine')
throw new HTTPException(502, {
message: `Failed to cancel workflow task in engine: ${err instanceof Error ? err.message : String(err)}`,
})
}
const errorMsg = 'Task was stopped by user'
const prevOutput =
typeof task.output === 'object' && task.output !== null
? (task.output as Record<string, unknown>)
: {}
const updated = await prisma.$transaction(async (tx) => {
const updateResult = await tx.workflowTask.updateMany({
where: {
id: task.id,
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
data: {
status: WorkflowTaskStatus.failed,
output: {
...prevOutput,
error: errorMsg,
},
},
})
if (updateResult.count === 0) {
const latestTask = await tx.workflowTask.findUniqueOrThrow({
where: { id: task.id },
})
throw new HTTPException(409, {
message: `Task is no longer active. Current status: ${latestTask.status}`,
})
}
if (task.assetId) {
await tx.$executeRaw`
UPDATE "assets"
SET
"status" = 'failed'::"AssetStatus",
"media" = COALESCE("media", '{}'::jsonb) || jsonb_build_object('error', ${errorMsg}::text)
WHERE "id" = ${task.assetId}
AND "is_deleted" = false
AND "status" != 'processed'::"AssetStatus"
`
}
return await tx.workflowTask.findUniqueOrThrow({
where: { id: task.id },
})
})
logger.info({ taskId: task.id, teamId: params.teamId }, 'Workflow task stopped by user')
const [enriched] = await this.enrichWorkflowTasks([updated])
return {
success: true,
task: enriched,
}
}
}
export const workflowTaskService = new WorkflowTaskService()
+1
View File
@@ -28,3 +28,4 @@ export * from './kanban'
export * from './recents'
export * from './context'
export * from './media-generation'
export * from './workflowTask'
+79
View File
@@ -0,0 +1,79 @@
import { z } from 'zod'
import { WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db/enums'
export { WorkflowTaskType, WorkflowTaskStatus }
export const workflowTaskTypeSchema = z.nativeEnum(WorkflowTaskType)
export type WorkflowTaskTypeEnum = z.infer<typeof workflowTaskTypeSchema>
export const workflowTaskStatusSchema = z.nativeEnum(WorkflowTaskStatus)
export type WorkflowTaskStatusEnum = z.infer<typeof workflowTaskStatusSchema>
export const workflowTaskItemSchema = z.object({
id: z.string(),
uid: z.string(),
teamId: z.string().nullable().optional(),
projectId: z.string().nullable().optional(),
projectName: z.string().nullable().optional(),
assetId: z.string(),
fileName: z.string().nullable().optional(),
fileSize: z.number().nullable().optional(),
type: z.nativeEnum(WorkflowTaskType).nullable().optional(),
status: z.nativeEnum(WorkflowTaskStatus).nullable().optional(),
payload: z.unknown().optional(),
output: z.unknown().optional(),
heartbeat: z.string().nullable().optional(),
inputTokens: z.number(),
outputTokens: z.number(),
model: z.string().nullable().optional(),
sessionId: z.string().nullable().optional(),
createdAt: z.string(),
updatedAt: z.string(),
})
export type WorkflowTaskItem = z.infer<typeof workflowTaskItemSchema>
export const listWorkflowTasksQuerySchema = z.object({
first: z.coerce.number().optional(),
after: z.string().optional(),
status: z
.union([z.nativeEnum(WorkflowTaskStatus), z.array(z.nativeEnum(WorkflowTaskStatus))])
.transform((val) => (Array.isArray(val) ? val : [val]))
.optional(),
types: z
.union([z.nativeEnum(WorkflowTaskType), z.array(z.nativeEnum(WorkflowTaskType))])
.transform((val) => (Array.isArray(val) ? val : [val]))
.optional(),
})
export type ListWorkflowTasksQuery = z.infer<typeof listWorkflowTasksQuerySchema>
export const listWorkflowTasksResponseSchema = z.object({
nodes: z.array(workflowTaskItemSchema),
pageInfo: z.object({
hasNextPage: z.boolean(),
endCursor: z.string().nullable(),
}),
total: z.number(),
})
export type ListWorkflowTasksResponse = z.infer<typeof listWorkflowTasksResponseSchema>
export const batchWorkflowTaskStatusSchema = z.object({
taskIds: z.array(z.string()).max(100),
})
export type BatchWorkflowTaskStatus = z.infer<typeof batchWorkflowTaskStatusSchema>
export const batchWorkflowTaskStatusResponseSchema = z.object({
tasks: z.array(workflowTaskItemSchema),
})
export type BatchWorkflowTaskStatusResponse = z.infer<typeof batchWorkflowTaskStatusResponseSchema>
export const stopWorkflowTaskResponseSchema = z.object({
success: z.boolean(),
task: workflowTaskItemSchema,
})
export type StopWorkflowTaskResponse = z.infer<typeof stopWorkflowTaskResponseSchema>
+2
View File
@@ -11,7 +11,9 @@ const customFetch = async (input: RequestInfo | URL, init?: RequestInit) => {
if (
!window.location.pathname.includes('/login') &&
!window.location.pathname.includes('/signup') &&
!window.location.pathname.includes('/reset-password') &&
!window.location.pathname.startsWith('/share/') &&
!url.includes('/api/auth') &&
!url.includes('/api/authn')
) {
useAuthStore.getState().clearAuth()
@@ -243,8 +243,7 @@ export function ChatbotSidebar({
const msgObj = msg as unknown as Record<string, unknown>
if (msg.role === 'custom' && msgObj.customType === 'context_display_info') {
const details = msgObj.details as
| { assets?: Array<{ id: string; name: string; type: string }> }
| undefined
{ assets?: Array<{ id: string; name: string; type: string }> } | undefined
const assets = details?.assets || []
if (assets.length === 0) return null
return (
@@ -325,11 +325,13 @@ export function AuditLogsDashboard({ teamId }: AuditLogsDashboardProps) {
<Table>
<TableHeader>
<TableRow className="hover:bg-transparent border-b border-border/50">
<TableHead className="w-[180px] text-xs font-semibold">{m.action()}</TableHead>
<TableHead className="w-[200px] text-xs font-semibold">{m.user()}</TableHead>
<TableHead className="text-xs font-semibold">{m.item_id()}</TableHead>
<TableHead className="text-xs font-semibold">{m.project_id()}</TableHead>
<TableHead className="w-[160px] text-right text-xs font-semibold">
<TableHead className="w-[180px] pl-6 text-xs font-semibold">
{m.action()}
</TableHead>
<TableHead className="w-[200px] px-4 text-xs font-semibold">{m.user()}</TableHead>
<TableHead className="px-4 text-xs font-semibold">{m.item_id()}</TableHead>
<TableHead className="px-4 text-xs font-semibold">{m.project_id()}</TableHead>
<TableHead className="w-[160px] pr-6 text-right text-xs font-semibold">
{m.timestamp()}
</TableHead>
</TableRow>
@@ -342,10 +344,10 @@ export function AuditLogsDashboard({ teamId }: AuditLogsDashboardProps) {
return (
<TableRow key={log.id} className="hover:bg-muted/40 transition-colors">
<TableCell className="py-3 font-medium">
<TableCell className="py-3 pl-6 font-medium">
{getActionBadge(log.action)}
</TableCell>
<TableCell className="py-3">
<TableCell className="py-3 px-4">
<div className="flex items-center gap-2">
<Avatar className="h-6 w-6">
<AvatarImage src={userImage || undefined} />
@@ -366,13 +368,13 @@ export function AuditLogsDashboard({ teamId }: AuditLogsDashboardProps) {
)}
</div>
</TableCell>
<TableCell className="py-3 text-xs font-mono text-muted-foreground">
<TableCell className="py-3 px-4 text-xs font-mono text-muted-foreground">
{log.itemId || '-'}
</TableCell>
<TableCell className="py-3 text-xs font-mono text-muted-foreground">
<TableCell className="py-3 px-4 text-xs font-mono text-muted-foreground">
{log.projectId || '-'}
</TableCell>
<TableCell className="py-3 text-right text-xs text-muted-foreground">
<TableCell className="py-3 pr-6 text-right text-xs text-muted-foreground">
{formatTimeAgo(log.createdAt)}
</TableCell>
</TableRow>
@@ -0,0 +1,241 @@
import { useState } from 'react'
import type { WorkflowTaskItem } from '@shumai/dtos'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import { Badge } from '@/ui/components/ui/badge'
import { Button } from '@/ui/components/ui/button'
import { Copy, Check, Clock, Cpu, FileText } from 'lucide-react'
import { m } from '@/ui/paraglide/messages.js'
import { formatTimeAgo } from '@/ui/lib/time'
import { formatSize } from '@/ui/lib/format'
interface WorkflowTaskDetailsDialogProps {
task: WorkflowTaskItem | null
open: boolean
onOpenChange: (open: boolean) => void
}
export function WorkflowTaskDetailsDialog({
task,
open,
onOpenChange,
}: WorkflowTaskDetailsDialogProps) {
const [copiedKey, setCopiedKey] = useState<string | null>(null)
if (!task) return null
const copyToClipboard = (text: string, key: string) => {
navigator.clipboard.writeText(text)
setCopiedKey(key)
setTimeout(() => {
setCopiedKey(null)
}, 2000)
}
const getStatusBadge = (status?: string | null) => {
switch (status) {
case 'completed':
return (
<Badge
variant="outline"
className="bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20 text-xs font-mono"
>
completed
</Badge>
)
case 'processing':
return (
<Badge
variant="outline"
className="bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20 text-xs font-mono"
>
processing
</Badge>
)
case 'pending':
return (
<Badge
variant="outline"
className="bg-yellow-500/10 text-yellow-600 dark:text-yellow-400 border-yellow-500/20 text-xs font-mono"
>
pending
</Badge>
)
case 'failed':
return (
<Badge
variant="outline"
className="bg-destructive/10 text-destructive border-destructive/20 text-xs font-mono"
>
failed
</Badge>
)
default:
return (
<Badge variant="outline" className="text-xs font-mono">
{status || 'unknown'}
</Badge>
)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[90vh] flex flex-col p-6">
<DialogHeader className="pb-2 border-b border-border/50">
<div className="flex items-center justify-between gap-2 pr-6">
<div className="flex items-center gap-2">
<FileText className="h-5 w-5 text-primary" />
<DialogTitle className="text-lg font-bold">{m.task_details()}</DialogTitle>
</div>
<div className="flex items-center gap-2">
{getStatusBadge(task.status)}
{task.type && (
<Badge variant="secondary" className="font-mono text-xs">
{task.type}
</Badge>
)}
</div>
</div>
<DialogDescription className="text-xs text-muted-foreground mt-1 flex items-center gap-2">
<span>
{m.task_id()}: <span className="font-mono text-foreground">{task.id}</span>
</span>
<Button
variant="ghost"
size="icon"
className="h-5 w-5 text-muted-foreground hover:text-foreground"
onClick={() => copyToClipboard(task.id, 'task_id')}
>
{copiedKey === 'task_id' ? (
<Check className="h-3 w-3 text-emerald-500" />
) : (
<Copy className="h-3 w-3" />
)}
</Button>
</DialogDescription>
</DialogHeader>
{/* Metadata Grid */}
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 py-3 text-xs border-b border-border/40">
<div>
<div className="text-muted-foreground">{m.file_name()}</div>
<div
className="truncate font-medium text-foreground mt-0.5"
title={task.fileName || '-'}
>
{task.fileName || '-'}
</div>
</div>
<div>
<div className="text-muted-foreground">{m.size()}</div>
<div className="font-mono truncate font-medium text-foreground mt-0.5">
{task.fileSize !== null && task.fileSize !== undefined
? formatSize(task.fileSize)
: '-'}
</div>
</div>
<div>
<div className="text-muted-foreground">{m.project_name()}</div>
<div
className="truncate font-medium text-foreground mt-0.5"
title={task.projectName || '-'}
>
{task.projectName || '-'}
</div>
</div>
<div>
<div className="text-muted-foreground">{m.asset_id()}</div>
<div className="font-mono truncate font-medium text-foreground mt-0.5">
{task.assetId || '-'}
</div>
</div>
<div>
<div className="text-muted-foreground">{m.project_id()}</div>
<div className="font-mono truncate font-medium text-foreground mt-0.5">
{task.projectId || '-'}
</div>
</div>
<div>
<div className="text-muted-foreground">{m.created_at()}</div>
<div className="font-medium text-foreground mt-0.5 flex items-center gap-1">
<Clock className="h-3 w-3 text-muted-foreground" />
{formatTimeAgo(task.createdAt)}
</div>
</div>
<div>
<div className="text-muted-foreground">{m.updated_at()}</div>
<div className="font-medium text-foreground mt-0.5">
{formatTimeAgo(task.updatedAt)}
</div>
</div>
{task.heartbeat && (
<div>
<div className="text-muted-foreground">{m.heartbeat()}</div>
<div className="font-medium text-foreground mt-0.5">
{formatTimeAgo(task.heartbeat)}
</div>
</div>
)}
{task.model && (
<div>
<div className="text-muted-foreground">{m.model()}</div>
<div className="font-mono truncate font-medium text-foreground mt-0.5">
{task.model}
</div>
</div>
)}
{(task.inputTokens > 0 || task.outputTokens > 0) && (
<div>
<div className="text-muted-foreground flex items-center gap-1">
<Cpu className="h-3 w-3" /> {m.tokens_label()}
</div>
<div className="font-medium text-foreground mt-0.5 font-mono">
{task.inputTokens.toLocaleString()} in / {task.outputTokens.toLocaleString()} out
</div>
</div>
)}
{task.sessionId && (
<div className="col-span-2">
<div className="text-muted-foreground">{m.session_id()}</div>
<div className="font-mono truncate font-medium text-foreground mt-0.5">
{task.sessionId}
</div>
</div>
)}
</div>
{/* Tabs for Payload and Output */}
<div className="flex-1 min-h-0 pt-3">
<Tabs defaultValue="payload" className="w-full h-full flex flex-col">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="payload">{m.payload()}</TabsTrigger>
<TabsTrigger value="output">{m.output()}</TabsTrigger>
</TabsList>
<TabsContent value="payload" className="flex-1 mt-2 min-h-0">
<ScrollArea className="h-64 w-full rounded-md border border-border/50 bg-muted/30 p-3 font-mono text-xs">
<pre className="whitespace-pre-wrap break-all text-foreground/90">
{task.payload ? JSON.stringify(task.payload, null, 2) : 'null'}
</pre>
</ScrollArea>
</TabsContent>
<TabsContent value="output" className="flex-1 mt-2 min-h-0">
<ScrollArea className="h-64 w-full rounded-md border border-border/50 bg-muted/30 p-3 font-mono text-xs">
<pre className="whitespace-pre-wrap break-all text-foreground/90">
{task.output ? JSON.stringify(task.output, null, 2) : 'null'}
</pre>
</ScrollArea>
</TabsContent>
</Tabs>
</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,180 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { WorkflowTasksDashboard } from './WorkflowTasksDashboard'
import type { ListWorkflowTasksResponse } from '@shumai/dtos'
const mockGetWorkflowTasks = vi.fn()
const mockBatchStatus = vi.fn()
const mockStopTask = vi.fn()
vi.mock('@/ui/api/client', () => ({
client: {
api: {
teams: {
':teamId': {
'workflow-tasks': {
$get: () => mockGetWorkflowTasks(),
'batch-status': {
$post: () => mockBatchStatus(),
},
':taskId': {
stop: {
$post: () => mockStopTask(),
},
},
},
},
},
},
},
}))
vi.mock('sonner', () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
},
}))
vi.mock('react-intersection-observer', () => ({
useInView: () => ({ ref: vi.fn(), inView: false }),
}))
const mockTasksData: ListWorkflowTasksResponse = {
nodes: [
{
id: 'task_01M5KTTEST1',
uid: 'uid-1',
teamId: 'team-1',
projectId: 'proj-1',
projectName: 'Project Alpha',
assetId: 'asset-1',
fileName: 'nature_video.mp4',
fileSize: 10485760, // 10.49 MB
type: 'transcode_video',
status: 'processing',
createdAt: '2026-10-23T10:00:00.000Z',
updatedAt: '2026-10-23T10:01:00.000Z',
inputTokens: 0,
outputTokens: 0,
},
{
id: 'task_01M5KTTEST2',
uid: 'uid-2',
teamId: 'team-1',
projectId: null,
projectName: null,
assetId: 'asset-2',
fileName: null,
fileSize: null,
type: 'chat',
status: 'completed',
createdAt: '2026-10-23T09:00:00.000Z',
updatedAt: '2026-10-23T09:05:00.000Z',
inputTokens: 100,
outputTokens: 50,
},
],
pageInfo: {
hasNextPage: false,
endCursor: null,
},
total: 2,
}
const createWrapper = () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
})
return ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
describe('WorkflowTasksDashboard', () => {
beforeEach(() => {
vi.clearAllMocks()
mockGetWorkflowTasks.mockResolvedValue({
ok: true,
json: async () => mockTasksData,
})
mockBatchStatus.mockResolvedValue({
ok: true,
json: async () => ({ tasks: [] }),
})
})
afterEach(() => {
cleanup()
})
it('renders table columns with File Name, Size, and Project Name, without Task ID column', async () => {
render(<WorkflowTasksDashboard teamId="team-1" />, { wrapper: createWrapper() })
// Wait for tasks to load
await waitFor(() => {
expect(screen.getByText('nature_video.mp4')).toBeTruthy()
})
// Check table headers
expect(screen.getByText('File Name')).toBeTruthy()
expect(screen.getByText('Size')).toBeTruthy()
expect(screen.getByText('Project Name')).toBeTruthy()
expect(screen.queryByText('Task ID')).toBeNull() // Not in table headers
// Check row data
expect(screen.getByText('nature_video.mp4')).toBeTruthy()
expect(screen.getByText('10.49 MB')).toBeTruthy()
expect(screen.getByText('Project Alpha')).toBeTruthy()
// Fallback row data
expect(screen.getByText('asset-2')).toBeTruthy()
})
it('opens details dialog and displays file name, size, project name, and task ID', async () => {
render(<WorkflowTasksDashboard teamId="team-1" />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByText('nature_video.mp4')).toBeTruthy()
})
const viewButtons = screen.getAllByTitle('View Details')
fireEvent.click(viewButtons[0])
await waitFor(() => {
expect(screen.getByText('Task Details')).toBeTruthy()
})
// Details dialog should show Task ID
expect(screen.getByText('task_01M5KTTEST1')).toBeTruthy()
// Details dialog should show File Name, Size, Project Name
expect(screen.getAllByText('nature_video.mp4').length).toBeGreaterThanOrEqual(1)
expect(screen.getAllByText('10.49 MB').length).toBeGreaterThanOrEqual(1)
expect(screen.getAllByText('Project Alpha').length).toBeGreaterThanOrEqual(1)
})
it('shows file name in stop task confirmation dialog', async () => {
render(<WorkflowTasksDashboard teamId="team-1" />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByText('nature_video.mp4')).toBeTruthy()
})
const stopButton = screen.getByText('Stop Task')
fireEvent.click(stopButton)
await waitFor(() => {
expect(screen.getByText('Stop Workflow Task')).toBeTruthy()
})
expect(screen.getByText(/task_01M5KTTEST1/)).toBeTruthy()
expect(screen.getAllByText('nature_video.mp4').length).toBeGreaterThanOrEqual(1)
})
})
@@ -0,0 +1,602 @@
import { useEffect, useMemo, useState } from 'react'
import {
useInfiniteQuery,
useMutation,
useQuery,
useQueryClient,
type InfiniteData,
} from '@tanstack/react-query'
import { useInView } from 'react-intersection-observer'
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import {
WorkflowTaskType,
WorkflowTaskStatus,
type WorkflowTaskItem,
type ListWorkflowTasksResponse,
} from '@shumai/dtos'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/ui/components/ui/table'
import { Badge } from '@/ui/components/ui/badge'
import { Button } from '@/ui/components/ui/button'
import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover'
import { Checkbox } from '@/ui/components/ui/checkbox'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/ui/components/ui/alert-dialog'
import { Loader2, Filter, Workflow, Square, Eye, RotateCw, AlertTriangle } from 'lucide-react'
import { formatTimeAgo } from '@/ui/lib/time'
import { formatSize } from '@/ui/lib/format'
import { toast } from 'sonner'
import { WorkflowTaskDetailsDialog } from './WorkflowTaskDetailsDialog'
const ALL_WORKFLOW_TASK_TYPES = Object.values(WorkflowTaskType)
const ALL_WORKFLOW_TASK_STATUSES = Object.values(WorkflowTaskStatus)
interface WorkflowTasksDashboardProps {
teamId: string
}
export function WorkflowTasksDashboard({ teamId }: WorkflowTasksDashboardProps) {
const queryClient = useQueryClient()
const [selectedStatuses, setSelectedStatuses] = useState<WorkflowTaskStatus[]>([])
const [selectedTypes, setSelectedTypes] = useState<WorkflowTaskType[]>([])
const [taskToStop, setTaskToStop] = useState<WorkflowTaskItem | null>(null)
const [detailsTask, setDetailsTask] = useState<WorkflowTaskItem | null>(null)
const { ref: loadMoreRef, inView } = useInView()
const queryKey = useMemo(
() => ['teams', teamId, 'workflow-tasks', selectedStatuses, selectedTypes],
[teamId, selectedStatuses, selectedTypes],
)
// Infinite query for listing workflow tasks
const {
data,
isLoading,
isError,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
refetch,
isRefetching,
} = useInfiniteQuery({
queryKey,
queryFn: async ({ pageParam }) => {
const res = await client.api.teams[':teamId']['workflow-tasks'].$get({
param: { teamId },
query: {
first: '20',
after: pageParam ? String(pageParam) : undefined,
status: selectedStatuses.length > 0 ? selectedStatuses : undefined,
types: selectedTypes.length > 0 ? selectedTypes : undefined,
},
})
if (!res.ok) throw new Error('Failed to fetch workflow tasks')
return (await res.json()) as ListWorkflowTasksResponse
},
initialPageParam: '',
getNextPageParam: (lastPage) => lastPage.pageInfo.endCursor || undefined,
enabled: !!teamId,
})
// Trigger next page when scrolling into view
useEffect(() => {
if (inView && hasNextPage && !isFetchingNextPage) {
fetchNextPage()
}
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
const allTasks = useMemo(() => data?.pages.flatMap((page) => page.nodes) || [], [data])
const totalCount = data?.pages[0]?.total ?? 0
// Targeted Active Task Poller: Extract active (pending/processing) task IDs
const activeTaskIds = useMemo(() => {
return allTasks
.filter((t) => t.status === 'pending' || t.status === 'processing')
.map((t) => t.id)
}, [allTasks])
// Polling query: Only active when there are pending or processing tasks
useQuery({
queryKey: ['teams', teamId, 'workflow-tasks', 'batch-status', activeTaskIds],
queryFn: async () => {
if (activeTaskIds.length === 0) return null
const res = await client.api.teams[':teamId']['workflow-tasks']['batch-status'].$post({
param: { teamId },
json: { taskIds: activeTaskIds },
})
if (!res.ok) return null
const result = await res.json()
// Update active tasks in-place in the infinite query cache
if (result.tasks && result.tasks.length > 0) {
queryClient.setQueryData(
queryKey,
(old: InfiniteData<ListWorkflowTasksResponse> | undefined) => {
if (!old) return old
const updatedMap = new Map(
result.tasks.map((task: WorkflowTaskItem) => [task.id, task]),
)
return {
...old,
pages: old.pages.map((page) => ({
...page,
nodes: page.nodes.map((node) => updatedMap.get(node.id) || node),
})),
}
},
)
}
return result
},
enabled: activeTaskIds.length > 0,
refetchInterval: 6000,
})
// Stop task mutation
const stopTaskMutation = useMutation({
mutationFn: async (taskId: string) => {
const res = await client.api.teams[':teamId']['workflow-tasks'][':taskId'].stop.$post({
param: { teamId, taskId },
})
if (!res.ok) {
const errorData = await res.json().catch(() => ({ message: 'Failed to stop task' }))
throw new Error((errorData as { message?: string }).message || 'Failed to stop task')
}
return await res.json()
},
onSuccess: (data) => {
toast.success(m.task_stopped_successfully())
// In-place update in infinite query cache
queryClient.setQueryData(
queryKey,
(old: InfiniteData<ListWorkflowTasksResponse> | undefined) => {
if (!old) return old
return {
...old,
pages: old.pages.map((page) => ({
...page,
nodes: page.nodes.map((node) => (node.id === data.task.id ? data.task : node)),
})),
}
},
)
setTaskToStop(null)
},
onError: (err: Error) => {
toast.error(err.message || 'Failed to stop task')
},
})
const toggleStatus = (status: WorkflowTaskStatus) => {
setSelectedStatuses((prev) =>
prev.includes(status) ? prev.filter((s) => s !== status) : [...prev, status],
)
}
const toggleType = (type: WorkflowTaskType) => {
setSelectedTypes((prev) =>
prev.includes(type) ? prev.filter((t) => t !== type) : [...prev, type],
)
}
const getStatusBadge = (status?: string | null) => {
switch (status) {
case 'completed':
return (
<Badge
variant="outline"
className="bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20 font-mono text-xs"
>
completed
</Badge>
)
case 'processing':
return (
<Badge
variant="outline"
className="bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20 font-mono text-xs gap-1.5"
>
<Loader2 className="h-3 w-3 animate-spin" />
processing
</Badge>
)
case 'pending':
return (
<Badge
variant="outline"
className="bg-yellow-500/10 text-yellow-600 dark:text-yellow-400 border-yellow-500/20 font-mono text-xs"
>
pending
</Badge>
)
case 'failed':
return (
<Badge
variant="outline"
className="bg-destructive/10 text-destructive border-destructive/20 font-mono text-xs"
>
failed
</Badge>
)
default:
return (
<Badge variant="outline" className="font-mono text-xs">
{status || '-'}
</Badge>
)
}
}
const getTypeBadge = (type?: string | null) => {
if (!type) return <Badge variant="outline">-</Badge>
if (type.startsWith('transcode')) {
return (
<Badge
variant="outline"
className="bg-purple-500/10 text-purple-600 dark:text-purple-400 border-purple-500/20 font-mono text-xs"
>
{type}
</Badge>
)
}
if (type.startsWith('ai_') || type === 'chat') {
return (
<Badge
variant="outline"
className="bg-indigo-500/10 text-indigo-600 dark:text-indigo-400 border-indigo-500/20 font-mono text-xs"
>
{type}
</Badge>
)
}
return (
<Badge variant="secondary" className="font-mono text-xs">
{type}
</Badge>
)
}
return (
<div className="space-y-6">
<Card className="border border-border/50 shadow-xs">
<CardHeader className="pb-4">
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<div>
<CardTitle className="text-xl font-bold flex items-center gap-2">
<Workflow className="h-5 w-5 text-primary" />
{m.workflow_tasks()}
</CardTitle>
<CardDescription className="mt-1">{m.workflow_tasks_description()}</CardDescription>
</div>
<div className="flex items-center gap-3">
{totalCount > 0 && (
<Badge variant="secondary" className="w-fit text-xs font-normal">
{totalCount} {m.workflow_tasks()}
</Badge>
)}
<Button
variant="outline"
size="sm"
className="h-9 gap-1.5 text-xs"
onClick={() => refetch()}
disabled={isRefetching}
>
<RotateCw className={`h-3.5 w-3.5 ${isRefetching ? 'animate-spin' : ''}`} />
{m.refresh_tasks()}
</Button>
</div>
</div>
{/* Filter Bar */}
<div className="mt-4 flex flex-wrap items-center gap-3 pt-4 border-t border-border/40">
{/* Status Filter */}
<Popover>
<PopoverTrigger asChild>
<Button variant="outline" size="sm" className="h-9 gap-2 text-xs border-dashed">
<Filter className="h-3.5 w-3.5" />
{m.filter_by_status()}
{selectedStatuses.length > 0 && (
<Badge variant="secondary" className="ml-1 px-1.5 py-0 text-[10px]">
{selectedStatuses.length}
</Badge>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-56 p-2" align="start">
<div className="text-xs font-semibold text-muted-foreground px-2 py-1 mb-1">
{m.select_status()}
</div>
<div className="space-y-1">
{ALL_WORKFLOW_TASK_STATUSES.map((status) => (
<label
key={status}
className="flex items-center gap-2 px-2 py-1.5 hover:bg-accent rounded-md cursor-pointer text-xs"
>
<Checkbox
checked={selectedStatuses.includes(status)}
onCheckedChange={() => toggleStatus(status)}
/>
<span className="font-mono">{status}</span>
</label>
))}
</div>
{selectedStatuses.length > 0 && (
<Button
variant="ghost"
size="sm"
className="w-full mt-2 h-7 text-xs text-muted-foreground hover:text-foreground"
onClick={() => setSelectedStatuses([])}
>
{m.clear_status()}
</Button>
)}
</PopoverContent>
</Popover>
{/* Type Filter */}
<Popover>
<PopoverTrigger asChild>
<Button variant="outline" size="sm" className="h-9 gap-2 text-xs border-dashed">
<Filter className="h-3.5 w-3.5" />
{m.filter_by_type()}
{selectedTypes.length > 0 && (
<Badge variant="secondary" className="ml-1 px-1.5 py-0 text-[10px]">
{selectedTypes.length}
</Badge>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-64 p-2" align="start">
<div className="text-xs font-semibold text-muted-foreground px-2 py-1 mb-1">
{m.select_type()}
</div>
<div className="max-h-60 overflow-y-auto space-y-1 pr-1">
{ALL_WORKFLOW_TASK_TYPES.map((type) => (
<label
key={type}
className="flex items-center gap-2 px-2 py-1.5 hover:bg-accent rounded-md cursor-pointer text-xs"
>
<Checkbox
checked={selectedTypes.includes(type)}
onCheckedChange={() => toggleType(type)}
/>
<span className="font-mono truncate">{type}</span>
</label>
))}
</div>
{selectedTypes.length > 0 && (
<Button
variant="ghost"
size="sm"
className="w-full mt-2 h-7 text-xs text-muted-foreground hover:text-foreground"
onClick={() => setSelectedTypes([])}
>
{m.clear_types()}
</Button>
)}
</PopoverContent>
</Popover>
{/* Clear All Filters */}
{(selectedStatuses.length > 0 || selectedTypes.length > 0) && (
<Button
variant="ghost"
size="sm"
className="h-9 px-2 text-xs text-muted-foreground hover:text-foreground"
onClick={() => {
setSelectedStatuses([])
setSelectedTypes([])
}}
>
{m.clear_all()}
</Button>
)}
</div>
</CardHeader>
<CardContent className="p-0">
{isLoading ? (
<div className="flex h-64 items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
) : isError ? (
<div className="p-8 text-center text-sm text-destructive">
{m.failed_to_load_workflow_tasks()}
</div>
) : allTasks.length === 0 ? (
<div className="p-12 text-center text-sm text-muted-foreground">
{m.no_workflow_tasks()}
</div>
) : (
<Table>
<TableHeader>
<TableRow className="hover:bg-transparent border-b border-border/50">
<TableHead className="w-[170px] pl-6 text-xs font-semibold">
{m.task_type()}
</TableHead>
<TableHead className="w-[130px] px-4 text-xs font-semibold">
{m.task_status()}
</TableHead>
<TableHead className="min-w-[180px] px-4 text-xs font-semibold">
{m.file_name()}
</TableHead>
<TableHead className="w-[110px] px-4 text-xs font-semibold">{m.size()}</TableHead>
<TableHead className="w-[160px] px-4 text-xs font-semibold">
{m.project_name()}
</TableHead>
<TableHead className="w-[130px] px-4 text-right text-xs font-semibold">
{m.created_at()}
</TableHead>
<TableHead className="w-[120px] pr-6 text-right text-xs font-semibold">
{m.actions()}
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{allTasks.map((task) => {
const canStop = task.status === 'pending' || task.status === 'processing'
return (
<TableRow key={task.id} className="hover:bg-muted/40 transition-colors">
<TableCell className="py-3 pl-6 font-medium">
{getTypeBadge(task.type)}
</TableCell>
<TableCell className="py-3 px-4 font-medium">
{getStatusBadge(task.status)}
</TableCell>
<TableCell className="py-3 px-4 text-xs font-medium">
<span
className="truncate block max-w-[220px]"
title={task.fileName || task.assetId || '-'}
>
{task.fileName || task.assetId || '-'}
</span>
</TableCell>
<TableCell className="py-3 px-4 text-xs font-mono text-muted-foreground">
{task.fileSize !== null && task.fileSize !== undefined
? formatSize(task.fileSize)
: '-'}
</TableCell>
<TableCell className="py-3 px-4 text-xs text-muted-foreground">
<span
className="truncate block max-w-[160px]"
title={task.projectName || task.projectId || '-'}
>
{task.projectName || task.projectId || '-'}
</span>
</TableCell>
<TableCell className="py-3 px-4 text-right text-xs text-muted-foreground whitespace-nowrap">
{formatTimeAgo(task.createdAt)}
</TableCell>
<TableCell className="py-3 pr-6 text-right">
<div className="flex items-center justify-end gap-1">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
onClick={() => setDetailsTask(task)}
title={m.view_details()}
>
<Eye className="h-4 w-4" />
</Button>
{canStop && (
<Button
variant="outline"
size="sm"
className="h-8 px-2 text-xs border-destructive/30 text-destructive hover:bg-destructive/10"
onClick={() => setTaskToStop(task)}
disabled={stopTaskMutation.isPending}
>
<Square className="h-3 w-3 mr-1 fill-current" />
{m.stop_task()}
</Button>
)}
</div>
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
)}
{/* Infinite Scroll Sentinel */}
<div ref={loadMoreRef} className="py-4 flex justify-center">
{isFetchingNextPage && (
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
)}
</div>
</CardContent>
</Card>
{/* Stop Task Confirmation Dialog */}
<AlertDialog
open={!!taskToStop}
onOpenChange={(open) => {
if (!open) setTaskToStop(null)
}}
>
<AlertDialogContent>
<AlertDialogHeader>
<div className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-destructive" />
<AlertDialogTitle>{m.stop_task_confirm_title()}</AlertDialogTitle>
</div>
<AlertDialogDescription className="pt-2 text-sm text-muted-foreground">
{m.stop_task_confirm_description()}
</AlertDialogDescription>
{taskToStop && (
<div className="mt-3 p-2.5 rounded-md bg-muted/50 border border-border/40 font-mono text-xs space-y-1">
<div>
{m.task_id()}: {taskToStop.id}
</div>
{taskToStop.fileName && (
<div className="font-sans">
{m.file_name()}:{' '}
<span className="font-medium text-foreground">{taskToStop.fileName}</span>
</div>
)}
<div>
{m.task_type()}: {taskToStop.type || 'unknown'}
</div>
<div>
{m.task_status()}: {taskToStop.status}
</div>
</div>
)}
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={stopTaskMutation.isPending}>
{m.cancel()}
</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive hover:bg-destructive/90 text-destructive-foreground"
disabled={stopTaskMutation.isPending}
onClick={() => {
if (taskToStop) {
stopTaskMutation.mutate(taskToStop.id)
}
}}
>
{stopTaskMutation.isPending ? (
<>
<Loader2 className="h-3.5 w-3.5 animate-spin mr-1.5" />
{m.stopping()}
</>
) : (
m.stop_task()
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Task Details Dialog */}
<WorkflowTaskDetailsDialog
task={detailsTask}
open={!!detailsTask}
onOpenChange={(open) => {
if (!open) setDetailsTask(null)
}}
/>
</div>
)
}
+32
View File
@@ -1184,6 +1184,38 @@
"search_item_id": "Search Item ID...",
"select_actions": "Select Actions",
"select_users": "Select Users",
"workflow_tasks": "Workflow Tasks",
"workflow_tasks_description": "View, monitor, and manage background workflow execution tasks.",
"no_workflow_tasks": "No workflow tasks found",
"filter_by_status": "Filter by Status",
"filter_by_type": "Filter by Type",
"select_status": "Select Status",
"select_type": "Select Type",
"clear_status": "Clear Status",
"clear_types": "Clear Types",
"clear_all": "Clear all",
"failed_to_load_workflow_tasks": "Failed to load workflow tasks.",
"stop_task": "Stop Task",
"stopping": "Stopping...",
"stop_task_confirm_title": "Stop Workflow Task",
"stop_task_confirm_description": "Are you sure you want to stop this task? Any ongoing processing will be cancelled.",
"task_stopped_successfully": "Workflow task has been stopped.",
"task_details": "Task Details",
"task_id": "Task ID",
"task_status": "Status",
"task_type": "Type",
"asset_id": "Asset ID",
"file_name": "File Name",
"payload": "Payload",
"output": "Output",
"input_tokens": "Input Tokens",
"output_tokens": "Output Tokens",
"tokens_label": "Tokens",
"session_id": "Session ID",
"heartbeat": "Heartbeat",
"updated_at": "Updated At",
"view_details": "View Details",
"refresh_tasks": "Refresh Tasks",
"watermark": "Watermark",
"watermark_enabled": "Enable Watermark",
"watermark_transcoding_processing": "Transcoding watermark media...",
+32
View File
@@ -1184,6 +1184,38 @@
"search_item_id": "搜索条目 ID...",
"select_actions": "选择操作",
"select_users": "选择用户",
"workflow_tasks": "工作流任务",
"workflow_tasks_description": "查看、监控和管理后台工作流执行任务。",
"no_workflow_tasks": "未找到工作流任务",
"filter_by_status": "按状态筛选",
"filter_by_type": "按类型筛选",
"select_status": "选择状态",
"select_type": "选择类型",
"clear_status": "清除状态",
"clear_types": "清除类型",
"clear_all": "清除全部",
"failed_to_load_workflow_tasks": "加载工作流任务失败。",
"stop_task": "停止任务",
"stopping": "正在停止...",
"stop_task_confirm_title": "停止工作流任务",
"stop_task_confirm_description": "确定要停止此任务吗?任何正在进行的处理都将被取消。",
"task_stopped_successfully": "工作流任务已停止。",
"task_details": "任务详情",
"task_id": "任务 ID",
"task_status": "状态",
"task_type": "类型",
"asset_id": "素材 ID",
"file_name": "文件名",
"payload": "负载数据",
"output": "输出结果",
"input_tokens": "输入 Token",
"output_tokens": "输出 Token",
"tokens_label": "Token",
"session_id": "会话 ID",
"heartbeat": "心跳时间",
"updated_at": "更新时间",
"view_details": "查看详情",
"refresh_tasks": "刷新任务",
"watermark": "水印",
"watermark_enabled": "启用水印",
"watermark_transcoding_processing": "水印媒体转码处理中...",
+1 -1
View File
@@ -71,7 +71,7 @@ function RootComponent() {
if (!res.ok) throw new Error('Failed to fetch me')
return await res.json()
},
enabled: !!storedTeamId,
enabled: !!storedTeamId && !!user,
})
if (!showSidebar) {
@@ -0,0 +1,39 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { useAuthStore } from '@/ui/stores/auth'
import { Route } from './reset-password'
describe('Reset Password Route beforeLoad guard', () => {
beforeEach(() => {
useAuthStore.getState().clearAuth()
})
it('redirects to / when user is authenticated in store and no reset token is present', () => {
useAuthStore.getState().setUser({ id: 'user-1', email: 'test@example.com' })
expect(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Route.options.beforeLoad?.({ search: { token: '' } } as any)
}).toThrow()
})
it('does NOT redirect and clears stale auth when a reset token is present in search params', () => {
useAuthStore.getState().setUser({ id: 'user-1', email: 'test@example.com' })
// When the user has stale auth in localStorage but provides a token,
// they should NOT be redirected to / (which would 401 and redirect to login)
expect(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Route.options.beforeLoad?.({ search: { token: 'valid-token-123' } } as any)
}).not.toThrow()
// And the stale auth store should be cleared
expect(useAuthStore.getState().user).toBeNull()
})
it('does not redirect when user is not logged in and no token is present', () => {
expect(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Route.options.beforeLoad?.({ search: { token: '' } } as any)
}).not.toThrow()
})
})
+10 -1
View File
@@ -8,7 +8,16 @@ const searchSchema = z.object({
export const Route = createFileRoute('/reset-password')({
validateSearch: (search) => searchSchema.parse(search),
beforeLoad: () => {
beforeLoad: ({ search }) => {
// If a reset token is present in the URL, prioritize password recovery
// and clear any stale local auth state so the user can cleanly reset and log in
if (search.token) {
if (useAuthStore.getState().user) {
useAuthStore.getState().clearAuth()
}
return
}
if (useAuthStore.getState().user) {
throw redirect({
to: '/',
@@ -8,9 +8,18 @@ import { AiUsageDashboard } from '@/ui/components/dashboard/AiUsageDashboard'
import { AgentSessionsDashboard } from '@/ui/components/dashboard/AgentSessionsDashboard'
import { QuotaUsageDashboard } from '@/ui/components/dashboard/QuotaUsageDashboard'
import { AuditLogsDashboard } from '@/ui/components/dashboard/AuditLogsDashboard'
import { Activity, BarChart2, Gauge, Loader2, MessagesSquare, ShieldAlert } from 'lucide-react'
import { WorkflowTasksDashboard } from '@/ui/components/dashboard/WorkflowTasksDashboard'
import {
Activity,
BarChart2,
Gauge,
Loader2,
MessagesSquare,
ShieldAlert,
Workflow,
} from 'lucide-react'
type DashboardTab = 'audit-logs' | 'ai-usage' | 'ai-sessions' | 'quotas'
type DashboardTab = 'audit-logs' | 'workflow-tasks' | 'ai-usage' | 'ai-sessions' | 'quotas'
function TeamDashboardPage() {
const { teamId } = Route.useParams()
@@ -77,6 +86,22 @@ function TeamDashboardPage() {
)}
</button>
<button
onClick={() => setActiveTab('workflow-tasks')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'workflow-tasks'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<Workflow className="w-5 h-5" />
{m.workflow_tasks()}
{activeTab === 'workflow-tasks' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
<button
onClick={() => setActiveTab('quotas')}
className={cn(
@@ -136,6 +161,7 @@ function TeamDashboardPage() {
<div className="flex-1 overflow-y-auto p-4 md:p-8">
<div className="max-w-6xl mx-auto space-y-8">
{activeTab === 'audit-logs' && <AuditLogsDashboard teamId={teamId} />}
{activeTab === 'workflow-tasks' && <WorkflowTasksDashboard teamId={teamId} />}
{activeTab === 'ai-usage' && <AiUsageDashboard teamId={teamId} />}
{activeTab === 'ai-sessions' && <AgentSessionsDashboard teamId={teamId} />}
{activeTab === 'quotas' && <QuotaUsageDashboard teamId={teamId} />}
@@ -62,8 +62,7 @@ function TeamPage() {
const { metadata, setMetadata: setUserMetadata } = useUserMetadataStore()
const sortKey = `team:${teamId}:projects:sort`
const savedSort = metadata[sortKey] as
| { sortBy?: string; sortDirection?: 'asc' | 'desc' }
| undefined
{ sortBy?: string; sortDirection?: 'asc' | 'desc' } | undefined
const [sortBy, setSortBy] = useState<string>(() => savedSort?.sortBy || 'name')
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>(
@@ -310,6 +310,17 @@ describe('DbosExecutor Tests', () => {
expect(heartbeats.has(taskId)).toBe(false)
})
it('should propagate error if client.cancelWorkflow fails', async () => {
const taskId = 'test-failing-cancel'
const mockClient = {
cancelWorkflow: vi.fn().mockRejectedValue(new Error('DBOS connection failure')),
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.spyOn(executor, 'getClient').mockResolvedValue(mockClient as any)
await expect(executor.cancel(taskId)).rejects.toThrow('DBOS connection failure')
})
})
describe('Submit', () => {
@@ -387,6 +387,7 @@ export class DbosExecutor extends EventEmitter {
logger.info({ taskId }, '[DbosExecutor] Cancelled workflow task')
} catch (err) {
logger.warn({ taskId, err }, '[DbosExecutor] Failed to cancel workflow task in DBOS')
throw err
}
}