Compare commits

...
9 Commits
Author SHA1 Message Date
yiling c2af7494ec Release v0.6.1 2026-10-24 13:21:50 +08:00
yiling b7d2748b00 docs(changelog): add bun 1.4.4 upgrade to unreleased changes 2026-10-24 12:02:22 +08:00
Yiling-J 3467c0d92b chore(docker): update Aliyun compose images and document transcode worker scaling in README_CN (#491) 2026-10-24 11:51:37 +08:00
Yiling-J 22fede0290 fix(webui): prevent clipping of long text overlay and date picker in cards (#490)
* fix(webui): prevent clipping of long text overlay and date picker in cards

* docs: update DeepWiki badge url in README and README_CN

* fix(webui): preserve expanded overlay height and textarea style in LongTextField

* fix(webui): add bottom padding to file list to prevent screen clipping of expanded fields

* fix(webui): expand directly into edit mode on single click for LongTextField

* fix(webui): prevent file selection when interacting with metadata fields in cards and list rows
2026-10-24 11:40:47 +08:00
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
81 changed files with 3484 additions and 296 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`.
+14
View File
@@ -12,6 +12,20 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Changed
## [0.6.1] - 2026-10-24
### Added
* **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
### Fixed
* **metadata**: Fix an issue where clicking to edit a metadata field on a card or list row inadvertently selected the file, and prevent expanded text overlays or date pickers from being clipped by container borders
### Changed
* **deps**: Upgrade Bun to 1.4.4
## [0.6.0] - 2026-10-20
### Added
+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 \
+36 -2
View File
@@ -12,7 +12,7 @@
<a href="https://hub.docker.com/r/shumaione/shumai"><img alt="Docker pulls" src="https://img.shields.io/docker/pulls/shumaione/shumai" /></a>
<a href="https://github.com/shumaiOne/shumai/releases"><img alt="GitHub latest release" src="https://img.shields.io/github/v/release/shumaiOne/shumai" /></a>
<a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-blue" /></a>
<a target="_blank" href="https://deepwiki.com/shumaiOne/shumai"><img alt="Ask DeepWiki" src="https://deepwiki.com/badge.svg" /></a>
<a target="_blank" href="https://deepwiki.com/shumaiOne/shumai"><img alt="Ask DeepWiki" src="https://img.shields.io/badge/Ask-DeepWiki-6E56CF" /></a>
</p>
<p align="center">
@@ -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:
+36 -1
View File
@@ -12,7 +12,7 @@
<a href="https://hub.docker.com/r/shumaione/shumai"><img alt="Docker pulls" src="https://img.shields.io/docker/pulls/shumaione/shumai" /></a>
<a href="https://github.com/shumaiOne/shumai/releases"><img alt="GitHub latest release" src="https://img.shields.io/github/v/release/shumaiOne/shumai" /></a>
<a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-blue" /></a>
<a target="_blank" href="https://deepwiki.com/shumaiOne/shumai"><img alt="Ask DeepWiki" src="https://deepwiki.com/badge.svg" /></a>
<a target="_blank" href="https://deepwiki.com/shumaiOne/shumai"><img alt="Ask DeepWiki" src="https://img.shields.io/badge/Ask-DeepWiki-6E56CF" /></a>
</p>
<p align="center">
@@ -165,6 +165,41 @@ https://gh-proxy.com/https://raw.githubusercontent.com/shumaiOne/shumai/main/REA
5. 打开浏览器,访问 `http://localhost:3000` 即可开始使用(若是远程部署,请访问 `http://<您的服务器IP>:3000`)。
#### **扩展转码 Worker(并行处理)**
默认情况下,Docker Compose 部署会按顺序逐个处理视频转码任务。这是出于系统设计考虑,因为视频转码属于计算密集型任务,容易耗尽可用的 CPU 或 GPU 资源。
但在批量上传(例如一次性上传 100+ 个视频)或处理需要耗费数小时的大型摄像机原始素材时,长时间的转码任务可能会阻塞后续文件的处理。此时,您可以通过增加额外的机器来横向扩展转码吞吐量。每台机器依然按顺序执行任务,但增加 worker 实例能够显著提升整体的并行处理能力。
Shumai 提供了独立的转码 Worker 镜像(支持 Docker Hub 与阿里云镜像源):
1. **连接准备**:启动一台临时机器,确保其能够正常访问您的 PostgreSQL 数据库和存储后端(例如 S3 或共享存储)。
2. **启动 Worker**:配置相同的数据库与存储连接凭据并运行容器:
**阿里云镜像(国内推荐):**
```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" \
crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai-transcode:latest
```
*如使用 Docker Hub,镜像为 [`shumaione/shumai-transcode:latest`](https://hub.docker.com/r/shumaione/shumai-transcode)。*
Worker 启动后会自动接入任务队列,并与主实例并行消费并处理积压的转码任务。
3. **随时停止**:当转码队列处理完毕(或不再需要额外的算力)时,只需停止或移除 Worker 容器:
```bash
docker stop shumai_transcode_worker
```
主 Shumai 服务的运行不会受到任何影响,亦无停机时间。
### 方案二:源码编译运行(开发环境)
如果您希望在本地参与 Shumai 的开发,请按以下步骤配置开发环境:
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/agent-app",
"version": "0.6.0",
"version": "0.6.1",
"private": true,
"type": "module",
"bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/cli",
"version": "0.6.0",
"version": "0.6.1",
"private": true,
"type": "module",
"bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/premiere-uxp",
"version": "0.6.0",
"version": "0.6.1",
"private": true,
"type": "commonjs",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/transcode-app",
"version": "0.6.0",
"version": "0.6.1",
"private": true,
"type": "module",
"bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/web-app",
"version": "0.6.0",
"version": "0.6.1",
"private": true,
"type": "module",
"dependencies": {
+19 -30
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",
@@ -33,7 +32,7 @@
},
"apps/agent": {
"name": "@shumai/agent-app",
"version": "0.6.0",
"version": "0.6.1",
"bin": {
"shumai-agent": "./src/index.ts",
},
@@ -45,7 +44,7 @@
},
"apps/cli": {
"name": "@shumai/cli",
"version": "0.6.0",
"version": "0.6.1",
"bin": {
"shumai-cli": "./src/index.ts",
},
@@ -60,7 +59,7 @@
},
"apps/premiere-uxp": {
"name": "@shumai/premiere-uxp",
"version": "0.6.0",
"version": "0.6.1",
"dependencies": {
"@shumai/api": "workspace:*",
"@shumai/dtos": "workspace:*",
@@ -114,7 +113,7 @@
},
"apps/transcode": {
"name": "@shumai/transcode-app",
"version": "0.6.0",
"version": "0.6.1",
"bin": {
"shumai-transcode": "./src/index.ts",
},
@@ -126,7 +125,7 @@
},
"apps/web": {
"name": "@shumai/web-app",
"version": "0.6.0",
"version": "0.6.1",
"dependencies": {
"@shumai/agent": "workspace:*",
"@shumai/api": "workspace:*",
@@ -146,7 +145,7 @@
},
"packages/agent": {
"name": "@shumai/agent",
"version": "0.6.0",
"version": "0.6.1",
"dependencies": {
"@anthropic-ai/sandbox-runtime": "0.0.74",
"@earendil-works/pi-agent-core": "0.82.1",
@@ -169,7 +168,7 @@
},
"packages/api": {
"name": "@shumai/api",
"version": "0.6.0",
"version": "0.6.1",
"dependencies": {
"@hono/zod-validator": "0.7.6",
"@shumai/core": "workspace:*",
@@ -183,7 +182,7 @@
},
"packages/core": {
"name": "@shumai/core",
"version": "0.6.0",
"version": "0.6.1",
"dependencies": {
"@ai-sdk/alibaba": "2.0.38",
"@ai-sdk/amazon-bedrock": "5.0.67",
@@ -244,7 +243,7 @@
},
"packages/db": {
"name": "@shumai/db",
"version": "0.6.0",
"version": "0.6.1",
"dependencies": {
"@earendil-works/pi-agent-core": "0.82.1",
"@prisma/adapter-pg": "7.10.0",
@@ -260,7 +259,7 @@
},
"packages/dtos": {
"name": "@shumai/dtos",
"version": "0.6.0",
"version": "0.6.1",
"dependencies": {
"@earendil-works/pi-agent-core": "0.82.1",
"zod": "4.5.4",
@@ -268,7 +267,7 @@
},
"packages/e2e": {
"name": "@shumai/e2e",
"version": "0.6.0",
"version": "0.6.1",
"dependencies": {
"@earendil-works/pi-agent-core": "0.82.1",
"@google/genai": "2.28.0",
@@ -283,11 +282,11 @@
},
"packages/tableprinter": {
"name": "@shumai/tableprinter",
"version": "0.6.0",
"version": "0.6.1",
},
"packages/transcode": {
"name": "@shumai/transcode",
"version": "0.6.0",
"version": "0.6.1",
"dependencies": {
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
@@ -298,7 +297,7 @@
},
"packages/webui": {
"name": "@shumai/webui",
"version": "0.6.0",
"version": "0.6.1",
"dependencies": {
"@base-ui/react": "1.7.0",
"@dnd-kit/abstract": "0.5.0",
@@ -400,7 +399,7 @@
},
"packages/workflow-core": {
"name": "@shumai/workflow-core",
"version": "0.6.0",
"version": "0.6.1",
"dependencies": {
"@dbos-inc/dbos-sdk": "5.2.11",
"@shumai/core": "workspace:*",
@@ -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=="],
@@ -15,7 +15,7 @@ services:
retries: 5
embedding-server:
image: shumaione/embedding-server:latest
image: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/embedding-server:latest
container_name: shumai_embedding
restart: unless-stopped
@@ -15,12 +15,12 @@ services:
retries: 5
embedding-server:
image: shumaione/embedding-server:latest
image: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/embedding-server:latest
container_name: shumai_embedding
restart: unless-stopped
turntable-renderer:
image: shumaione/turntable-renderer:latest
image: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/turntable-renderer:latest
container_name: shumai_turntable
restart: unless-stopped
+16
View File
@@ -3,6 +3,22 @@ title: "Changelog"
description: "Recent updates, new features, and improvements in Shumai"
---
<Update label="v0.6.1" description="October 24, 2026">
### Added
* **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
### Fixed
* **metadata**: Fix an issue where clicking to edit a metadata field on a card or list row inadvertently selected the file, and prevent expanded text overlays or date pickers from being clipped by container borders
### Changed
* **deps**: Upgrade Bun to 1.4.4
</Update>
<Update label="v0.6.0" description="October 20, 2026">
### Added
+4 -5
View File
@@ -1,6 +1,6 @@
{
"name": "shumai",
"version": "0.6.0",
"version": "0.6.1",
"private": true,
"type": "module",
"repository": {
@@ -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 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/agent",
"version": "0.6.0",
"version": "0.6.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+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.')
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/api",
"version": "0.6.0",
"version": "0.6.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+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
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/core",
"version": "0.6.0",
"version": "0.6.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+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 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/db",
"version": "0.6.0",
"version": "0.6.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/dtos",
"version": "0.6.0",
"version": "0.6.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+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>
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/e2e",
"version": "0.6.0",
"version": "0.6.1",
"private": true,
"type": "module",
"dependencies": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/tableprinter",
"version": "0.6.0",
"version": "0.6.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/transcode",
"version": "0.6.0",
"version": "0.6.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+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>
)
}
@@ -0,0 +1,94 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import React from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import DateField from './date-field'
describe('DateField Component', () => {
afterEach(() => {
cleanup()
vi.clearAllMocks()
})
const dummyConfig = {
name: 'Due Date',
type: 'date' as const,
date: {
displayFormat: 'iso' as const,
includeTime: false,
},
}
const dummyConfigWithTime = {
name: 'Event Time',
type: 'date' as const,
date: {
displayFormat: 'iso' as const,
includeTime: true,
timeFormat: 'twenty_four_hour' as const,
},
}
it('renders Empty state when value is empty', () => {
render(<DateField value="" config={dummyConfig} onSave={vi.fn()} />)
expect(screen.getByText('Empty')).toBeTruthy()
})
it('renders formatted date when value is present', () => {
render(<DateField value="2026-06-15T00:00:00.000Z" config={dummyConfig} onSave={vi.fn()} />)
expect(screen.getByText(/2026-06-15/)).toBeTruthy()
})
it('opens calendar popover on click and calls onSave when selecting a day', () => {
const onSave = vi.fn()
render(<DateField value="2026-06-15T00:00:00.000Z" config={dummyConfig} onSave={onSave} />)
// Click trigger to open popover
const trigger = screen.getByText(/2026-06-15/)
fireEvent.click(trigger)
// Month heading should be present
expect(screen.getByText(/June 2026/i)).toBeTruthy()
// Day 20 button should be clickable
const day20 = screen.getByRole('button', { name: '20' })
fireEvent.click(day20)
expect(onSave).toHaveBeenCalled()
const savedArg = onSave.mock.calls[0][0]
expect(new Date(savedArg).getDate()).toBe(20)
})
it('supports time picker when includeTime is true', () => {
const onSave = vi.fn()
render(
<DateField value="2026-06-15T10:00:00.000Z" config={dummyConfigWithTime} onSave={onSave} />,
)
const trigger = screen.getByText(/2026-06-15/)
fireEvent.click(trigger)
// "Time" section should be visible
expect(screen.getByText(/Time/)).toBeTruthy()
// Select hour '14'
const hour14 = screen.getByTestId('hour-14')
fireEvent.click(hour14)
expect(onSave).toHaveBeenCalled()
const savedArg = onSave.mock.calls[0][0]
expect(new Date(savedArg).getHours()).toBe(14)
})
it('does not open popover in readOnly mode', () => {
const onSave = vi.fn()
render(
<DateField value="2026-06-15T00:00:00.000Z" config={dummyConfig} onSave={onSave} readOnly />,
)
const trigger = screen.getByText(/2026-06-15/)
fireEvent.click(trigger)
expect(screen.queryByText(/June 2026/i)).toBeNull()
})
})
+38 -44
View File
@@ -12,16 +12,15 @@ import {
isValid,
} from 'date-fns'
import { ChevronLeft, ChevronRight, Clock } from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import React, { useEffect, useState } from 'react'
import type { FieldProps } from './field-types'
import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover'
const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOnly }) => {
const dateConfig = config?.date
const [isEditing, setIsEditing] = useState(false)
const containerRef = useRef<HTMLDivElement>(null)
// Parse value or default to today
// Replaced parseISO with new Date() to avoid import errors
const parsedDate = value ? new Date(value) : new Date()
const safeDate = isValid(parsedDate) ? parsedDate : new Date()
@@ -35,25 +34,17 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
}
}, [isEditing, value])
// Click outside to close
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
if (isEditing) {
setIsEditing(false)
}
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [isEditing])
const handleStartEdit = () => {
if (!readOnly) {
setIsEditing(true)
}
}
const handleOpenChange = (open: boolean) => {
if (readOnly) return
setIsEditing(open)
}
const getDisplayValue = (isoString: string) => {
if (!isoString) return ''
const date = new Date(isoString)
@@ -81,17 +72,14 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
}
// Calendar Logic
// Replaced startOfMonth with native Date manipulation
const monthStart = new Date(viewDate.getFullYear(), viewDate.getMonth(), 1)
const monthEnd = endOfMonth(viewDate)
const daysInMonth = eachDayOfInterval({ start: monthStart, end: monthEnd })
const startDayOfWeek = getDay(monthStart) // 0 = Sunday
const handleDateClick = (day: Date) => {
// Preserve time from current value if exists
const newDate = new Date(day)
if (dateConfig?.includeTime) {
// Replaced setHours/setMinutes with native methods
newDate.setHours(getHours(safeDate))
newDate.setMinutes(getMinutes(safeDate))
}
@@ -116,23 +104,36 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
const hours = Array.from({ length: 24 }, (_, i) => i)
const minutes = Array.from({ length: 12 }, (_, i) => i * 5) // 0, 5, 10...
if (isEditing) {
return (
<div className="relative w-full" ref={containerRef}>
<div className="w-full px-2 py-1 border border-ring rounded bg-background text-sm shadow-sm min-h-[28px] flex items-center">
{value ? (
getDisplayValue(value)
) : (
<span className="text-muted-foreground">Select date...</span>
)}
</div>
return (
<div className="relative w-full" onClick={(e) => e.stopPropagation()}>
<Popover open={!readOnly && isEditing} onOpenChange={handleOpenChange}>
<PopoverTrigger asChild>
<div
onClick={handleStartEdit}
className={`w-full min-h-[28px] px-2 py-1 text-sm text-foreground rounded truncate border transition-colors ${
isEditing ? 'border-ring bg-background shadow-sm' : 'border-transparent'
} ${!readOnly ? 'cursor-pointer hover:bg-accent hover:border-border' : ''}`}
>
{value ? (
getDisplayValue(value)
) : (
<span className="text-muted-foreground italic">Empty</span>
)}
</div>
</PopoverTrigger>
<div className="absolute z-50 top-full left-0 mt-1 bg-popover border border-border rounded-lg shadow-xl flex flex-col md:flex-row overflow-hidden min-w-[280px]">
<PopoverContent
side="bottom"
align="start"
sideOffset={4}
className="p-0 w-auto bg-popover border border-border rounded-lg shadow-xl flex flex-col md:flex-row overflow-hidden"
onClick={(e) => e.stopPropagation()}
>
{/* Date Picker */}
<div className="p-4 w-64">
<div className="flex justify-between items-center mb-4">
{/* Replaced subMonths with addMonths(-1) */}
<button
type="button"
onClick={() => setViewDate(addMonths(viewDate, -1))}
className="p-1 hover:bg-accent rounded"
>
@@ -140,6 +141,7 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
</button>
<span className="font-semibold text-sm">{format(viewDate, 'MMMM yyyy')}</span>
<button
type="button"
onClick={() => setViewDate(addMonths(viewDate, 1))}
className="p-1 hover:bg-accent rounded"
>
@@ -168,6 +170,7 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
return (
<button
type="button"
key={date.toString()}
onClick={() => handleDateClick(date)}
className={`w-8 h-8 rounded-full flex items-center justify-center hover:bg-accent transition-colors ${
@@ -194,6 +197,7 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
{hours.map((h) => (
<div
key={h}
data-testid={`hour-${h}`}
onClick={() => handleTimeChange('hour', h)}
className={`px-2 py-1 text-center text-sm cursor-pointer hover:bg-accent ${getHours(safeDate) === h ? 'bg-primary/10 font-medium text-primary' : ''}`}
>
@@ -205,6 +209,7 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
{minutes.map((m) => (
<div
key={m}
data-testid={`minute-${m}`}
onClick={() => handleTimeChange('minute', m)}
className={`px-2 py-1 text-center text-sm cursor-pointer hover:bg-accent ${getMinutes(safeDate) === m ? 'bg-primary/10 font-medium text-primary' : ''}`}
>
@@ -215,19 +220,8 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
</div>
</div>
)}
</div>
</div>
)
}
return (
<div
onClick={handleStartEdit}
className={`w-full min-h-[28px] px-2 py-1 text-sm text-foreground rounded border border-transparent transition-colors ${
!readOnly ? 'cursor-pointer hover:bg-accent hover:border-border' : ''
}`}
>
{value ? getDisplayValue(value) : <span className="text-muted-foreground italic">Empty</span>}
</PopoverContent>
</Popover>
</div>
)
}
@@ -17,8 +17,9 @@ describe('LongTextField Component', () => {
it('renders collapsed placeholder with fixed 2-row height and whitespace-pre-wrap', () => {
render(<LongTextField value="Line 1\nLine 2\nLine 3" config={dummyConfig} onSave={vi.fn()} />)
const collapsed = screen.getByTitle('Click to expand')
const collapsed = screen.getByTestId('long-text-placeholder')
expect(collapsed).toBeTruthy()
expect(collapsed.title).toBe('Click to edit')
expect(collapsed.className).toContain('h-[48px]')
expect(collapsed.className).toContain('line-clamp-2')
expect(collapsed.className).toContain('whitespace-pre-wrap')
@@ -26,17 +27,102 @@ describe('LongTextField Component', () => {
it('renders Empty state inside 2-row container when value is empty', () => {
render(<LongTextField value="" config={dummyConfig} onSave={vi.fn()} />)
const collapsed = screen.getByTitle('Click to expand')
const collapsed = screen.getByTestId('long-text-placeholder')
expect(collapsed.className).toContain('h-[48px]')
expect(screen.getByText('Empty')).toBeTruthy()
})
it('expands on click to show full content overlay', () => {
render(<LongTextField value="Line 1\nLine 2\nLine 3" config={dummyConfig} onSave={vi.fn()} />)
const collapsed = screen.getByTitle('Click to expand')
it('single click expands directly into textarea editing mode and positions cursor at the end', () => {
const text = 'Line 1\nLine 2\nLine 3'
render(<LongTextField value={text} config={dummyConfig} onSave={vi.fn()} />)
const collapsed = screen.getByTestId('long-text-placeholder')
fireEvent.click(collapsed)
const elements = screen.getAllByText(/Line 1/)
expect(elements.length).toBe(2)
const textarea = screen.getByRole('textbox') as HTMLTextAreaElement
expect(textarea).toBeTruthy()
expect(textarea.value).toBe(text)
expect(textarea.selectionStart).toBe(text.length)
expect(textarea.selectionEnd).toBe(text.length)
expect(collapsed.className).toContain('invisible')
})
it('saves updated content on blur', () => {
const onSave = vi.fn()
render(<LongTextField value="Initial content" config={dummyConfig} onSave={onSave} />)
// Single click directly opens editing textarea
fireEvent.click(screen.getByTestId('long-text-placeholder'))
const textarea = screen.getByRole('textbox') as HTMLTextAreaElement
expect(textarea).toBeTruthy()
expect(textarea.value).toBe('Initial content')
// Change value and blur
fireEvent.change(textarea, { target: { value: 'Updated content' } })
fireEvent.blur(textarea)
expect(onSave).toHaveBeenCalledWith('Updated content')
expect(screen.queryByRole('textbox')).toBeNull()
})
it('does not call onSave on blur if value did not change', () => {
const onSave = vi.fn()
render(<LongTextField value="Unchanged" config={dummyConfig} onSave={onSave} />)
fireEvent.click(screen.getByTestId('long-text-placeholder'))
const textarea = screen.getByRole('textbox') as HTMLTextAreaElement
fireEvent.blur(textarea)
expect(onSave).not.toHaveBeenCalled()
expect(screen.queryByRole('textbox')).toBeNull()
})
it('blurs and saves when pressing Cmd+Enter in textarea', () => {
const onSave = vi.fn()
render(<LongTextField value="Initial content" config={dummyConfig} onSave={onSave} />)
fireEvent.click(screen.getByTestId('long-text-placeholder'))
const textarea = screen.getByRole('textbox') as HTMLTextAreaElement
fireEvent.change(textarea, { target: { value: 'Content saved via shortcut' } })
fireEvent.keyDown(textarea, { key: 'Enter', metaKey: true })
expect(onSave).toHaveBeenCalledWith('Content saved via shortcut')
expect(screen.queryByRole('textbox')).toBeNull()
})
it('cancels editing on Escape key and discards changes', () => {
const onSave = vi.fn()
render(<LongTextField value="Line 1\nLine 2" config={dummyConfig} onSave={onSave} />)
fireEvent.click(screen.getByTestId('long-text-placeholder'))
const textarea = screen.getByRole('textbox') as HTMLTextAreaElement
expect(textarea).toBeTruthy()
fireEvent.change(textarea, { target: { value: 'Changed content' } })
fireEvent.keyDown(document, { key: 'Escape' })
expect(screen.queryByRole('textbox')).toBeNull()
expect(onSave).not.toHaveBeenCalled()
})
it('does not allow editing in readOnly mode, only expanding view', () => {
const onSave = vi.fn()
render(<LongTextField value="Readonly text" config={dummyConfig} onSave={onSave} readOnly />)
const collapsed = screen.getByTestId('long-text-placeholder')
expect(collapsed.title).toBe('Click to expand')
fireEvent.click(collapsed)
// Expanded read-only overlay is present, but no textarea
expect(screen.queryByRole('textbox')).toBeNull()
const expandedView = screen.getByTestId('long-text-expanded-overlay')
expect(expandedView).toBeTruthy()
expect(expandedView.textContent).toContain('Readonly text')
// Escape closes read-only overlay
fireEvent.keyDown(document, { key: 'Escape' })
expect(screen.queryByTestId('long-text-expanded-overlay')).toBeNull()
expect(onSave).not.toHaveBeenCalled()
})
})
@@ -1,4 +1,5 @@
import React, { useEffect, useRef, useState } from 'react'
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import type { FieldProps } from './field-types'
const LongTextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }) => {
@@ -6,92 +7,210 @@ const LongTextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }
const [localValue, setLocalValue] = useState(value || '')
const textareaRef = useRef<HTMLTextAreaElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
const overlayRef = useRef<HTMLDivElement | HTMLTextAreaElement | null>(null)
const [expanded, setExpanded] = useState(false)
const [coords, setCoords] = useState<{
top: number
left: number
width: number
height: number
} | null>(null)
useEffect(() => {
setLocalValue(value || '')
}, [value])
const updateCoords = () => {
if (containerRef.current) {
const rect = containerRef.current.getBoundingClientRect()
setCoords({
top: rect.top,
left: rect.left,
width: rect.width,
height: rect.height,
})
}
}
useLayoutEffect(() => {
if (expanded || isEditing) {
updateCoords()
}
}, [expanded, isEditing])
const adjustHeight = () => {
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
const baseHeight = Math.max(80, coords?.height || 0)
const newHeight = Math.min(240, Math.max(baseHeight, textareaRef.current.scrollHeight))
textareaRef.current.style.height = `${newHeight}px`
}
}
useLayoutEffect(() => {
if (isEditing) {
adjustHeight()
}
}, [isEditing, localValue])
useEffect(() => {
if (isEditing && textareaRef.current) {
textareaRef.current.focus()
setExpanded(false)
const len = textareaRef.current.value.length
textareaRef.current.setSelectionRange(len, len)
}
}, [isEditing])
// Handle click outside to close expanded state
// Handle click outside and Escape to close expanded or editing state
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
const target = event.target as Node
if (
expanded &&
containerRef.current &&
!containerRef.current.contains(event.target as Node)
!containerRef.current.contains(target) &&
overlayRef.current &&
!overlayRef.current.contains(target)
) {
setExpanded(false)
if (isEditing) {
handleBlur()
} else {
setExpanded(false)
}
}
}
if (expanded) {
const handleKeyDownGlobal = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
if (isEditing) {
setIsEditing(false)
setLocalValue(value || '')
} else {
setExpanded(false)
}
}
}
const handleScrollOrResize = (event: Event) => {
if (overlayRef.current && overlayRef.current.contains(event.target as Node)) {
return
}
updateCoords()
}
if (expanded || isEditing) {
document.addEventListener('mousedown', handleClickOutside)
document.addEventListener('keydown', handleKeyDownGlobal)
window.addEventListener('scroll', handleScrollOrResize, true)
window.addEventListener('resize', handleScrollOrResize)
}
return () => {
document.removeEventListener('mousedown', handleClickOutside)
document.removeEventListener('keydown', handleKeyDownGlobal)
window.removeEventListener('scroll', handleScrollOrResize, true)
window.removeEventListener('resize', handleScrollOrResize)
}
}, [expanded])
}, [expanded, isEditing, localValue, value])
const handleBlur = () => {
setIsEditing(false)
onSave(localValue)
setExpanded(false)
if (localValue !== (value || '')) {
onSave(localValue)
}
}
const handlePlaceholderClick = (e: React.MouseEvent) => {
e.stopPropagation()
setExpanded(true)
}
const handleOverlayClick = (e: React.MouseEvent) => {
e.stopPropagation()
updateCoords()
if (!readOnly) {
setIsEditing(true)
} else {
setExpanded(true)
}
}
if (isEditing) {
return (
<textarea
ref={textareaRef}
value={localValue}
onChange={(e) => setLocalValue(e.target.value)}
onBlur={handleBlur}
className="w-full min-h-[80px] p-2 border border-ring rounded bg-background text-sm outline-none shadow-sm resize-none"
/>
)
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
e.currentTarget.blur()
}
}
const setTextareaRef = (el: HTMLTextAreaElement | null) => {
textareaRef.current = el
overlayRef.current = el
}
return (
<div ref={containerRef} className="relative w-full text-sm">
{/* Placeholder */}
<div
ref={containerRef}
className="relative w-full text-sm"
onClick={(e) => e.stopPropagation()}
>
{/* In-card placeholder: fixed 48px height so card height never changes */}
<div
data-testid="long-text-placeholder"
onClick={handlePlaceholderClick}
className={`w-full text-foreground rounded border border-transparent transition-all px-2 py-1 h-[48px] line-clamp-2 whitespace-pre-wrap overflow-hidden ${
!readOnly ? 'cursor-pointer hover:bg-accent hover:border-border' : 'cursor-pointer'
}`}
title="Click to expand"
expanded || isEditing ? 'invisible pointer-events-none select-none' : ''
} ${!readOnly ? 'cursor-pointer hover:bg-accent hover:border-border' : 'cursor-pointer'}`}
title={
!expanded && !isEditing ? (!readOnly ? 'Click to edit' : 'Click to expand') : undefined
}
>
{value ? value : <span className="text-muted-foreground italic">Empty</span>}
</div>
{/* Expanded Overlay */}
{expanded && (
<div
onClick={handleOverlayClick}
className={`absolute top-0 left-0 w-full min-h-full h-auto z-50 bg-background border border-ring rounded shadow-lg px-2 py-1 whitespace-pre-wrap ${
!readOnly ? 'cursor-text' : ''
}`}
>
{value ? value : <span className="text-muted-foreground italic">Empty</span>}
</div>
)}
{/* Expanded overlay or textarea: portaled to document.body so card border never clips it */}
{(expanded || isEditing) &&
coords &&
typeof document !== 'undefined' &&
createPortal(
isEditing ? (
<textarea
ref={setTextareaRef}
data-testid="long-text-editing-overlay"
value={localValue}
onChange={(e) => {
setLocalValue(e.target.value)
adjustHeight()
}}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
style={{
position: 'fixed',
top: coords.top,
left: coords.left,
width: coords.width > 0 ? coords.width : 'auto',
minWidth: coords.width > 0 ? coords.width : 200,
minHeight: Math.max(80, coords.height),
maxHeight: 240,
zIndex: 50,
}}
className="bg-background border border-ring rounded shadow-lg px-2 py-1 text-sm outline-none resize-none overflow-y-auto"
/>
) : (
<div
ref={(el) => {
overlayRef.current = el
}}
data-testid="long-text-expanded-overlay"
style={{
position: 'fixed',
top: coords.top,
left: coords.left,
width: coords.width > 0 ? coords.width : 'auto',
minWidth: coords.width > 0 ? coords.width : 200,
minHeight: Math.max(80, coords.height),
maxHeight: 240,
zIndex: 50,
}}
className="min-h-[80px] bg-background border border-ring rounded shadow-lg px-2 py-1 whitespace-pre-wrap overflow-y-auto text-sm cursor-pointer"
>
{value ? value : <span className="text-muted-foreground italic">Empty</span>}
</div>
),
document.body,
)}
</div>
)
}
@@ -0,0 +1,84 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import React from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import NumberField from './number-field'
describe('NumberField Component', () => {
afterEach(() => {
cleanup()
vi.clearAllMocks()
})
const dummyConfig = {
name: 'Score',
type: 'number' as const,
number: {
scale: 2,
},
}
it('renders Empty state when value is undefined', () => {
render(<NumberField value={undefined} config={dummyConfig} onSave={vi.fn()} />)
expect(screen.getByText('Empty')).toBeTruthy()
})
it('formats number with scale', () => {
render(<NumberField value={42} config={dummyConfig} onSave={vi.fn()} />)
expect(screen.getByText('42.00')).toBeTruthy()
})
it('enters edit mode on click and stops event propagation', () => {
const parentClick = vi.fn()
const parentDoubleClick = vi.fn()
render(
<div onClick={parentClick} onDoubleClick={parentDoubleClick}>
<NumberField value={10} config={dummyConfig} onSave={vi.fn()} />
</div>,
)
const display = screen.getByText('10.00')
fireEvent.click(display)
const input = screen.getByRole('spinbutton') as HTMLInputElement
expect(input).toBeTruthy()
expect(input.value).toBe('10')
expect(parentClick).not.toHaveBeenCalled()
fireEvent.doubleClick(input)
expect(parentDoubleClick).not.toHaveBeenCalled()
})
it('saves parsed number on blur', () => {
const onSave = vi.fn()
render(<NumberField value={10} config={dummyConfig} onSave={onSave} />)
fireEvent.click(screen.getByText('10.00'))
const input = screen.getByRole('spinbutton') as HTMLInputElement
fireEvent.change(input, { target: { value: '25.5' } })
fireEvent.blur(input)
expect(onSave).toHaveBeenCalledWith(25.5)
})
it('cancels edit on Escape key', () => {
const onSave = vi.fn()
render(<NumberField value={10} config={dummyConfig} onSave={onSave} />)
fireEvent.click(screen.getByText('10.00'))
const input = screen.getByRole('spinbutton') as HTMLInputElement
fireEvent.change(input, { target: { value: '99' } })
fireEvent.keyDown(input, { key: 'Escape' })
expect(screen.queryByRole('spinbutton')).toBeNull()
expect(screen.getByText('10.00')).toBeTruthy()
expect(onSave).not.toHaveBeenCalled()
})
it('does not enter edit mode when readOnly', () => {
render(<NumberField value={10} config={dummyConfig} onSave={vi.fn()} readOnly />)
fireEvent.click(screen.getByText('10.00'))
expect(screen.queryByRole('spinbutton')).toBeNull()
})
})
@@ -23,7 +23,8 @@ const NumberField: React.FC<FieldProps<number | undefined>> = ({
}
}, [isEditing])
const handleStartEdit = () => {
const handleStartEdit = (e: React.MouseEvent) => {
e.stopPropagation()
if (!readOnly) {
setIsEditing(true)
}
@@ -44,6 +45,11 @@ const NumberField: React.FC<FieldProps<number | undefined>> = ({
e.stopPropagation()
inputRef.current?.blur()
}
if (e.key === 'Escape') {
e.stopPropagation()
setIsEditing(false)
setLocalValue(value !== undefined && value !== null ? value.toString() : '')
}
}
const formatNumber = (val: number | undefined) => {
@@ -51,34 +57,37 @@ const NumberField: React.FC<FieldProps<number | undefined>> = ({
return val.toFixed(numberConfig?.scale)
}
if (isEditing) {
return (
<input
ref={inputRef}
type="number"
step={1 / Math.pow(10, numberConfig?.scale || 0)}
value={localValue}
onChange={(e) => setLocalValue(e.target.value)}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
onDoubleClick={(e) => e.stopPropagation()}
className="w-full px-2 py-1 border border-ring rounded bg-background text-sm outline-none shadow-sm text-left font-mono"
/>
)
}
return (
<div
onClick={handleStartEdit}
className="relative w-full"
onClick={(e) => e.stopPropagation()}
onDoubleClick={(e) => e.stopPropagation()}
className={`w-full min-h-[28px] px-2 py-1 text-sm text-foreground rounded border border-transparent transition-colors text-left font-mono ${
!readOnly ? 'cursor-pointer hover:bg-accent hover:border-border' : ''
}`}
>
{value !== undefined && value !== null ? (
formatNumber(value)
{isEditing ? (
<input
ref={inputRef}
type="number"
step={1 / Math.pow(10, numberConfig?.scale || 0)}
value={localValue}
onChange={(e) => setLocalValue(e.target.value)}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
onClick={(e) => e.stopPropagation()}
className="w-full px-2 py-1 border border-ring rounded bg-background text-sm outline-none shadow-sm text-left font-mono"
/>
) : (
<span className="text-muted-foreground italic font-sans text-left block">Empty</span>
<div
onClick={handleStartEdit}
className={`w-full min-h-[28px] px-2 py-1 text-sm text-foreground rounded border border-transparent transition-colors text-left font-mono ${
!readOnly ? 'cursor-pointer hover:bg-accent hover:border-border' : ''
}`}
>
{value !== undefined && value !== null ? (
formatNumber(value)
) : (
<span className="text-muted-foreground italic font-sans text-left block">Empty</span>
)}
</div>
)}
</div>
)
@@ -25,6 +25,7 @@ const RatingField: React.FC<FieldProps<number>> = ({ value, config, onSave, read
return (
<div
className="flex items-center gap-1 h-[28px]"
onClick={(e) => e.stopPropagation()}
onMouseLeave={() => !readOnly && setHoverValue(null)}
onDoubleClick={(e) => e.stopPropagation()}
>
@@ -0,0 +1,100 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import React from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import TextField from './text-field'
describe('TextField Component', () => {
afterEach(() => {
cleanup()
vi.clearAllMocks()
})
const dummyConfig = {
name: 'Title',
type: 'text' as const,
}
it('renders Empty state when value is empty', () => {
render(<TextField value="" config={dummyConfig} onSave={vi.fn()} />)
expect(screen.getByText('Empty')).toBeTruthy()
})
it('enters edit mode on click and stops event propagation', () => {
const parentClick = vi.fn()
const parentDoubleClick = vi.fn()
render(
<div onClick={parentClick} onDoubleClick={parentDoubleClick}>
<TextField value="Test Text" config={dummyConfig} onSave={vi.fn()} />
</div>,
)
const display = screen.getByText('Test Text')
fireEvent.click(display)
const input = screen.getByRole('textbox') as HTMLInputElement
expect(input).toBeTruthy()
expect(input.value).toBe('Test Text')
expect(parentClick).not.toHaveBeenCalled()
fireEvent.doubleClick(input)
expect(parentDoubleClick).not.toHaveBeenCalled()
})
it('saves on blur when value changed', () => {
const onSave = vi.fn()
render(<TextField value="Initial" config={dummyConfig} onSave={onSave} />)
fireEvent.click(screen.getByText('Initial'))
const input = screen.getByRole('textbox') as HTMLInputElement
fireEvent.change(input, { target: { value: 'Updated' } })
fireEvent.blur(input)
expect(onSave).toHaveBeenCalledWith('Updated')
expect(screen.queryByRole('textbox')).toBeNull()
})
it('does not save on blur if value is unchanged', () => {
const onSave = vi.fn()
render(<TextField value="Same" config={dummyConfig} onSave={onSave} />)
fireEvent.click(screen.getByText('Same'))
const input = screen.getByRole('textbox') as HTMLInputElement
fireEvent.blur(input)
expect(onSave).not.toHaveBeenCalled()
})
it('blurs on Enter key', () => {
const onSave = vi.fn()
render(<TextField value="Initial" config={dummyConfig} onSave={onSave} />)
fireEvent.click(screen.getByText('Initial'))
const input = screen.getByRole('textbox') as HTMLInputElement
fireEvent.change(input, { target: { value: 'Enter Saved' } })
fireEvent.keyDown(input, { key: 'Enter' })
expect(onSave).toHaveBeenCalledWith('Enter Saved')
})
it('cancels edit and discards changes on Escape key', () => {
const onSave = vi.fn()
render(<TextField value="Original" config={dummyConfig} onSave={onSave} />)
fireEvent.click(screen.getByText('Original'))
const input = screen.getByRole('textbox') as HTMLInputElement
fireEvent.change(input, { target: { value: 'Discarded' } })
fireEvent.keyDown(input, { key: 'Escape' })
expect(screen.queryByRole('textbox')).toBeNull()
expect(screen.getByText('Original')).toBeTruthy()
expect(onSave).not.toHaveBeenCalled()
})
it('does not enter edit mode when readOnly', () => {
render(<TextField value="ReadOnly Text" config={dummyConfig} onSave={vi.fn()} readOnly />)
fireEvent.click(screen.getByText('ReadOnly Text'))
expect(screen.queryByRole('textbox')).toBeNull()
})
})
+34 -21
View File
@@ -17,7 +17,8 @@ const TextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }) =>
}
}, [isEditing])
const handleStartEdit = () => {
const handleStartEdit = (e: React.MouseEvent) => {
e.stopPropagation()
if (!readOnly) {
setIsEditing(true)
}
@@ -25,37 +26,49 @@ const TextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }) =>
const handleBlur = () => {
setIsEditing(false)
onSave(localValue)
if (localValue !== (value || '')) {
onSave(localValue)
}
}
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
inputRef.current?.blur()
}
}
if (isEditing) {
return (
<input
ref={inputRef}
type="text"
value={localValue}
onChange={(e) => setLocalValue(e.target.value)}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
className="w-full px-2 py-1 border border-ring rounded bg-background text-sm outline-none shadow-sm"
/>
)
if (e.key === 'Escape') {
setIsEditing(false)
setLocalValue(value || '')
}
}
return (
<div
onClick={handleStartEdit}
className={`w-full min-h-[28px] px-2 py-1 text-sm text-foreground rounded truncate border border-transparent transition-colors ${
!readOnly ? 'cursor-pointer hover:bg-accent hover:border-border' : ''
}`}
className="relative w-full"
onClick={(e) => e.stopPropagation()}
onDoubleClick={(e) => e.stopPropagation()}
>
{value || <span className="text-muted-foreground italic">Empty</span>}
{isEditing ? (
<input
ref={inputRef}
type="text"
value={localValue}
onChange={(e) => setLocalValue(e.target.value)}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
onClick={(e) => e.stopPropagation()}
className="w-full px-2 py-1 border border-ring rounded bg-background text-sm outline-none shadow-sm"
/>
) : (
<div
data-testid="text-field-display"
onClick={handleStartEdit}
className={`w-full min-h-[28px] px-2 py-1 text-sm text-foreground rounded truncate border border-transparent transition-colors ${
!readOnly ? 'cursor-pointer hover:bg-accent hover:border-border' : ''
}`}
>
{value || <span className="text-muted-foreground italic">Empty</span>}
</div>
)}
</div>
)
}
@@ -476,4 +476,102 @@ describe('FileCard', () => {
expect(matchedDuration).toBeTruthy()
expect(matchedDuration.textContent).toBe('01:05 - 02:05')
})
it('renders custom fields and allows expanding longText in FileCard', () => {
const itemWithFields: AssetInfo = {
...fileItem,
fieldValues: [
{
fieldId: 'field_long_text',
value: 'Line 1\nLine 2\nLine 3\nLine 4',
},
],
} as AssetInfo
const fields = [
{
id: 'field_long_text',
name: 'Notes',
scope: 'project',
readOnly: false,
visible: true,
description: '',
config: {
type: 'longText' as const,
name: 'Notes',
},
},
]
renderComponent({ item: itemWithFields, fields })
expect(screen.getByText('Notes')).toBeTruthy()
const collapsed = screen.getByTestId('long-text-placeholder')
expect(collapsed).toBeTruthy()
// Expanding directly enters editing mode on single click
fireEvent.click(collapsed)
const textarea = screen.getByRole('textbox') as HTMLTextAreaElement
expect(textarea).toBeTruthy()
expect(textarea.value).toContain('Line 1')
expect(textarea.value).toContain('Line 4')
})
it('does not trigger onSelect when clicking a single line text field or number field to edit', () => {
const onSelect = vi.fn()
const itemWithFields: AssetInfo = {
...fileItem,
fieldValues: [
{
fieldId: 'field_text',
value: 'Single line text',
},
{
fieldId: 'field_number',
value: 42,
},
],
} as AssetInfo
const fields = [
{
id: 'field_text',
name: 'Title',
scope: 'project',
readOnly: false,
visible: true,
description: '',
config: {
type: 'text' as const,
name: 'Title',
},
},
{
id: 'field_number',
name: 'Score',
scope: 'project',
readOnly: false,
visible: true,
description: '',
config: {
type: 'number' as const,
name: 'Score',
},
},
]
renderComponent({ item: itemWithFields, fields, onSelect })
// Click single line text field
const textField = screen.getByText('Single line text')
fireEvent.click(textField)
expect(screen.getByDisplayValue('Single line text')).toBeTruthy()
expect(onSelect).not.toHaveBeenCalled()
// Click number field
const numberField = screen.getByText('42')
fireEvent.click(numberField)
expect(screen.getByDisplayValue('42')).toBeTruthy()
expect(onSelect).not.toHaveBeenCalled()
})
})
@@ -617,7 +617,11 @@ export function FileCard({
)}
</div>
{fields && fields.length > 0 && (
<div className="space-y-2 border-t p-1 pt-3 mx-2">
<div
className="space-y-2 border-t p-1 pt-3 mx-2"
onClick={(e) => e.stopPropagation()}
onDoubleClick={(e) => e.stopPropagation()}
>
{fields.map((field) => {
const Icon = field.config?.type
? FIELD_TYPE_ICONS[field.config.type as FieldType]
@@ -147,4 +147,40 @@ describe('FileListItem', () => {
expect(failedLabel).toBeTruthy()
expect(failedLabel.textContent).toMatch(/Processing failed|处理失败/i)
})
it('does not trigger onSelect when clicking a custom field in list view', () => {
const onSelect = vi.fn()
const itemWithFields: AssetInfo = {
...mockItem,
fieldValues: [
{
fieldId: 'field_text',
value: 'List text value',
},
],
} as AssetInfo
const fields = [
{
id: 'field_text',
name: 'Custom Column',
scope: 'project',
readOnly: false,
visible: true,
description: '',
config: {
type: 'text' as const,
name: 'Custom Column',
},
},
]
renderComponent({ item: itemWithFields, fields, onSelect })
const textField = screen.getByText('List text value')
fireEvent.click(textField)
expect(screen.getByDisplayValue('List text value')).toBeTruthy()
expect(onSelect).not.toHaveBeenCalled()
})
})
@@ -328,6 +328,8 @@ export function FileListItem({
fields.map((field) => (
<div
key={field.id}
onClick={(e) => e.stopPropagation()}
onDoubleClick={(e) => e.stopPropagation()}
className="px-4 py-2 truncate border-r shrink-0 flex items-center"
style={{
width: columnSizing?.[field.id!] || 150,
@@ -182,6 +182,7 @@ export function FileBrowserGridView({
[rows],
),
overscan: 5,
paddingEnd: 240,
})
const virtualItems = rowVirtualizer.getVirtualItems()
@@ -332,6 +332,7 @@ export function FileBrowserListView({
[items, folders, files],
),
overscan: 10,
paddingEnd: 240,
})
const virtualItems = rowVirtualizer.getVirtualItems()
+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
@@ -1,6 +1,6 @@
{
"name": "@shumai/webui",
"version": "0.6.0",
"version": "0.6.1",
"private": true,
"type": "module",
"main": "./index.html",
+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'>(
+1 -1
View File
@@ -1 +1 @@
export const APP_VERSION = '0.6.0'
export const APP_VERSION = '0.6.1'
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/workflow-core",
"version": "0.6.0",
"version": "0.6.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
@@ -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
}
}