Compare commits

..
4 Commits
109 changed files with 596 additions and 6521 deletions
+2 -12
View File
@@ -8,22 +8,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
### Fixed
### Changed
## [0.5.2] - 2026-10-13
### Added
* **3d asset**: Add support for 3D model files (.glb, .gltf, .obj, .fbx, .stl, .dae, .usd, .usda, .usdc, .usdz) with automated turntable video rendering, hover sprite scrubbing, and an interactive 3D turntable viewer featuring 360° ruler scrubbing and degree-based markup comments
* **3d**: Add support for 3D model files (.glb, .gltf, .obj, .fbx, .stl, .dae, .usd, .usda, .usdc, .usdz) with automated turntable video rendering, hover sprite scrubbing, and an interactive 3D turntable viewer featuring 360° ruler scrubbing and degree-based markup comments
* **settings**: Add Turntable Renderer settings card with server connection testing and environment variable override support
* **kanban**: Related assets on a task are now clickable, taking you directly to that file or folder in its project
* **settings**: Add an Integrations section to Team Settings with dedicated configuration for Gotenberg Document Converter, supporting connection testing and environment variable override protection
### Fixed
* **transcode**: Fix an issue where portrait photos from cameras and phones appeared sideways in thumbnails, previews, watermarked share links and annotated snapshots, and were listed with their width and height swapped
### Changed
## [0.5.1] - 2026-10-06
-1
View File
@@ -33,7 +33,6 @@ Shumai is an open-source Frame.io alternative built for creative teams to collab
* **Custom Asset Metadata**: Define dynamic metadata fields tailored to your production pipeline.
* **Share Link Watermarking**: Protect shared media with customizable text and image watermarks, and save watermark as reusable templates.
* **Wide File Format Support**: Preview common creative file formats, including images (with PSD support), videos, audio, and documents, while allowing any file type to be uploaded and stored.
* **3D Asset Turntable Previews**: Generate interactive 3D model turntable previews and videos for formats like GLB, FBX, OBJ, STL, USD, and DAE using [turntable-renderer](https://docs.shumai.one/using-shumai/3d-asset-support).
* **Office & Document PDF Proxying via Gotenberg**: Convert Word, PowerPoint, Excel, Markdown, HTML, and CSV documents to high-quality PDF proxies for in-browser previewing using [Gotenberg](https://docs.shumai.one/using-shumai/gotenberg).
* **NLE Export & Premiere Pro Plugin (Experimental)**: Export timestamped review comments to your favorite non-linear editor (Premiere Pro XML, DaVinci Resolve EDL, Final Cut Pro, Avid Media Composer) or use the experimental Premiere Pro UXP plugin to import media assets and auto-sync comments directly to sequence timeline markers. See [documentation](https://docs.shumai.one/using-shumai/nle-and-premiere).
-1
View File
@@ -33,7 +33,6 @@ Shumai 是一个开源的 Frame.io 替代方案,专为创意团队打造,让
* **自定义素材元数据**:可以按你的制作流程,自由定义动态元数据字段。
* **分享链接水印**:通过可自定义的文字和图片水印保护共享媒体,并将水印配置保存为模板以便重复使用。
* **丰富的文件格式支持**:支持预览常见创意文件格式,包括图片(支持 PSD)、视频、音频和文档,同时可上传和存储任意类型的文件。
* **基于转盘渲染服务的 3D 资产预览**:通过集成 [turntable-renderer](https://docs.shumai.one/using-shumai/3d-asset-support) 支持为 GLB、FBX、OBJ、STL、USD 和 DAE 等 3D 模型生成高质量的交互式转盘预览与视频。
* **基于 Gotenberg 的文档 PDF 转码代理**:通过集成 [Gotenberg](https://docs.shumai.one/using-shumai/gotenberg) 支持将 Word、PowerPoint、Excel、Markdown、HTML 和 CSV 文档高质量转换为 PDF 代理文件进行在线预览。
* **非编剪辑导出与 Premiere 插件(实验性)**:支持将时间戳审阅评论导出至常用非编软件(Premiere Pro XML、DaVinci Resolve EDL、Final Cut Pro、Avid Media Composer),或使用实验性的 Premiere Pro 原生 UXP 插件导入媒体素材并将评论自动同步为时间轴标记。详见[相关文档](https://docs.shumai.one/using-shumai/nle-and-premiere)。
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/agent-app",
"version": "0.5.2",
"version": "0.5.1",
"private": true,
"type": "module",
"bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/cli",
"version": "0.5.2",
"version": "0.5.1",
"private": true,
"type": "module",
"bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/premiere-uxp",
"version": "0.5.2",
"version": "0.5.1",
"private": true,
"type": "commonjs",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/transcode-app",
"version": "0.5.2",
"version": "0.5.1",
"private": true,
"type": "module",
"bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/web-app",
"version": "0.5.2",
"version": "0.5.1",
"private": true,
"type": "module",
"dependencies": {
+15 -15
View File
@@ -33,7 +33,7 @@
},
"apps/agent": {
"name": "@shumai/agent-app",
"version": "0.5.2",
"version": "0.5.1",
"bin": {
"shumai-agent": "./src/index.ts",
},
@@ -45,7 +45,7 @@
},
"apps/cli": {
"name": "@shumai/cli",
"version": "0.5.2",
"version": "0.5.1",
"bin": {
"shumai-cli": "./src/index.ts",
},
@@ -60,7 +60,7 @@
},
"apps/premiere-uxp": {
"name": "@shumai/premiere-uxp",
"version": "0.5.2",
"version": "0.5.1",
"dependencies": {
"@shumai/api": "workspace:*",
"@shumai/dtos": "workspace:*",
@@ -114,7 +114,7 @@
},
"apps/transcode": {
"name": "@shumai/transcode-app",
"version": "0.5.2",
"version": "0.5.1",
"bin": {
"shumai-transcode": "./src/index.ts",
},
@@ -126,7 +126,7 @@
},
"apps/web": {
"name": "@shumai/web-app",
"version": "0.5.2",
"version": "0.5.1",
"dependencies": {
"@shumai/agent": "workspace:*",
"@shumai/api": "workspace:*",
@@ -146,7 +146,7 @@
},
"packages/agent": {
"name": "@shumai/agent",
"version": "0.5.2",
"version": "0.5.1",
"dependencies": {
"@anthropic-ai/sandbox-runtime": "0.0.74",
"@earendil-works/pi-agent-core": "0.82.1",
@@ -171,7 +171,7 @@
},
"packages/api": {
"name": "@shumai/api",
"version": "0.5.2",
"version": "0.5.1",
"dependencies": {
"@hono/zod-validator": "0.7.6",
"@shumai/core": "workspace:*",
@@ -185,7 +185,7 @@
},
"packages/core": {
"name": "@shumai/core",
"version": "0.5.2",
"version": "0.5.1",
"dependencies": {
"@ai-sdk/alibaba": "2.0.38",
"@ai-sdk/amazon-bedrock": "5.0.67",
@@ -247,7 +247,7 @@
},
"packages/db": {
"name": "@shumai/db",
"version": "0.5.2",
"version": "0.5.1",
"dependencies": {
"@earendil-works/pi-agent-core": "0.82.1",
"@prisma/adapter-pg": "7.10.0",
@@ -263,7 +263,7 @@
},
"packages/dtos": {
"name": "@shumai/dtos",
"version": "0.5.2",
"version": "0.5.1",
"dependencies": {
"@earendil-works/pi-agent-core": "0.82.1",
"zod": "4.5.4",
@@ -271,7 +271,7 @@
},
"packages/e2e": {
"name": "@shumai/e2e",
"version": "0.5.2",
"version": "0.5.1",
"dependencies": {
"@earendil-works/pi-agent-core": "0.82.1",
"@google/genai": "2.19.0",
@@ -286,11 +286,11 @@
},
"packages/tableprinter": {
"name": "@shumai/tableprinter",
"version": "0.5.2",
"version": "0.5.1",
},
"packages/transcode": {
"name": "@shumai/transcode",
"version": "0.5.2",
"version": "0.5.1",
"dependencies": {
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
@@ -304,7 +304,7 @@
},
"packages/webui": {
"name": "@shumai/webui",
"version": "0.5.2",
"version": "0.5.1",
"dependencies": {
"@base-ui/react": "1.7.0",
"@dnd-kit/abstract": "0.5.0",
@@ -406,7 +406,7 @@
},
"packages/workflow-core": {
"name": "@shumai/workflow-core",
"version": "0.5.2",
"version": "0.5.1",
"dependencies": {
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
-16
View File
@@ -3,22 +3,6 @@ title: "Changelog"
description: "Recent updates, new features, and improvements in Shumai"
---
<Update label="v0.5.2" description="October 13, 2026">
### Added
* **3d asset**: Add support for 3D model files (.glb, .gltf, .obj, .fbx, .stl, .dae, .usd, .usda, .usdc, .usdz) with automated turntable video rendering, hover sprite scrubbing, and an interactive 3D turntable viewer featuring 360° ruler scrubbing and degree-based markup comments
* **kanban**: Related assets on a task are now clickable, taking you directly to that file or folder in its project
* **settings**: Add an Integrations section to Team Settings with dedicated configuration for Gotenberg Document Converter, supporting connection testing and environment variable override protection
### Fixed
* **transcode**: Fix an issue where portrait photos from cameras and phones appeared sideways in thumbnails, previews, watermarked share links and annotated snapshots, and were listed with their width and height swapped
### Changed
</Update>
<Update label="v0.5.1" description="October 6, 2026">
### Added
-26
View File
@@ -99,29 +99,3 @@ API keys to AI providers on startup.
| `GEMINI_API_KEY` | API key for Google Gemini provider. | `AIzaSy...` |
| `OPENAI_API_KEY` | API key for OpenAI provider. | `sk-proj-...` |
| `ANTHROPIC_API_KEY` | API key for Anthropic provider. | `sk-ant-...` |
---
## External Integrations Config
Environment variables can configure external microservices globally. When set, these environment variables take precedence over any team-level settings configured in **Team Settings → Integrations**, and lock the corresponding settings fields in the WebUI to read-only.
### Gotenberg Document Converter
Used to convert Office documents, HTML, Markdown, and CSV files into high-fidelity PDF proxies for in-browser previewing. See the [Gotenberg Guide](/using-shumai/gotenberg) for setup instructions.
| Variable | Description | Example / Default |
| :------------------------------ | :----------------------------------------------------------------------- | :---------------------- |
| `GOTENBERG_URL` | Base URL of the external Gotenberg conversion API. | `http://gotenberg:3000` |
| `GOTENBERG_BASIC_AUTH_USERNAME` | Username when Basic Authentication is enabled on the Gotenberg instance. | `admin` |
| `GOTENBERG_BASIC_AUTH_PASSWORD` | Password when Basic Authentication is enabled on the Gotenberg instance. | `secret` |
### 3D Turntable Renderer
Used to convert 3D model files (GLB, OBJ, FBX, USD, STL, DAE) into interactive 360° turntable video proxies, posters, and hover sprites. See the [3D Asset Support Guide](/using-shumai/3d-asset-support) for setup instructions.
| Variable | Description | Example / Default |
| :--------------------------------------- | :-------------------------------------------------------------------------------------------------------------- | :------------------------------- |
| `TURNTABLE_RENDERER_URL` | Base URL of the external turntable-renderer service. | `http://turntable-renderer:3000` |
| `TURNTABLE_RENDERER_BASIC_AUTH_USERNAME` | Username when Basic Authentication is enabled on the turntable renderer (alias: `TURNTABLE_RENDERER_USERNAME`). | `admin` |
| `TURNTABLE_RENDERER_BASIC_AUTH_PASSWORD` | Password when Basic Authentication is enabled on the turntable renderer (alias: `TURNTABLE_RENDERER_PASSWORD`). | `secret` |
-1
View File
@@ -44,7 +44,6 @@
"using-shumai/collections",
"using-shumai/share-links",
"using-shumai/nle-and-premiere",
"using-shumai/3d-asset-support",
"using-shumai/gotenberg"
]
},
-153
View File
@@ -1,153 +0,0 @@
---
title: 3D Asset Support with Turntable Renderer
description: Render interactive 3D model turntable previews, sprite scrubbing, and video proxies using turntable-renderer.
---
3D models and mesh assets cannot always be rendered consistently or inspected reliably across diverse client web browsers and mobile devices. Shumai integrates with [turntable-renderer](https://github.com/shumaiOne/turntable-renderer) — a standalone service that executes isolated, headless Blender 5.2 LTS subprocesses — to convert 3D model uploads into standardized, high-fidelity turntable previews.
Turntable Renderer automatically produces:
- **1080×1080 Turntable Video (`turntable.mp4`)**: A 4-second, 24-frame, 6 fps video rotating the model 360° (15° per frame) clockwise under dark studio lighting with a pure black background.
- **Poster Image (`poster.webp`)**: A crisp still poster for grid cards and immediate file display.
- **Hover Sprite Sheet (`sprite.webp`)**: A fast scrubbing sheet allowing users to rotate and inspect the model directly from the file browser on hover.
- **Interactive 3D Viewer**: A specialized web viewer featuring 360° ruler scrubbing, rotation angle control (0° to 345°), playback controls, and angle-specific review comments and visual markups.
---
## Supported File Types
When turntable-renderer is configured, Shumai automatically generates 3D turntable proxies for the following formats:
| Format / Standard | Extensions |
| --------------------------- | --------------------------------- |
| Binary glTF | `.glb` |
| Universal Scene Description | `.usd`, `.usda`, `.usdc`, `.usdz` |
| Autodesk FBX | `.fbx` |
| Wavefront OBJ | `.obj` |
| Stereolithography (STL) | `.stl` |
| COLLADA | `.dae` |
---
## Configuration
Shumai supports configuring the turntable renderer either through the **WebUI** or via **Environment Variables**.
### 1. WebUI (Team Settings → Integrations)
Team owners can configure the turntable renderer directly from the web interface:
1. Navigate to **Team Settings** from the sidebar.
2. Select the **Integrations** tab.
3. Under **3D Turntable Renderer**, enter the **Server URL** (e.g. `http://turntable-renderer:3000` or `http://localhost:3003`).
4. Enter the **Username** and **Password** if Basic Authentication is enabled on the service.
5. Click **Test Connection** to verify that Shumai can communicate with the renderer and check the detected Blender version.
6. Click **Save Changes**.
### 2. Environment Variables
You can also configure turntable-renderer globally across the system using environment variables on the machine running Shumai or the transcode workers:
| Variable | Required | Description |
| ---------------------------------------- | --------------- | ------------------------------------------------------------------------------------- |
| `TURNTABLE_RENDERER_URL` | Yes (to enable) | Base URL of the turntable renderer service, e.g. `http://turntable-renderer:3000`. |
| `TURNTABLE_RENDERER_BASIC_AUTH_USERNAME` | No | Username when Basic Authentication is enabled (alias: `TURNTABLE_RENDERER_USERNAME`). |
| `TURNTABLE_RENDERER_BASIC_AUTH_PASSWORD` | No | Password when Basic Authentication is enabled (alias: `TURNTABLE_RENDERER_PASSWORD`). |
### Configuration Priority & Read-Only Mode
> [!IMPORTANT]
> **Environment variables take highest priority.** If `TURNTABLE_RENDERER_URL` is set in your environment, Shumai will always use the environment variable configuration.
>
> When configured via environment variables, the settings in **Team Settings → Integrations** will display a **Configured via environment variables (Read-only)** badge, and the input fields will be locked to prevent accidental changes or configuration drift.
---
## Deploying Turntable Renderer
### Docker Quickstart
The easiest way to run `turntable-renderer` is using the prebuilt Docker image:
```bash
docker run -d --rm \
--name turntable-renderer \
-p 3003:3000 \
-e TURNTABLE_RENDERER_API_BASIC_AUTH_USERNAME=admin \
-e TURNTABLE_RENDERER_API_BASIC_AUTH_PASSWORD=your_password \
shumaione/turntable-renderer:latest
```
> **Note**: Host port `3003` maps to internal container port `3000`.
### Docker Compose Setup
Add a `turntable-renderer` service to your `docker-compose.yaml`:
```yaml
services:
turntable-renderer:
image: shumaione/turntable-renderer:latest
restart: unless-stopped
ports:
- '3003:3000'
environment:
TURNTABLE_RENDERER_API_BASIC_AUTH_USERNAME: admin
TURNTABLE_RENDERER_API_BASIC_AUTH_PASSWORD: your_password
```
Then point Shumai at it:
```bash
TURNTABLE_RENDERER_URL=http://localhost:3003
TURNTABLE_RENDERER_BASIC_AUTH_USERNAME=admin
TURNTABLE_RENDERER_BASIC_AUTH_PASSWORD=your_password
```
_(If both Shumai and turntable-renderer run within the same Docker Compose network, use `http://turntable-renderer:3000` as the URL)._
### GPU Acceleration
A dedicated GPU is optional — turntable-renderer's CPU rendering pipeline is fast enough for modest hardware. When a GPU is passed into the container, it is automatically detected and leveraged.
#### Intel / AMD (Open Source Drivers)
Pass the DRI render node:
```bash
docker run -d --rm \
--name turntable-renderer \
--shm-size=1gb \
-p 3003:3000 \
--device /dev/dri \
-e TURNTABLE_RENDERER_API_BASIC_AUTH_USERNAME=admin \
-e TURNTABLE_RENDERER_API_BASIC_AUTH_PASSWORD=your_password \
shumaione/turntable-renderer:latest
```
#### NVIDIA (Proprietary Drivers)
Requires host driver 580+ and the NVIDIA Container Toolkit (`--runtime nvidia`):
```bash
docker run -d --rm \
--name turntable-renderer \
--shm-size=1gb \
-p 3003:3000 \
--runtime nvidia \
--gpus all \
--device /dev/nvidia-modeset \
-e TURNTABLE_RENDERER_API_BASIC_AUTH_USERNAME=admin \
-e TURNTABLE_RENDERER_API_BASIC_AUTH_PASSWORD=your_password \
shumaione/turntable-renderer:latest
```
---
## Behavior Without Turntable Renderer
If turntable-renderer is not configured or unreachable:
- The 3D model upload completes successfully with status `processed`.
- No turntable video proxy, sprite, or poster is generated.
- The original raw 3D file is safely preserved and can be downloaded by team members.
+1 -25
View File
@@ -32,22 +32,7 @@ When Gotenberg is configured, Shumai automatically generates a PDF proxy for the
## Configuration
Shumai supports configuring Gotenberg either through the **WebUI** or via **Environment Variables**.
### 1. WebUI (Team Settings → Integrations)
Team owners can configure Gotenberg directly from the web interface:
1. Navigate to **Team Settings** from the sidebar.
2. Select the **Integrations** tab.
3. Under **Gotenberg Document Converter**, enter the **Server URL** (e.g. `http://gotenberg:3000` or `http://localhost:3000`).
4. Enter the **Username** and **Password** if Basic Authentication is enabled on the service.
5. Click **Test Connection** to test communication with Gotenberg and verify its health.
6. Click **Save Changes**.
### 2. Environment Variables
Gotenberg can also be configured globally across the system using environment variables on the machine running Shumai or the transcode workers:
Gotenberg support is opt-in and controlled by the following environment variables on the machine running the transcode workers:
| Variable | Required | Description |
| ------------------------------- | --------------- | ---------------------------------------------------------------- |
@@ -55,15 +40,6 @@ Gotenberg can also be configured globally across the system using environment va
| `GOTENBERG_BASIC_AUTH_USERNAME` | No | Username when Basic Authentication is enabled on Gotenberg. |
| `GOTENBERG_BASIC_AUTH_PASSWORD` | No | Password when Basic Authentication is enabled on Gotenberg. |
### Configuration Priority & Read-Only Mode
> [!IMPORTANT]
> **Environment variables take highest priority.** If `GOTENBERG_URL` is set in your environment, Shumai will always use the environment variable configuration.
>
> When configured via environment variables, the settings in **Team Settings → Integrations** will display a **Configured via environment variables (Read-only)** badge, and the input fields will be locked to prevent accidental changes or configuration drift.
### Deploying Gotenberg
### Docker Quickstart
You can start a Gotenberg container with a single command:
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "shumai",
"version": "0.5.2",
"version": "0.5.1",
"private": true,
"type": "module",
"repository": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/agent",
"version": "0.5.2",
"version": "0.5.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
-132
View File
@@ -662,23 +662,6 @@ describe('Agent Activities', () => {
const pdfPrompt = mockHarness.prompt.mock.calls[1]?.[0] ?? ''
expect(pdfPrompt).toContain('Document pages: 50')
expect(pdfPrompt).not.toContain('Video duration')
// For a 3D asset, should produce 3D Model recommendation
await autofillAiActivity({
teamId: 't1',
assetId: 'model-3',
assetName: 'robot.glb',
mediaType: 'model/gltf-binary',
images: [],
fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }],
context,
})
const modelPrompt = mockHarness.prompt.mock.calls[2]?.[0] ?? ''
expect(modelPrompt).toContain('3D Model: This asset has an orthogonal 4-view composite image')
expect(modelPrompt).toContain(
'Front view at top-left, Right side view at top-right, Back view at bottom-left, Left side view at bottom-right',
)
})
})
@@ -1187,43 +1170,6 @@ describe('Agent Database Activities Integration', () => {
expect((rootEntry as any)?.details?.thread).toBeUndefined()
})
it('should set media position to degree for 3D asset comments', async () => {
const asset3d = await prisma.asset.create({
data: {
name: 'robot.glb',
type: 'file',
status: 'processed',
mediaType: 'model/gltf-binary',
media: { proxyType: '3d' } as unknown as PrismaJson.MediaInfo,
projectId: project.id,
},
})
const comment3d = await prisma.assetComment.create({
data: {
assetId: asset3d.id,
message: 'Nice angle',
creatorId: user.id,
second: 0.5, // 45°
},
})
const sessionId = await initializeAgentSessionActivity({
teamId: team.id,
agentId: 'test-agent-id',
userCommentId: comment3d.id,
userId: user.id,
})
const storage = new DatabaseSessionStorage(sessionId)
const pathEntries = await storage.getPathToRoot(comment3d.id)
const entry = pathEntries.find((e) => e.id === comment3d.id)
expect(entry).toBeDefined()
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- test entry position parsing
expect((entry as any)?.details?.position).toEqual({ type: 'degree', degree: 45 })
})
it('should return user name and role for team member', async () => {
const info = await getUserTeamInfoActivity({
userId: user.id,
@@ -2159,83 +2105,5 @@ describe('Agent Database Activities Integration', () => {
expect(systemPromptArg).toContain('<thread id="..." reply_count="..." />')
expect(systemPromptArg).toContain('read_thread')
})
it('agentChatActivity injects # 3D Model Inspection into systemPrompt', async () => {
const user = await prisma.user.create({
data: { name: 'User_3d_Prompt', email: `prompt-3d-${Date.now()}@example.com` },
})
const team = await prisma.team.create({
data: { name: 'Team_3d_Prompt_' + Date.now() },
})
const project = await prisma.project.create({
data: { name: 'Project_3d_Prompt', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'robot.glb',
type: 'file',
status: 'processed',
mediaType: 'model/gltf-binary',
media: { proxyType: '3d' } as unknown as PrismaJson.MediaInfo,
projectId: project.id,
},
})
const comment = await prisma.assetComment.create({
data: {
assetId: asset.id,
creatorId: user.id,
message: 'Check this 3d model',
},
})
const mockSession = {
id: 'mock-session-id',
subscribe: vi.fn(),
getEntries: vi.fn().mockResolvedValue([]),
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
}
const mockHarness = {
subscribe: vi.fn(),
prompt: vi.fn().mockResolvedValue({
content: [{ type: 'text', text: 'Response' }],
usage: { input: 10, output: 20 },
}),
}
vi.mocked(piAgent.createAgentSession).mockResolvedValue({
session: mockSession as unknown as Session<DatabaseSessionMetadata>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Mock AgentHarness instance for activity test
harness: mockHarness as unknown as AgentHarness<any, any, any, any>,
})
const context = {
agent: { id: 'agent-1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } },
dbProviders: [],
teamSkills: [],
allowedDomains: [],
} as unknown as AgentExecutionContext
await agentChatActivity({
teamId: team.id,
agentId: 'agent-1',
message: 'Hello',
imageUrls: [],
projectId: project.id,
folderId: asset.id,
assetId: asset.id,
sessionId: 'mock-session-id',
userCommentId: comment.id,
userId: user.id,
context,
})
const lastCall = vi.mocked(piAgent.createAgentSession).mock.calls.at(-1)
const systemPromptArg = lastCall?.[0].systemPrompt as string
expect(systemPromptArg).toContain('# 3D Model Inspection')
expect(systemPromptArg).toContain('media_type="3d"')
expect(systemPromptArg).toContain('config3d')
expect(systemPromptArg).toContain('<position type="degree" degree="..." />')
})
})
})
+3 -21
View File
@@ -21,7 +21,6 @@ import {
import { aiUsageService } from '@shumai/core/src/ai-usage/ai-usage'
import { quotaService, QuotaExceededError } from '@shumai/core/src/quota/quota-service'
import { getProxyType } from '@shumai/core/src/utils/mime'
import { secondToDegree } from '@shumai/core/src/utils/model3d'
import {
UpdateAssetMetadataRequest,
type ShumaiMessageContext,
@@ -180,8 +179,6 @@ User messages may contain a <context> block detailing the user, active asset loc
systemPrompt += `\n\n# Comment Threads\nWhen operating in comment mode, previous top-level messages in the conversation history may contain a <thread id="..." reply_count="..." /> tag indicating an earlier discussion thread with replies. If a user's question refers to or depends on earlier comments or discussions, you can use the 'read_thread' tool with the thread ID to inspect all replies in that thread.`
}
systemPrompt += `\n\n# 3D Model Inspection\nWhen interacting with 3D model assets (media_type="3d"), you can visually inspect the asset using 'read_asset'. Calling 'read_asset' with config3d: null (or config3d: {}) returns an orthogonal 4-view composite image (Front at top-left, Right side at top-right, Back at bottom-left, Left side at bottom-right). If a <position type="degree" degree="..." /> tag is present or a specific angle is discussed, pass 'config3d: { degree: ... }' (integer 0, 15, 30, ..., 345) to inspect that view angle. If an <annotation id="..." /> tag is present on a 3D asset, pass 'annotationId' to inspect the angle with the user's visual markup drawings overlaid.`
if (agent.type === 'autofill') {
systemPrompt += `\n\n# Autofill Instructions\nWhen performing metadata autofill, inspect the asset content using the 'read_asset' tool. If 'read_asset' fails or returns an error, do not autofill any metadata and report to the user directly. Do not try anything fancy, for example downloading the file or using python/ffmpeg to extract content.`
}
@@ -567,7 +564,6 @@ export async function autofillAiActivity(params: AutofillAiParams) {
const proxyType = getProxyType(params.mediaType, params.assetName)
const isVideoOrAudio = proxyType === 'video' || proxyType === 'audio'
const isPdf = proxyType === 'pdf'
const is3d = proxyType === '3d'
if (params.duration !== undefined && params.duration > 0 && (!proxyType || isVideoOrAudio)) {
promptLines.push(
@@ -579,16 +575,11 @@ export async function autofillAiActivity(params: AutofillAiParams) {
`- Document pages: ${params.pageCount}. Recommended inspection: call read_asset with docConfig: { mode: "pages", startPage: 1, endPage: ${Math.min(params.pageCount, 20)} } or mode: "text".`,
)
}
if (is3d) {
promptLines.push(
'- 3D Model: This asset has an orthogonal 4-view composite image (2x2 grid showing Front view at top-left, Right side view at top-right, Back view at bottom-left, Left side view at bottom-right). Call read_asset to inspect the 4 views.',
)
}
promptLines.push(
'',
'Instructions:',
`1. Call the "read_asset" tool with assetId: "${params.assetId || ''}" to inspect the asset content (use imageConfig, videoConfig, or docConfig according to the media type; for 3D assets, call read_asset directly to inspect the 4-view composite image).`,
`1. Call the "read_asset" tool with assetId: "${params.assetId || ''}" to inspect the asset content (use imageConfig, videoConfig, or docConfig according to the media type).`,
'2. After analyzing the retrieved content, call the "autofill_metadata" tool to provide the extracted metadata values.',
'3. If "read_asset" fails or returns an error, do not autofill any metadata and report to the user directly. Do not try anything fancy, for example downloading the file or using python/ffmpeg to extract content.',
)
@@ -843,9 +834,7 @@ export async function initializeAgentSessionActivity(params: {
let position: ShumaiMediaPosition | undefined = undefined
if (c.second !== null && c.second !== undefined) {
if (proxyType === '3d') {
position = { type: 'degree', degree: secondToDegree(c.second) }
} else if (proxyType === 'pdf') {
if (proxyType === 'pdf') {
position = { type: 'page', page: Math.round(c.second) }
} else {
position = { type: 'time', seconds: c.second }
@@ -863,14 +852,7 @@ export async function initializeAgentSessionActivity(params: {
id: att.asset.id,
name: att.asset.name,
type: att.asset.type,
mediaType: attProxyType as
| 'image'
| 'video'
| 'pdf'
| 'audio'
| '3d'
| 'other'
| undefined,
mediaType: attProxyType as 'image' | 'video' | 'pdf' | 'audio' | 'other' | undefined,
mimeType: att.asset.mediaType || undefined,
})
}
@@ -350,24 +350,5 @@ describe('serializeContextToXml', () => {
'<context>\n <annotation id="test&lt;id&gt;&amp;&quot;123&quot;" />\n</context>',
)
})
it('serializes position type="degree" with integer degree attribute without seconds', () => {
const context: ShumaiMessageContext = {
currentAsset: {
id: 'ast_3d',
name: 'robot.glb',
type: 'file',
mediaType: '3d',
path: 'robot.glb',
},
position: {
type: 'degree',
degree: 45,
},
}
expect(serializeContextToXml(context)).toBe(
'<context>\n <current_asset id="ast_3d" name="robot.glb" type="file" media_type="3d" path="robot.glb" />\n <position type="degree" degree="45" />\n</context>',
)
})
})
})
@@ -4,7 +4,6 @@ import { setupTestDbHooks } from '@shumai/db/test'
import { resolveAnnotationsById } from './annotation-resolver'
import { DatabaseSessionStorage } from '../database-session-storage'
import type { SessionTreeEntry } from '@earendil-works/pi-agent-core'
import { degreeToSecond } from '@shumai/core/src/utils/model3d'
describe('resolveAnnotationsById', () => {
setupTestDbHooks()
@@ -211,89 +210,6 @@ describe('resolveAnnotationsById', () => {
])
})
it('resolves annotations and degree position timestamp from 1-on-1 chat AgentSessionEntry for 3D assets', async () => {
const user = await prisma.user.create({
data: { name: 'User 3D', email: 'user3d@test.com', password: 'pw' },
})
const team = await prisma.team.create({
data: { name: 'Team 3D' },
})
const project = await prisma.project.create({
data: { name: 'Project 3D', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'robot.glb',
type: 'file',
projectId: project.id,
status: 'uploaded',
},
})
const agentUser = await prisma.user.create({
data: { name: 'Agent 3D', email: 'agent3d@example.com', type: 'agent' },
})
const agent = await prisma.agent.create({
data: {
id: agentUser.id,
teamId: team.id,
type: 'chat',
config: { provider: 'test-provider', model: 'test-model' },
},
})
const storage = await DatabaseSessionStorage.create({
agentId: agent.id,
userId: user.id,
assetId: asset.id,
})
storage.currentMessageContext = {
currentAsset: {
id: asset.id,
name: asset.name,
type: 'file',
path: asset.name,
},
position: { type: 'degree', degree: 45 },
annotation: true,
annotations: [
{
type: 'rectangle',
x: 10,
y: 20,
width: 30,
height: 40,
},
],
}
const userEntry: SessionTreeEntry = {
type: 'message',
id: '01JTEST3DENTRY123456789',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'user',
content: 'Check markup at 45 degrees',
timestamp: Date.now(),
},
}
await storage.appendEntry(userEntry)
const result = await resolveAnnotationsById(asset.id, '01JTEST3DENTRY123456789')
expect(result.timestamp).toBeCloseTo(degreeToSecond(45))
expect(result.annotations).toEqual([
{
type: 'rectangle',
x: 10,
y: 20,
width: 30,
height: 40,
},
])
})
it('throws an error when AgentSessionEntry belongs to a different asset', async () => {
const user = await prisma.user.create({
data: { name: 'User', email: 'user3@test.com', password: 'pw' },
@@ -1,6 +1,5 @@
import { prisma } from '@shumai/db'
import type { ShumaiMessageContext } from '@shumai/dtos'
import { degreeToSecond } from '@shumai/core/src/utils/model3d'
export async function resolveAnnotationsById(
assetId: string,
@@ -45,14 +44,7 @@ export async function resolveAnnotationsById(
const list = details?.annotations
const annotations =
Array.isArray(list) && list.length > 0 ? (list as unknown as PrismaJson.AnnotationList) : null
let timestamp: number | null = null
if (details?.position?.type === 'time') {
timestamp = details.position.seconds
} else if (details?.position?.type === 'degree') {
timestamp = degreeToSecond(details.position.degree)
} else if (details?.position?.type === 'page') {
timestamp = details.position.page
}
const timestamp = details?.position?.type === 'time' ? details.position.seconds : null
return { annotations, timestamp }
}
-471
View File
@@ -11,7 +11,6 @@ import { s3Service } from '@shumai/core/src/s3/s3'
import { workflowService } from '@shumai/workflow-core'
import { authzService } from '@shumai/core/src/authz/authz'
import * as annotationResolver from './annotation-resolver'
import { degreeToSecond } from '@shumai/core/src/utils/model3d'
vi.mock('@shumai/db', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/db')>()
@@ -212,476 +211,6 @@ describe('readAssetTool', () => {
})
})
describe('3D Assets', () => {
it('should read 3D asset 4-views image and return image with quadrant layout description', async () => {
vi.mocked(authzService.hasPermission).mockResolvedValue()
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'model-1',
name: 'robot.glb',
mediaType: 'model/gltf-binary',
storageKey: { key: 'raw/robot.glb' },
media: {
proxyType: '3d',
imageTranscodes: [{ key: 'proxy/views.webp' }],
},
} as unknown as Asset)
vi.mocked(s3Service.getObject).mockResolvedValue({
buffer: Buffer.from('fake-views-bytes'),
contentType: 'image/webp',
} as unknown as { buffer: Buffer; contentType: string })
const tool = createReadAssetTool('user-1')
const result = await tool.execute('call-3d', {
assetId: 'model-1',
annotationId: null,
imageConfig: null,
videoConfig: null,
docConfig: null,
})
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'Read',
type: 'asset',
id: 'model-1',
})
expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'proxy/views.webp')
const textItem = result.content[0] as { type: 'text'; text: string }
const imageItem = result.content[1] as { type: 'image'; data: string; mimeType: string }
expect(textItem.text).toContain('Orthogonal 4-view composite image')
expect(textItem.text).toContain('Top-Left quadrant: Front view (0°)')
expect(textItem.text).toContain('Top-Right quadrant: Right side view (90°)')
expect(textItem.text).toContain('Bottom-Left quadrant: Back view (180°)')
expect(textItem.text).toContain('Bottom-Right quadrant: Left side view (270°)')
expect(imageItem.type).toBe('image')
expect(imageItem.data).toBe(Buffer.from('fake-views-bytes').toString('base64'))
expect(result.details.key).toBe('proxy/views.webp')
})
it('should support s3KeyOnly mode for 3D assets', async () => {
vi.mocked(authzService.hasPermission).mockResolvedValue()
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'model-1',
name: 'robot.glb',
mediaType: 'model/gltf-binary',
media: {
proxyType: '3d',
imageTranscodes: [{ key: 'proxy/views.webp' }],
},
} as unknown as Asset)
const tool = createReadAssetTool('user-1')
const result = await tool.execute('call-3d-s3', {
assetId: 'model-1',
annotationId: null,
s3KeyOnly: true,
imageConfig: null,
videoConfig: null,
docConfig: null,
})
expect(result.content).toHaveLength(1)
const textItem = result.content[0] as { type: 'text'; text: string }
expect(textItem.text).toContain('proxy/views.webp')
expect(textItem.text).toContain('Front view (0°)')
expect(result.details.key).toBe('proxy/views.webp')
})
it('should throw error if videoConfig is passed for 3D assets', async () => {
vi.mocked(authzService.hasPermission).mockResolvedValue()
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'model-1',
name: 'robot.glb',
mediaType: 'model/gltf-binary',
media: {
proxyType: '3d',
imageTranscodes: [{ key: 'proxy/views.webp' }],
},
} as unknown as Asset)
const tool = createReadAssetTool('user-1')
await expect(
tool.execute('call-3d-err', {
assetId: 'model-1',
annotationId: null,
imageConfig: null,
videoConfig: { start: 0, end: 4, count: 4 },
docConfig: null,
}),
).rejects.toThrow(
"To inspect specific angles pass 'config3d: { degree: ... }'; do not pass videoConfig",
)
})
it('should throw error if 3D asset imageTranscodes is missing when overview is requested', async () => {
vi.mocked(authzService.hasPermission).mockResolvedValue()
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'model-1',
name: 'robot.glb',
mediaType: 'model/gltf-binary',
media: {
proxyType: '3d',
imageTranscodes: [],
},
} as unknown as Asset)
const tool = createReadAssetTool('user-1')
await expect(
tool.execute('call-3d-err2', {
assetId: 'model-1',
annotationId: null,
imageConfig: null,
videoConfig: null,
docConfig: null,
}),
).rejects.toThrow('4-views image (views.webp) is missing')
})
it('should extract specific turntable frame when config3d.degree is provided', async () => {
vi.mocked(authzService.hasPermission).mockResolvedValue()
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'model-1',
name: 'robot.glb',
mediaType: 'model/gltf-binary',
projectId: 'proj-1',
media: {
proxyType: '3d',
videoTranscodes: [{ key: 'proxy/turntable.mp4' }],
imageTranscodes: [{ key: 'proxy/views.webp' }],
},
} as unknown as Asset)
vi.mocked(prisma.workflowTask.create).mockResolvedValue({
id: 'task-shot-3d',
} as unknown as WorkflowTask)
vi.mocked(workflowService.executeWait).mockResolvedValue({
id: 'task-shot-3d',
status: WorkflowTaskStatus.completed,
output: {
screenshots: [{ key: 'proxy/shot-45.webp', timestamp: 0.5833 }],
},
} as unknown as WorkflowTask)
vi.mocked(s3Service.getObject).mockResolvedValue({
buffer: Buffer.from('fake-shot-45-bytes'),
contentType: 'image/webp',
} as unknown as { buffer: Buffer; contentType: string })
const tool = createReadAssetTool('user-1')
const result = await tool.execute('call-3d-degree', {
assetId: 'model-1',
annotationId: null,
config3d: { degree: 45 },
imageConfig: null,
videoConfig: null,
docConfig: null,
})
expect(prisma.workflowTask.create).toHaveBeenCalledWith({
data: expect.objectContaining({
type: WorkflowTaskType.transcode_screenshot,
assetId: 'model-1',
payload: {
projectId: 'proj-1',
screenshot: {
start: expect.any(Number),
end: expect.any(Number),
count: 1,
commentTimestamp: expect.any(Number),
annotations: undefined,
},
},
}),
})
const textItem = result.content[0] as { type: 'text'; text: string }
const imageItem = result.content[1] as { type: 'image'; data: string; mimeType: string }
expect(textItem.text).toContain('view at 45°:')
expect(imageItem.data).toBe(Buffer.from('fake-shot-45-bytes').toString('base64'))
expect(result.details.key).toBe('proxy/shot-45.webp')
})
it('should throw error when config3d.degree is not a multiple of 15 or out of range', async () => {
vi.mocked(authzService.hasPermission).mockResolvedValue()
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'model-1',
name: 'robot.glb',
mediaType: 'model/gltf-binary',
media: {
proxyType: '3d',
videoTranscodes: [{ key: 'proxy/turntable.mp4' }],
},
} as unknown as Asset)
const tool = createReadAssetTool('user-1')
await expect(
tool.execute('call-3d-invalid-deg', {
assetId: 'model-1',
annotationId: null,
config3d: { degree: 40 },
imageConfig: null,
videoConfig: null,
docConfig: null,
}),
).rejects.toThrow('Invalid turntable degree: 40')
await expect(
tool.execute('call-3d-out-of-range', {
assetId: 'model-1',
annotationId: null,
config3d: { degree: 360 },
imageConfig: null,
videoConfig: null,
docConfig: null,
}),
).rejects.toThrow('Invalid turntable degree: 360')
})
it('should extract frame with overlaid markups when annotationId is provided on 3D asset', async () => {
vi.mocked(authzService.hasPermission).mockResolvedValue()
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'model-1',
name: 'robot.glb',
mediaType: 'model/gltf-binary',
projectId: 'proj-1',
media: {
proxyType: '3d',
videoTranscodes: [{ key: 'proxy/turntable.mp4' }],
},
} as unknown as Asset)
vi.spyOn(annotationResolver, 'resolveAnnotationsById').mockResolvedValue({
annotations: [
{
type: 'freehand',
color: '#ff0000',
points: [
[0, 0],
[10, 10],
],
},
],
timestamp: 0.5, // 0.5s = 45°
})
vi.mocked(prisma.workflowTask.create).mockResolvedValue({
id: 'task-shot-ann',
} as unknown as WorkflowTask)
vi.mocked(workflowService.executeWait).mockResolvedValue({
id: 'task-shot-ann',
status: WorkflowTaskStatus.completed,
output: {
screenshots: [{ key: 'proxy/shot-annotated.webp', timestamp: 0.5 }],
},
} as unknown as WorkflowTask)
vi.mocked(s3Service.getObject).mockResolvedValue({
buffer: Buffer.from('fake-shot-ann-bytes'),
contentType: 'image/webp',
} as unknown as { buffer: Buffer; contentType: string })
const tool = createReadAssetTool('user-1')
const result = await tool.execute('call-3d-ann', {
assetId: 'model-1',
annotationId: 'comm-1',
config3d: null,
imageConfig: null,
videoConfig: null,
docConfig: null,
})
expect(prisma.workflowTask.create).toHaveBeenCalledWith({
data: expect.objectContaining({
type: WorkflowTaskType.transcode_screenshot,
assetId: 'model-1',
payload: {
projectId: 'proj-1',
screenshot: {
start: 0.5,
end: 0.5,
count: 1,
commentTimestamp: 0.5,
annotations: [
{
type: 'freehand',
color: '#ff0000',
points: [
[0, 0],
[10, 10],
],
},
],
},
},
}),
})
const textItem = result.content[0] as { type: 'text'; text: string }
expect(textItem.text).toContain('view at 45° with visual markups overlaid:')
expect(result.details.key).toBe('proxy/shot-annotated.webp')
})
it('should extract turntable frame at resolved degree angle for 3D session annotations', async () => {
vi.mocked(authzService.hasPermission).mockResolvedValue()
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'model-1',
name: 'robot.glb',
mediaType: 'model/gltf-binary',
projectId: 'proj-1',
media: {
proxyType: '3d',
videoTranscodes: [{ key: 'proxy/turntable.mp4' }],
},
} as unknown as Asset)
const expectedTime = degreeToSecond(90)
vi.spyOn(annotationResolver, 'resolveAnnotationsById').mockResolvedValue({
annotations: [
{
type: 'box',
color: '#00ff00',
points: [
[10, 20],
[40, 60],
],
},
],
timestamp: expectedTime,
})
vi.mocked(prisma.workflowTask.create).mockResolvedValue({
id: 'task-shot-3d-session',
} as unknown as WorkflowTask)
vi.mocked(workflowService.executeWait).mockResolvedValue({
id: 'task-shot-3d-session',
status: WorkflowTaskStatus.completed,
output: {
screenshots: [{ key: 'proxy/shot-annotated-90.webp', timestamp: expectedTime }],
},
} as unknown as WorkflowTask)
vi.mocked(s3Service.getObject).mockResolvedValue({
buffer: Buffer.from('fake-shot-90-bytes'),
contentType: 'image/webp',
} as unknown as { buffer: Buffer; contentType: string })
const tool = createReadAssetTool('user-1')
const result = await tool.execute('call-3d-session-ann', {
assetId: 'model-1',
annotationId: 'session-entry-1',
config3d: null,
imageConfig: null,
videoConfig: null,
docConfig: null,
})
expect(prisma.workflowTask.create).toHaveBeenCalledWith({
data: expect.objectContaining({
type: WorkflowTaskType.transcode_screenshot,
assetId: 'model-1',
payload: {
projectId: 'proj-1',
screenshot: {
start: expectedTime,
end: expectedTime,
count: 1,
commentTimestamp: expectedTime,
annotations: [
{
type: 'box',
color: '#00ff00',
points: [
[10, 20],
[40, 60],
],
},
],
},
},
}),
})
const textItem = result.content[0] as { type: 'text'; text: string }
expect(textItem.text).toContain('view at 90° with visual markups overlaid:')
expect(result.details.key).toBe('proxy/shot-annotated-90.webp')
})
it('should throw error if config3d.degree conflicts with annotation angle', async () => {
vi.mocked(authzService.hasPermission).mockResolvedValue()
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'model-1',
name: 'robot.glb',
mediaType: 'model/gltf-binary',
projectId: 'proj-1',
media: {
proxyType: '3d',
videoTranscodes: [{ key: 'proxy/turntable.mp4' }],
},
} as unknown as Asset)
vi.spyOn(annotationResolver, 'resolveAnnotationsById').mockResolvedValue({
annotations: [
{
type: 'box',
color: '#ff0000',
points: [
[0, 0],
[10, 10],
],
},
],
timestamp: 0.5, // 45°
})
const tool = createReadAssetTool('user-1')
await expect(
tool.execute('call-3d-conflict', {
assetId: 'model-1',
annotationId: 'comm-1',
config3d: { degree: 90 }, // Conflicts with 45°
imageConfig: null,
videoConfig: null,
docConfig: null,
}),
).rejects.toThrow(
'Annotation "comm-1" was drawn at 45°, but degree 90° was specified. Do not pass a conflicting degree with annotationId.',
)
})
it('should throw error if 3D asset turntable video is missing when angle inspection is requested', async () => {
vi.mocked(authzService.hasPermission).mockResolvedValue()
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'model-1',
name: 'robot.glb',
mediaType: 'model/gltf-binary',
media: {
proxyType: '3d',
videoTranscodes: [],
},
} as unknown as Asset)
const tool = createReadAssetTool('user-1')
await expect(
tool.execute('call-3d-missing-turntable', {
assetId: 'model-1',
annotationId: null,
config3d: { degree: 45 },
imageConfig: null,
videoConfig: null,
docConfig: null,
}),
).rejects.toThrow('turntable video (turntable.mp4) is missing')
})
})
describe('Video Assets', () => {
it('should throw error if videoConfig is missing for video assets', async () => {
vi.mocked(authzService.hasPermission).mockResolvedValue()
+3 -237
View File
@@ -7,12 +7,6 @@ import { workflowService } from '@shumai/workflow-core'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { resolveAnnotationsById } from './annotation-resolver'
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
import { is3dModel } from '@shumai/core/src/utils/mime'
import {
isValidTurntableDegree,
secondToDegree,
degreeToSecond,
} from '@shumai/core/src/utils/model3d'
export const readAssetSchema = Type.Object(
{
@@ -43,31 +37,6 @@ export const readAssetSchema = Type.Object(
),
Type.Null(),
]),
config3d: Type.Optional(
Type.Union([
Type.Object(
{
degree: Type.Optional(
Type.Union([
Type.Integer({
minimum: 0,
maximum: 345,
description:
'Turntable rotation degree (integer: 0, 15, 30, ..., 345 in 15° increments) to inspect a specific angle of a 3D model. Leave null/omitted to view the 4-view composite overview.',
}),
Type.Null(),
]),
),
},
{
additionalProperties: false,
description:
'Configuration for 3D model assets. Pass null if inspecting another asset type. Optionally pass degree to inspect a specific turntable angle, or leave null/omitted to view the 4-view composite overview.',
},
),
Type.Null(),
]),
),
videoConfig: Type.Union([
Type.Object(
{
@@ -198,12 +167,12 @@ export function createReadAssetTool(
label: 'Read Asset',
description:
'Inspects and reads the content of an asset in the workspace. ' +
'Supports visual analysis for images, 3D models (overview or specific degree angle), video frame extraction, PDF page rendering, and direct text reading for text/markdown files. ' +
'Pass assetId, and provide the specific config (imageConfig, config3d, videoConfig, or docConfig) while setting unused configs to null. ' +
'Supports visual analysis for images, video frame extraction, PDF page rendering, and direct text reading for text/markdown files. ' +
'Pass assetId, and provide the specific config (imageConfig, videoConfig, or docConfig) while setting unused configs to null. ' +
'Optionally provide annotationId to view visual markups drawn on the asset.',
parameters: readAssetSchema,
execute: async (_toolCallId, params) => {
const { assetId, annotationId, s3KeyOnly, config3d, videoConfig, docConfig } = params
const { assetId, annotationId, s3KeyOnly, videoConfig, docConfig } = params
if (agentType === 'autofill' && !userId) {
if (!targetAssetId) {
@@ -274,209 +243,6 @@ export function createReadAssetTool(
const filename = asset.name?.toLowerCase() || ''
const bucket = process.env.S3_BUCKET || 'shumai'
// ----------------------------------------------------------------------
// Branch 0: 3D Assets (Orthogonal 4-View Composite Image or Degree Angle)
// ----------------------------------------------------------------------
const is3d = proxyType === '3d' || is3dModel(mediaType, filename)
if (is3d) {
if (videoConfig) {
throw new Error(
`Asset ${asset.id} is a 3D model. To inspect specific angles pass 'config3d: { degree: ... }'; do not pass videoConfig.`,
)
}
if (config3d?.degree !== undefined && config3d?.degree !== null) {
if (!isValidTurntableDegree(config3d.degree)) {
throw new Error(
`Invalid turntable degree: ${config3d.degree}. Degree must be an integer multiple of 15 between 0 and 345 (e.g. 0, 15, 30, 45, ..., 345).`,
)
}
}
let annotations: PrismaJson.AnnotationList | null = null
let commentTimestamp: number | null = null
if (annotationId) {
const resolved = await resolveAnnotationsById(asset.id, annotationId)
annotations = resolved.annotations
commentTimestamp = resolved.timestamp
if (commentTimestamp !== null && commentTimestamp !== undefined) {
const commentDegree = secondToDegree(commentTimestamp)
if (
config3d?.degree !== undefined &&
config3d?.degree !== null &&
config3d.degree !== commentDegree
) {
throw new Error(
`Annotation "${annotationId}" was drawn at ${commentDegree}°, but degree ${config3d.degree}° was specified. Do not pass a conflicting degree with annotationId.`,
)
}
}
}
if ((config3d?.degree !== undefined && config3d?.degree !== null) || annotationId) {
if (!mediaInfo?.videoTranscodes || mediaInfo.videoTranscodes.length === 0) {
throw new Error(
`Asset ${asset.id} is a 3D model, but its turntable video (turntable.mp4) is missing.`,
)
}
let targetDegree: number
let targetSecond: number
if (config3d?.degree !== undefined && config3d?.degree !== null) {
targetDegree = config3d.degree
targetSecond = degreeToSecond(targetDegree)
} else {
targetSecond =
commentTimestamp !== null && commentTimestamp !== undefined ? commentTimestamp : 0
targetDegree = secondToDegree(targetSecond)
}
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
projectId: asset.projectId || 'none',
type: WorkflowTaskType.transcode_screenshot,
status: WorkflowTaskStatus.pending,
payload: {
projectId: asset.projectId || 'none',
screenshot: {
start: targetSecond,
end: targetSecond,
count: 1,
commentTimestamp: targetSecond,
annotations: annotations ?? undefined,
},
},
},
})
const completedTask = await workflowService.executeWait(task)
// 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
if (!screenshots || screenshots.length === 0) {
throw new Error(
`Failed to extract 3D turntable frame for asset ${asset.id} at ${targetDegree}°.`,
)
}
const shotKey = screenshots[0].key
const downloadUrl = await s3Service.presign(
bucket,
shotKey,
'GET',
true,
asset.name || undefined,
)
const content: Array<TextContent | ImageContent> = []
const hasMarkup = Boolean(annotations && annotations.length > 0)
const textDescription = hasMarkup
? `3D asset "${asset.name}" (ID: ${asset.id}, S3 Key: "${shotKey}") view at ${targetDegree}° with visual markups overlaid:`
: `3D asset "${asset.name}" (ID: ${asset.id}, S3 Key: "${shotKey}") view at ${targetDegree}°:`
if (s3KeyOnly) {
content.push({
type: 'text',
text: textDescription,
})
} else {
const { buffer, contentType } = await s3Service.getObject(bucket, shotKey)
const actualMimeType =
contentType && contentType !== 'application/octet-stream' ? contentType : 'image/webp'
content.push({
type: 'text',
text: textDescription,
})
content.push({
type: 'image',
data: buffer.toString('base64'),
mimeType: actualMimeType,
})
}
return {
content,
details: {
assetId: asset.id,
name: asset.name,
mediaType: asset.mediaType,
key: shotKey,
downloadUrl,
sourceKeys: [shotKey],
},
}
}
if (!mediaInfo?.imageTranscodes || mediaInfo.imageTranscodes.length === 0) {
throw new Error(
`Asset ${asset.id} is a 3D model, but its 4-views image (views.webp) is missing.`,
)
}
const mediaKey = mediaInfo.imageTranscodes[0].key
if (!mediaKey) {
throw new Error(`Asset ${asset.id} is a 3D model, but its 4-views image key is missing.`)
}
const keyToUse = mediaKey
const mimeType = 'image/webp'
const downloadUrl = await s3Service.presign(
bucket,
keyToUse,
'GET',
true,
asset.name || undefined,
)
const content: Array<TextContent | ImageContent> = []
const textDescription = [
`3D asset "${asset.name}" (ID: ${asset.id}, MIME: ${mimeType}, S3 Key: "${keyToUse}"):`,
'Orthogonal 4-view composite image (2x2 grid across 360° rotation):',
'- Top-Left quadrant: Front view (0°)',
'- Top-Right quadrant: Right side view (90°)',
'- Bottom-Left quadrant: Back view (180°)',
'- Bottom-Right quadrant: Left side view (270°)',
].join('\n')
if (s3KeyOnly) {
content.push({
type: 'text',
text: textDescription,
})
} else {
const { buffer, contentType } = await s3Service.getObject(bucket, keyToUse)
const actualMimeType =
contentType && contentType !== 'application/octet-stream' ? contentType : mimeType
content.push({
type: 'text',
text: textDescription,
})
content.push({
type: 'image',
data: buffer.toString('base64'),
mimeType: actualMimeType,
})
}
return {
content,
details: {
assetId: asset.id,
name: asset.name,
mediaType: asset.mediaType,
key: keyToUse,
downloadUrl,
sourceKeys: [keyToUse],
},
}
}
// ----------------------------------------------------------------------
// Branch 1: Image Assets
// ----------------------------------------------------------------------
@@ -129,42 +129,6 @@ describe('createReadThreadTool', () => {
expect(textContent).toContain('- [Ai Agent] (id: reply-1, has_markup: false): Agent answer')
})
it('should format 3d asset comment timestamps as degree: X°', async () => {
vi.mocked(prisma.assetComment.findUnique).mockResolvedValue({
id: 'root-3d',
message: 'Notice this angle',
creator: { name: 'Alice' },
second: 0.5,
annotation: [{ type: 'box' }],
asset: {
media: { proxyType: '3d' },
mediaType: 'model/gltf-binary',
name: 'robot.glb',
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
vi.mocked(prisma.assetComment.findMany).mockResolvedValue([
{
id: 'reply-3d-1',
message: 'Looking at back side',
creator: { name: 'Bob' },
second: 2.0,
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
] as any)
const tool = createReadThreadTool()
const result = await tool.execute('call-3d', { threadId: 'root-3d' })
const textContent = (result.content[0] as { text: string }).text
expect(textContent).toContain(
'Thread Root [Alice] (id: root-3d, degree: 45°, has_markup: true): Notice this angle',
)
expect(textContent).toContain(
'- [Bob] (id: reply-3d-1, degree: 180°, has_markup: false): Looking at back side',
)
})
it('should describe threadId parameter as referencing <thread id="..." /> in <context>', () => {
const tool = createReadThreadTool()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
+9 -26
View File
@@ -1,8 +1,6 @@
import { prisma } from '@shumai/db'
import { Type } from 'typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { secondToDegree } from '@shumai/core/src/utils/model3d'
import { getProxyType } from '@shumai/core/src/utils/mime'
const readThreadSchema = Type.Object({
threadId: Type.String({
@@ -11,21 +9,14 @@ const readThreadSchema = Type.Object({
}),
})
function formatCommentMeta(
c: {
id: string
second?: number | null
annotation?: unknown
},
proxyType?: string,
): string {
function formatCommentMeta(c: {
id: string
second?: number | null
annotation?: unknown
}): string {
const parts = [`id: ${c.id}`]
if (c.second !== null && c.second !== undefined) {
if (proxyType === '3d') {
parts.push(`degree: ${secondToDegree(c.second)}°`)
} else {
parts.push(`time: ${c.second}s`)
}
parts.push(`time: ${c.second}s`)
}
const hasMarkup = Boolean(c.annotation && Array.isArray(c.annotation) && c.annotation.length > 0)
parts.push(`has_markup: ${hasMarkup}`)
@@ -43,10 +34,7 @@ export const createReadThreadTool = (): AgentTool<
execute: async (_toolCallId, params) => {
const rootComment = await prisma.assetComment.findUnique({
where: { id: params.threadId },
include: {
creator: true,
asset: { select: { media: true, mediaType: true, name: true } },
},
include: { creator: true },
})
if (!rootComment) {
@@ -73,14 +61,9 @@ export const createReadThreadTool = (): AgentTool<
include: { creator: true },
})
const proxyType =
(rootComment.asset?.media as PrismaJson.MediaInfo | null)?.proxyType ||
getProxyType(rootComment.asset?.mediaType, rootComment.asset?.name) ||
undefined
const isRootAgent = rootComment.creator?.type === 'agent' || rootComment.sessionId !== null
const rootAuthor = rootComment.creator?.name || (isRootAgent ? 'Ai Agent' : 'User')
const rootMeta = formatCommentMeta(rootComment, proxyType)
const rootMeta = formatCommentMeta(rootComment)
let output = `Thread Root [${rootAuthor}] ${rootMeta}: ${rootComment.message || ''}\n\nReplies (${replies.length}):`
if (replies.length === 0) {
@@ -89,7 +72,7 @@ export const createReadThreadTool = (): AgentTool<
for (const reply of replies) {
const isAgent = reply.creator?.type === 'agent' || reply.sessionId !== null
const author = reply.creator?.name || (isAgent ? 'Ai Agent' : 'User')
const replyMeta = formatCommentMeta(reply, proxyType)
const replyMeta = formatCommentMeta(reply)
output += `\n- [${author}] ${replyMeta}: ${reply.message || ''}`
}
}
@@ -806,89 +806,4 @@ describe('Agent Chat Workflow', () => {
}),
)
})
it('should format mediaPosition as degree for 3D assets in 1-on-1 chat', async () => {
mockActivities.getAssetActivity.mockResolvedValue({
id: 'a-3d',
project: { teamId: 't1' },
type: 'file',
name: 'model.glb',
mediaType: 'model/gltf-binary',
media: { proxyType: '3d' },
parentId: null,
})
const task = await prisma.workflowTask.create({
data: {
type: 'chat',
status: 'pending',
assetId: 'a-3d',
payload: {
projectId: 'p1',
agent: {
agentId: 'b1',
prompt: 'Look at this angle',
sessionId: 'session-3d-1',
second: 0.5, // 0.5s turntable time = 45°
},
},
},
})
await agentChat(task)
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
expect.objectContaining({
messageContext: expect.objectContaining({
position: { type: 'degree', degree: 45 },
}),
}),
)
})
it('should format mediaPosition as degree for 3D assets in comment mode', async () => {
mockActivities.getAssetActivity.mockResolvedValue({
id: 'a-3d',
project: { teamId: 't1' },
type: 'file',
name: 'model.glb',
mediaType: 'model/gltf-binary',
media: { proxyType: '3d' },
parentId: null,
})
mockActivities.getCommentActivity.mockResolvedValue({
id: 'comment-3d-1',
creatorId: 'user-c1',
message: 'Look at the back',
replyToId: null,
second: 2.0, // 2.0s = 180°
attachments: [],
})
const task = await prisma.workflowTask.create({
data: {
type: 'chat',
status: 'pending',
assetId: 'a-3d',
payload: {
projectId: 'p1',
agent: {
agentId: 'b1',
userCommentId: 'comment-3d-1',
},
},
},
})
await agentChat(task)
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
expect.objectContaining({
messageContext: expect.objectContaining({
position: { type: 'degree', degree: 180 },
}),
}),
)
})
})
+1 -4
View File
@@ -8,7 +8,6 @@ import type {
ShumaiMediaPosition,
} from '@shumai/dtos'
import { getProxyType } from '@shumai/core/src/utils/mime'
import { secondToDegree } from '@shumai/core/src/utils/model3d'
export async function agentChat(task: WorkflowTask): Promise<void> {
const {
@@ -274,9 +273,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
// Build position
let mediaPosition: ShumaiMediaPosition | undefined
if (commentTimestamp !== undefined && commentTimestamp !== null) {
if (proxyType === '3d') {
mediaPosition = { type: 'degree', degree: secondToDegree(commentTimestamp) }
} else if (proxyType === 'pdf') {
if (proxyType === 'pdf') {
mediaPosition = { type: 'page', page: Math.round(commentTimestamp) }
} else {
mediaPosition = { type: 'time', seconds: commentTimestamp }
@@ -211,68 +211,6 @@ describe('Agent Embedding Workflow', () => {
})
})
it('should run agent embedding workflow successfully for 3D asset using 4-views image', async () => {
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: {
id: 'model-1',
mediaType: 'model/gltf-binary',
storageKey: { key: 'raw/model.glb' },
media: {
proxyType: '3d',
imageTranscodes: [{ key: 'files/views.webp', format: 'webp' }],
},
},
chunkDuration: 60.0,
chunkOverlap: 5.0,
})
const task = await prisma.workflowTask.create({
data: {
type: 'ai_embedding',
status: 'pending',
assetId: 'model-1',
teamId: 't1',
},
})
await agentEmbeddingMedia(task)
expect(mockActivities.generateImageEmbeddingActivity).toHaveBeenCalledWith({
teamId: 't1',
assetKey: 'files/views.webp',
mediaType: 'image/webp',
})
})
it('should reject 3D asset for embeddings if imageTranscodes is missing', async () => {
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: {
id: 'model-1',
mediaType: 'model/gltf-binary',
storageKey: { key: 'raw/model.glb' },
media: {
proxyType: '3d',
imageTranscodes: [],
},
},
})
const task = await prisma.workflowTask.create({
data: {
type: 'ai_embedding',
status: 'pending',
assetId: 'model-1',
teamId: 't1',
},
})
await expect(agentEmbeddingMedia(task)).rejects.toThrow(
'unsupported media type for embeddings: model/gltf-binary',
)
})
it('should run agent embedding workflow successfully for video in chunks', async () => {
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
@@ -70,10 +70,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { asset, chunkDuration, chunkOverlap } = context as any
const mediaInfo = asset.media as PrismaJson.MediaInfo | null
const is3dWithViews =
mediaInfo?.proxyType === '3d' && (mediaInfo.imageTranscodes?.length ?? 0) > 0
const isImage = asset.mediaType?.startsWith('image/') || is3dWithViews
const isImage = asset.mediaType?.startsWith('image/')
const isVideo = asset.mediaType?.startsWith('video/')
if (!isImage && !isVideo) {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/api",
"version": "0.5.2",
"version": "0.5.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+3 -21
View File
@@ -42,8 +42,7 @@ async function applyWatermarkToAssetMedia(
password?: string,
): Promise<AssetInfo> {
if (!asset.media) return asset
if (asset.proxyType !== 'video' && asset.proxyType !== 'image' && asset.proxyType !== '3d')
return asset
if (asset.proxyType !== 'video' && asset.proxyType !== 'image') return asset
const updatedMedia = { ...asset.media }
const bucket = process.env.S3_BUCKET || 'shumai'
@@ -59,27 +58,10 @@ async function applyWatermarkToAssetMedia(
height: vt.height ?? 0,
size: 0,
hdr: vt.hdr,
resolution: vt.resolution,
})),
)
: []
if (watermarkMedia?.videoTranscodes && watermarkMedia.videoTranscodes.length > 0) {
if (updatedMedia.videoPreview) {
const watermarkedKey =
watermarkMedia.videoPreview?.key || watermarkMedia.videoTranscodes[0]?.key
if (watermarkedKey) {
updatedMedia.videoPreview = {
...updatedMedia.videoPreview,
key: watermarkedKey,
url: await s3Service.presign(bucket, watermarkedKey, 'GET'),
}
}
}
} else {
delete updatedMedia.videoPreview
}
updatedMedia.imageTranscodes =
watermarkMedia?.imageTranscodes && watermarkMedia.imageTranscodes.length > 0
? await Promise.all(
@@ -272,11 +254,11 @@ const route = app
let asset = await assetService.getAsset({ assetId: fileId })
// Only video/image/3d assets are subject to watermark protection; skip the
// Only video/image assets are subject to watermark protection; skip the
// watermark lookup entirely for other media types (pdf, audio, ...).
if (
shareLink.watermarkConfigId &&
(asset.proxyType === 'video' || asset.proxyType === 'image' || asset.proxyType === '3d')
(asset.proxyType === 'video' || asset.proxyType === 'image')
) {
const targetAssetId = await assetService.resolveLatestVersionId(fileId)
const wfMap = await watermarkService.getCompletedWatermarkMediaMap(
-115
View File
@@ -513,121 +513,6 @@ describe('Share API', () => {
expect(body.media.hls).toBeUndefined()
})
test('serves watermarked turntable video for a 3d asset when watermark enabled and completed', async () => {
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithWatermark)
const asset3d = {
id: 'file1',
name: 'model.glb',
sizeByte: 1024,
fileCount: 0,
type: 'file',
status: 'processed',
proxyType: '3d',
media: {
proxyType: '3d',
videoPreview: {
url: 'http://s3/unwatermarked-turntable.mp4',
key: 'files/turntable.mp4',
},
videoTranscodes: [
{
id: 'orig-turntable',
url: 'http://s3/unwatermarked-turntable.mp4',
key: 'files/turntable.mp4',
width: 1080,
height: 1080,
},
],
original: { key: 'files/model.glb' },
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any
vi.spyOn(assetService, 'getAsset').mockResolvedValue(asset3d)
vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(
new Map([
[
'file1',
watermarkMediaInfo({
proxyType: '3d',
videoTranscodes: [
{
key: 'files/watermarked-turntable.mp4',
width: 1080,
height: 1080,
resolution: '1080p',
},
],
videoPreview: { key: 'files/watermarked-turntable.mp4', width: 1080, height: 1080 },
}),
],
]),
)
const res = await app.request('/shares/share1/files/file1', {
method: 'GET',
headers: { 'x-share-password': 'pass' },
})
expect(res.status).toBe(200)
const body = await res.json()
expect(body.media.videoTranscodes).toEqual([
{
id: 'files/watermarked-turntable.mp4',
url: 'http://s3/presigned',
key: 'files/watermarked-turntable.mp4',
width: 1080,
height: 1080,
size: 0,
resolution: '1080p',
},
])
expect(body.media.videoPreview?.url).toBe('http://s3/presigned')
expect(body.media.videoPreview?.key).toBe('files/watermarked-turntable.mp4')
})
test('strips videoPreview url and serves empty videoTranscodes for a 3d asset while watermark is in flight', async () => {
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithWatermark)
const asset3d = {
id: 'file1',
name: 'model.glb',
sizeByte: 1024,
fileCount: 0,
type: 'file',
status: 'processed',
proxyType: '3d',
media: {
proxyType: '3d',
videoPreview: {
url: 'http://s3/unwatermarked-turntable.mp4',
key: 'files/turntable.mp4',
},
videoTranscodes: [
{
id: 'orig-turntable',
url: 'http://s3/unwatermarked-turntable.mp4',
key: 'files/turntable.mp4',
width: 1080,
height: 1080,
},
],
original: { key: 'files/model.glb' },
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any
vi.spyOn(assetService, 'getAsset').mockResolvedValue(asset3d)
vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map())
const res = await app.request('/shares/share1/files/file1', {
method: 'GET',
headers: { 'x-share-password': 'pass' },
})
expect(res.status).toBe(200)
const body = await res.json()
expect(body.media.videoTranscodes).toEqual([])
expect(body.media.videoPreview?.url).toBeUndefined()
})
test('leaves non-video/image media untouched when watermark enabled', async () => {
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithWatermark)
vi.spyOn(assetService, 'getAsset').mockResolvedValue({
-109
View File
@@ -60,14 +60,6 @@ vi.mock('@shumai/core/src/turntable/turntable', () => ({
},
}))
vi.mock('@shumai/core/src/gotenberg/gotenberg', () => ({
gotenbergService: {
getSettings: vi.fn(),
updateSettings: vi.fn(),
testConnection: vi.fn(),
},
}))
describe('team api', () => {
const app = new Hono().use('*', authMiddleware).route('/', teamRoute)
let mockCreateTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
@@ -756,106 +748,5 @@ describe('team api', () => {
expect(data.ok).toBe(true)
expect(data.blender).toBe('5.2.0')
})
it('GET /teams/:teamId/gotenberg-settings returns gotenberg settings', async () => {
const { gotenbergService } = await import('@shumai/core/src/gotenberg/gotenberg')
vi.mocked(gotenbergService.getSettings).mockResolvedValue({
url: 'http://localhost:3000',
username: 'user',
hasPassword: true,
isEnvConfigured: false,
})
const res = await app.request('/teams/t1/gotenberg-settings')
expect(res.status).toBe(200)
const data = await res.json()
expect(data).toEqual({
url: 'http://localhost:3000',
username: 'user',
hasPassword: true,
isEnvConfigured: false,
})
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
permission: Permission.Read,
type: ResourceType.Team,
id: 't1',
}),
)
})
it('PUT /teams/:teamId/gotenberg-settings updates settings when not env configured', async () => {
const { gotenbergService } = await import('@shumai/core/src/gotenberg/gotenberg')
vi.mocked(gotenbergService.updateSettings).mockResolvedValue({
url: 'http://custom:3000',
username: 'newuser',
hasPassword: true,
isEnvConfigured: false,
})
const res = await app.request('/teams/t1/gotenberg-settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
url: 'http://custom:3000',
username: 'newuser',
password: 'secretpassword',
}),
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.url).toBe('http://custom:3000')
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
permission: Permission.Admin,
type: ResourceType.Team,
id: 't1',
}),
)
})
it('PUT /teams/:teamId/gotenberg-settings returns 400 when env configured', async () => {
const { gotenbergService } = await import('@shumai/core/src/gotenberg/gotenberg')
vi.mocked(gotenbergService.updateSettings).mockRejectedValue(
new Error(
'Gotenberg settings are configured via environment variables and cannot be edited',
),
)
const res = await app.request('/teams/t1/gotenberg-settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
url: 'http://custom:3000',
}),
})
expect(res.status).toBe(400)
const data = await res.json()
expect(data.message).toContain('configured via environment variables')
})
it('POST /teams/:teamId/gotenberg-settings/test tests connection', async () => {
const { gotenbergService } = await import('@shumai/core/src/gotenberg/gotenberg')
vi.mocked(gotenbergService.testConnection).mockResolvedValue({
ok: true,
version: '8.3.0',
})
const res = await app.request('/teams/t1/gotenberg-settings/test', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
url: 'http://custom:3000',
}),
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.ok).toBe(true)
expect(data.version).toBe('8.3.0')
})
})
})
-59
View File
@@ -11,7 +11,6 @@ import {
listMembersQuerySchema,
updateSandboxSettingsRequestSchema,
updateTurntableSettingsRequestSchema,
updateGotenbergSettingsRequestSchema,
updateMeRequestSchema,
updateTeamMemberRoleRequestSchema,
createApiTokenRequestSchema,
@@ -26,7 +25,6 @@ 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 { turntableService } from '@shumai/core/src/turntable/turntable'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { NotificationType } from '@shumai/db'
import type { Prisma } from '@shumai/db'
@@ -326,63 +324,6 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(res)
},
)
.get('/teams/:teamId/gotenberg-settings', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
})
const settings = await gotenbergService.getSettings(teamId)
return c.json(settings)
})
.put(
'/teams/:teamId/gotenberg-settings',
zValidator('json', updateGotenbergSettingsRequestSchema),
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,
})
try {
const settings = await gotenbergService.updateSettings(teamId, req)
return c.json(settings)
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
return c.json({ message }, 400)
}
},
)
.post(
'/teams/:teamId/gotenberg-settings/test',
zValidator('json', updateGotenbergSettingsRequestSchema.partial()),
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 res = await gotenbergService.testConnection(req, teamId)
return c.json(res)
},
)
.get('/teams/:teamId/user-metadata', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/core",
"version": "0.5.2",
"version": "0.5.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
@@ -2,12 +2,9 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import * as fs from 'fs'
import * as path from 'path'
import * as os from 'os'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { GotenbergService } from './gotenberg'
describe('GotenbergService', () => {
setupTestDbHooks()
const originalEnv = process.env
let tmpDir: string
let testFilePath: string
@@ -219,148 +216,4 @@ describe('GotenbergService', () => {
expect(indexHtmlText).toContain('{{ toHTML "file.md" }}')
})
})
describe('team settings & fallback', () => {
it('resolves config from team settings when env is not set', async () => {
delete process.env.GOTENBERG_URL
const team = await prisma.team.create({
data: {
name: 'Gotenberg Team',
settings: {
gotenberg: {
url: 'http://custom-gotenberg:4000',
username: 'team-user',
password: 'team-password',
},
},
},
})
const service = new GotenbergService()
const config = await service.resolveConfig(team.id)
expect(config).toEqual({
url: 'http://custom-gotenberg:4000',
username: 'team-user',
password: 'team-password',
isEnv: false,
})
})
it('prioritizes environment variables over team settings', async () => {
process.env.GOTENBERG_URL = 'http://env-gotenberg:3000'
const team = await prisma.team.create({
data: {
name: 'Gotenberg Team',
settings: {
gotenberg: {
url: 'http://custom-gotenberg:4000',
},
},
},
})
const service = new GotenbergService()
const config = await service.resolveConfig(team.id)
expect(config.url).toBe('http://env-gotenberg:3000')
expect(config.isEnv).toBe(true)
})
it('getSettings returns masked settings response', async () => {
delete process.env.GOTENBERG_URL
const team = await prisma.team.create({
data: {
name: 'Gotenberg Team',
settings: {
gotenberg: {
url: 'http://custom-gotenberg:4000',
username: 'team-user',
password: 'team-password',
},
},
},
})
const service = new GotenbergService()
const settings = await service.getSettings(team.id)
expect(settings).toEqual({
url: 'http://custom-gotenberg:4000',
username: 'team-user',
hasPassword: true,
isEnvConfigured: false,
})
})
it('updateSettings updates team settings and rejects edits when env is set', async () => {
delete process.env.GOTENBERG_URL
const team = await prisma.team.create({
data: { name: 'Gotenberg Team' },
})
const service = new GotenbergService()
const updated = await service.updateSettings(team.id, {
url: 'http://new-gotenberg:3000',
username: 'admin',
password: 'secret-password',
})
expect(updated.url).toBe('http://new-gotenberg:3000')
expect(updated.username).toBe('admin')
expect(updated.hasPassword).toBe(true)
// When env is set, reject update
process.env.GOTENBERG_URL = 'http://env-gotenberg:3000'
await expect(service.updateSettings(team.id, { url: 'http://another:3000' })).rejects.toThrow(
'Gotenberg settings are configured via environment variables and cannot be edited',
)
})
})
describe('testConnection', () => {
it('returns error when url is empty and no team settings exist', async () => {
delete process.env.GOTENBERG_URL
const service = new GotenbergService()
const result = await service.testConnection({})
expect(result.ok).toBe(false)
expect(result.error).toBe('URL is required')
})
it('successfully connects to /health and enriches with /version', async () => {
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (url) => {
const urlStr = String(url)
if (urlStr.endsWith('/health')) {
return { ok: true, status: 200 } as Response
}
if (urlStr.endsWith('/version')) {
return {
ok: true,
status: 200,
json: async () => ({ version: '8.3.0' }),
} as Response
}
return { ok: false, status: 404 } as Response
})
const service = new GotenbergService()
const result = await service.testConnection({
url: 'http://gotenberg.local:3000',
username: 'test-user',
password: 'test-pass',
})
expect(result.ok).toBe(true)
expect(result.version).toBe('8.3.0')
expect(fetchSpy).toHaveBeenCalledWith(
'http://gotenberg.local:3000/health',
expect.objectContaining({
method: 'GET',
headers: expect.objectContaining({
Authorization: expect.stringMatching(/^Basic /),
}),
}),
)
})
})
})
+29 -126
View File
@@ -1,135 +1,40 @@
import * as fs from 'fs'
import type { GotenbergSettingsResponse, UpdateGotenbergSettingsRequest } from '@shumai/dtos'
import {
IntegrationDefinition,
resolveIntegrationConfig,
getIntegrationSettings,
updateIntegrationSettings,
resolveTestConnectionConfig,
getIntegrationBasicAuthHeader,
ResolvedIntegrationConfig,
} from '@shumai/core/src/integrations/helper'
export const GOTENBERG_INTEGRATION_DEF: IntegrationDefinition<'gotenberg'> = {
name: 'Gotenberg',
settingsKey: 'gotenberg',
envKeys: {
url: ['GOTENBERG_URL'],
username: ['GOTENBERG_BASIC_AUTH_USERNAME'],
password: ['GOTENBERG_BASIC_AUTH_PASSWORD'],
},
}
export interface GotenbergConvertOptions {
landscape?: boolean
teamId?: string
}
export class GotenbergService {
async resolveConfig(teamId?: string): Promise<ResolvedIntegrationConfig> {
return resolveIntegrationConfig(GOTENBERG_INTEGRATION_DEF, teamId)
private getUrl(): string | undefined {
const url = process.env.GOTENBERG_URL?.trim()
return url ? url.replace(/\/+$/, '') : undefined
}
private getAuthHeader(config: { username?: string; password?: string }): string | undefined {
return getIntegrationBasicAuthHeader(config)
}
private getAuthHeader(): string | undefined {
const username = process.env.GOTENBERG_BASIC_AUTH_USERNAME
const password = process.env.GOTENBERG_BASIC_AUTH_PASSWORD
async getSettings(teamId: string): Promise<GotenbergSettingsResponse> {
return getIntegrationSettings(GOTENBERG_INTEGRATION_DEF, teamId)
}
async updateSettings(
teamId: string,
req: UpdateGotenbergSettingsRequest,
): Promise<GotenbergSettingsResponse> {
return updateIntegrationSettings(GOTENBERG_INTEGRATION_DEF, teamId, req)
}
async testConnection(
config?: UpdateGotenbergSettingsRequest,
teamId?: string,
): Promise<{ ok: boolean; version?: string; error?: string }> {
const target = await resolveTestConnectionConfig(GOTENBERG_INTEGRATION_DEF, config, teamId)
if (!target.resolvedUrl) {
return { ok: false, error: 'URL is required' }
}
const cleanUrl = target.resolvedUrl.replace(/\/+$/, '')
try {
const headers: Record<string, string> = {}
const authHeader = this.getAuthHeader({
username: target.resolvedUsername,
password: target.resolvedPassword,
})
if (authHeader) {
headers['Authorization'] = authHeader
}
const response = await fetch(`${cleanUrl}/health`, {
method: 'GET',
headers,
signal: AbortSignal.timeout(5000),
})
if (!response.ok) {
const errText = await response.text().catch(() => '')
return {
ok: false,
error: `Health check returned status ${response.status}: ${errText || response.statusText}`,
}
}
// Optionally try /version to obtain version string
let version: string | undefined
try {
const versionRes = await fetch(`${cleanUrl}/version`, {
method: 'GET',
headers,
signal: AbortSignal.timeout(2000),
})
if (versionRes.ok) {
const vData = (await versionRes.json().catch(() => null)) as
| { version?: string }
| string
| null
if (vData && typeof vData === 'object' && 'version' in vData) {
version = String(vData.version)
} else if (typeof vData === 'string') {
version = vData
}
}
} catch {
// Version endpoint is optional in some Gotenberg versions
}
return {
ok: true,
version,
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
return {
ok: false,
error: msg,
}
if (username && password) {
const credentials = Buffer.from(`${username}:${password}`).toString('base64')
return `Basic ${credentials}`
}
return undefined
}
async isAvailable(teamId?: string): Promise<boolean> {
const config = await this.resolveConfig(teamId)
if (!config.url) {
async isAvailable(): Promise<boolean> {
const baseUrl = this.getUrl()
if (!baseUrl) {
return false
}
try {
const headers: Record<string, string> = {}
const authHeader = this.getAuthHeader(config)
const authHeader = this.getAuthHeader()
if (authHeader) {
headers['Authorization'] = authHeader
}
const response = await fetch(`${config.url}/health`, {
const response = await fetch(`${baseUrl}/health`, {
method: 'GET',
headers,
signal: AbortSignal.timeout(3000),
@@ -145,11 +50,9 @@ export class GotenbergService {
filePath: string,
filename: string,
options: GotenbergConvertOptions = {},
teamId?: string,
): Promise<Buffer> {
const effectiveTeamId = teamId ?? options.teamId
const config = await this.resolveConfig(effectiveTeamId)
if (!config.url) {
const baseUrl = this.getUrl()
if (!baseUrl) {
throw new Error('Gotenberg URL is not configured.')
}
@@ -162,12 +65,12 @@ export class GotenbergService {
}
const headers: Record<string, string> = {}
const authHeader = this.getAuthHeader(config)
const authHeader = this.getAuthHeader()
if (authHeader) {
headers['Authorization'] = authHeader
}
const response = await fetch(`${config.url}/forms/libreoffice/convert`, {
const response = await fetch(`${baseUrl}/forms/libreoffice/convert`, {
method: 'POST',
headers,
body: formData,
@@ -185,9 +88,9 @@ export class GotenbergService {
return Buffer.from(arrayBuffer)
}
async convertHtmlToPdf(filePath: string, filename: string, teamId?: string): Promise<Buffer> {
const config = await this.resolveConfig(teamId)
if (!config.url) {
async convertHtmlToPdf(filePath: string, filename: string): Promise<Buffer> {
const baseUrl = this.getUrl()
if (!baseUrl) {
throw new Error('Gotenberg URL is not configured.')
}
@@ -200,12 +103,12 @@ export class GotenbergService {
formData.append('files', new Blob([fileBytes]), targetFilename)
const headers: Record<string, string> = {}
const authHeader = this.getAuthHeader(config)
const authHeader = this.getAuthHeader()
if (authHeader) {
headers['Authorization'] = authHeader
}
const response = await fetch(`${config.url}/forms/chromium/convert/html`, {
const response = await fetch(`${baseUrl}/forms/chromium/convert/html`, {
method: 'POST',
headers,
body: formData,
@@ -223,9 +126,9 @@ export class GotenbergService {
return Buffer.from(arrayBuffer)
}
async convertMarkdownToPdf(filePath: string, filename: string, teamId?: string): Promise<Buffer> {
const config = await this.resolveConfig(teamId)
if (!config.url) {
async convertMarkdownToPdf(filePath: string, filename: string): Promise<Buffer> {
const baseUrl = this.getUrl()
if (!baseUrl) {
throw new Error('Gotenberg URL is not configured.')
}
@@ -248,12 +151,12 @@ export class GotenbergService {
formData.append('files', new Blob([fileBytes]), mdFilename)
const headers: Record<string, string> = {}
const authHeader = this.getAuthHeader(config)
const authHeader = this.getAuthHeader()
if (authHeader) {
headers['Authorization'] = authHeader
}
const response = await fetch(`${config.url}/forms/chromium/convert/markdown`, {
const response = await fetch(`${baseUrl}/forms/chromium/convert/markdown`, {
method: 'POST',
headers,
body: formData,
-2
View File
@@ -32,5 +32,3 @@ export * from './media-generation/media-generation'
export * from './sandbox'
export * from './asset/comments-export'
export * from './turntable/turntable'
export * from './utils/model3d'
export * from './integrations/helper'
@@ -1,271 +0,0 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import {
IntegrationDefinition,
resolveIntegrationConfig,
getIntegrationSettings,
updateIntegrationSettings,
resolveTestConnectionConfig,
getIntegrationBasicAuthHeader,
} from './helper'
const TEST_INTEGRATION_DEF: IntegrationDefinition<'turntable'> = {
name: 'TestIntegration',
settingsKey: 'turntable',
envKeys: {
url: ['TEST_INTEGRATION_URL', 'FALLBACK_INTEGRATION_URL'],
username: ['TEST_INTEGRATION_USERNAME'],
password: ['TEST_INTEGRATION_PASSWORD'],
},
}
describe('Integration Config Helper', () => {
setupTestDbHooks()
const originalEnv = process.env
beforeEach(() => {
process.env = { ...originalEnv }
delete process.env.TEST_INTEGRATION_URL
delete process.env.FALLBACK_INTEGRATION_URL
delete process.env.TEST_INTEGRATION_USERNAME
delete process.env.TEST_INTEGRATION_PASSWORD
})
afterEach(() => {
process.env = originalEnv
})
describe('resolveIntegrationConfig', () => {
it('prioritizes environment variables over database settings', async () => {
const team = await prisma.team.create({
data: {
name: 'Test Team',
settings: {
turntable: {
url: 'http://db-server:1234',
username: 'db-user',
password: 'db-password',
},
},
},
})
process.env.TEST_INTEGRATION_URL = 'http://env-server:5678/'
process.env.TEST_INTEGRATION_USERNAME = 'env-user'
process.env.TEST_INTEGRATION_PASSWORD = 'env-pass'
const config = await resolveIntegrationConfig(TEST_INTEGRATION_DEF, team.id)
expect(config).toEqual({
url: 'http://env-server:5678',
username: 'env-user',
password: 'env-pass',
isEnv: true,
})
})
it('falls back to second env key if first is missing', async () => {
process.env.FALLBACK_INTEGRATION_URL = 'http://fallback-server:8080'
const config = await resolveIntegrationConfig(TEST_INTEGRATION_DEF)
expect(config.url).toBe('http://fallback-server:8080')
expect(config.isEnv).toBe(true)
})
it('reads from team settings when environment variables are not set', async () => {
const team = await prisma.team.create({
data: {
name: 'Test Team',
settings: {
turntable: {
url: 'http://db-server:1234/',
username: 'db-user',
password: 'db-password',
},
},
},
})
const config = await resolveIntegrationConfig(TEST_INTEGRATION_DEF, team.id)
expect(config).toEqual({
url: 'http://db-server:1234',
username: 'db-user',
password: 'db-password',
isEnv: false,
})
})
it('returns isEnv: false and undefined fields when neither env nor DB are set', async () => {
const team = await prisma.team.create({
data: { name: 'Empty Team' },
})
const config = await resolveIntegrationConfig(TEST_INTEGRATION_DEF, team.id)
expect(config).toEqual({
isEnv: false,
})
})
})
describe('getIntegrationSettings', () => {
it('returns safe response masking password', async () => {
const team = await prisma.team.create({
data: {
name: 'Test Team',
settings: {
turntable: {
url: 'http://db-server:1234',
username: 'db-user',
password: 'db-password',
},
},
},
})
const res = await getIntegrationSettings(TEST_INTEGRATION_DEF, team.id)
expect(res).toEqual({
url: 'http://db-server:1234',
username: 'db-user',
hasPassword: true,
isEnvConfigured: false,
})
})
})
describe('updateIntegrationSettings', () => {
it('throws error when environment variable is configured', async () => {
const team = await prisma.team.create({
data: { name: 'Test Team' },
})
process.env.TEST_INTEGRATION_URL = 'http://env-server:5678'
await expect(
updateIntegrationSettings(TEST_INTEGRATION_DEF, team.id, {
url: 'http://new-url:1234',
}),
).rejects.toThrow(
'TestIntegration settings are configured via environment variables and cannot be edited',
)
})
it('updates settings and preserves existing password when not supplied', async () => {
const team = await prisma.team.create({
data: {
name: 'Test Team',
settings: {
turntable: {
url: 'http://original:1234',
username: 'original-user',
password: 'secret-password',
},
},
},
})
const res = await updateIntegrationSettings(TEST_INTEGRATION_DEF, team.id, {
url: 'http://updated:5678/',
username: 'new-user',
})
expect(res).toEqual({
url: 'http://updated:5678',
username: 'new-user',
hasPassword: true,
isEnvConfigured: false,
})
const config = await resolveIntegrationConfig(TEST_INTEGRATION_DEF, team.id)
expect(config.password).toBe('secret-password')
})
it('clears settings in database when URL is empty or whitespace', async () => {
const team = await prisma.team.create({
data: {
name: 'Test Team',
settings: {
turntable: {
url: 'http://to-be-cleared:1234',
username: 'user',
password: 'pwd',
},
},
},
})
const res = await updateIntegrationSettings(TEST_INTEGRATION_DEF, team.id, {
url: ' ',
})
expect(res).toEqual({
url: undefined,
username: undefined,
hasPassword: false,
isEnvConfigured: false,
})
const updatedTeam = await prisma.team.findUnique({
where: { id: team.id },
})
// Check that turntable is removed from team settings
expect((updatedTeam?.settings as Record<string, unknown>)?.turntable).toBeUndefined()
})
})
describe('resolveTestConnectionConfig', () => {
it('uses provided credentials directly when supplied', async () => {
const target = await resolveTestConnectionConfig(TEST_INTEGRATION_DEF, {
url: 'http://direct:1234',
username: 'direct-user',
password: 'direct-password',
})
expect(target).toEqual({
resolvedUrl: 'http://direct:1234',
resolvedUsername: 'direct-user',
resolvedPassword: 'direct-password',
})
})
it('falls back to saved database settings when testing with partial inputs', async () => {
const team = await prisma.team.create({
data: {
name: 'Test Team',
settings: {
turntable: {
url: 'http://db:1234',
username: 'db-user',
password: 'db-password',
},
},
},
})
const target = await resolveTestConnectionConfig(
TEST_INTEGRATION_DEF,
{ url: 'http://new-url:9999' },
team.id,
)
expect(target).toEqual({
resolvedUrl: 'http://new-url:9999',
resolvedUsername: 'db-user',
resolvedPassword: 'db-password',
})
})
})
describe('getIntegrationBasicAuthHeader', () => {
it('generates base64 basic auth header when username and password are provided', () => {
const header = getIntegrationBasicAuthHeader({ username: 'admin', password: 'secret' })
expect(header).toBe(`Basic ${Buffer.from('admin:secret').toString('base64')}`)
})
it('returns undefined when username or password is missing', () => {
expect(getIntegrationBasicAuthHeader({ username: 'admin' })).toBeUndefined()
expect(getIntegrationBasicAuthHeader({ password: 'secret' })).toBeUndefined()
expect(getIntegrationBasicAuthHeader({})).toBeUndefined()
})
})
})
-188
View File
@@ -1,188 +0,0 @@
import { prisma } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
import { logger } from '@shumai/core/src/logger'
export interface IntegrationEnvKeys {
url: string[]
username?: string[]
password?: string[]
}
export interface IntegrationDefinition<TKey extends keyof PrismaJson.Settings> {
name: string
settingsKey: TKey
envKeys: IntegrationEnvKeys
}
export interface ResolvedIntegrationConfig {
url?: string
username?: string
password?: string
isEnv: boolean
}
export interface IntegrationSettingsResponse {
url?: string
username?: string
hasPassword: boolean
isEnvConfigured: boolean
}
export interface UpdateIntegrationSettingsRequest {
url?: string
username?: string
password?: string
}
function getFirstEnvValue(keys?: string[]): string | undefined {
if (!keys) return undefined
for (const key of keys) {
const val = process.env[key]?.trim()
if (val) return val
}
return undefined
}
export async function resolveIntegrationConfig<TKey extends keyof PrismaJson.Settings>(
def: IntegrationDefinition<TKey>,
teamId?: string,
): Promise<ResolvedIntegrationConfig> {
const envUrl = getFirstEnvValue(def.envKeys.url)
const envUsername = getFirstEnvValue(def.envKeys.username)
const envPassword = getFirstEnvValue(def.envKeys.password)
if (envUrl) {
return {
url: envUrl.replace(/\/+$/, ''),
username: envUsername || undefined,
password: envPassword || undefined,
isEnv: true,
}
}
if (teamId) {
try {
const team = await prisma.team.findUnique({
where: { id: teamId },
select: { settings: true },
})
const teamSettings = team?.settings as PrismaJson.Settings | null
const serviceSettings = teamSettings?.[def.settingsKey] as
| { url?: string; username?: string; password?: string }
| undefined
if (serviceSettings?.url?.trim()) {
return {
url: serviceSettings.url.trim().replace(/\/+$/, ''),
username: serviceSettings.username?.trim() || undefined,
password: serviceSettings.password?.trim() || undefined,
isEnv: false,
}
}
} catch (err) {
logger.error({ err, teamId }, `Failed to load team ${def.name} settings`)
}
}
return {
isEnv: false,
}
}
export async function getIntegrationSettings<TKey extends keyof PrismaJson.Settings>(
def: IntegrationDefinition<TKey>,
teamId: string,
): Promise<IntegrationSettingsResponse> {
const config = await resolveIntegrationConfig(def, teamId)
return {
url: config.url,
username: config.username,
hasPassword: Boolean(config.password),
isEnvConfigured: config.isEnv,
}
}
export async function updateIntegrationSettings<TKey extends keyof PrismaJson.Settings>(
def: IntegrationDefinition<TKey>,
teamId: string,
req: UpdateIntegrationSettingsRequest,
): Promise<IntegrationSettingsResponse> {
const currentConfig = await resolveIntegrationConfig(def, teamId)
if (currentConfig.isEnv) {
throw new Error(
`${def.name} settings are configured via environment variables and cannot be edited`,
)
}
const team = await prisma.team.findUnique({
where: { id: teamId },
select: { settings: true },
})
const settings = { ...((team?.settings || {}) as PrismaJson.Settings) }
const prevSettings = (settings[def.settingsKey] || {}) as {
url?: string
username?: string
password?: string
}
const trimmedUrl = req.url?.trim()
if (!trimmedUrl) {
// If URL is empty/unset, clear the integration settings
delete settings[def.settingsKey]
} else {
const updatedServiceSettings: { url: string; username?: string; password?: string } = {
url: trimmedUrl.replace(/\/+$/, ''),
username:
req.username !== undefined ? req.username.trim() || undefined : prevSettings.username,
password: req.password !== undefined ? req.password : prevSettings.password,
}
settings[def.settingsKey] = updatedServiceSettings as unknown as PrismaJson.Settings[TKey]
}
await prisma.team.update({
where: { id: teamId },
data: { settings },
})
return getIntegrationSettings(def, teamId)
}
export async function resolveTestConnectionConfig<TKey extends keyof PrismaJson.Settings>(
def: IntegrationDefinition<TKey>,
config?: UpdateIntegrationSettingsRequest,
teamId?: string,
): Promise<{ resolvedUrl?: string; resolvedUsername?: string; resolvedPassword?: string }> {
let resolvedUrl = config?.url?.trim()
let resolvedUsername = config?.username?.trim()
let resolvedPassword = config?.password
if (teamId && (!resolvedUrl || resolvedPassword === undefined)) {
const savedConfig = await resolveIntegrationConfig(def, teamId)
if (!resolvedUrl) {
resolvedUrl = savedConfig.url
}
if (!resolvedUsername && savedConfig.username) {
resolvedUsername = savedConfig.username
}
if (resolvedPassword === undefined) {
resolvedPassword = savedConfig.password
}
}
return {
resolvedUrl,
resolvedUsername,
resolvedPassword,
}
}
export function getIntegrationBasicAuthHeader(config: {
username?: string
password?: string
}): string | undefined {
if (config.username && config.password) {
const credentials = Buffer.from(`${config.username}:${config.password}`).toString('base64')
return `Basic ${credentials}`
}
return undefined
}
-18
View File
@@ -381,12 +381,6 @@ describe('TeamService', () => {
url: undefined,
username: undefined,
},
gotenberg: {
hasPassword: false,
isEnvConfigured: false,
url: undefined,
username: undefined,
},
appearance: { hideAgent: false },
})
@@ -410,12 +404,6 @@ describe('TeamService', () => {
url: undefined,
username: undefined,
},
gotenberg: {
hasPassword: false,
isEnvConfigured: false,
url: undefined,
username: undefined,
},
appearance: { hideAgent: false },
})
@@ -448,12 +436,6 @@ describe('TeamService', () => {
url: undefined,
username: undefined,
},
gotenberg: {
hasPassword: false,
isEnvConfigured: false,
url: undefined,
username: undefined,
},
appearance: { hideAgent: true },
semanticSearchEnabled: false,
})
-2
View File
@@ -8,7 +8,6 @@ import { HTTPException } from 'hono/http-exception'
import { getAllowedAgentRoles } from '@shumai/core/src/agent/permissions'
import { sandboxService } from '@shumai/core/src/sandbox/sandbox-service'
import { turntableService } from '@shumai/core/src/turntable/turntable'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import {
ServiceCreateTeamRequest,
ServiceGetUserTeamsRequest,
@@ -346,7 +345,6 @@ export class TeamService {
}
settings.turntable = await turntableService.getSettings(teamId)
settings.gotenberg = await gotenbergService.getSettings(teamId)
return settings
}
@@ -25,11 +25,6 @@ export interface RawPreviewResult {
width: number
height: number
orientation?: number
/**
* True when the file is already upright (dcraw_emu output), so downstream sharp must not
* auto-orient it even though `orientation` is undefined.
*/
orientationApplied?: boolean
rawWidth?: number
rawHeight?: number
}
@@ -387,7 +382,6 @@ export async function extractAndValidateRawPreview(
previewPath: decoded.previewPath,
cleanup: decoded.cleanup,
orientation: decoded.orientation,
orientationApplied: true,
rawWidth: decoded.rawWidth,
rawHeight: decoded.rawHeight,
...dims,
@@ -1,252 +0,0 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import * as fs from 'fs'
import * as path from 'path'
import sharp from 'sharp'
import { transcodeService } from './transcode'
// Only the storage layer is mocked: these tests run the real sharp pipeline end to end.
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
downloadToFile: vi.fn(),
putObject: vi.fn(),
resolveInput: vi.fn(),
presign: vi.fn(),
},
}))
// Only the RAW preview extraction is replaced, so the RAW branch of transcodeImage can be driven
// with a prepared file (the dcraw_emu fallback result) without ExifTool or dcraw_emu installed.
const extractRawMock = vi.hoisted(() => vi.fn())
vi.mock('./raw-extract', async (importOriginal) => ({
...(await importOriginal<typeof import('./raw-extract')>()),
extractAndValidateRawPreview: extractRawMock,
}))
// Windows keeps cached files open, which would make the temp dir cleanup fail with EBUSY.
sharp.cache(false)
type Corner = 'TL' | 'TR' | 'BL' | 'BR'
// Stored (sensor) pixels are landscape. Each quadrant has its own color so the direction of the
// rotation or flip can be read back from the corners of the output.
const STORED_WIDTH = 64
const STORED_HEIGHT = 48
const QUADRANT_COLORS: Record<Corner, [number, number, number]> = {
TL: [220, 30, 30], // red
TR: [30, 200, 30], // green
BL: [30, 30, 220], // blue
BR: [230, 230, 30], // yellow
}
/**
* For each EXIF orientation: the displayed size and which stored corner ends up at the displayed
* top-left and bottom-right. Orientations 5 to 8 swap width and height.
*/
const ORIENTATIONS: Array<{
orientation: number
name: string
swapped: boolean
topLeftIs: Corner
bottomRightIs: Corner
}> = [
{ orientation: 1, name: 'normal', swapped: false, topLeftIs: 'TL', bottomRightIs: 'BR' },
{
orientation: 2,
name: 'mirror horizontal',
swapped: false,
topLeftIs: 'TR',
bottomRightIs: 'BL',
},
{ orientation: 3, name: 'rotate 180', swapped: false, topLeftIs: 'BR', bottomRightIs: 'TL' },
{ orientation: 4, name: 'mirror vertical', swapped: false, topLeftIs: 'BL', bottomRightIs: 'TR' },
{ orientation: 5, name: 'transpose', swapped: true, topLeftIs: 'TL', bottomRightIs: 'BR' },
{ orientation: 6, name: 'rotate 90 CW', swapped: true, topLeftIs: 'BL', bottomRightIs: 'TR' },
{ orientation: 7, name: 'transverse', swapped: true, topLeftIs: 'BR', bottomRightIs: 'TL' },
{ orientation: 8, name: 'rotate 270 CW', swapped: true, topLeftIs: 'TR', bottomRightIs: 'BL' },
]
async function makeJpeg(orientation: number): Promise<Buffer> {
const halfW = STORED_WIDTH / 2
const halfH = STORED_HEIGHT / 2
const block = (corner: Corner) => ({
create: {
width: halfW,
height: halfH,
channels: 3 as const,
background: {
r: QUADRANT_COLORS[corner][0],
g: QUADRANT_COLORS[corner][1],
b: QUADRANT_COLORS[corner][2],
},
},
})
const tile = async (corner: Corner) => sharp(block(corner)).png().toBuffer()
return sharp({
create: {
width: STORED_WIDTH,
height: STORED_HEIGHT,
channels: 3,
background: { r: 0, g: 0, b: 0 },
},
})
.composite([
{ input: await tile('TL'), left: 0, top: 0 },
{ input: await tile('TR'), left: halfW, top: 0 },
{ input: await tile('BL'), left: 0, top: halfH },
{ input: await tile('BR'), left: halfW, top: halfH },
])
.jpeg({ quality: 100, chromaSubsampling: '4:4:4' })
.withMetadata({ orientation })
.toBuffer()
}
/** Which quadrant color is nearest to the pixel a few pixels inside the given output corner. */
async function cornerColor(file: string, where: 'TL' | 'BR'): Promise<Corner> {
const { data, info } = await sharp(fs.readFileSync(file))
.removeAlpha()
.raw()
.toBuffer({ resolveWithObject: true })
const inset = 3
const x = where === 'TL' ? inset : info.width - 1 - inset
const y = where === 'TL' ? inset : info.height - 1 - inset
const offset = (y * info.width + x) * info.channels
const pixel = [data[offset], data[offset + 1], data[offset + 2]]
let best: Corner = 'TL'
let bestDistance = Infinity
for (const corner of Object.keys(QUADRANT_COLORS) as Corner[]) {
const distance = QUADRANT_COLORS[corner].reduce(
(sum, channel, i) => sum + (channel - pixel[i]) ** 2,
0,
)
if (distance < bestDistance) {
best = corner
bestDistance = distance
}
}
return best
}
describe('EXIF orientation (real sharp)', () => {
let tempDir: string
beforeEach(() => {
tempDir = transcodeService.createTempDir('orientation-test-')
})
afterEach(() => {
transcodeService.removeDir(tempDir)
})
const expectedSize = (swapped: boolean) =>
swapped
? { width: STORED_HEIGHT, height: STORED_WIDTH }
: { width: STORED_WIDTH, height: STORED_HEIGHT }
it.each(ORIENTATIONS)(
'getImageInfo reports the displayed size for orientation $orientation ($name)',
async ({ orientation, swapped }) => {
const inputPath = path.join(tempDir, `in-${orientation}.jpg`)
fs.writeFileSync(inputPath, await makeJpeg(orientation))
const info = await transcodeService.getImageInfo(inputPath)
const expected = expectedSize(swapped)
expect(info.originalWidth).toBe(expected.width)
expect(info.originalHeight).toBe(expected.height)
},
)
it.each(ORIENTATIONS)(
'transcodeImage outputs an upright image for orientation $orientation ($name)',
async ({ orientation, swapped, topLeftIs, bottomRightIs }) => {
const inputPath = path.join(tempDir, `in-${orientation}.jpg`)
const outputPath = path.join(tempDir, `out-${orientation}.webp`)
fs.writeFileSync(inputPath, await makeJpeg(orientation))
await transcodeService.transcodeImage(inputPath, outputPath, 1000, 100)
const meta = await sharp(fs.readFileSync(outputPath)).metadata()
const expected = expectedSize(swapped)
expect(meta.width).toBe(expected.width)
expect(meta.height).toBe(expected.height)
// Direction, not just size: the stored corner that lands top-left and bottom-right.
expect(await cornerColor(outputPath, 'TL')).toBe(topLeftIs)
expect(await cornerColor(outputPath, 'BR')).toBe(bottomRightIs)
},
)
it('transcodeImage sizes a rotated preview from the displayed dimensions', async () => {
// Stored 64x48 with orientation 6 is displayed 48x64 (portrait): the short edge is the width.
const inputPath = path.join(tempDir, 'preview-in.jpg')
const outputPath = path.join(tempDir, 'preview-out.webp')
fs.writeFileSync(inputPath, await makeJpeg(6))
await transcodeService.transcodeImage(inputPath, outputPath, 24, 80, { isPreview: true })
const meta = await sharp(fs.readFileSync(outputPath)).metadata()
expect(meta.width).toBeLessThan(meta.height ?? 0)
})
describe('RAW inputs', () => {
const rawPreview = (previewPath: string, extra: Record<string, unknown>) => ({
previewPath,
cleanup: () => {},
width: STORED_WIDTH,
height: STORED_HEIGHT,
...extra,
})
it('never auto-orients dcraw_emu output that still carries an Orientation tag', async () => {
// The dcraw fallback reports orientation undefined (already upright) but flags it as applied.
const tiffLike = path.join(tempDir, 'dcraw.jpg')
const outputPath = path.join(tempDir, 'dcraw-out.webp')
fs.writeFileSync(tiffLike, await makeJpeg(6))
extractRawMock.mockResolvedValueOnce(
rawPreview(tiffLike, { orientation: undefined, orientationApplied: true }),
)
await transcodeService.transcodeImage(path.join(tempDir, 'photo.cr2'), outputPath, 1000, 100)
const meta = await sharp(fs.readFileSync(outputPath)).metadata()
// Stored landscape stays landscape and the stored corners stay put: no second rotation.
expect(meta.width).toBe(STORED_WIDTH)
expect(meta.height).toBe(STORED_HEIGHT)
expect(await cornerColor(outputPath, 'TL')).toBe('TL')
expect(await cornerColor(outputPath, 'BR')).toBe('BR')
})
it('still auto-orients an embedded preview that has no container orientation', async () => {
const embedded = path.join(tempDir, 'embedded.jpg')
const outputPath = path.join(tempDir, 'embedded-out.webp')
fs.writeFileSync(embedded, await makeJpeg(6))
extractRawMock.mockResolvedValueOnce(rawPreview(embedded, { orientation: undefined }))
await transcodeService.transcodeImage(path.join(tempDir, 'photo.cr2'), outputPath, 1000, 100)
const meta = await sharp(fs.readFileSync(outputPath)).metadata()
expect(meta.width).toBe(STORED_HEIGHT)
expect(meta.height).toBe(STORED_WIDTH)
})
})
it('overlayAnnotationsOnBuffer keeps the displayed orientation', async () => {
const annotations = [
{
type: 'box',
color: '#ffffff',
points: [
[0.1, 0.1],
[0.4, 0.4],
],
},
] as unknown as PrismaJson.AnnotationList
const annotated = await transcodeService.overlayAnnotationsOnBuffer(
await makeJpeg(6),
annotations,
)
const meta = await sharp(annotated).metadata()
expect(meta.width).toBe(STORED_HEIGHT)
expect(meta.height).toBe(STORED_WIDTH)
})
})
+5 -156
View File
@@ -330,7 +330,7 @@ describe('TranscodeService', () => {
const outputFile = path.join(tempDir, 'output.webp')
await transcodeService.transcodeImage('input.png', outputFile, 300, 80, { isPreview: true })
expect(sharp).toHaveBeenCalledWith('input.png', { limitInputPixels: false, autoOrient: true })
expect(sharp).toHaveBeenCalledWith('input.png', { limitInputPixels: false })
const mockSharp = vi.mocked(sharp).mock.results[0].value
expect(mockSharp.toColorspace).toHaveBeenCalledWith('srgb')
expect(mockSharp.resize).toHaveBeenCalledWith(400, 300, expect.any(Object))
@@ -544,11 +544,7 @@ describe('TranscodeService', () => {
await transcodeService.transcodeImage(rawPath, outputFile, 1920, 85)
// The RAW container orientation (1 here) is authoritative, so no auto-orient on top of it.
expect(sharp).toHaveBeenCalledWith('/tmp/extracted-raw.jpg', {
limitInputPixels: false,
autoOrient: false,
})
expect(sharp).toHaveBeenCalledWith('/tmp/extracted-raw.jpg', { limitInputPixels: false })
const mockSharp = vi.mocked(sharp).mock.results[vi.mocked(sharp).mock.results.length - 1].value
expect(mockSharp.toColorspace).toHaveBeenCalledWith('srgb')
expect(mockSharp.webp).toHaveBeenCalledWith({ quality: 85 })
@@ -572,10 +568,7 @@ describe('TranscodeService', () => {
await transcodeService.transcodeImage(rawPath, outputFile, 1920, 85)
expect(sharp).toHaveBeenCalledWith('/tmp/decoded-dcraw.tiff', {
limitInputPixels: false,
autoOrient: true,
})
expect(sharp).toHaveBeenCalledWith('/tmp/decoded-dcraw.tiff', { limitInputPixels: false })
const mockSharp = vi.mocked(sharp).mock.results[vi.mocked(sharp).mock.results.length - 1].value
expect(mockSharp.rotate).not.toHaveBeenCalled()
expect(mockSharp.toColorspace).toHaveBeenCalledWith('srgb')
@@ -600,67 +593,9 @@ describe('TranscodeService', () => {
const mockSharp = vi.mocked(sharp).mock.results[vi.mocked(sharp).mock.results.length - 1].value
expect(mockSharp.rotate).toHaveBeenCalledWith(90)
// Rotated from the container EXIF only, never also auto-oriented (would double-rotate).
expect(sharp).toHaveBeenCalledWith('/tmp/extracted-rotated.jpg', {
limitInputPixels: false,
autoOrient: false,
})
expect(cleanupSpy).toHaveBeenCalled()
})
it('should apply EXIF orientation when transcoding a rotated photo', async () => {
// A camera portrait: stored 7728x5152 (landscape) with EXIF orientation 8, shown 5152x7728.
const mockRotated = {
resize: vi.fn().mockReturnThis(),
toColorspace: vi.fn().mockReturnThis(),
webp: vi.fn().mockReturnThis(),
toFile: vi.fn().mockResolvedValue({}),
metadata: vi.fn().mockResolvedValue({
width: 7728,
height: 5152,
orientation: 8,
autoOrient: { width: 5152, height: 7728 },
format: 'jpeg',
}),
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(sharp).mockReturnValueOnce(mockRotated as any)
await transcodeService.transcodeImage(
'DSCF5056.JPG',
path.join(tempDir, 'rotated.webp'),
300,
80,
{ isPreview: true },
)
expect(sharp).toHaveBeenCalledWith(
'DSCF5056.JPG',
expect.objectContaining({ autoOrient: true }),
)
// Portrait preview: 300 wide on the short edge, not a 450x300 landscape one.
expect(mockRotated.resize).toHaveBeenCalledWith(300, 450, expect.any(Object))
})
it('should report the displayed size of a rotated photo', async () => {
const mockRotated = {
metadata: vi.fn().mockResolvedValue({
width: 7728,
height: 5152,
orientation: 8,
autoOrient: { width: 5152, height: 7728 },
format: 'jpeg',
}),
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(sharp).mockReturnValueOnce(mockRotated as any)
const info = await transcodeService.getImageInfo('DSCF5056.JPG')
expect(info.originalWidth).toBe(5152)
expect(info.originalHeight).toBe(7728)
})
it('should throw error when transcoding RAW without usable preview', async () => {
const rawPath = path.join(tempDir, 'corrupt.raf')
const outputFile = path.join(tempDir, 'output-fail.webp')
@@ -683,10 +618,7 @@ describe('TranscodeService', () => {
await transcodeService.transcodeImage('http://example.com/image.png', outputFile, 480, 80)
expect(global.fetch).toHaveBeenCalledWith('http://example.com/image.png')
expect(sharp).toHaveBeenCalledWith(expect.any(Buffer), {
limitInputPixels: false,
autoOrient: true,
})
expect(sharp).toHaveBeenCalledWith(expect.any(Buffer), { limitInputPixels: false })
})
it('should support Buffer as input for image transcoding', async () => {
@@ -694,7 +626,7 @@ describe('TranscodeService', () => {
const outputFile = path.join(tempDir, 'output-buffer.webp')
await transcodeService.transcodeImage(inputBuffer, outputFile, 480, 80)
expect(sharp).toHaveBeenCalledWith(inputBuffer, { limitInputPixels: false, autoOrient: true })
expect(sharp).toHaveBeenCalledWith(inputBuffer, { limitInputPixels: false })
const mockSharp = vi.mocked(sharp).mock.results[vi.mocked(sharp).mock.results.length - 1].value
expect(mockSharp.toColorspace).toHaveBeenCalledWith('srgb')
expect(mockSharp.resize).toHaveBeenCalledWith(400, 300, expect.any(Object))
@@ -4432,89 +4364,6 @@ describe('TranscodeService', () => {
})
})
describe('generate3dViews', () => {
it('executes ffmpeg with 2x2 grid filter, libwebp encoder, and q=85', async () => {
let executedArgs: string[] = []
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.execFile as any).mockImplementation(
(
_cmd: string,
args: string[],
cb: (err: unknown, result: { stdout: string; stderr: string }) => void,
) => {
executedArgs = args
cb(null, { stdout: '', stderr: '' })
},
)
const inputPath = path.join(tempDir, 'turntable.mp4')
const outputPath = path.join(tempDir, 'views.webp')
await transcodeService.generate3dViews(inputPath, outputPath)
expect(child_process.execFile).toHaveBeenCalledWith(
'ffmpeg',
expect.any(Array),
expect.any(Function),
)
expect(executedArgs).toEqual([
'-y',
'-loglevel',
'warning',
'-i',
inputPath,
'-filter_complex',
"[0:v]select='eq(n\\,0)+eq(n\\,6)+eq(n\\,12)+eq(n\\,18)',scale=1440:1440,tile=2x2[views_out]",
'-map',
'[views_out]',
'-frames:v',
'1',
'-c:v',
'libwebp',
'-q:v',
'85',
outputPath,
])
})
it('passes abort signal to execFile when provided', async () => {
const controller = new AbortController()
let optionsPassed: unknown = null
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.execFile as any).mockImplementation(
(_cmd: string, _args: string[], optionsOrCb: unknown, maybeCb?: unknown) => {
const cb = (typeof optionsOrCb === 'function' ? optionsOrCb : maybeCb) as (
err: unknown,
result: { stdout: string; stderr: string },
) => void
if (typeof optionsOrCb !== 'function') {
optionsPassed = optionsOrCb
}
cb(null, { stdout: '', stderr: '' })
},
)
const inputPath = path.join(tempDir, 'turntable.mp4')
const outputPath = path.join(tempDir, 'views.webp')
await transcodeService.generate3dViews(inputPath, outputPath, controller.signal)
expect(optionsPassed).toMatchObject({ signal: controller.signal })
})
it('rejects with cancellation error if aborted before execution', async () => {
const controller = new AbortController()
controller.abort()
const inputPath = path.join(tempDir, 'aborted.mp4')
const outputPath = path.join(tempDir, 'views.webp')
await expect(
transcodeService.generate3dViews(inputPath, outputPath, controller.signal),
).rejects.toThrow('3D views generation cancelled')
})
})
describe('HLS utilities', () => {
it('builds master playlist correctly with bandwidth and codecs', () => {
const playlist = buildHlsMasterPlaylist([
+9 -75
View File
@@ -8,7 +8,7 @@ import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import PDFDocument from 'pdfkit'
import sharp, { type Metadata as SharpMetadata } from 'sharp'
import sharp from 'sharp'
import { ulid } from 'ulid'
import { promisify } from 'util'
import { mapConcurrent } from '../utils/async'
@@ -419,28 +419,6 @@ function normalizeRotation(rotation: number): number {
return ((Math.round(rotation) % 360) + 360) % 360
}
interface OrientationOptions {
/** True when a RAW container orientation is applied by hand, so sharp must not also auto-orient. */
rawOrientationApplied?: boolean
}
/**
* Sharp input options. The webp output drops the EXIF orientation tag, so camera portraits would
* come out sideways unless sharp applies it; skip that when the RAW orientation is already applied,
* otherwise the image would rotate twice.
*/
function orientedSharpOptions({ rawOrientationApplied = false }: OrientationOptions = {}) {
return { limitInputPixels: false, autoOrient: !rawOrientationApplied } as const
}
/** Width and height as displayed: sharp reports the EXIF-oriented size under `autoOrient`. */
function displayedDimensions(
metadata: SharpMetadata,
{ rawOrientationApplied = false }: OrientationOptions = {},
): Pick<SharpMetadata, 'width' | 'height'> {
return rawOrientationApplied ? metadata : (metadata.autoOrient ?? metadata)
}
export function parseBitrateKbps(bitrate: string | number): number {
if (typeof bitrate === 'number') {
return Math.round(bitrate / 1000)
@@ -977,11 +955,9 @@ export class TranscodeService {
}
const metadata = await sharp(input, { limitInputPixels: false }).metadata()
// Cameras store portraits sideways plus an EXIF orientation; report the size as displayed.
const shown = displayedDimensions(metadata)
return {
originalWidth: shown.width || 0,
originalHeight: shown.height || 0,
originalWidth: metadata.width || 0,
originalHeight: metadata.height || 0,
duration: 0,
bitRate: 0,
frameRate: 0,
@@ -1946,7 +1922,6 @@ export class TranscodeService {
// RAW branch — extract embedded preview or decode RAW to temporary file + orientation, then treat as normal image
let rawOrientation: number | undefined
let rawOutputUpright = false
let rawCleanup: (() => void) | null = null
if (typeof input === 'string' && isRawImage(input)) {
const extracted = await extractAndValidateRawPreview(input)
@@ -1957,7 +1932,6 @@ export class TranscodeService {
}
input = extracted.previewPath
rawOrientation = extracted.orientation
rawOutputUpright = extracted.orientationApplied === true
rawCleanup = extracted.cleanup
}
@@ -1966,17 +1940,11 @@ export class TranscodeService {
let targetW = width > 0 ? Math.min(width, WEBP_MAX_DIMENSION) : WEBP_MAX_DIMENSION
let targetH = height && height > 0 ? Math.min(height, WEBP_MAX_DIMENSION) : WEBP_MAX_DIMENSION
// RAW previews are oriented from the container EXIF below, so only auto-orient other
// inputs: the webp output drops the tag, which would leave camera portraits sideways.
// dcraw_emu output is already upright, so it is never auto-oriented (no double rotation).
const rawOrientationApplied = rawOrientation !== undefined || rawOutputUpright
const sharpInstance = sharp(input, orientedSharpOptions({ rawOrientationApplied }))
const sharpInstance = sharp(input, { limitInputPixels: false })
if (isPreview) {
try {
const meta = displayedDimensions(await sharpInstance.metadata(), {
rawOrientationApplied,
})
const meta = await sharpInstance.metadata()
if (meta.width && meta.height) {
const isSwapped =
rawOrientation !== undefined && rawOrientation >= 5 && rawOrientation <= 8
@@ -2035,7 +2003,7 @@ export class TranscodeService {
// Apply EXIF orientation from the RAW container to the extracted buffer.
// The buffer itself often lacks orientation EXIF, so Sharp won't auto-rotate.
// For non-RAW images, autoOrient above applies the image's own EXIF.
// For non-RAW images, Sharp auto-rotates from the image's own EXIF.
if (rawOrientation && EXIF_ORIENTATION_TO_ROTATION[rawOrientation]) {
const { angle, flip, flop } = EXIF_ORIENTATION_TO_ROTATION[rawOrientation]
if (angle) sharpInstance.rotate(angle)
@@ -3051,15 +3019,12 @@ export class TranscodeService {
return imageBuffer
}
// Annotations are drawn in the displayed (EXIF-oriented) coordinate space.
const meta = displayedDimensions(
await sharp(imageBuffer, { limitInputPixels: false }).metadata(),
)
const meta = await sharp(imageBuffer, { limitInputPixels: false }).metadata()
const width = meta.width || 1920
const height = meta.height || 1080
const svgStr = renderAnnotationsToSvg(width, height, annotations)
return await sharp(imageBuffer, orientedSharpOptions())
return await sharp(imageBuffer, { limitInputPixels: false })
.composite([{ input: Buffer.from(svgStr), top: 0, left: 0 }])
.toColorspace('srgb')
.resize(16383, 16383, { fit: 'inside', withoutEnlargement: true })
@@ -3146,7 +3111,7 @@ export class TranscodeService {
width: number,
height: number,
): Promise<void> {
await sharp(inputPath, orientedSharpOptions())
await sharp(inputPath, { limitInputPixels: false })
.toColorspace('srgb')
.resize(width, height, { fit: 'inside' })
.composite([{ input: overlayPngBuffer }])
@@ -3192,37 +3157,6 @@ export class TranscodeService {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
}
}
async generate3dViews(
inputFile: string,
outputViews: string,
signal?: AbortSignal,
): Promise<void> {
if (signal?.aborted) {
throw new Error('3D views generation cancelled')
}
const filterComplex = `[0:v]select='eq(n\\,0)+eq(n\\,6)+eq(n\\,12)+eq(n\\,18)',scale=1440:1440,tile=2x2[views_out]`
const args = [
'-i',
inputFile,
'-filter_complex',
filterComplex,
'-map',
'[views_out]',
'-frames:v',
'1',
'-c:v',
'libwebp',
'-q:v',
'85',
outputViews,
]
if (signal) {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args], { signal })
} else {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
}
}
}
function renderAnnotationsToSvg(
+104 -31
View File
@@ -1,23 +1,7 @@
import * as fs from 'fs'
import { prisma } from '@shumai/db'
import type { TurntableSettingsResponse, UpdateTurntableSettingsRequest } from '@shumai/dtos'
import {
IntegrationDefinition,
resolveIntegrationConfig,
getIntegrationSettings,
updateIntegrationSettings,
resolveTestConnectionConfig,
getIntegrationBasicAuthHeader,
} from '@shumai/core/src/integrations/helper'
export const TURNTABLE_INTEGRATION_DEF: IntegrationDefinition<'turntable'> = {
name: 'Turntable',
settingsKey: 'turntable',
envKeys: {
url: ['TURNTABLE_RENDERER_URL'],
username: ['TURNTABLE_RENDERER_BASIC_AUTH_USERNAME', 'TURNTABLE_RENDERER_USERNAME'],
password: ['TURNTABLE_RENDERER_BASIC_AUTH_PASSWORD', 'TURNTABLE_RENDERER_PASSWORD'],
},
}
import { logger } from '../logger'
export interface TurntableConfig {
url?: string
@@ -83,11 +67,55 @@ export interface TurntableTaskResponse {
export class TurntableService {
async resolveConfig(teamId?: string): Promise<TurntableConfig> {
return resolveIntegrationConfig(TURNTABLE_INTEGRATION_DEF, teamId)
const envUrl = process.env.TURNTABLE_RENDERER_URL?.trim()
const envUsername =
process.env.TURNTABLE_RENDERER_BASIC_AUTH_USERNAME?.trim() ||
process.env.TURNTABLE_RENDERER_USERNAME?.trim()
const envPassword =
process.env.TURNTABLE_RENDERER_BASIC_AUTH_PASSWORD?.trim() ||
process.env.TURNTABLE_RENDERER_PASSWORD?.trim()
if (envUrl) {
return {
url: envUrl.replace(/\/+$/, ''),
username: envUsername || undefined,
password: envPassword || undefined,
isEnv: true,
}
}
if (teamId) {
try {
const team = await prisma.team.findUnique({
where: { id: teamId },
select: { settings: true },
})
const teamSettings = team?.settings as PrismaJson.Settings | null
const turntable = teamSettings?.turntable
if (turntable?.url?.trim()) {
return {
url: turntable.url.trim().replace(/\/+$/, ''),
username: turntable.username?.trim() || undefined,
password: turntable.password?.trim() || undefined,
isEnv: false,
}
}
} catch (err) {
logger.error({ err, teamId }, 'Failed to load team turntable settings')
}
}
return {
isEnv: false,
}
}
private getAuthHeader(config: TurntableConfig): string | undefined {
return getIntegrationBasicAuthHeader(config)
if (config.username && config.password) {
const credentials = Buffer.from(`${config.username}:${config.password}`).toString('base64')
return `Basic ${credentials}`
}
return undefined
}
async isAvailable(teamId?: string): Promise<boolean> {
@@ -116,14 +144,45 @@ export class TurntableService {
}
async getSettings(teamId: string): Promise<TurntableSettingsResponse> {
return getIntegrationSettings(TURNTABLE_INTEGRATION_DEF, teamId)
const config = await this.resolveConfig(teamId)
return {
url: config.url,
username: config.username,
hasPassword: Boolean(config.password),
isEnvConfigured: config.isEnv,
}
}
async updateSettings(
teamId: string,
req: UpdateTurntableSettingsRequest,
): Promise<TurntableSettingsResponse> {
return updateIntegrationSettings(TURNTABLE_INTEGRATION_DEF, teamId, req)
const currentConfig = await this.resolveConfig(teamId)
if (currentConfig.isEnv) {
throw new Error(
'Turntable settings are configured via environment variables and cannot be edited',
)
}
const team = await prisma.team.findUnique({
where: { id: teamId },
select: { settings: true },
})
const settings = (team?.settings || {}) as PrismaJson.Settings
const prevTurntable = settings.turntable || {}
settings.turntable = {
url: req.url !== undefined ? req.url : prevTurntable.url,
username: req.username !== undefined ? req.username : prevTurntable.username,
password: req.password !== undefined ? req.password : prevTurntable.password,
}
await prisma.team.update({
where: { id: teamId },
data: { settings },
})
return this.getSettings(teamId)
}
async testConnection(
@@ -134,21 +193,35 @@ export class TurntableService {
},
teamId?: string,
): Promise<{ ok: boolean; version?: string; blender?: string; error?: string }> {
const target = await resolveTestConnectionConfig(TURNTABLE_INTEGRATION_DEF, config, teamId)
let resolvedUrl = config?.url?.trim()
let resolvedUsername = config?.username?.trim()
let resolvedPassword = config?.password
if (!target.resolvedUrl) {
if (teamId && (!resolvedUrl || resolvedPassword === undefined)) {
const savedConfig = await this.resolveConfig(teamId)
if (!resolvedUrl) {
resolvedUrl = savedConfig.url
}
if (!resolvedUsername && savedConfig.username) {
resolvedUsername = savedConfig.username
}
if (resolvedPassword === undefined) {
resolvedPassword = savedConfig.password
}
}
if (!resolvedUrl) {
return { ok: false, error: 'URL is required' }
}
const cleanUrl = target.resolvedUrl.replace(/\/+$/, '')
const cleanUrl = resolvedUrl.replace(/\/+$/, '')
try {
const headers: Record<string, string> = {}
const authHeader = getIntegrationBasicAuthHeader({
username: target.resolvedUsername,
password: target.resolvedPassword,
})
if (authHeader) {
headers['Authorization'] = authHeader
if (resolvedUsername && resolvedPassword) {
const credentials = Buffer.from(`${resolvedUsername}:${resolvedPassword}`).toString(
'base64',
)
headers['Authorization'] = `Basic ${credentials}`
}
const response = await fetch(`${cleanUrl}/version`, {
-87
View File
@@ -451,93 +451,6 @@ describe('UploadService', () => {
expect(workflowTask).toBeNull()
})
it('should create transcode_pdf for office documents when Gotenberg is configured in team settings without global env', async () => {
vi.restoreAllMocks()
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
const url = String(input)
if (url.includes('/health')) {
return new Response(JSON.stringify({ status: 'up' }), { status: 200 })
}
return new Response('Not Found', { status: 404 })
})
const originalEnv = process.env.GOTENBERG_URL
delete process.env.GOTENBERG_URL
try {
await prisma.team.update({
where: { id: teamId },
data: {
settings: {
gotenberg: {
url: 'http://gotenberg.local:3000',
},
},
},
})
const task = await prisma.task.create({
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
})
const asset = await prisma.asset.create({
data: {
name: 'report.docx',
type: AssetType.file,
project: { connect: { id: projectId } },
parent: { connect: { id: parentId } },
status: AssetStatus.uploading,
storageKey: {
connectOrCreate: {
where: { key: 'test-key-doc-team-settings' },
create: { key: 'test-key-doc-team-settings' },
},
},
mediaType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
},
})
await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id })
const workflowTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode_pdf },
})
expect(workflowTask).not.toBeNull()
expect(workflowTask?.status).toBe(TaskStatus.pending)
// Test HTML document as well
const htmlTask = await prisma.task.create({
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
})
const htmlAsset = await prisma.asset.create({
data: {
name: 'index.html',
type: AssetType.file,
project: { connect: { id: projectId } },
parent: { connect: { id: parentId } },
status: AssetStatus.uploading,
storageKey: {
connectOrCreate: {
where: { key: 'test-key-html-team-settings' },
create: { key: 'test-key-html-team-settings' },
},
},
mediaType: 'text/html',
},
})
await uploadService.confirmFileUpload(userId, htmlTask.id, { fileId: htmlAsset.id })
const htmlWorkflowTask = await prisma.workflowTask.findFirst({
where: { assetId: htmlAsset.id, type: WorkflowTaskType.transcode_pdf },
})
expect(htmlWorkflowTask).not.toBeNull()
expect(htmlWorkflowTask?.status).toBe(TaskStatus.pending)
} finally {
if (originalEnv !== undefined) {
process.env.GOTENBERG_URL = originalEnv
}
}
})
it('should confirm file upload and create transcode_3d for 3D model when turntable is available', async () => {
vi.spyOn(turntableService, 'isAvailable').mockResolvedValue(true)
const task = await prisma.task.create({
+1 -1
View File
@@ -363,7 +363,7 @@ export class UploadService {
const isHtml = isHtmlDocument(asset.mediaType, asset.name)
if (isOffice || isHtml) {
const gotenbergAvailable = await gotenbergService.isAvailable(team.id)
const gotenbergAvailable = await gotenbergService.isAvailable()
if (!gotenbergAvailable) {
await tx.asset.update({
where: { id: asset.id },
+2 -2
View File
@@ -128,7 +128,9 @@ describe('getProxyType', () => {
it('should detect 3d proxyType for supported 3D models', () => {
expect(getProxyType('model/gltf-binary', 'model.glb')).toBe('3d')
expect(getProxyType('model/gltf+json', 'model.gltf')).toBe('3d')
expect(getProxyType(null, 'model.glb')).toBe('3d')
expect(getProxyType(null, 'model.gltf')).toBe('3d')
expect(getProxyType(null, 'character.fbx')).toBe('3d')
expect(getProxyType('model/obj', 'mesh.obj')).toBe('3d')
expect(getProxyType(null, 'mesh.obj')).toBe('3d')
@@ -145,7 +147,5 @@ describe('getProxyType', () => {
it('should return null for unsupported files', () => {
expect(getProxyType('application/zip', 'archive.zip')).toBeNull()
expect(getProxyType(null, 'unknown.bin')).toBeNull()
expect(getProxyType('model/gltf+json', 'model.gltf')).toBeNull()
expect(getProxyType(null, 'model.gltf')).toBeNull()
})
})
+2 -4
View File
@@ -6,12 +6,9 @@ export function is3dModel(mediaType?: string | null, filename?: string | null):
const lowerMediaType = mediaType?.toLowerCase() || ''
const lowerFilename = filename?.toLowerCase() || ''
if (lowerMediaType === 'model/gltf+json' || lowerFilename.endsWith('.gltf')) {
return false
}
const modelExtensions = [
'.glb',
'.gltf',
'.usd',
'.usda',
'.usdc',
@@ -28,6 +25,7 @@ export function is3dModel(mediaType?: string | null, filename?: string | null):
if (
lowerMediaType.startsWith('model/') ||
lowerMediaType === 'model/gltf-binary' ||
lowerMediaType === 'model/gltf+json' ||
lowerMediaType === 'model/obj' ||
lowerMediaType === 'model/stl' ||
lowerMediaType === 'model/vnd.usdz+zip' ||
-90
View File
@@ -1,90 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
calculateTurntableFrameCenterTime,
degreeToSecond,
degreeToTurntableFrame,
isValidTurntableDegree,
secondToDegree,
secondToTurntableFrame,
TOTAL_TURNTABLE_FRAMES,
TURNTABLE_FPS,
} from './model3d'
describe('model3d utils', () => {
describe('secondToTurntableFrame', () => {
it('converts playback seconds to frame indices (0..23)', () => {
expect(secondToTurntableFrame(0)).toBe(0)
expect(secondToTurntableFrame(0.167)).toBe(1)
expect(secondToTurntableFrame(0.5)).toBe(3)
expect(secondToTurntableFrame(2.0)).toBe(12)
expect(secondToTurntableFrame(3.9)).toBe(23)
})
it('clamps out-of-range seconds', () => {
expect(secondToTurntableFrame(-1)).toBe(0)
expect(secondToTurntableFrame(10)).toBe(TOTAL_TURNTABLE_FRAMES - 1)
})
})
describe('secondToDegree', () => {
it('converts seconds to turntable degrees (0, 15, ..., 345)', () => {
expect(secondToDegree(0)).toBe(0)
expect(secondToDegree(1 / TURNTABLE_FPS)).toBe(15)
expect(secondToDegree(0.5)).toBe(45)
expect(secondToDegree(2.0)).toBe(180)
expect(secondToDegree(3.9)).toBe(345)
})
})
describe('degreeToTurntableFrame', () => {
it('converts discrete degrees to frame indices', () => {
expect(degreeToTurntableFrame(0)).toBe(0)
expect(degreeToTurntableFrame(15)).toBe(1)
expect(degreeToTurntableFrame(45)).toBe(3)
expect(degreeToTurntableFrame(90)).toBe(6)
expect(degreeToTurntableFrame(180)).toBe(12)
expect(degreeToTurntableFrame(345)).toBe(23)
})
it('normalizes degrees outside [0, 360)', () => {
expect(degreeToTurntableFrame(360)).toBe(0)
expect(degreeToTurntableFrame(-15)).toBe(23)
expect(degreeToTurntableFrame(720)).toBe(0)
})
})
describe('calculateTurntableFrameCenterTime and degreeToSecond', () => {
it('calculates frame center times within bounds', () => {
const centerTime0 = calculateTurntableFrameCenterTime(0)
expect(centerTime0).toBeCloseTo(0.5 / TURNTABLE_FPS)
const centerTime23 = calculateTurntableFrameCenterTime(23)
expect(centerTime23).toBeLessThan(TOTAL_TURNTABLE_FRAMES / TURNTABLE_FPS)
expect(centerTime23).toBeGreaterThan(23 / TURNTABLE_FPS)
expect(degreeToSecond(0)).toBeCloseTo(centerTime0)
expect(degreeToSecond(45)).toBeCloseTo((3 + 0.5) / TURNTABLE_FPS)
expect(degreeToSecond(345)).toBeCloseTo(centerTime23)
})
})
describe('isValidTurntableDegree', () => {
it('returns true for integer multiples of 15 from 0 to 345', () => {
for (let deg = 0; deg < 360; deg += 15) {
expect(isValidTurntableDegree(deg)).toBe(true)
}
})
it('returns false for non-multiples of 15', () => {
expect(isValidTurntableDegree(10)).toBe(false)
expect(isValidTurntableDegree(44)).toBe(false)
expect(isValidTurntableDegree(45.5)).toBe(false)
})
it('returns false for out of range or negative degrees', () => {
expect(isValidTurntableDegree(-15)).toBe(false)
expect(isValidTurntableDegree(360)).toBe(false)
expect(isValidTurntableDegree(720)).toBe(false)
})
})
})
-58
View File
@@ -1,58 +0,0 @@
export const TOTAL_TURNTABLE_FRAMES = 24
export const TURNTABLE_FPS = 6
export const TURNTABLE_FRAME_DURATION = 1 / TURNTABLE_FPS
/**
* Converts a playback second into a turntable frame index (0..23), clamped.
*/
export function secondToTurntableFrame(second: number): number {
return Math.min(
Math.max(0, Math.floor(second * TURNTABLE_FPS + 1e-4)),
TOTAL_TURNTABLE_FRAMES - 1,
)
}
/**
* Converts a turntable playback second to turntable degree (0, 15, 30, ..., 345).
*/
export function secondToDegree(second: number): number {
const frameIndex = secondToTurntableFrame(second)
return (frameIndex * 15) % 360
}
/**
* Calculates the presentation time within a turntable frame.
* Seeking near frame center avoids PTS boundary inaccuracies in video decoders.
*/
export function calculateTurntableFrameCenterTime(frameIndex: number): number {
const normalizedFrame =
((frameIndex % TOTAL_TURNTABLE_FRAMES) + TOTAL_TURNTABLE_FRAMES) % TOTAL_TURNTABLE_FRAMES
if (normalizedFrame === TOTAL_TURNTABLE_FRAMES - 1) {
return normalizedFrame * TURNTABLE_FRAME_DURATION + TURNTABLE_FRAME_DURATION * 0.25
}
return (normalizedFrame + 0.5) * TURNTABLE_FRAME_DURATION
}
/**
* Converts a rotation degree (0..345) to a turntable frame index (0..23).
*/
export function degreeToTurntableFrame(degree: number): number {
const normalizedDegree = ((Math.round(degree) % 360) + 360) % 360
return Math.round(normalizedDegree / 15) % TOTAL_TURNTABLE_FRAMES
}
/**
* Converts a rotation degree into a turntable video playback second (center time of that frame).
*/
export function degreeToSecond(degree: number): number {
const frameIndex = degreeToTurntableFrame(degree)
return calculateTurntableFrameCenterTime(frameIndex)
}
/**
* Validates whether a degree is a valid discrete turntable angle:
* integer multiple of 15 between 0 and 345 inclusive (0, 15, 30, ..., 345).
*/
export function isValidTurntableDegree(degree: number): boolean {
return Number.isInteger(degree) && degree >= 0 && degree <= 345 && degree % 15 === 0
}
@@ -258,57 +258,6 @@ describe('WatermarkService', () => {
expect(mediaIds).toContain(mediaFile.id)
})
it('should include 3D assets with turntable video in getMediaAssetIdsInShareLink', async () => {
const user = await prisma.user.create({
data: { name: '3D User', email: '3d-wm@example.com' },
})
const team = await teamService.createTeam(user, { name: '3D Team' })
const projectFolder = await prisma.asset.create({
data: { name: 'root', type: 'root', status: 'processed' },
})
const project = await prisma.project.create({
data: { name: '3D Project', teamId: team.id, rootFolderId: projectFolder.id },
})
const shareLink = await shareService.createShareLink(project.id, { name: '3D Share' }, user.id)
const modelAsset = await prisma.asset.create({
data: {
name: 'robot.glb',
type: 'file',
mediaType: 'model/gltf-binary',
status: 'processed',
projectId: project.id,
media: {
duration: 4,
filesize: 100,
frames: 24,
proxyType: '3d',
videoTranscodes: [
{ key: 'files/asset-3d/turntable.mp4', width: 1080, height: 1080, resolution: '1080p' },
],
finishedAt: new Date().toISOString(),
original: { key: 'files/asset-3d/robot.glb', filesizeInBytes: 100, codec: '' },
} as PrismaJson.MediaInfo,
},
})
await prisma.asset.create({
data: {
name: 'robot.glb',
type: 'symlink',
status: 'processed',
projectId: project.id,
parentId: shareLink.rootFolderId,
targetId: modelAsset.id,
},
})
const mediaIds = await watermarkService.getMediaAssetIdsInShareLink(shareLink.rootFolderId)
expect(mediaIds).toContain(modelAsset.id)
})
describe('purgeOrphanWatermarkConfigs', () => {
const bucket = 'shumai-gc-test-bucket'
+1 -3
View File
@@ -23,7 +23,6 @@ import {
} from '@shumai/core/src/share/errors'
import { shareService } from '@shumai/core/src/share/share'
import { logger } from '@shumai/core/src/logger'
import { is3dModel } from '@shumai/core/src/utils/mime'
// Union of the global client and interactive-transaction client, which share the
// same delegate shapes for the models used by this service.
@@ -320,9 +319,8 @@ export class WatermarkService {
const proxyType = mediaInfo?.proxyType
const isVideo = proxyType === 'video' || asset.mediaType?.startsWith('video/')
const isImage = proxyType === 'image' || asset.mediaType?.startsWith('image/')
const is3d = proxyType === '3d' || is3dModel(asset.mediaType)
if (isVideo || isImage || is3d) {
if (isVideo || isImage) {
mediaAssetIds.push(asset.id)
}
} else if (asset.type === 'folder' || asset.type === 'version_stack') {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/db",
"version": "0.5.2",
"version": "0.5.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
-7
View File
@@ -109,16 +109,9 @@ declare global {
password?: string
}
export interface GotenbergSettings {
url?: string
username?: string
password?: string
}
export interface Settings {
transcode?: TranscodeSettings
turntable?: TurntableSettings
gotenberg?: GotenbergSettings
mediaGeneration?: MediaGenerationSettings
appearance?: AppearanceSettings
emailNotification?: EmailNotificationSettings
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/dtos",
"version": "0.5.2",
"version": "0.5.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+2 -3
View File
@@ -47,7 +47,7 @@ export const shumaiAssetContextSchema = z.object({
id: z.string(),
name: z.string(),
type: z.string(),
mediaType: z.enum(['image', 'video', 'pdf', 'audio', '3d', 'other']).optional(),
mediaType: z.enum(['image', 'video', 'pdf', 'audio', 'other']).optional(),
mimeType: z.string().optional(),
parentId: z.string().optional(),
path: z.string().optional(),
@@ -64,7 +64,7 @@ export const shumaiAttachedFileContextSchema = z.object({
id: z.string(),
name: z.string(),
type: z.string(),
mediaType: z.enum(['image', 'video', 'pdf', 'audio', '3d', 'other']).optional(),
mediaType: z.enum(['image', 'video', 'pdf', 'audio', 'other']).optional(),
mimeType: z.string().optional(),
path: z.string().optional(),
url: z.string().optional(),
@@ -75,7 +75,6 @@ export type ShumaiAttachedFileContext = z.infer<typeof shumaiAttachedFileContext
export const shumaiMediaPositionSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('time'), seconds: z.number() }),
z.object({ type: z.literal('page'), page: z.number() }),
z.object({ type: z.literal('degree'), degree: z.number().int() }),
])
export type ShumaiMediaPosition = z.infer<typeof shumaiMediaPositionSchema>
-2
View File
@@ -104,8 +104,6 @@ export function serializeContextToXml(context?: ShumaiMessageContext | null): st
lines.push(` <position type="time" seconds="${context.position.seconds.toFixed(4)}" />`)
} else if (context.position.type === 'page') {
lines.push(` <position type="page" page="${Math.round(context.position.page)}" />`)
} else if (context.position.type === 'degree') {
lines.push(` <position type="degree" degree="${Math.round(context.position.degree)}" />`)
}
}
-16
View File
@@ -157,21 +157,6 @@ export const updateTurntableSettingsRequestSchema = z.object({
})
export type UpdateTurntableSettingsRequest = z.infer<typeof updateTurntableSettingsRequestSchema>
export const gotenbergSettingsResponseSchema = z.object({
url: z.string().optional(),
username: z.string().optional(),
hasPassword: z.boolean(),
isEnvConfigured: z.boolean(),
})
export type GotenbergSettingsResponse = z.infer<typeof gotenbergSettingsResponseSchema>
export const updateGotenbergSettingsRequestSchema = z.object({
url: z.string().optional(),
username: z.string().optional(),
password: z.string().optional(),
})
export type UpdateGotenbergSettingsRequest = z.infer<typeof updateGotenbergSettingsRequestSchema>
export interface TeamAppearanceSettings {
hideAgent?: boolean
}
@@ -186,7 +171,6 @@ export interface TeamSettingsResponse {
hlsResolutions?: HlsResolutionLadder[]
}
turntable?: TurntableSettingsResponse
gotenberg?: GotenbergSettingsResponse
appearance?: TeamAppearanceSettings
semanticSearchEnabled?: boolean
[key: string]: unknown
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/e2e",
"version": "0.5.2",
"version": "0.5.1",
"private": true,
"type": "module",
"dependencies": {
@@ -295,85 +295,5 @@ describe.each(['local', 'temporal'] as const)(
expect(mediaInfo.imageTranscodes.length).toBeGreaterThan(0)
expect(mediaInfo.thumbnail).toBeDefined()
}, 50000)
it('should transcode a rotated camera photo upright', async () => {
// 1. Seed Database
const team = await prisma.team.create({
data: { name: 'E2E Rotated Transcode Team' },
})
const project = await prisma.project.create({
data: { name: 'E2E Rotated Transcode Project', teamId: team.id },
})
const storageKey = await prisma.storageKey.create({
data: {
key: 'projects/e2e/portrait-rotated.jpg',
},
})
const asset = await prisma.asset.create({
data: {
name: 'portrait-rotated.jpg',
type: 'file',
status: 'uploaded',
mediaType: 'image/jpeg',
projectId: project.id,
storageKeyId: storageKey.id,
},
})
// 2. Seed S3 Storage from fixture portrait-rotated.jpg: stored 600x400 with EXIF
// orientation 6, the way cameras save portrait shots, so it is displayed 400x600.
const jpgPath = path.join(fixturesDir, 'portrait-rotated.jpg')
const jpgBuffer = fs.readFileSync(jpgPath)
await s3Service.putObject(
'shumai-e2e-test-bucket-transcode',
'projects/e2e/portrait-rotated.jpg',
jpgBuffer,
jpgBuffer.length,
'image/jpeg',
)
// 3. Create Workflow Task
const task = await prisma.workflowTask.create({
data: {
type: 'transcode_image',
status: 'pending',
assetId: asset.id,
projectId: project.id,
teamId: team.id,
payload: {
projectId: project.id,
transcode: {
thumbnail: true,
},
},
},
})
// 4. Wait for workflow to complete
console.log(
`Submitted E2E Rotated Image Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
)
const completedTask = await workflowService.executeWait(task, 45000)
// 5. Verification: the asset and its transcode are portrait, not the stored landscape.
expect(completedTask.status).toBe('completed')
const updatedAsset = await prisma.asset.findUnique({
where: { id: asset.id },
})
expect(updatedAsset?.status).toBe(AssetStatus.processed)
const mediaInfo = updatedAsset?.media as unknown as {
imageTranscodes: Array<{ width: number; height: number }>
metadata: { originalWidth: number; originalHeight: number }
}
expect(mediaInfo.metadata.originalWidth).toBe(400)
expect(mediaInfo.metadata.originalHeight).toBe(600)
expect(mediaInfo.imageTranscodes[0].width).toBe(400)
expect(mediaInfo.imageTranscodes[0].height).toBe(600)
}, 50000)
},
)
@@ -312,128 +312,6 @@ describe.each(['local', 'temporal'] as const)(
expect(mediaInfo?.videoTranscodes?.[0].resolution).toBe('360p')
})
it('should generate watermark proxy for a 3d asset from turntable video and update sharelink status to ready', async () => {
// 1. Seed Database
const team = await prisma.team.create({
data: { name: 'E2E Watermark 3D Team' },
})
const projectFolder = await prisma.asset.create({
data: { name: 'root', type: 'root', status: 'processed' },
})
const project = await prisma.project.create({
data: {
name: 'E2E Watermark 3D Project',
teamId: team.id,
rootFolderId: projectFolder.id,
},
})
const storageKey = await prisma.storageKey.create({
data: { key: 'files/e2e-watermark-3d/model.glb' },
})
const turntableKey = 'files/e2e-watermark-3d/turntable.mp4'
const videoPath = path.join(fixturesDir, 'small.mp4')
const videoBuffer = fs.readFileSync(videoPath)
await s3Service.putObject(
'shumai-e2e-test-bucket-watermark',
turntableKey,
videoBuffer,
videoBuffer.length,
'video/mp4',
)
const asset = await prisma.asset.create({
data: {
name: 'model.glb',
type: 'file',
mediaType: 'model/gltf-binary',
status: 'processed',
projectId: project.id,
storageKeyId: storageKey.id,
media: {
duration: 1,
filesize: videoBuffer.length,
frames: 30,
proxyType: '3d',
imageTranscodes: [],
videoTranscodes: [{ key: turntableKey, width: 640, height: 360, resolution: '360p' }],
videoPreview: { key: turntableKey, width: 640, height: 360, resolution: '360p' },
poster: { key: 'files/e2e-watermark-3d/poster.webp' },
finishedAt: new Date().toISOString(),
metadata: {
originalWidth: 640,
originalHeight: 360,
duration: 1,
bitRate: 0,
frameRate: 30,
totalFrames: 30,
startTimecode: '00:00:00:00',
hasAudio: false,
format: {},
},
original: {
key: storageKey.key,
filesizeInBytes: 100,
codec: '',
},
},
},
})
const shareLink = await shareService.createShareLink(project.id, {
name: 'Public Watermarked 3D Share',
})
await shareService.addAssetToShare(shareLink.id, { assetIds: [asset.id] })
const watermarkConfig: WatermarkConfigSpec = {
blocks: [
{
id: 'b1',
type: 'text',
x: 0.5,
y: 0.5,
opacity: 0.5,
rotation: 0,
text: 'CONFIDENTIAL 3D',
size: 0.2,
color: '#FF0000',
},
],
}
const updatedShare = await watermarkService.updateShareLinkWatermark(
shareLink.id,
true,
watermarkConfig,
)
expect(updatedShare.watermarkStatus).toBe('processing')
let share = await shareService.getShareLink(shareLink.id)
const startTime = Date.now()
while (share.watermarkStatus === 'processing' && Date.now() - startTime < 60000) {
await new Promise((resolve) => setTimeout(resolve, 500))
share = await shareService.getShareLink(shareLink.id)
}
expect(share.watermarkStatus).toBe('ready')
const wf = await prisma.watermarkFile.findUnique({
where: {
// eslint-disable-next-line @typescript-eslint/naming-convention
assetId_watermarkConfigId: {
assetId: asset.id,
watermarkConfigId: updatedShare.watermarkConfigId!,
},
},
})
expect(wf).toBeDefined()
expect(wf?.status).toBe(WatermarkFileStatus.completed)
const media = wf?.media as PrismaJson.MediaInfo
expect(media.proxyType).toBe('3d')
expect(media.videoTranscodes?.length).toBeGreaterThan(0)
expect(media.videoPreview?.key).toBe(media.videoTranscodes?.[0]?.key)
})
it('should watermark a newly added asset after the sharelink is already ready', async () => {
// 1. Seed Database
const team = await prisma.team.create({
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/tableprinter",
"version": "0.5.2",
"version": "0.5.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/transcode",
"version": "0.5.2",
"version": "0.5.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
@@ -1,11 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
render3dModelActivity,
start3dRenderActivity,
waitFor3dVideoRenderActivity,
generate3dSpriteActivity,
generate3dViewsActivity,
} from './transcode'
import { render3dModelActivity, generate3dSpriteActivity } from './transcode'
import { turntableService } from '@shumai/core/src/turntable/turntable'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/core/src/transcode/transcode'
@@ -32,7 +26,6 @@ vi.mock('@shumai/core/src/transcode/transcode', () => ({
transcodeService: {
convertImageToWebp: vi.fn(),
generate3dSprite: vi.fn(),
generate3dViews: vi.fn(),
},
}))
@@ -57,169 +50,11 @@ describe('3D Transcode Activities', () => {
vi.mocked(fs.readFileSync).mockReturnValue(Buffer.from('mock-bytes'))
vi.mocked(transcodeService.convertImageToWebp).mockResolvedValue(Buffer.from('webp-bytes'))
vi.mocked(transcodeService.generate3dSprite).mockResolvedValue()
vi.mocked(transcodeService.generate3dViews).mockResolvedValue()
vi.mocked(s3Service.putObject).mockResolvedValue({} as never)
vi.mocked(turntableService.deleteTask).mockResolvedValue(true)
})
describe('start3dRenderActivity', () => {
it('uploads file, starts render, immediately downloads and uploads poster to S3', async () => {
vi.mocked(turntableService.uploadFile).mockResolvedValue({
id: 'f_input',
name: 'model.glb',
size: 1024,
})
vi.mocked(turntableService.startRender).mockResolvedValue({
taskId: 'task_render_1',
status: 'queued',
poster: {
fileId: 'f_poster',
contentType: 'image/png',
width: 1080,
height: 1080,
size: 5000,
},
metadata: { format: 'glb', vertices: 120 },
})
vi.mocked(turntableService.downloadFile).mockResolvedValue(Buffer.from('poster-raw-data'))
const res = await start3dRenderActivity({
taskId: 'wf-task-1',
teamId: 'team-1',
assetId: 'asset-1',
assetKey: 'files/asset-1/model.glb',
filePath: '/tmp/model.glb',
filename: 'model.glb',
targetPosterKey: 'files/asset-1/poster.webp',
})
expect(turntableService.uploadFile).toHaveBeenCalledWith(
'/tmp/model.glb',
'model.glb',
'team-1',
)
expect(turntableService.startRender).toHaveBeenCalledWith('f_input', {}, 'team-1')
expect(turntableService.downloadFile).toHaveBeenCalledWith('f_poster', undefined, 'team-1')
expect(transcodeService.convertImageToWebp).toHaveBeenCalledWith(
Buffer.from('poster-raw-data'),
)
expect(s3Service.putObject).toHaveBeenCalledWith(
'shumai',
'files/asset-1/poster.webp',
Buffer.from('webp-bytes'),
Buffer.from('webp-bytes').length,
'image/webp',
)
expect(res.renderTaskId).toBe('task_render_1')
expect(res.posterFilePath).toBe('/tmp/poster.webp')
expect(res.posterWidth).toBe(1080)
expect(res.posterHeight).toBe(1080)
expect(res.modelMetadata).toEqual({ format: 'glb', vertices: 120 })
})
it('throws ApplicationFailure when poster file ID is missing', async () => {
vi.mocked(turntableService.uploadFile).mockResolvedValue({
id: 'f_input',
name: 'model.glb',
size: 1024,
})
vi.mocked(turntableService.startRender).mockResolvedValue({
taskId: 'task_render_1',
status: 'queued',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
poster: undefined as any,
})
await expect(
start3dRenderActivity({
taskId: 'wf-task-1',
teamId: 'team-1',
assetId: 'asset-1',
assetKey: 'files/asset-1/model.glb',
filePath: '/tmp/model.glb',
filename: 'model.glb',
targetPosterKey: 'files/asset-1/poster.webp',
}),
).rejects.toThrow('Poster file ID missing from turntable render result')
expect(turntableService.deleteTask).toHaveBeenCalledWith('task_render_1', 'team-1')
})
})
describe('waitFor3dVideoRenderActivity', () => {
it('polls until complete, downloads video, uploads to S3, and cleans up task', async () => {
vi.mocked(turntableService.getTaskStatus).mockResolvedValue({
taskId: 'task_render_1',
status: 'completed',
createdAt: new Date().toISOString(),
video: {
fileId: 'f_video',
contentType: 'video/mp4',
width: 1080,
height: 1080,
size: 1000,
},
})
vi.mocked(turntableService.downloadFile).mockResolvedValue(Buffer.from('video-data'))
const res = await waitFor3dVideoRenderActivity({
taskId: 'wf-task-1',
teamId: 'team-1',
assetKey: 'files/asset-1/model.glb',
renderTaskId: 'task_render_1',
targetVideoKey: 'files/asset-1/turntable.mp4',
tmpDir: '/tmp',
})
expect(turntableService.getTaskStatus).toHaveBeenCalledWith('task_render_1', 'team-1')
expect(turntableService.downloadFile).toHaveBeenCalledWith(
'f_video',
'/tmp/turntable.mp4',
'team-1',
)
expect(s3Service.putObject).toHaveBeenCalledWith(
'shumai',
'files/asset-1/turntable.mp4',
Buffer.from('video-data'),
Buffer.from('video-data').length,
'video/mp4',
)
expect(turntableService.deleteTask).toHaveBeenCalledWith('task_render_1', 'team-1')
expect(res.videoFilePath).toBe('/tmp/turntable.mp4')
})
it('throws ApplicationFailure when render fails on turntable-renderer', async () => {
vi.mocked(turntableService.getTaskStatus).mockResolvedValue({
taskId: 'task_render_2',
status: 'failed',
createdAt: new Date().toISOString(),
error: {
code: 'render_failed',
message: 'Blender failed to import model',
},
})
await expect(
waitFor3dVideoRenderActivity({
taskId: 'wf-task-2',
teamId: 'team-1',
assetKey: 'files/asset-1/model.glb',
renderTaskId: 'task_render_2',
targetVideoKey: 'files/asset-1/turntable.mp4',
tmpDir: '/tmp',
}),
).rejects.toThrow('Blender failed to import model')
expect(turntableService.deleteTask).toHaveBeenCalledWith('task_render_2', 'team-1')
})
})
describe('render3dModelActivity (legacy wrapper)', () => {
describe('render3dModelActivity', () => {
it('uploads file, starts render, polls until complete, and uploads to S3', async () => {
vi.mocked(turntableService.uploadFile).mockResolvedValue({
id: 'f_input',
@@ -301,6 +136,51 @@ describe('3D Transcode Activities', () => {
expect(res.videoFilePath).toBe('/tmp/turntable.mp4')
expect(res.posterFilePath).toBe('/tmp/poster.webp')
})
it('throws ApplicationFailure when render fails on turntable-renderer', async () => {
vi.mocked(turntableService.uploadFile).mockResolvedValue({
id: 'f_input',
name: 'model.glb',
size: 1024,
})
vi.mocked(turntableService.startRender).mockResolvedValue({
taskId: 'task_render_2',
status: 'queued',
poster: {
fileId: 'f_poster',
contentType: 'image/png',
width: 1080,
height: 1080,
size: 5000,
},
})
vi.mocked(turntableService.getTaskStatus).mockResolvedValue({
taskId: 'task_render_2',
status: 'failed',
createdAt: new Date().toISOString(),
error: {
code: 'render_failed',
message: 'Blender failed to import model',
},
})
await expect(
render3dModelActivity({
taskId: 'wf-task-2',
teamId: 'team-1',
assetId: 'asset-1',
assetKey: 'files/asset-1/model.glb',
filePath: '/tmp/model.glb',
filename: 'model.glb',
targetVideoKey: 'files/asset-1/turntable.mp4',
targetPosterKey: 'files/asset-1/poster.webp',
}),
).rejects.toThrow('Blender failed to import model')
expect(turntableService.deleteTask).toHaveBeenCalledWith('task_render_2', 'team-1')
})
})
describe('generate3dSpriteActivity', () => {
@@ -327,29 +207,4 @@ describe('3D Transcode Activities', () => {
expect(res.spriteKey).toBe('files/asset-1/sprite.webp')
})
})
describe('generate3dViewsActivity', () => {
it('generates 3d 4-views composite image and uploads to S3', async () => {
const res = await generate3dViewsActivity({
taskId: 'wf-task-4',
assetKey: 'files/asset-1/model.glb',
videoFilePath: '/tmp/turntable.mp4',
viewsKey: 'files/asset-1/views.webp',
})
expect(transcodeService.generate3dViews).toHaveBeenCalledWith(
'/tmp/turntable.mp4',
'/tmp/views.webp',
undefined,
)
expect(s3Service.putObject).toHaveBeenCalledWith(
'shumai',
'files/asset-1/views.webp',
expect.any(Buffer),
expect.any(Number),
'image/webp',
)
expect(res.viewsKey).toBe('files/asset-1/views.webp')
})
})
})
@@ -27,7 +27,6 @@ import {
transcodeVideoChunkActivity,
deleteS3ObjectActivity,
createAutofillTaskIfEnabledActivity,
createEmbeddingTaskIfEnabledActivity,
} from './transcode'
vi.mock('@shumai/core/src/s3/s3', () => ({
@@ -1718,115 +1717,4 @@ describe('Transcode Activities', () => {
expect((task?.payload as any)?.agent?.agentId).toBe(autofillAgent.id)
})
})
describe('createEmbeddingTaskIfEnabledActivity', () => {
it('should create ai_embedding task for 3D asset with imageTranscodes', async () => {
const user = await prisma.user.create({
data: { name: 'Test User Embedding', email: 'test-embedding-agent@test.com' },
})
const team = await prisma.team.create({
data: { name: 'Test Team Embedding' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: user.id, role: 'owner' },
})
const project = await prisma.project.create({
data: { name: 'Test Project Embedding', teamId: team.id },
})
const embeddingAgent = await prisma.agent.create({
data: {
id: user.id,
type: 'embedding',
enabled: true,
teamId: team.id,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: { provider: 'test', model: 'test' } as any,
},
})
const asset = await prisma.asset.create({
data: {
name: 'robot.glb',
mediaType: 'model/gltf-binary',
type: 'file',
status: 'processed',
projectId: project.id,
media: {
proxyType: '3d',
imageTranscodes: [
{
key: 'files/asset-1/views.webp',
width: 2880,
height: 2880,
quality: 85,
format: 'webp',
},
],
} as unknown as PrismaJson.MediaInfo,
},
})
await createEmbeddingTaskIfEnabledActivity({
assetId: asset.id,
teamId: team.id,
projectId: project.id,
})
const task = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: 'ai_embedding' },
})
expect(task).toBeDefined()
expect(task?.status).toBe('pending')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((task?.payload as any)?.agent?.agentId).toBe(embeddingAgent.id)
})
it('should NOT create ai_embedding task for 3D asset without imageTranscodes', async () => {
const user = await prisma.user.create({
data: { name: 'Test User Embedding 2', email: 'test-embedding-agent-2@test.com' },
})
const team = await prisma.team.create({
data: { name: 'Test Team Embedding 2' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: user.id, role: 'owner' },
})
const project = await prisma.project.create({
data: { name: 'Test Project Embedding 2', teamId: team.id },
})
await prisma.agent.create({
data: {
id: user.id,
type: 'embedding',
enabled: true,
teamId: team.id,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: { provider: 'test', model: 'test' } as any,
},
})
const asset = await prisma.asset.create({
data: {
name: 'robot.glb',
mediaType: 'model/gltf-binary',
type: 'file',
status: 'processed',
projectId: project.id,
media: {
proxyType: '3d',
imageTranscodes: [],
} as unknown as PrismaJson.MediaInfo,
},
})
await createEmbeddingTaskIfEnabledActivity({
assetId: asset.id,
teamId: team.id,
projectId: project.id,
})
const task = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: 'ai_embedding' },
})
expect(task).toBeNull()
})
})
})
+56 -229
View File
@@ -8,10 +8,7 @@ import {
} from '@shumai/core/src/transcode/transcode'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { getDerivedArtifactDirectory, stemFromKey } from '@shumai/core/src/utils/filename'
import {
gotenbergService,
type GotenbergConvertOptions,
} from '@shumai/core/src/gotenberg/gotenberg'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { turntableService } from '@shumai/core/src/turntable/turntable'
import { parseCsvContent } from '@shumai/core/src/transcode/transcode'
import { resolutionToDimensions } from '../workflows/transcode-utils'
@@ -919,7 +916,6 @@ export async function generateSpriteActivity(params: GenerateSpriteActivityParam
}
export interface GeneratePdfProxyActivityParams {
teamId?: string | null
assetId: string
assetKey: string
filePath: string
@@ -946,12 +942,8 @@ export async function generatePdfProxyActivity(
const tmpDir = path.dirname(params.filePath)
const pdfFilePath = path.join(tmpDir, 'proxy.pdf')
const targetTeamId = params.teamId || undefined
try {
const gotenbergAvailable = await (targetTeamId
? gotenbergService.isAvailable(targetTeamId)
: gotenbergService.isAvailable())
const gotenbergAvailable = await gotenbergService.isAvailable()
if (isOffice) {
if (!gotenbergAvailable) {
@@ -959,14 +951,10 @@ export async function generatePdfProxyActivity(
'Gotenberg service is required for Office document conversion but is unavailable.',
)
}
const pdfBuffer = await (targetTeamId
? gotenbergService.convertDocumentToPdf(
params.filePath,
params.filename,
{ teamId: targetTeamId },
targetTeamId,
)
: gotenbergService.convertDocumentToPdf(params.filePath, params.filename))
const pdfBuffer = await gotenbergService.convertDocumentToPdf(
params.filePath,
params.filename,
)
fs.writeFileSync(pdfFilePath, pdfBuffer)
} else if (isHtml) {
if (!gotenbergAvailable) {
@@ -974,9 +962,7 @@ export async function generatePdfProxyActivity(
'Gotenberg service is required for HTML document conversion but is unavailable.',
)
}
const pdfBuffer = await (targetTeamId
? gotenbergService.convertHtmlToPdf(params.filePath, params.filename, targetTeamId)
: gotenbergService.convertHtmlToPdf(params.filePath, params.filename))
const pdfBuffer = await gotenbergService.convertHtmlToPdf(params.filePath, params.filename)
fs.writeFileSync(pdfFilePath, pdfBuffer)
} else if (isCsv) {
if (gotenbergAvailable) {
@@ -989,14 +975,10 @@ export async function generatePdfProxyActivity(
} catch {
// Fallback landscape calculation
}
const options: GotenbergConvertOptions = {
landscape: isLandscape,
...(targetTeamId ? { teamId: targetTeamId } : {}),
}
const pdfBuffer = await gotenbergService.convertDocumentToPdf(
params.filePath,
params.filename,
options,
{ landscape: isLandscape },
)
fs.writeFileSync(pdfFilePath, pdfBuffer)
} else {
@@ -1004,23 +986,20 @@ export async function generatePdfProxyActivity(
}
} else if (isMd) {
if (gotenbergAvailable) {
const pdfBuffer = await (targetTeamId
? gotenbergService.convertMarkdownToPdf(params.filePath, params.filename, targetTeamId)
: gotenbergService.convertMarkdownToPdf(params.filePath, params.filename))
const pdfBuffer = await gotenbergService.convertMarkdownToPdf(
params.filePath,
params.filename,
)
fs.writeFileSync(pdfFilePath, pdfBuffer)
} else {
await transcodeService.generatePdfFromText(params.filePath, pdfFilePath)
}
} else if (isTxt) {
if (gotenbergAvailable) {
const pdfBuffer = await (targetTeamId
? gotenbergService.convertDocumentToPdf(
params.filePath,
params.filename,
{ teamId: targetTeamId },
targetTeamId,
)
: gotenbergService.convertDocumentToPdf(params.filePath, params.filename))
const pdfBuffer = await gotenbergService.convertDocumentToPdf(
params.filePath,
params.filename,
)
fs.writeFileSync(pdfFilePath, pdfBuffer)
} else {
await transcodeService.generatePdfFromText(params.filePath, pdfFilePath)
@@ -1360,11 +1339,8 @@ export async function createEmbeddingTaskIfEnabledActivity(
return
}
const mediaInfo = asset.media as PrismaJson.MediaInfo | null
const isVideo = asset.mediaType?.startsWith('video/')
const isImage =
asset.mediaType?.startsWith('image/') ||
(mediaInfo?.proxyType === '3d' && (mediaInfo.imageTranscodes?.length ?? 0) > 0)
const isImage = asset.mediaType?.startsWith('image/')
if (!isVideo && !isImage) {
return
}
@@ -1594,27 +1570,9 @@ export interface Render3dModelActivityResult {
modelMetadata?: Record<string, unknown>
}
export interface Start3dRenderActivityParams {
taskId: string
teamId: string
assetId: string
assetKey: string
filePath: string
filename: string
targetPosterKey: string
}
export interface Start3dRenderActivityResult {
renderTaskId: string
posterFilePath: string
posterWidth?: number
posterHeight?: number
modelMetadata?: Record<string, unknown>
}
export async function start3dRenderActivity(
params: Start3dRenderActivityParams,
): Promise<Start3dRenderActivityResult> {
export async function render3dModelActivity(
params: Render3dModelActivityParams,
): Promise<Render3dModelActivityResult> {
const signal = getActivityCancellationSignal(params.taskId)
if (signal?.aborted) {
throw ApplicationFailure.create({
@@ -1625,9 +1583,9 @@ export async function start3dRenderActivity(
const bucket = process.env.S3_BUCKET || 'shumai'
const tmpDir = path.dirname(params.filePath)
const videoFilePath = path.join(tmpDir, 'turntable.mp4')
const posterFilePath = path.join(tmpDir, 'poster.webp')
let fileId: string | undefined
let renderTaskId: string | undefined
try {
@@ -1636,7 +1594,7 @@ export async function start3dRenderActivity(
params.filename,
params.teamId,
)
fileId = uploadResult.id
const fileId = uploadResult.id
if (signal?.aborted) {
await turntableService.deleteFile(fileId, params.teamId).catch(() => {})
@@ -1649,87 +1607,14 @@ export async function start3dRenderActivity(
const startResult = await turntableService.startRender(fileId, {}, params.teamId)
renderTaskId = startResult.taskId
const posterFileId = startResult.poster?.fileId
if (!posterFileId) {
throw ApplicationFailure.create({
message: 'Poster file ID missing from turntable render result',
nonRetryable: true,
})
}
const posterBuffer = await turntableService.downloadFile(posterFileId, undefined, params.teamId)
const posterWebpBuffer = await transcodeService.convertImageToWebp(posterBuffer)
fs.writeFileSync(posterFilePath, posterWebpBuffer)
await ensureAssetNotPurging(params.assetKey)
await s3Service.putObject(
bucket,
params.targetPosterKey,
posterWebpBuffer,
posterWebpBuffer.length,
'image/webp',
)
return {
renderTaskId,
posterFilePath,
posterWidth: startResult.poster?.width,
posterHeight: startResult.poster?.height,
modelMetadata: (startResult.metadata as Record<string, unknown>) || {},
}
} catch (err) {
if (renderTaskId) {
await turntableService.deleteTask(renderTaskId, params.teamId).catch(() => {})
} else if (fileId) {
await turntableService.deleteFile(fileId, params.teamId).catch(() => {})
}
if (err instanceof ApplicationFailure) {
throw err
}
const errMsg = err instanceof Error ? err.message : String(err)
throw ApplicationFailure.create({
message: `Failed to start 3D render: ${errMsg}`,
nonRetryable: true,
})
}
}
export interface WaitFor3dVideoRenderActivityParams {
taskId: string
teamId: string
assetKey: string
renderTaskId: string
targetVideoKey: string
tmpDir: string
}
export interface WaitFor3dVideoRenderActivityResult {
videoFilePath: string
}
export async function waitFor3dVideoRenderActivity(
params: WaitFor3dVideoRenderActivityParams,
): Promise<WaitFor3dVideoRenderActivityResult> {
const signal = getActivityCancellationSignal(params.taskId)
if (signal?.aborted) {
await turntableService.deleteTask(params.renderTaskId, params.teamId).catch(() => {})
throw ApplicationFailure.create({
message: 'Render cancelled',
nonRetryable: true,
})
}
const bucket = process.env.S3_BUCKET || 'shumai'
const videoFilePath = path.join(params.tmpDir, 'turntable.mp4')
try {
let finishedStatus: 'completed' | 'failed' | null = null
let taskRecord: Awaited<ReturnType<typeof turntableService.getTaskStatus>> | null = null
for (let i = 0; i < 360; i++) {
if (signal?.aborted) {
await turntableService.deleteTask(params.renderTaskId, params.teamId).catch(() => {})
if (renderTaskId) {
await turntableService.deleteTask(renderTaskId, params.teamId).catch(() => {})
}
throw ApplicationFailure.create({
message: 'Render cancelled',
nonRetryable: true,
@@ -1740,7 +1625,7 @@ export async function waitFor3dVideoRenderActivity(
await new Promise((resolve) => setTimeout(resolve, 5000))
}
taskRecord = await turntableService.getTaskStatus(params.renderTaskId, params.teamId)
taskRecord = await turntableService.getTaskStatus(renderTaskId, params.teamId)
if (taskRecord.status === 'completed') {
finishedStatus = 'completed'
break
@@ -1770,11 +1655,24 @@ export async function waitFor3dVideoRenderActivity(
})
}
const posterFileId = startResult.poster?.fileId
if (!posterFileId) {
throw ApplicationFailure.create({
message: 'Poster file ID missing from turntable render result',
nonRetryable: true,
})
}
const videoBuffer = await turntableService.downloadFile(
videoFileId,
videoFilePath,
params.teamId,
)
const posterBuffer = await turntableService.downloadFile(posterFileId, undefined, params.teamId)
const posterWebpBuffer = await transcodeService.convertImageToWebp(posterBuffer)
fs.writeFileSync(posterFilePath, posterWebpBuffer)
await ensureAssetNotPurging(params.assetKey)
@@ -1786,62 +1684,39 @@ export async function waitFor3dVideoRenderActivity(
'video/mp4',
)
await turntableService.deleteTask(params.renderTaskId, params.teamId).catch((err) => {
logger.warn(
{ err, taskId: params.renderTaskId },
'Failed to delete turntable task after completion',
)
await s3Service.putObject(
bucket,
params.targetPosterKey,
posterWebpBuffer,
posterWebpBuffer.length,
'image/webp',
)
await turntableService.deleteTask(renderTaskId, params.teamId).catch((err) => {
logger.warn({ err, taskId: renderTaskId }, 'Failed to delete turntable task after completion')
})
renderTaskId = undefined
return {
videoFilePath,
posterFilePath,
modelMetadata: (startResult.metadata as Record<string, unknown>) || {},
}
} catch (err) {
await turntableService.deleteTask(params.renderTaskId, params.teamId).catch(() => {})
if (renderTaskId) {
await turntableService.deleteTask(renderTaskId, params.teamId).catch(() => {})
}
if (err instanceof ApplicationFailure) {
throw err
}
const errMsg = err instanceof Error ? err.message : String(err)
throw ApplicationFailure.create({
message: `Failed to render 3D model video: ${errMsg}`,
message: `Failed to render 3D model: ${errMsg}`,
nonRetryable: true,
})
}
}
/**
* @deprecated Legacy monolithic 3D render activity. Prefer using `start3dRenderActivity` and `waitFor3dVideoRenderActivity`.
*/
export async function render3dModelActivity(
params: Render3dModelActivityParams,
): Promise<Render3dModelActivityResult> {
const tmpDir = path.dirname(params.filePath)
const startResult = await start3dRenderActivity({
taskId: params.taskId,
teamId: params.teamId,
assetId: params.assetId,
assetKey: params.assetKey,
filePath: params.filePath,
filename: params.filename,
targetPosterKey: params.targetPosterKey,
})
const videoResult = await waitFor3dVideoRenderActivity({
taskId: params.taskId,
teamId: params.teamId,
assetKey: params.assetKey,
renderTaskId: startResult.renderTaskId,
targetVideoKey: params.targetVideoKey,
tmpDir,
})
return {
videoFilePath: videoResult.videoFilePath,
posterFilePath: startResult.posterFilePath,
modelMetadata: startResult.modelMetadata,
}
}
export interface Generate3dSpriteActivityParams {
taskId: string
assetKey: string
@@ -1889,51 +1764,3 @@ export async function generate3dSpriteActivity(
})
}
}
export interface Generate3dViewsActivityParams {
taskId: string
assetKey: string
videoFilePath: string
viewsKey: string
}
export async function generate3dViewsActivity(
params: Generate3dViewsActivityParams,
): Promise<{ viewsKey: string }> {
const signal = getActivityCancellationSignal(params.taskId)
if (signal?.aborted) {
throw ApplicationFailure.create({
message: '3D views generation cancelled',
nonRetryable: true,
})
}
const bucket = process.env.S3_BUCKET || 'shumai'
const tmpDir = path.dirname(params.videoFilePath)
const viewsFilePath = path.join(tmpDir, 'views.webp')
try {
await transcodeService.generate3dViews(params.videoFilePath, viewsFilePath, signal)
const viewsBuffer = fs.readFileSync(viewsFilePath)
await ensureAssetNotPurging(params.assetKey)
await s3Service.putObject(
bucket,
params.viewsKey,
viewsBuffer,
viewsBuffer.length,
'image/webp',
)
return { viewsKey: params.viewsKey }
} catch (err) {
if (err instanceof ApplicationFailure) {
throw err
}
const errMsg = err instanceof Error ? err.message : String(err)
throw ApplicationFailure.create({
message: `Failed to generate 3D views: ${errMsg}`,
nonRetryable: true,
})
}
}
@@ -618,125 +618,6 @@ describe('Watermark Activities', () => {
}),
)
})
it('produces a watermarked mp4 proxy from the turntable video for a 3d asset', async () => {
const storageKey = await prisma.storageKey.create({
data: { key: 'files/asset-3d/robot.glb' },
})
const asset = await prisma.asset.create({
data: {
name: 'robot.glb',
type: 'file',
mediaType: 'model/gltf-binary',
status: 'processed',
storageKeyId: storageKey.id,
media: {
duration: 4,
filesize: 100,
frames: 24,
proxyType: '3d',
videoTranscodes: [
{
key: 'files/asset-3d/turntable.mp4',
width: 1080,
height: 1080,
resolution: '1080p',
},
],
videoPreview: {
key: 'files/asset-3d/turntable.mp4',
width: 1080,
height: 1080,
resolution: '1080p',
},
poster: { key: 'files/asset-3d/poster.webp' },
sprite: { key: 'files/asset-3d/sprite.webp', frames: 100, tileX: 10, tileY: 10 },
finishedAt: new Date().toISOString(),
metadata: {
originalWidth: 1080,
originalHeight: 1080,
duration: 4,
bitRate: 0,
frameRate: 6,
totalFrames: 24,
startTimecode: '00:00:00:00',
hasAudio: false,
format: {},
},
original: {
key: 'files/asset-3d/robot.glb',
filesizeInBytes: 100,
codec: '',
},
} as PrismaJson.MediaInfo,
},
})
const config = await seedConfig()
vi.mocked(transcodeService.getVideoInfo).mockResolvedValue({
originalWidth: 1080,
originalHeight: 1080,
duration: 4,
bitRate: 2000,
frameRate: 6,
totalFrames: 24,
startTimecode: '00:00:00:00',
hasAudio: false,
mimeType: 'video/mp4',
})
vi.mocked(s3Service.putObject).mockResolvedValue(undefined as never)
const stem = 'robot'
const configId = config.id
const outFilePath = path.join('/tmp', `${stem}-watermark-${configId}-1080p.mp4`)
fs.writeFileSync(outFilePath, Buffer.from('fake 3d watermarked turntable mp4'))
const media = await transcodeWatermarkMediaActivity({
assetId: asset.id,
watermarkConfigId: config.id,
})
expect(media.proxyType).toBe('3d')
expect(media.videoTranscodes?.length).toBeGreaterThan(0)
expect(media.videoTranscodes?.[0].key).toContain('watermark-')
expect(media.videoPreview?.key).toBe(media.videoTranscodes?.[0].key)
expect(media.poster?.key).toBe('files/asset-3d/poster.webp')
expect(media.sprite?.key).toBe('files/asset-3d/sprite.webp')
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
bucket,
'files/asset-3d/turntable.mp4',
expect.any(String),
)
fs.rmSync(outFilePath, { force: true })
})
it('throws non-retryable ApplicationFailure when 3d asset has no turntable video transcode', async () => {
const storageKey = await prisma.storageKey.create({
data: { key: 'files/asset-3d/robot.glb' },
})
const asset = await prisma.asset.create({
data: {
name: 'robot.glb',
type: 'file',
mediaType: 'model/gltf-binary',
status: 'processing',
storageKeyId: storageKey.id,
media: {
proxyType: '3d',
videoTranscodes: [],
} as unknown as PrismaJson.MediaInfo,
},
})
const config = await seedConfig()
await expect(
transcodeWatermarkMediaActivity({
assetId: asset.id,
watermarkConfigId: config.id,
}),
).rejects.toThrow('Turntable video transcode not found for 3D asset')
})
})
describe('completeWatermarkFileActivity', () => {
+16 -44
View File
@@ -163,39 +163,17 @@ export async function transcodeWatermarkMediaActivity(
const stem = stemFromKey(assetKey)
const tmpDir = transcodeService.createTempDir('watermark-')
const rawFilePath = path.join(tmpDir, path.basename(assetKey))
try {
const is3d = (asset.media as PrismaJson.MediaInfo | null)?.proxyType === '3d'
await s3Service.downloadToFile(bucket, assetKey, rawFilePath)
const isVideo =
!is3d &&
(asset.mediaType?.startsWith('video/') ||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'video')
asset.mediaType?.startsWith('video/') ||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'video'
const isImage =
!is3d &&
(asset.mediaType?.startsWith('image/') ||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'image')
if (!isVideo && !isImage && !is3d) {
throw ApplicationFailure.create({
message: `Asset ${params.assetId} is neither video nor image`,
nonRetryable: true,
})
}
const inputKey = is3d
? (asset.media as PrismaJson.MediaInfo | null)?.videoTranscodes?.[0]?.key ||
(asset.media as PrismaJson.MediaInfo | null)?.videoPreview?.key
: assetKey
if (is3d && !inputKey) {
throw ApplicationFailure.create({
message: `Turntable video transcode not found for 3D asset ${params.assetId}`,
nonRetryable: true,
})
}
const rawFilePath = path.join(tmpDir, path.basename(inputKey!))
await s3Service.downloadToFile(bucket, inputKey!, rawFilePath)
asset.mediaType?.startsWith('image/') ||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'image'
let originalWidth = 1920
let originalHeight = 1080
@@ -214,7 +192,7 @@ export async function transcodeWatermarkMediaActivity(
let hdrType: PrismaJson.HdrType | undefined
let dvProfile: number | undefined
if (isVideo || is3d) {
if (isVideo) {
const info = await transcodeService.getVideoInfo(rawFilePath)
originalWidth = info.originalWidth
originalHeight = info.originalHeight
@@ -236,6 +214,11 @@ export async function transcodeWatermarkMediaActivity(
const info = await transcodeService.getImageInfo(rawFilePath)
originalWidth = info.originalWidth
originalHeight = info.originalHeight
} else {
throw ApplicationFailure.create({
message: `Asset ${params.assetId} is neither video nor image`,
nonRetryable: true,
})
}
// Process image blocks if any
@@ -277,11 +260,9 @@ export async function transcodeWatermarkMediaActivity(
duration,
filesize: 0,
frames: totalFrames,
proxyType: is3d ? '3d' : isVideo ? 'video' : 'image',
proxyType: isVideo ? 'video' : 'image',
imageTranscodes: [],
videoTranscodes: [],
poster: originalMedia?.poster,
sprite: originalMedia?.sprite,
finishedAt: new Date().toISOString(),
metadata: {
originalWidth,
@@ -299,7 +280,7 @@ export async function transcodeWatermarkMediaActivity(
isHdr: isHdr ?? originalMedia?.metadata?.isHdr,
hdrType: hdrType ?? originalMedia?.metadata?.hdrType,
dvProfile: dvProfile ?? originalMedia?.metadata?.dvProfile,
format: originalMedia?.metadata?.format ?? {},
format: {},
},
original: {
key: assetKey,
@@ -352,7 +333,7 @@ export async function transcodeWatermarkMediaActivity(
})
}
mediaInfo.filesize = totalSize
} else if (isVideo || is3d) {
} else if (isVideo) {
const originalTranscodes = originalMedia?.videoTranscodes || []
let totalSize = 0
@@ -414,15 +395,6 @@ export async function transcodeWatermarkMediaActivity(
})
}
if (is3d && mediaInfo.videoTranscodes.length > 0) {
mediaInfo.videoPreview = {
key: mediaInfo.videoTranscodes[0].key,
width: mediaInfo.videoTranscodes[0].width,
height: mediaInfo.videoTranscodes[0].height,
resolution: mediaInfo.videoTranscodes[0].resolution,
}
}
if (originalMedia?.isHls && originalMedia?.hls?.resolutions?.length) {
const hlsWatermarkDirKey = path.posix.join(
path.posix.dirname(assetKey),
@@ -24,12 +24,7 @@ describe('transcode3dWorkflow', () => {
}),
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
render3dModelActivity: Object.assign(vi.fn(), { _activityName: 'render3dModelActivity' }),
start3dRenderActivity: Object.assign(vi.fn(), { _activityName: 'start3dRenderActivity' }),
waitFor3dVideoRenderActivity: Object.assign(vi.fn(), {
_activityName: 'waitFor3dVideoRenderActivity',
}),
generate3dSpriteActivity: Object.assign(vi.fn(), { _activityName: 'generate3dSpriteActivity' }),
generate3dViewsActivity: Object.assign(vi.fn(), { _activityName: 'generate3dViewsActivity' }),
updateAssetMediaActivity: Object.assign(vi.fn(), {
_activityName: 'updateAssetMediaActivity',
}),
@@ -104,16 +99,10 @@ describe('transcode3dWorkflow', () => {
sizeByte: BigInt(1024),
})
mockActivities.start3dRenderActivity.mockResolvedValue({
renderTaskId: 'task_render_1',
posterFilePath: '/tmp/poster.webp',
posterWidth: 1080,
posterHeight: 1080,
modelMetadata: { format: 'glb' },
})
mockActivities.waitFor3dVideoRenderActivity.mockResolvedValue({
mockActivities.render3dModelActivity.mockResolvedValue({
videoFilePath: '/tmp/turntable.mp4',
posterFilePath: '/tmp/poster.webp',
modelMetadata: { format: 'glb' },
})
mockActivities.generate3dSpriteActivity.mockResolvedValue({
@@ -127,44 +116,15 @@ describe('transcode3dWorkflow', () => {
status: AssetStatus.processing,
})
expect(mockActivities.start3dRenderActivity).toHaveBeenCalledWith({
expect(mockActivities.render3dModelActivity).toHaveBeenCalledWith({
taskId: 'task-3d',
teamId: 'team-1',
assetId: 'asset-3d',
assetKey: 'files/asset-3d/robot.glb',
filePath: '/tmp/model.glb',
filename: 'robot.glb',
targetPosterKey: 'files/asset-3d/poster.webp',
})
// Verify initial updateAssetMediaActivity with poster was called before waitFor3dVideoRenderActivity
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith(
expect.objectContaining({
assetId: 'asset-3d',
mediaInfo: expect.objectContaining({
proxyType: '3d',
poster: { key: 'files/asset-3d/poster.webp' },
metadata: expect.objectContaining({
format: { format: 'glb' },
originalHeight: 1080,
originalWidth: 1080,
}),
}),
}),
)
const firstMediaUpdateOrder =
mockActivities.updateAssetMediaActivity.mock.invocationCallOrder[0]
const waitVideoOrder = mockActivities.waitFor3dVideoRenderActivity.mock.invocationCallOrder[0]
expect(firstMediaUpdateOrder).toBeLessThan(waitVideoOrder)
expect(mockActivities.waitFor3dVideoRenderActivity).toHaveBeenCalledWith({
taskId: 'task-3d',
teamId: 'team-1',
assetKey: 'files/asset-3d/robot.glb',
renderTaskId: 'task_render_1',
targetVideoKey: 'files/asset-3d/turntable.mp4',
tmpDir: '/tmp',
targetPosterKey: 'files/asset-3d/poster.webp',
})
expect(mockActivities.generate3dSpriteActivity).toHaveBeenCalledWith({
@@ -174,13 +134,6 @@ describe('transcode3dWorkflow', () => {
spriteKey: 'files/asset-3d/sprite.webp',
})
expect(mockActivities.generate3dViewsActivity).toHaveBeenCalledWith({
taskId: 'task-3d',
assetKey: 'files/asset-3d/robot.glb',
videoFilePath: '/tmp/turntable.mp4',
viewsKey: 'files/asset-3d/views.webp',
})
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith(
expect.objectContaining({
assetId: 'asset-3d',
@@ -190,15 +143,6 @@ describe('transcode3dWorkflow', () => {
frames: 24,
poster: { key: 'files/asset-3d/poster.webp' },
sprite: expect.objectContaining({ key: 'files/asset-3d/sprite.webp' }),
imageTranscodes: [
{
key: 'files/asset-3d/views.webp',
width: 2880,
height: 2880,
quality: 85,
format: 'webp',
},
],
}),
}),
)
@@ -250,7 +194,7 @@ describe('transcode3dWorkflow', () => {
sizeByte: BigInt(512),
})
mockActivities.start3dRenderActivity.mockRejectedValue(new Error('Renderer crashed'))
mockActivities.render3dModelActivity.mockRejectedValue(new Error('Renderer crashed'))
await expect(transcode3dWorkflow(task)).rejects.toThrow('Renderer crashed')
@@ -20,10 +20,8 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
const {
updateAssetStatusActivity,
downloadMediaToTmpActivity,
start3dRenderActivity,
waitFor3dVideoRenderActivity,
render3dModelActivity,
generate3dSpriteActivity,
generate3dViewsActivity,
updateAssetMediaActivity,
createEmbeddingTaskIfEnabledActivity,
createAutofillTaskIfEnabledActivity,
@@ -47,20 +45,24 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
const videoKey = assetDir ? `${assetDir}/turntable.mp4` : 'turntable.mp4'
const posterKey = assetDir ? `${assetDir}/poster.webp` : 'poster.webp'
const spriteKey = assetDir ? `${assetDir}/sprite.webp` : 'sprite.webp'
const viewsKey = assetDir ? `${assetDir}/views.webp` : 'views.webp'
const renderStart = await executeActivity(workerQueue, start3dRenderActivity, {
const renderResult = await executeActivity(workerQueue, render3dModelActivity, {
taskId: task.id,
teamId: task.teamId,
assetId: asset.id,
assetKey: key,
filePath: currentFilePath,
filename: asset.name || 'model.glb',
targetVideoKey: videoKey,
targetPosterKey: posterKey,
})
const posterWidth = renderStart.posterWidth || 1080
const posterHeight = renderStart.posterHeight || 1080
await executeActivity(workerQueue, generate3dSpriteActivity, {
taskId: task.id,
assetKey: key,
videoFilePath: renderResult.videoFilePath,
spriteKey,
})
const mediaInfo: PrismaJson.MediaInfo = {
duration: 4,
@@ -68,21 +70,40 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
frames: 24,
proxyType: '3d',
imageTranscodes: [],
videoTranscodes: [],
videoTranscodes: [
{
key: videoKey,
width: 1080,
height: 1080,
resolution: '1080p',
},
],
videoPreview: {
key: videoKey,
width: 1080,
height: 1080,
resolution: '1080p',
},
poster: {
key: posterKey,
},
sprite: {
key: spriteKey,
frames: 100,
tileX: 10,
tileY: 10,
},
finishedAt: new Date().toISOString(),
metadata: {
originalHeight: posterHeight,
originalWidth: posterWidth,
originalHeight: 1080,
originalWidth: 1080,
hasAudio: false,
duration: 4,
bitRate: 0,
frameRate: 6,
totalFrames: 24,
startTimecode: '00:00:00:00',
format: renderStart.modelMetadata ?? {},
format: renderResult.modelMetadata ?? {},
},
original: {
key,
@@ -96,72 +117,6 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
mediaInfo,
})
const renderVideo = await executeActivity(workerQueue, waitFor3dVideoRenderActivity, {
taskId: task.id,
teamId: task.teamId,
assetKey: key,
renderTaskId: renderStart.renderTaskId,
targetVideoKey: videoKey,
tmpDir,
})
await executeActivity(workerQueue, generate3dSpriteActivity, {
taskId: task.id,
assetKey: key,
videoFilePath: renderVideo.videoFilePath,
spriteKey,
})
mediaInfo.sprite = {
key: spriteKey,
frames: 100,
tileX: 10,
tileY: 10,
}
await executeActivity(workerQueue, generate3dViewsActivity, {
taskId: task.id,
assetKey: key,
videoFilePath: renderVideo.videoFilePath,
viewsKey,
})
mediaInfo.imageTranscodes = [
{
key: viewsKey,
width: 2880,
height: 2880,
quality: 85,
format: 'webp',
},
]
await executeActivity(workerQueue, updateAssetMediaActivity, {
assetId: asset.id,
mediaInfo,
})
mediaInfo.videoTranscodes = [
{
key: videoKey,
width: 1080,
height: 1080,
resolution: '1080p',
},
]
mediaInfo.videoPreview = {
key: videoKey,
width: 1080,
height: 1080,
resolution: '1080p',
}
mediaInfo.finishedAt = new Date().toISOString()
await executeActivity(workerQueue, updateAssetMediaActivity, {
assetId: asset.id,
mediaInfo,
})
await executeActivity(workerQueue, updateAssetStatusActivity, {
assetId: asset.id,
status: 'processed',
@@ -42,7 +42,6 @@ export async function transcodePdfWorkflow(task: WorkflowTask): Promise<void> {
tmpDir = download.tmpDir
const pdfProxy = await executeActivity(workerQueue, generatePdfProxyActivity, {
teamId: task.teamId,
assetId: asset.id,
assetKey: key,
filePath: currentFilePath,
@@ -263,45 +263,4 @@ describe('BreadcrumbNav component', () => {
expect(items.some((i) => i.textContent?.includes('1080p'))).toBe(true)
expect(items.some((i) => i.textContent?.includes('1920p'))).toBe(false)
})
it('correctly labels 1080p square / 3D turntable transcode in download menu', () => {
render(
<QueryClientProvider client={queryClient}>
<BreadcrumbNav
{...baseProps}
fileId="file-3d"
currentAsset={{
id: 'file-3d',
name: 'model.glb',
type: 'file',
version: 1,
proxyType: '3d',
}}
allowDownload={true}
downloadInfo={{
originalKey: 'model.glb',
videoTranscodes: [
{
key: 'turntable-1080p.mp4',
width: 1080,
height: 1080,
resolution: '1080p',
hdr: false,
},
],
}}
/>
</QueryClientProvider>,
)
const triggerButton = screen.getByRole('button', { name: 'model.glb' })
fireEvent.pointerDown(triggerButton, { button: 0, ctrlKey: false })
const downloadSubTrigger = screen.getByText('Download')
fireEvent.click(downloadSubTrigger)
const items = screen.getAllByRole('menuitem')
expect(items.some((i) => i.textContent?.includes('1080p'))).toBe(true)
expect(items.some((i) => i.textContent?.includes('480p'))).toBe(false)
})
})
@@ -58,7 +58,6 @@ export const FilePreview = ({ item, showDuration = false }: FilePreviewProps) =>
thumbnailUrl={item.preview.thumbnailUrl!}
videoWidth={item.preview.originalWidth!}
videoHeight={item.preview.originalHeight!}
reverse={is3D}
/>
{overlay}
</>
@@ -12,7 +12,6 @@ export function FileViewer({
onPlay,
onPause,
onTimeUpdate,
onSeek,
annotations,
startTime,
shareId,
@@ -31,7 +30,6 @@ export function FileViewer({
onPlay={onPlay}
onPause={onPause}
onTimeUpdate={onTimeUpdate}
onSeek={onSeek}
annotations={annotations}
startTime={startTime}
shareId={shareId}
@@ -156,11 +156,6 @@ export function MobileFileDetail({
setSelectedCommentId(null)
}
const handleSeek = () => {
setAnnotations([])
setSelectedCommentId(null)
}
const handleCommentSelect = (comment: CommentInfo) => {
setSelectedCommentId(comment.id || null)
const newAnnotations = comment.annotations as Annotation[]
@@ -243,7 +238,6 @@ export function MobileFileDetail({
mediaControllerRef={mediaControllerRef}
onPlay={handlePlay}
onTimeUpdate={setCurrentTime}
onSeek={handleSeek}
annotations={annotations}
startTime={startTime}
shareId={shareId}
@@ -385,11 +385,6 @@ export function PublicShareManager({
setSelectedCommentId(null)
}
const handleSeek = () => {
setAnnotations([])
setSelectedCommentId(null)
}
const updateCompareSearch = (patch: Record<string, unknown>) => {
if (!viewingFileId) return
navigate({
@@ -661,7 +656,6 @@ export function PublicShareManager({
mediaControllerRef={mediaControllerRef}
onPlay={handlePlay}
onTimeUpdate={setCurrentTime}
onSeek={handleSeek}
annotations={annotations}
startTime={startTime}
shareId={shareId}
@@ -1,210 +0,0 @@
// @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 { GotenbergSettingsCard } from './GotenbergSettingsCard'
import type { GotenbergSettingsResponse } from '@shumai/dtos'
const mockGetSettings = vi.fn()
const mockPutSettings = vi.fn()
const mockTestSettings = vi.fn()
vi.mock('@/ui/api/client', () => ({
client: {
api: {
teams: {
':teamId': {
'gotenberg-settings': {
$get: () => mockGetSettings(),
$put: (args: unknown) => mockPutSettings(args),
test: {
$post: (args: unknown) => mockTestSettings(args),
},
},
},
},
},
},
}))
vi.mock('sonner', () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
},
}))
vi.mock('@/ui/paraglide/messages.js', () => ({
m: {
gotenberg_settings: () => 'Gotenberg Document Converter',
gotenberg_settings_description: () => 'Configure external Gotenberg service',
gotenberg_env_configured: () => 'Configured via Environment',
gotenberg_server_url: () => 'Server URL',
gotenberg_server_url_placeholder: () => 'http://localhost:3000',
gotenberg_username: () => 'Username',
gotenberg_password: () => 'Password',
gotenberg_password_placeholder: () => 'Saved password',
gotenberg_test_connection: () => 'Test Connection',
gotenberg_testing: () => 'Testing...',
gotenberg_connection_success: () => 'Connection successful',
gotenberg_connection_failed: () => 'Connection failed',
save: () => 'Save',
settings_updated: () => 'Settings updated',
failed_update_settings: () => 'Failed to update settings',
},
}))
const createWrapper = () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
return ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
describe('GotenbergSettingsCard', () => {
beforeEach(() => {
vi.clearAllMocks()
})
afterEach(() => {
cleanup()
})
it('renders loaded settings with URL and username', async () => {
const settings: GotenbergSettingsResponse = {
isEnvConfigured: false,
url: 'http://gotenberg.local:3000',
username: 'gotenberg-user',
hasPassword: true,
}
mockGetSettings.mockResolvedValueOnce({
ok: true,
json: async () => settings,
})
render(<GotenbergSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByDisplayValue('http://gotenberg.local:3000')).toBeDefined()
expect(screen.getByDisplayValue('gotenberg-user')).toBeDefined()
})
})
it('disables inputs and displays badge when configured via environment', async () => {
const settings: GotenbergSettingsResponse = {
isEnvConfigured: true,
url: 'http://env-gotenberg:3000',
username: 'env-user',
hasPassword: true,
}
mockGetSettings.mockResolvedValueOnce({
ok: true,
json: async () => settings,
})
render(<GotenbergSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByText('Configured via Environment')).toBeDefined()
const urlInput = screen.getByDisplayValue('http://env-gotenberg:3000') as HTMLInputElement
expect(urlInput.disabled).toBe(true)
const saveBtn = screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement
expect(saveBtn.disabled).toBe(true)
})
})
it('saves updated settings', async () => {
const settings: GotenbergSettingsResponse = {
isEnvConfigured: false,
url: '',
username: '',
hasPassword: false,
}
mockGetSettings.mockResolvedValueOnce({
ok: true,
json: async () => settings,
})
mockPutSettings.mockResolvedValueOnce({
ok: true,
json: async () => ({
isEnvConfigured: false,
url: 'http://custom:3000',
username: 'user1',
hasPassword: true,
}),
})
render(<GotenbergSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByLabelText('Server URL')).toBeDefined()
})
const urlInput = screen.getByLabelText('Server URL')
const usernameInput = screen.getByLabelText('Username')
const passwordInput = document.getElementById('gotenberg-password') as HTMLInputElement
fireEvent.change(urlInput, { target: { value: 'http://custom:3000' } })
fireEvent.change(usernameInput, { target: { value: 'user1' } })
fireEvent.change(passwordInput, { target: { value: 'newpass' } })
const saveBtn = screen.getByRole('button', { name: 'Save' })
fireEvent.click(saveBtn)
await waitFor(() => {
expect(mockPutSettings).toHaveBeenCalledWith(
expect.objectContaining({
param: { teamId: 'team-123' },
json: {
url: 'http://custom:3000',
username: 'user1',
password: 'newpass',
},
}),
)
})
})
it('handles test connection with success result', async () => {
const settings: GotenbergSettingsResponse = {
isEnvConfigured: false,
url: 'http://test-gotenberg:3000',
username: 'user',
hasPassword: false,
}
mockGetSettings.mockResolvedValueOnce({
ok: true,
json: async () => settings,
})
mockTestSettings.mockResolvedValueOnce({
ok: true,
json: async () => ({ ok: true, version: '8.3.0' }),
})
render(<GotenbergSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByDisplayValue('http://test-gotenberg:3000')).toBeDefined()
})
const testBtn = screen.getByRole('button', { name: 'Test Connection' })
fireEvent.click(testBtn)
await waitFor(() => {
expect(screen.getByText(/Connection successful/)).toBeDefined()
expect(screen.getByText(/\(v8\.3\.0\)/)).toBeDefined()
})
})
})
@@ -1,242 +0,0 @@
import React, { useState, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import {
Card,
CardHeader,
CardTitle,
CardDescription,
CardContent,
CardFooter,
} from '@/ui/components/ui/card'
import { Input } from '@/ui/components/ui/input'
import { Button } from '@/ui/components/ui/button'
import { Badge } from '@/ui/components/ui/badge'
import { Loader2, CheckCircle2, XCircle, Info } from 'lucide-react'
import { toast } from 'sonner'
import { m } from '@/ui/paraglide/messages.js'
interface GotenbergSettingsCardProps {
teamId: string
}
export const GotenbergSettingsCard: React.FC<GotenbergSettingsCardProps> = ({ teamId }) => {
const queryClient = useQueryClient()
const [url, setUrl] = useState('')
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [testResult, setTestResult] = useState<{
ok: boolean
version?: string
error?: string
} | null>(null)
const [isTesting, setIsTesting] = useState(false)
const { data: gotenbergSettings, isLoading } = useQuery({
queryKey: ['teams', teamId, 'gotenberg-settings'],
queryFn: async () => {
const res = await client.api.teams[':teamId']['gotenberg-settings'].$get({
param: { teamId },
})
if (!res.ok) throw new Error('Failed to load gotenberg settings')
return await res.json()
},
enabled: !!teamId,
})
useEffect(() => {
if (gotenbergSettings) {
setUrl(gotenbergSettings.url || '')
setUsername(gotenbergSettings.username || '')
setPassword('')
setTestResult(null)
}
}, [gotenbergSettings])
const { mutateAsync: saveSettings, isPending: isSaving } = useMutation({
mutationFn: async () => {
const res = await client.api.teams[':teamId']['gotenberg-settings'].$put({
param: { teamId },
json: {
url: url.trim(),
username: username.trim() || undefined,
password: password || undefined,
},
})
if (!res.ok) {
const err = await res.json().catch(() => ({}))
throw new Error(
(err as { message?: string }).message || 'Failed to update gotenberg settings',
)
}
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'gotenberg-settings'],
})
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'settings'],
})
toast.success(m.settings_updated())
},
onError: (err: Error) => {
toast.error(err.message || m.failed_update_settings())
},
})
const handleTestConnection = async () => {
setIsTesting(true)
setTestResult(null)
try {
const res = await client.api.teams[':teamId']['gotenberg-settings'].test.$post({
param: { teamId },
json: {
url: url.trim() || undefined,
username: username.trim() || undefined,
password: password || undefined,
},
})
if (!res.ok) {
const err = await res.json().catch(() => ({}))
const errorMsg = (err as { message?: string }).message || 'Request failed'
setTestResult({ ok: false, error: errorMsg })
toast.error(m.gotenberg_connection_failed())
return
}
const data = await res.json()
setTestResult(data)
if (data.ok) {
toast.success(m.gotenberg_connection_success())
} else {
toast.error(data.error || m.gotenberg_connection_failed())
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
setTestResult({ ok: false, error: msg })
toast.error(m.gotenberg_connection_failed())
} finally {
setIsTesting(false)
}
}
const isEnvConfigured = Boolean(gotenbergSettings?.isEnvConfigured)
return (
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>{m.gotenberg_settings()}</CardTitle>
{isEnvConfigured && (
<Badge variant="secondary" className="gap-1">
<Info className="w-3 h-3" />
{m.gotenberg_env_configured()}
</Badge>
)}
</div>
<CardDescription>{m.gotenberg_settings_description()}</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{isLoading ? (
<div className="flex items-center justify-center py-6">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : (
<>
<div className="space-y-1.5">
<label htmlFor="gotenberg-url" className="text-sm font-medium">
{m.gotenberg_server_url()}
</label>
<Input
id="gotenberg-url"
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder={m.gotenberg_server_url_placeholder()}
disabled={isEnvConfigured || isSaving}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-1.5">
<label htmlFor="gotenberg-username" className="text-sm font-medium">
{m.gotenberg_username()}
</label>
<Input
id="gotenberg-username"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="admin"
disabled={isEnvConfigured || isSaving}
/>
</div>
<div className="space-y-1.5">
<label htmlFor="gotenberg-password" className="text-sm font-medium">
{m.gotenberg_password()}
</label>
<Input
id="gotenberg-password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={
gotenbergSettings?.hasPassword ? m.gotenberg_password_placeholder() : '••••••••'
}
disabled={isEnvConfigured || isSaving}
/>
</div>
</div>
{testResult && (
<div
className={`flex items-center gap-2 p-3 rounded-lg border text-sm ${
testResult.ok
? 'border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400'
: 'border-destructive/30 bg-destructive/10 text-destructive'
}`}
>
{testResult.ok ? (
<>
<CheckCircle2 className="w-4 h-4 shrink-0" />
<span>
{m.gotenberg_connection_success()}
{testResult.version ? ` (v${testResult.version})` : ''}
</span>
</>
) : (
<>
<XCircle className="w-4 h-4 shrink-0" />
<span>
{m.gotenberg_connection_failed()}: {testResult.error}
</span>
</>
)}
</div>
)}
</>
)}
</CardContent>
<CardFooter className="flex justify-between border-t border-border pt-4">
<Button
type="button"
variant="outline"
onClick={handleTestConnection}
disabled={isLoading || isTesting || !url.trim()}
>
{isTesting && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
{isTesting ? m.gotenberg_testing() : m.gotenberg_test_connection()}
</Button>
<Button
type="button"
onClick={() => saveSettings()}
disabled={isEnvConfigured || isSaving || isLoading}
>
{isSaving && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
{m.save()}
</Button>
</CardFooter>
</Card>
)
}
@@ -60,8 +60,8 @@ export const TurntableSettingsCard: React.FC<TurntableSettingsCardProps> = ({ te
const res = await client.api.teams[':teamId']['turntable-settings'].$put({
param: { teamId },
json: {
url: url.trim(),
username: username.trim() || undefined,
url: url || undefined,
username: username || undefined,
password: password || undefined,
},
})
@@ -1,158 +0,0 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render } from '@testing-library/react'
import React from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { SpriteScrubber } from './sprite-scrubber'
import { FilePreview } from './file-browser/file-preview'
class MockResizeObserver {
observe = vi.fn()
unobserve = vi.fn()
disconnect = vi.fn()
}
globalThis.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver
describe('SpriteScrubber', () => {
afterEach(() => {
cleanup()
})
it('scrubs forward by default when hovering from left to right', () => {
const { getByTestId } = render(
<SpriteScrubber
spriteUrl="https://example.com/sprite.webp"
thumbnailUrl="https://example.com/thumb.webp"
videoWidth={1080}
videoHeight={1080}
/>,
)
const scrubber = getByTestId('sprite-scrubber')
vi.spyOn(scrubber, 'getBoundingClientRect').mockReturnValue({
left: 0,
top: 0,
width: 100,
height: 100,
right: 100,
bottom: 100,
x: 0,
y: 0,
toJSON: () => ({}),
})
// At x = 0 (left edge): frame 0
fireEvent.mouseMove(scrubber, { clientX: 0 })
expect(scrubber.getAttribute('data-frame')).toBe('0')
// At x = 50 (middle): frame 50
fireEvent.mouseMove(scrubber, { clientX: 50 })
expect(scrubber.getAttribute('data-frame')).toBe('50')
// At x = 99 (near right edge): frame 99
fireEvent.mouseMove(scrubber, { clientX: 99 })
expect(scrubber.getAttribute('data-frame')).toBe('99')
})
it('scrubs in reverse when reverse={true} (moving right decreases frame index)', () => {
const { getByTestId } = render(
<SpriteScrubber
spriteUrl="https://example.com/sprite.webp"
thumbnailUrl="https://example.com/thumb.webp"
videoWidth={1080}
videoHeight={1080}
reverse={true}
/>,
)
const scrubber = getByTestId('sprite-scrubber')
vi.spyOn(scrubber, 'getBoundingClientRect').mockReturnValue({
left: 0,
top: 0,
width: 100,
height: 100,
right: 100,
bottom: 100,
x: 0,
y: 0,
toJSON: () => ({}),
})
// At x = 0 (left edge): frame 99
fireEvent.mouseMove(scrubber, { clientX: 0 })
expect(scrubber.getAttribute('data-frame')).toBe('99')
// At x = 25: frame 74 (rotated right / CCW)
fireEvent.mouseMove(scrubber, { clientX: 25 })
expect(scrubber.getAttribute('data-frame')).toBe('74')
// At x = 50: frame 49
fireEvent.mouseMove(scrubber, { clientX: 50 })
expect(scrubber.getAttribute('data-frame')).toBe('49')
// At x = 99 (right edge): frame 0
fireEvent.mouseMove(scrubber, { clientX: 99 })
expect(scrubber.getAttribute('data-frame')).toBe('0')
})
it('FilePreview passes reverse={true} for 3D assets and reverse={false} for video assets', () => {
const asset3D = {
proxyType: '3d' as const,
preview: {
proxyType: '3d' as const,
spriteUrl: 'https://example.com/3d-sprite.webp',
thumbnailUrl: 'https://example.com/3d-poster.webp',
originalWidth: 1080,
originalHeight: 1080,
},
}
const { getByTestId, unmount } = render(<FilePreview item={asset3D} />)
const scrubber3D = getByTestId('sprite-scrubber')
vi.spyOn(scrubber3D, 'getBoundingClientRect').mockReturnValue({
left: 0,
top: 0,
width: 100,
height: 100,
right: 100,
bottom: 100,
x: 0,
y: 0,
toJSON: () => ({}),
})
// Moving right decreases frame index for 3D assets
fireEvent.mouseMove(scrubber3D, { clientX: 25 })
expect(scrubber3D.getAttribute('data-frame')).toBe('74')
unmount()
const assetVideo = {
proxyType: 'video' as const,
preview: {
proxyType: 'video' as const,
spriteUrl: 'https://example.com/video-sprite.webp',
thumbnailUrl: 'https://example.com/video-poster.webp',
originalWidth: 1920,
originalHeight: 1080,
},
}
const { getByTestId: getVideoScrubber } = render(<FilePreview item={assetVideo} />)
const scrubberVideo = getVideoScrubber('sprite-scrubber')
vi.spyOn(scrubberVideo, 'getBoundingClientRect').mockReturnValue({
left: 0,
top: 0,
width: 100,
height: 100,
right: 100,
bottom: 100,
x: 0,
y: 0,
toJSON: () => ({}),
})
// Moving right increases frame index for video assets
fireEvent.mouseMove(scrubberVideo, { clientX: 25 })
expect(scrubberVideo.getAttribute('data-frame')).toBe('25')
})
})
@@ -13,8 +13,6 @@ interface SpriteScrubberProps {
frameWidth?: number
/** Optional custom class name for the container */
className?: string
/** Whether to reverse scrubbing order (e.g. for 3D model rotation so moving right rotates right) */
reverse?: boolean
}
interface Dimensions {
@@ -32,7 +30,6 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
videoWidth,
videoHeight,
className = '',
reverse = false,
}) => {
const containerRef = useRef<HTMLDivElement>(null)
const [containerSize, setContainerSize] = useState<Dimensions>({
@@ -102,8 +99,7 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
setCursorX(clampedX)
const percentage = clampedX / rect.width
const rawFrame = Math.min(Math.floor(percentage * TOTAL_FRAMES), TOTAL_FRAMES - 1)
const frameIndex = reverse ? TOTAL_FRAMES - 1 - rawFrame : rawFrame
const frameIndex = Math.min(Math.floor(percentage * TOTAL_FRAMES), TOTAL_FRAMES - 1)
setCurrentFrame(frameIndex)
}
@@ -163,8 +159,6 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
return (
<div
ref={containerRef}
data-testid="sprite-scrubber"
data-frame={currentFrame}
className={`relative w-full h-full overflow-hidden cursor-crosshair group bg-black select-none ${className}`}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
@@ -1,8 +1,10 @@
import { FileTypeDefinition } from '../types'
import ModelViewer from './model-viewer'
import { secondToDegree } from './utils'
export { secondToDegree } from './utils'
export function secondToDegree(second: number): number {
const frameIndex = Math.min(Math.max(0, Math.floor(second * 6)), 23)
return frameIndex * 15
}
export const modelTypeDefinition: FileTypeDefinition = {
id: '3d',
@@ -1,5 +1,5 @@
import React from 'react'
import { Play, Pause, Maximize, Minimize, Minus, Plus, Download } from 'lucide-react'
import { Play, Pause, RotateCcw, Maximize, Minimize, Minus, Plus, Download } from 'lucide-react'
import { cn } from '@/ui/lib/utils'
import { RulerSlider } from './ruler-slider'
@@ -9,9 +9,11 @@ export interface ModelControlBarProps {
zoom: number
isFullScreen: boolean
allowDownload?: boolean
onDownload?: () => void
downloadUrl?: string
fileName?: string
togglePlay: () => void
onSeekDegree: (degree: number) => void
onResetRotation: () => void
onZoomChange: (zoom: number) => void
onZoomReset: () => void
toggleFullScreen: () => void
@@ -23,58 +25,80 @@ export const ModelControlBar: React.FC<ModelControlBarProps> = ({
zoom,
isFullScreen,
allowDownload = true,
onDownload,
downloadUrl,
fileName,
togglePlay,
onSeekDegree,
onResetRotation,
onZoomChange,
onZoomReset,
toggleFullScreen,
}) => {
const handleDownload = () => {
if (!downloadUrl) return
const a = document.createElement('a')
a.href = downloadUrl
a.download = fileName || 'model.glb'
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
return (
<div
className={cn(
'transition-all duration-300 ease-in-out z-20 text-foreground',
isFullScreen
? 'absolute bottom-0 left-0 right-0 px-2 py-2 sm:px-4 sm:py-2.5 bg-card/90 backdrop-blur-md border-t border-border'
: 'relative w-full bg-card border-t border-border px-2 py-2 sm:px-4 sm:py-2.5 z-10 transition-colors duration-200',
? 'absolute bottom-0 left-0 right-0 px-4 py-3 bg-card/90 backdrop-blur-md border-t border-border'
: 'relative w-full bg-card border-t border-border px-4 py-3 z-10 transition-colors duration-200',
)}
>
{/* Unified Single Row Controls */}
<div className="flex items-center justify-between text-foreground gap-1.5 sm:gap-3 md:gap-4">
{/* Left Side: Play/Pause, Degree Readout */}
<div className="flex items-center gap-1.5 sm:gap-3 justify-start min-w-0 flex-1">
{/* Top: Ruler Slider across full width */}
<div className="mb-3 px-1">
<RulerSlider currentDegree={currentDegree} onChange={onSeekDegree} />
</div>
{/* Bottom: Lower Controls Row */}
<div className="flex items-center justify-between text-foreground">
{/* Left Side: Play/Pause, Degree Readout, Reset Rotation */}
<div className="flex items-center gap-4">
<button
type="button"
onClick={togglePlay}
aria-label={isPlaying ? 'Pause' : 'Play'}
className="hover:text-primary transition-colors shrink-0 p-0.5 sm:p-1"
className="hover:text-primary transition-colors"
data-testid="play-toggle"
data-playing={isPlaying}
>
{isPlaying ? (
<Pause className="w-4 h-4 sm:w-5 sm:h-5 fill-current" />
<Pause className="w-6 h-6 fill-current" />
) : (
<Play className="w-4 h-4 sm:w-5 sm:h-5 fill-current" />
<Play className="w-6 h-6 fill-current" />
)}
</button>
<div
className="flex items-center text-xs sm:text-sm font-medium tabular-nums select-none shrink-0"
className="flex items-center gap-1 text-sm font-medium tabular-nums select-none min-w-[90px]"
data-testid="degree-readout"
>
<span className="text-muted-foreground font-mono">{currentDegree}° / 360°</span>
</div>
</div>
{/* Center: RulerSlider with encapsulated minus & plus buttons */}
<div className="flex items-center w-full max-w-[130px] sm:max-w-[220px] md:max-w-[320px] justify-center mx-auto shrink min-w-0">
<RulerSlider currentDegree={currentDegree} onChange={onSeekDegree} className="w-full" />
<button
type="button"
onClick={onResetRotation}
title="Reset to 0°"
aria-label="Reset rotation to 0°"
className="p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
>
<RotateCcw className="w-4 h-4" />
</button>
</div>
{/* Right Side: Zoom controls, Download, Fullscreen */}
<div className="flex items-center gap-1 sm:gap-2 justify-end min-w-0 flex-1">
<div className="flex items-center gap-2">
{/* Zoom controls */}
<div className="flex items-center gap-0.5 sm:gap-1 bg-muted/60 rounded-lg p-0.5 border border-border/40 shrink-0">
<div className="flex items-center gap-1 bg-muted/60 rounded-lg p-0.5 border border-border/40">
<button
type="button"
onClick={() => onZoomChange(Math.max(0.2, zoom - 0.2))}
@@ -87,7 +111,7 @@ export const ModelControlBar: React.FC<ModelControlBarProps> = ({
type="button"
onClick={onZoomReset}
aria-label="Reset zoom"
className="px-1 sm:px-1.5 py-0.5 text-[10px] sm:text-[11px] font-mono text-muted-foreground hover:text-foreground transition-colors"
className="px-1.5 py-0.5 text-[11px] font-mono text-muted-foreground hover:text-foreground transition-colors"
>
{Math.round(zoom * 100)}%
</button>
@@ -102,13 +126,13 @@ export const ModelControlBar: React.FC<ModelControlBarProps> = ({
</div>
{/* Download */}
{allowDownload && onDownload && (
{allowDownload && downloadUrl && (
<button
type="button"
onClick={onDownload}
onClick={handleDownload}
title="Download asset"
aria-label="Download asset"
className="p-1 sm:p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
className="p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
>
<Download className="w-4 h-4" />
</button>
@@ -120,7 +144,7 @@ export const ModelControlBar: React.FC<ModelControlBarProps> = ({
onClick={toggleFullScreen}
title={isFullScreen ? 'Exit fullscreen' : 'Fullscreen'}
aria-label={isFullScreen ? 'Exit fullscreen' : 'Fullscreen'}
className="p-1 sm:p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
className="p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
>
{isFullScreen ? <Minimize className="w-4 h-4" /> : <Maximize className="w-4 h-4" />}
</button>
@@ -1,54 +1,19 @@
// @vitest-environment happy-dom
import { act, cleanup, fireEvent, render } from '@testing-library/react'
import { cleanup, fireEvent, render } from '@testing-library/react'
import React, { createRef } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ModelViewer } from './model-viewer'
import type { MediaController } from '../types'
import type { AssetInfo } from '@shumai/dtos'
import type { Annotation } from '@/ui/types'
vi.mock('@/ui/components/drawing-canvas', () => ({
default: (props: { annotations?: unknown[] }) => (
<div data-testid="drawing-canvas" data-annotation-count={props.annotations?.length ?? 0} />
),
default: () => <div data-testid="drawing-canvas" />,
}))
vi.mock('@/ui/paraglide/messages.js', () => ({
m: new Proxy({}, { get: () => () => '' }),
}))
const mockFileDownloadPost = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ url: 'https://example.com/download-model.glb' }),
})
const mockShareDownloadPost = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ url: 'https://example.com/share-download-model.glb' }),
})
vi.mock('@/ui/api/client', () => ({
client: {
api: {
files: {
'download-url': {
$post: (...args: unknown[]) => mockFileDownloadPost(...args),
},
},
shares: {
':shareId': {
files: {
':fileId': {
'download-url': {
$post: (...args: unknown[]) => mockShareDownloadPost(...args),
},
},
},
},
},
},
},
}))
class MockResizeObserver {
observe = vi.fn(() => {
// Immediate callback with mock size
@@ -103,30 +68,13 @@ describe('ModelViewer', () => {
})
it('renders model viewer container, surface, video, and control bar', () => {
const { container, getByTestId, getByText } = render(<ModelViewer file={mockAsset} />)
const { getByTestId, getByText } = render(<ModelViewer file={mockAsset} />)
expect(getByTestId('model-viewer-container')).toBeDefined()
expect(getByTestId('model-viewer-surface')).toBeDefined()
expect(getByTestId('drawing-canvas')).toBeDefined()
// Control bar shows 0° / 360° initially
expect(getByText(/0°\s*\/\s*360°/)).toBeDefined()
// Video does not use low-res poster
expect(container.querySelector('video')?.getAttribute('poster')).toBeNull()
})
it('prioritizes videoTranscodes URL over videoPreview URL for watermarked share compatibility', () => {
const fileWithBoth = {
...mockAsset,
media: {
...mockAsset.media,
videoPreview: { url: 'https://example.com/unwatermarked-turntable.mp4' },
videoTranscodes: [{ url: 'https://example.com/watermarked-turntable.mp4' }],
},
} as unknown as AssetInfo
const { container } = render(<ModelViewer file={fileWithBoth} />)
const video = container.querySelector('video')
expect(video?.getAttribute('src')).toBe('https://example.com/watermarked-turntable.mp4')
})
it('toggles play/pause via spacebar hotkey', () => {
@@ -156,20 +104,12 @@ describe('ModelViewer', () => {
fireEvent.keyDown(window, { key: 'ArrowRight' })
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(1 / 6, 2))
// Press ArrowRight second time -> advance to frame 2 (30 deg = 2/6 sec)
fireEvent.keyDown(window, { key: 'ArrowRight' })
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(2 / 6, 2))
// Press ArrowLeft -> back 1 frame (frame 1 = 1/6 sec)
fireEvent.keyDown(window, { key: 'ArrowLeft' })
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(1 / 6, 2))
// Press ArrowLeft -> back 1 frame (frame 0 = 0 sec)
fireEvent.keyDown(window, { key: 'ArrowLeft' })
expect(onTimeUpdate).toHaveBeenCalledWith(0)
})
it('handles pointer dragging to rotate 3D asset (drag right rotates counterclockwise)', () => {
it('handles pointer dragging to rotate 3D asset', () => {
const onTimeUpdate = vi.fn()
const { getByTestId } = render(<ModelViewer file={mockAsset} onTimeUpdate={onTimeUpdate} />)
@@ -182,16 +122,12 @@ describe('ModelViewer', () => {
fireEvent.pointerDown(surface, { clientX: 100, button: 0, pointerId: 1 })
expect(surface.setPointerCapture).toHaveBeenCalledWith(1)
// Move right by 24px (drag right rotates counterclockwise: frame 0 - 2 = 22 frames = 22/6s)
// Move right by 24px (+2 frames = +30 deg)
fireEvent.pointerMove(surface, { clientX: 124, button: 0, pointerId: 1 })
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(22 / 6, 2))
// Move left by 24px from origin (frame 0 - (-2) = 2 frames = 2/6s)
fireEvent.pointerMove(surface, { clientX: 76, button: 0, pointerId: 1 })
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(2 / 6, 2))
// Release drag
fireEvent.pointerUp(surface, { clientX: 76, button: 0, pointerId: 1 })
fireEvent.pointerUp(surface, { clientX: 124, button: 0, pointerId: 1 })
expect(surface.releasePointerCapture).toHaveBeenCalledWith(1)
})
@@ -213,6 +149,18 @@ describe('ModelViewer', () => {
expect(ref.current?.getCurrentTime?.()).toBeDefined()
})
it('resets rotation to 0° when reset button is clicked', () => {
const onTimeUpdate = vi.fn()
const { getByRole } = render(
<ModelViewer file={mockAsset} startTime={1} onTimeUpdate={onTimeUpdate} />,
)
// Reset rotation button has aria-label 'Reset rotation to 0°'
const resetBtn = getByRole('button', { name: /Reset rotation/i })
fireEvent.click(resetBtn)
expect(onTimeUpdate).toHaveBeenCalledWith(0)
})
it('renders children alongside viewer surface when provided', () => {
const { getByTestId } = render(
<ModelViewer file={mockAsset}>
@@ -223,347 +171,4 @@ describe('ModelViewer', () => {
expect(getByTestId('test-sidebar')).toBeDefined()
expect(getByTestId('model-viewer-surface')).toBeDefined()
})
it('steps rotation by 15° forward and backward via plus and minus buttons', () => {
const onTimeUpdate = vi.fn()
const { getByTestId } = render(
<ModelViewer file={mockAsset} startTime={0} onTimeUpdate={onTimeUpdate} />,
)
const plusBtn = getByTestId('ruler-step-plus')
const minusBtn = getByTestId('ruler-step-minus')
// Click plus button at 0° -> seeks to 15° (frame 1, 1/6s)
fireEvent.click(plusBtn)
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(1 / 6, 2))
// Click minus button at 0° (or current) -> wraps backward
fireEvent.click(minusBtn)
expect(onTimeUpdate).toHaveBeenCalledWith(0)
})
it('updates playback smoothly on each frame via requestVideoFrameCallback without skipping degrees', () => {
let frameCallback: ((now: number, metadata: { mediaTime: number }) => void) | null = null
const rvfcMock = vi.fn().mockImplementation((cb) => {
frameCallback = cb
return 101
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(HTMLVideoElement.prototype as any).requestVideoFrameCallback = rvfcMock
const onTimeUpdate = vi.fn()
const { container, getByTestId } = render(
<ModelViewer file={mockAsset} onTimeUpdate={onTimeUpdate} />,
)
const video = container.querySelector('video')
expect(video).toBeDefined()
// Start playing
fireEvent.play(video!)
expect(rvfcMock).toHaveBeenCalled()
// Simulate decoded frames arriving sequentially at 6 FPS (every 1/6 second)
const degreeReadout = getByTestId('degree-readout')
// Frame 0: 0.083s -> 0°
act(() => {
frameCallback!(100, { mediaTime: 0.083 })
})
expect(degreeReadout.textContent).toContain('0° / 360°')
// Frame 1: 0.25s -> 15°
act(() => {
frameCallback!(267, { mediaTime: 0.25 })
})
expect(degreeReadout.textContent).toContain('15° / 360°')
// Frame 2: 0.417s -> 30°
act(() => {
frameCallback!(433, { mediaTime: 0.417 })
})
expect(degreeReadout.textContent).toContain('30° / 360°')
// Frame 3: 0.583s -> 45°
act(() => {
frameCallback!(600, { mediaTime: 0.583 })
})
expect(degreeReadout.textContent).toContain('45° / 360°')
// Frame 4: 0.75s -> 60°
act(() => {
frameCallback!(767, { mediaTime: 0.75 })
})
expect(degreeReadout.textContent).toContain('60° / 360°')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
delete (HTMLVideoElement.prototype as any).requestVideoFrameCallback
})
it('cancels frame callback loop when video is paused', () => {
const cancelMock = vi.fn()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(HTMLVideoElement.prototype as any).requestVideoFrameCallback = vi.fn().mockReturnValue(123)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(HTMLVideoElement.prototype as any).cancelVideoFrameCallback = cancelMock
const { container } = render(<ModelViewer file={mockAsset} />)
const video = container.querySelector('video')
fireEvent.play(video!)
fireEvent.pause(video!)
expect(cancelMock).toHaveBeenCalledWith(123)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
delete (HTMLVideoElement.prototype as any).requestVideoFrameCallback
// eslint-disable-next-line @typescript-eslint/no-explicit-any
delete (HTMLVideoElement.prototype as any).cancelVideoFrameCallback
})
it('zooms viewer and prevents browser default on touchpad pinch (ctrl+wheel)', () => {
const { getByTestId, getByRole } = render(<ModelViewer file={mockAsset} />)
const surface = getByTestId('model-viewer-surface')
const resetZoomBtn = getByRole('button', { name: 'Reset zoom' })
const initialZoomText = resetZoomBtn.textContent
surface.getBoundingClientRect = () =>
({
left: 0,
top: 0,
width: 800,
height: 600,
right: 800,
bottom: 600,
x: 0,
y: 0,
toJSON: () => {},
}) as DOMRect
const wheelEvent = new WheelEvent('wheel', {
deltaY: -100,
deltaMode: 0,
bubbles: true,
cancelable: true,
})
Object.defineProperty(wheelEvent, 'ctrlKey', { value: true })
Object.defineProperty(wheelEvent, 'clientX', { value: 400 })
Object.defineProperty(wheelEvent, 'clientY', { value: 300 })
let notPrevented = true
act(() => {
notPrevented = surface.dispatchEvent(wheelEvent)
})
expect(notPrevented).toBe(false)
expect(resetZoomBtn.textContent).not.toBe(initialZoomText)
})
it('pans viewer content and prevents scroll on two-finger wheel when zoomed in', () => {
const { getByTestId, getByRole } = render(<ModelViewer file={mockAsset} />)
const surface = getByTestId('model-viewer-surface')
const zoomInBtn = getByRole('button', { name: 'Zoom in' })
// Zoom in multiple times so zoom exceeds baseScale significantly
fireEvent.click(zoomInBtn)
fireEvent.click(zoomInBtn)
fireEvent.click(zoomInBtn)
const mediaWrapper = surface.querySelector('div.absolute.pointer-events-none') as HTMLElement
const initialTransform = mediaWrapper.style.transform
const scrollEvent = new WheelEvent('wheel', {
deltaX: 20,
deltaY: 30,
bubbles: true,
cancelable: true,
})
Object.defineProperty(scrollEvent, 'ctrlKey', { value: false })
let notPrevented = true
act(() => {
notPrevented = surface.dispatchEvent(scrollEvent)
})
expect(notPrevented).toBe(false)
expect(mediaWrapper.style.transform).not.toBe(initialTransform)
})
it('keeps video loop attribute disabled when paused to prevent browser EOF reset, and enables loop when playing', () => {
const { container } = render(<ModelViewer file={mockAsset} />)
const video = container.querySelector('video') as HTMLVideoElement
expect(video).toBeDefined()
// Paused initially: loop should be false so seeking to final frame does not trigger browser loop-reset
expect(video.loop).toBe(false)
// Play: loop should become true
fireEvent.play(video)
expect(video.loop).toBe(true)
// Pause: loop should become false again
fireEvent.pause(video)
expect(video.loop).toBe(false)
})
it('seeks safely to 345° without touching 4.0s EOF boundary', () => {
const onTimeUpdate = vi.fn()
const { container, getByTestId } = render(
<ModelViewer file={mockAsset} onTimeUpdate={onTimeUpdate} />,
)
const video = container.querySelector('video') as HTMLVideoElement
const degreeReadout = getByTestId('degree-readout')
// At 0°, press ArrowLeft to rotate counterclockwise to 345° (Frame 23)
fireEvent.keyDown(window, { key: 'ArrowLeft' })
// Target time should be 23 / 6s = 3.8333s
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(23 / 6, 2))
// Video currentTime should be safely offset from 4.0s EOF (3.875s)
expect(video.currentTime).toBeCloseTo(3.875, 3)
expect(video.currentTime).toBeLessThan(4.0)
expect(degreeReadout.textContent).toContain('345° / 360°')
})
it('downloads the original model via files download-url endpoint when Download asset is clicked', async () => {
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
const { getByTitle } = render(<ModelViewer file={mockAsset} />)
const downloadBtn = getByTitle('Download asset')
expect(downloadBtn).toBeDefined()
await act(async () => {
fireEvent.click(downloadBtn)
})
expect(mockFileDownloadPost).toHaveBeenCalledWith({
json: { key: 'files/robot.glb', assetId: 'asset-3d-1' },
})
expect(clickSpy).toHaveBeenCalled()
clickSpy.mockRestore()
})
it('downloads the model via shares download-url endpoint when shareId is provided', async () => {
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
const { getByTitle } = render(<ModelViewer file={mockAsset} shareId="share-test-123" />)
const downloadBtn = getByTitle('Download asset')
expect(downloadBtn).toBeDefined()
await act(async () => {
fireEvent.click(downloadBtn)
})
expect(mockShareDownloadPost).toHaveBeenCalledWith({
param: { shareId: 'share-test-123', fileId: 'asset-3d-1' },
json: { key: 'files/robot.glb' },
})
expect(clickSpy).toHaveBeenCalled()
clickSpy.mockRestore()
})
it('hides the download button when allowDownload is false', () => {
const { queryByTitle } = render(<ModelViewer file={mockAsset} allowDownload={false} />)
expect(queryByTitle('Download asset')).toBeNull()
})
it('hides the download button when original key is missing', () => {
const assetWithoutOriginal = {
...mockAsset,
media: {
...mockAsset.media,
original: undefined,
},
} as unknown as AssetInfo
const { queryByTitle } = render(<ModelViewer file={assetWithoutOriginal} />)
expect(queryByTitle('Download asset')).toBeNull()
})
describe('onSeek callback for rotation interactions', () => {
it('calls onSeek when dragging the viewer surface to rotate', () => {
const onSeek = vi.fn()
const { getByTestId } = render(<ModelViewer file={mockAsset} onSeek={onSeek} />)
const surface = getByTestId('model-viewer-surface')
// Pointer down at x=100
fireEvent.pointerDown(surface, {
button: 0,
clientX: 100,
pointerId: 1,
})
expect(onSeek).not.toHaveBeenCalled()
// Drag right by +24px (2 frames rotation)
fireEvent.pointerMove(surface, {
clientX: 124,
pointerId: 1,
})
expect(onSeek).toHaveBeenCalledTimes(1)
})
it('calls onSeek when changing degree via slider', () => {
const onSeek = vi.fn()
const { getByTestId } = render(<ModelViewer file={mockAsset} onSeek={onSeek} />)
const minusBtn = getByTestId('ruler-step-minus')
expect(minusBtn).toBeDefined()
fireEvent.click(minusBtn)
expect(onSeek).toHaveBeenCalledTimes(1)
})
it('calls onSeek when pressing keyboard arrow keys to rotate', () => {
const onSeek = vi.fn()
render(<ModelViewer file={mockAsset} onSeek={onSeek} />)
fireEvent.keyDown(window, { key: 'ArrowLeft' })
expect(onSeek).toHaveBeenCalledTimes(1)
fireEvent.keyDown(window, { key: 'ArrowRight' })
expect(onSeek).toHaveBeenCalledTimes(2)
})
it('does not call onSeek when programmatic seekTo is called via ref', () => {
const onSeek = vi.fn()
const ref = createRef<MediaController>()
render(<ModelViewer ref={ref} file={mockAsset} onSeek={onSeek} />)
act(() => {
ref.current?.seekTo(1.5)
})
expect(onSeek).not.toHaveBeenCalled()
})
it('clears displayed annotations when container onSeek empties annotations prop upon rotation', () => {
const initialAnnotation: Annotation = {
type: 'arrow',
color: '#ef4444',
points: [
[0, 0],
[100, 100],
],
}
function Harness() {
const [annotations, setAnnotations] = React.useState<Annotation[]>([initialAnnotation])
return (
<ModelViewer
file={mockAsset}
annotations={annotations}
onSeek={() => setAnnotations([])}
/>
)
}
const { getByTestId } = render(<Harness />)
const canvas = getByTestId('drawing-canvas')
expect(canvas.getAttribute('data-annotation-count')).toBe('1')
// Rotate via ruler step minus
fireEvent.click(getByTestId('ruler-step-minus'))
// Markup annotation disappears
expect(canvas.getAttribute('data-annotation-count')).toBe('0')
})
})
})
@@ -1,20 +1,16 @@
import React, { useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react'
import { AlertCircle, Loader2 } from 'lucide-react'
import { cn } from '@/ui/lib/utils'
import { client } from '@/ui/api/client'
import DrawingCanvas from '@/ui/components/drawing-canvas'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
import type { FileViewerProps, MediaController } from '../types'
import { centeredPan, fitScale, zoomAtPoint } from '../pan-zoom'
import { usePanZoomGestures } from '../use-pan-zoom'
import { ModelControlBar } from './model-control-bar'
import {
secondToDegree,
secondToFrame,
calculateFrameCenterTime,
TOTAL_FRAMES,
FRAME_DURATION,
} from './utils'
import { secondToDegree } from './index'
const TOTAL_FRAMES = 24
const FPS = 6
const FRAME_DURATION = 1 / FPS
export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
(
@@ -23,10 +19,8 @@ export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
onPlay,
onPause,
onTimeUpdate,
onSeek,
annotations,
startTime,
shareId,
children,
allowDownload = true,
autoPlay = false,
@@ -49,41 +43,14 @@ export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
const [pan, setPan] = useState({ x: 0, y: 0 })
const [hasManuallyZoomed, setHasManuallyZoomed] = useState(false)
useEffect(() => {
setHasManuallyZoomed(false)
}, [data.id])
// Drag-to-rotate state
const [isDraggingRotation, setIsDraggingRotation] = useState(false)
const dragStartRef = useRef<{ clientX: number; frame: number }>({ clientX: 0, frame: 0 })
const hasTriggeredSeekInDragRef = useRef(false)
const videoSrc = data.media?.videoTranscodes?.[0]?.url || data.media?.videoPreview?.url || ''
const videoSrc = data.media?.videoPreview?.url || data.media?.videoTranscodes?.[0]?.url || ''
const handleDownload = async () => {
const key = data.media?.original?.key
if (!key || !data.id) return
try {
const res = shareId
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
param: { shareId, fileId: data.id },
json: { key },
})
: await client.api.files['download-url'].$post({
json: { key, assetId: data.id },
})
if (!res.ok) return
const { url } = await res.json()
const link = document.createElement('a')
link.href = url
link.download = data.name || 'model.glb'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} catch {
// fail silently
}
}
const posterUrl = data.preview?.thumbnailUrl || undefined
const downloadUrl = data.media?.original?.key ? videoSrc : undefined
// Drawing Annotation store
const {
@@ -99,7 +66,6 @@ export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
const mediaWidth = data.media?.metadata?.originalWidth || 1080
const mediaHeight = data.media?.metadata?.originalHeight || 1080
const baseScale = fitScale(containerSize.width, containerSize.height, mediaWidth, mediaHeight)
// Resize observer
useEffect(() => {
@@ -120,109 +86,24 @@ export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
// Initial scale and center
useEffect(() => {
if (containerSize.width > 0 && containerSize.height > 0 && !hasManuallyZoomed) {
setZoom(baseScale)
const scale = fitScale(containerSize.width, containerSize.height, mediaWidth, mediaHeight)
setZoom(scale)
setPan(
centeredPan(
containerSize.width,
containerSize.height,
mediaWidth,
mediaHeight,
baseScale,
),
centeredPan(containerSize.width, containerSize.height, mediaWidth, mediaHeight, scale),
)
}
}, [containerSize, mediaWidth, mediaHeight, baseScale, hasManuallyZoomed])
usePanZoomGestures({
containerRef,
zoom,
pan,
baseScale,
onZoomChange: (next) => {
setHasManuallyZoomed(true)
setZoom(next.zoom)
setPan(next.pan)
},
onPanChange: setPan,
})
}, [containerSize, mediaWidth, mediaHeight, hasManuallyZoomed])
// Current angle
const currentDegree = secondToDegree(currentTime)
const onTimeUpdateRef = useRef(onTimeUpdate)
useEffect(() => {
onTimeUpdateRef.current = onTimeUpdate
}, [onTimeUpdate])
const onSeekRef = useRef(onSeek)
useEffect(() => {
onSeekRef.current = onSeek
}, [onSeek])
// Synchronized playback frame loop (via requestVideoFrameCallback / requestAnimationFrame)
useEffect(() => {
if (!isPlaying) return
const video = videoRef.current
if (!video) return
let animationFrameId: number | null = null
let rvfcId: number | null = null
let isCancelled = false
type VideoWithRvfc = HTMLVideoElement & {
requestVideoFrameCallback?: (
callback: (now: DOMHighResTimeStamp, metadata: { mediaTime: number }) => void,
) => number
cancelVideoFrameCallback?: (id: number) => void
}
const videoWithRvfc = video as VideoWithRvfc
const rvfcSupported = typeof videoWithRvfc.requestVideoFrameCallback === 'function'
const updateTime = (time: number) => {
if (!isDraggingRotation) {
setCurrentTime(time)
onTimeUpdateRef.current?.(time)
}
}
if (rvfcSupported) {
const onFrame = (_now: DOMHighResTimeStamp, metadata: { mediaTime: number }) => {
if (isCancelled) return
updateTime(metadata.mediaTime)
rvfcId = videoWithRvfc.requestVideoFrameCallback!(onFrame)
}
rvfcId = videoWithRvfc.requestVideoFrameCallback!(onFrame)
} else {
const loop = () => {
if (isCancelled) return
if (videoRef.current) {
updateTime(videoRef.current.currentTime)
}
animationFrameId = requestAnimationFrame(loop)
}
animationFrameId = requestAnimationFrame(loop)
}
return () => {
isCancelled = true
if (rvfcId !== null && typeof videoWithRvfc.cancelVideoFrameCallback === 'function') {
videoWithRvfc.cancelVideoFrameCallback(rvfcId)
}
if (animationFrameId !== null) {
cancelAnimationFrame(animationFrameId)
}
}
}, [isPlaying, isDraggingRotation])
// Seek helper
const seekToFrame = useCallback(
(frameIndex: number) => {
const normalizedFrame = ((frameIndex % TOTAL_FRAMES) + TOTAL_FRAMES) % TOTAL_FRAMES
const targetSec = normalizedFrame * FRAME_DURATION
const centerSec = calculateFrameCenterTime(normalizedFrame)
if (videoRef.current) {
videoRef.current.currentTime = centerSec
videoRef.current.currentTime = targetSec
}
setCurrentTime(targetSec)
onTimeUpdate?.(targetSec)
@@ -232,8 +113,6 @@ export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
const seekToDegree = useCallback(
(degree: number) => {
onSeekRef.current?.()
videoRef.current?.pause()
const frame = Math.round((((degree % 360) + 360) % 360) / 15) % TOTAL_FRAMES
seekToFrame(frame)
},
@@ -262,7 +141,7 @@ export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
videoRef.current?.pause()
},
seekTo: (second: number) => {
seekToFrame(secondToFrame(second))
seekToFrame(Math.floor(second * FPS))
},
getCurrentTime: () => videoRef.current?.currentTime || 0,
getDuration: () => 4,
@@ -288,13 +167,11 @@ export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
togglePlay()
} else if (e.key === 'ArrowLeft') {
e.preventDefault()
onSeekRef.current?.()
const currentFrame = secondToFrame(currentTime)
const currentFrame = Math.floor(currentTime * FPS)
seekToFrame(currentFrame - 1)
} else if (e.key === 'ArrowRight') {
e.preventDefault()
onSeekRef.current?.()
const currentFrame = secondToFrame(currentTime)
const currentFrame = Math.floor(currentTime * FPS)
seekToFrame(currentFrame + 1)
}
}
@@ -310,12 +187,11 @@ export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
target.setPointerCapture(e.pointerId)
videoRef.current?.pause()
const currentFrame = Math.round(currentDegree / 15) % TOTAL_FRAMES
const currentFrame = Math.floor(currentTime * FPS)
dragStartRef.current = {
clientX: e.clientX,
frame: currentFrame,
}
hasTriggeredSeekInDragRef.current = false
setIsDraggingRotation(true)
}
@@ -323,19 +199,12 @@ export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
if (!isDraggingRotation) return
const deltaX = e.clientX - dragStartRef.current.clientX
// 12px drag movement corresponds to 1 frame (15°)
// Dragging right (deltaX > 0) rotates turntable counterclockwise (decreasing frame index)
const deltaFrames = Math.round(deltaX / 12)
if (deltaFrames !== 0 && !hasTriggeredSeekInDragRef.current) {
hasTriggeredSeekInDragRef.current = true
onSeekRef.current?.()
}
const targetFrame = dragStartRef.current.frame - deltaFrames
seekToFrame(targetFrame)
seekToFrame(dragStartRef.current.frame + deltaFrames)
}
const handleViewerPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
if (!isDraggingRotation) return
hasTriggeredSeekInDragRef.current = false
setIsDraggingRotation(false)
try {
e.currentTarget.releasePointerCapture(e.pointerId)
@@ -378,15 +247,10 @@ export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
const handleZoomReset = () => {
setHasManuallyZoomed(false)
if (containerSize.width > 0 && containerSize.height > 0) {
setZoom(baseScale)
const scale = fitScale(containerSize.width, containerSize.height, mediaWidth, mediaHeight)
setZoom(scale)
setPan(
centeredPan(
containerSize.width,
containerSize.height,
mediaWidth,
mediaHeight,
baseScale,
),
centeredPan(containerSize.width, containerSize.height, mediaWidth, mediaHeight, scale),
)
}
}
@@ -437,15 +301,16 @@ export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
<video
ref={videoRef}
src={videoSrc}
poster={posterUrl}
playsInline
loop={isPlaying}
loop
muted
autoPlay={autoPlay}
preload="auto"
onLoadedData={() => {
setIsLoading(false)
if (startTime && startTime > 0) {
seekToFrame(secondToFrame(startTime))
seekToFrame(Math.floor(startTime * FPS))
}
}}
onPlay={() => {
@@ -456,8 +321,11 @@ export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
setIsPlaying(false)
onPause?.()
}}
onEnded={() => {
setIsPlaying(false)
onTimeUpdate={() => {
if (videoRef.current && !isDraggingRotation) {
setCurrentTime(videoRef.current.currentTime)
onTimeUpdate?.(videoRef.current.currentTime)
}
}}
onError={() => {
setIsLoading(false)
@@ -514,9 +382,11 @@ export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
zoom={zoom}
isFullScreen={isFullScreen}
allowDownload={allowDownload}
onDownload={data.media?.original?.key ? handleDownload : undefined}
downloadUrl={downloadUrl}
fileName={data.name}
togglePlay={togglePlay}
onSeekDegree={seekToDegree}
onResetRotation={() => seekToDegree(0)}
onZoomChange={handleZoomChange}
onZoomReset={handleZoomReset}
toggleFullScreen={toggleFullScreen}
@@ -8,157 +8,54 @@ describe('RulerSlider', () => {
afterEach(() => {
cleanup()
})
it('renders slider with fixed center indicator and aria values', () => {
it('renders slider and shows current degree text', () => {
const onChange = vi.fn()
const { getByRole, getByTestId, queryByTestId } = render(
const { getByRole, getAllByText } = render(
<RulerSlider currentDegree={90} onChange={onChange} />,
)
const slider = getByRole('slider')
expect(slider).toBeDefined()
expect(slider.getAttribute('aria-valuenow')).toBe('90')
expect(slider.getAttribute('aria-valuetext')).toBe('90°')
// Fixed center indicator exists
expect(getByTestId('ruler-center-indicator')).toBeDefined()
// Tooltip should not be rendered while not dragging
expect(queryByTestId('ruler-slider-tooltip')).toBeNull()
expect(getAllByText('90°').length).toBeGreaterThan(0)
})
it('renders ticks at 15° intervals, longer at 60° intervals, and no numeric tick labels', () => {
const onChange = vi.fn()
const { container, getAllByTestId } = render(
<RulerSlider currentDegree={0} onChange={onChange} />,
)
// Major ticks at multiples of 60°
const ticks0 = getAllByTestId('tick-0')
expect(ticks0.length).toBeGreaterThan(0)
expect(ticks0[0]?.getAttribute('data-major')).toBe('true')
const ticks60 = getAllByTestId('tick-60')
expect(ticks60.length).toBeGreaterThan(0)
expect(ticks60[0]?.getAttribute('data-major')).toBe('true')
// Regular tick at 15° is not major
const ticks15 = getAllByTestId('tick-15')
expect(ticks15.length).toBeGreaterThan(0)
expect(ticks15[0]?.getAttribute('data-major')).toBe('false')
// No numeric degree text inside the slider track
expect(container.textContent).toBe('')
})
it('shows tooltip displaying degree while dragging and hides on pointer up', () => {
const onChange = vi.fn()
const { getByRole, getByTestId, queryByTestId } = render(
<RulerSlider currentDegree={45} onChange={onChange} />,
)
const slider = getByRole('slider')
slider.setPointerCapture = vi.fn()
slider.releasePointerCapture = vi.fn()
// Initially no tooltip
expect(queryByTestId('ruler-slider-tooltip')).toBeNull()
// Start dragging
fireEvent.pointerDown(slider, { clientX: 100, button: 0, pointerId: 1 })
const tooltip = getByTestId('ruler-slider-tooltip')
expect(tooltip).toBeDefined()
expect(tooltip.textContent).toBe('45°')
// Release drag
fireEvent.pointerUp(slider, { clientX: 100, button: 0, pointerId: 1 })
expect(queryByTestId('ruler-slider-tooltip')).toBeNull()
})
it('handles keyboard navigation with 15 degree stepping and wrapping', () => {
it('handles keyboard navigation with 15 degree snapping', () => {
const onChange = vi.fn()
const { getByRole } = render(<RulerSlider currentDegree={45} onChange={onChange} />)
const slider = getByRole('slider')
// 45 + 15 = 60
fireEvent.keyDown(slider, { key: 'ArrowRight' })
expect(onChange).toHaveBeenCalledWith(60)
// 45 - 15 = 30
fireEvent.keyDown(slider, { key: 'ArrowLeft' })
expect(onChange).toHaveBeenCalledWith(30)
// Home -> 0
fireEvent.keyDown(slider, { key: 'Home' })
expect(onChange).toHaveBeenCalledWith(0)
// End -> 345
fireEvent.keyDown(slider, { key: 'End' })
expect(onChange).toHaveBeenCalledWith(345)
expect(onChange).toHaveBeenCalledWith(360)
})
it('wraps around 0° and 360° on keyboard navigation', () => {
const onChange = vi.fn()
const { getByRole, rerender } = render(<RulerSlider currentDegree={0} onChange={onChange} />)
const slider = getByRole('slider')
// 0 - 15 wraps to 345
fireEvent.keyDown(slider, { key: 'ArrowLeft' })
expect(onChange).toHaveBeenCalledWith(345)
// 345 + 15 wraps to 0
rerender(<RulerSlider currentDegree={345} onChange={onChange} />)
fireEvent.keyDown(slider, { key: 'ArrowRight' })
expect(onChange).toHaveBeenCalledWith(0)
})
it('handles pointer drag interaction with 15 degree snapping and wrapping', () => {
it('snaps pointer events to nearest 15 degrees', () => {
const onChange = vi.fn()
const { getByRole } = render(<RulerSlider currentDegree={0} onChange={onChange} />)
const slider = getByRole('slider')
slider.setPointerCapture = vi.fn()
slider.releasePointerCapture = vi.fn()
// Mock getBoundingClientRect
slider.getBoundingClientRect = () =>
({
left: 0,
width: 360,
top: 0,
height: 40,
right: 360,
bottom: 40,
}) as DOMRect
// Start drag at x = 100
fireEvent.pointerDown(slider, { clientX: 100, button: 0, pointerId: 1 })
expect(slider.setPointerCapture).toHaveBeenCalledWith(1)
// Drag left by 24px (15° forward: deltaX = -24 => deltaDeg = +15)
fireEvent.pointerMove(slider, { clientX: 76, button: 0, pointerId: 1 })
expect(onChange).toHaveBeenCalledWith(15)
// Drag right by 24px from origin (x=124 => deltaX = +24 => deltaDeg = -15 => wraps to 345)
fireEvent.pointerMove(slider, { clientX: 124, button: 0, pointerId: 1 })
expect(onChange).toHaveBeenCalledWith(345)
// Release pointer
fireEvent.pointerUp(slider, { clientX: 124, button: 0, pointerId: 1 })
expect(slider.releasePointerCapture).toHaveBeenCalledWith(1)
})
it('steps degree forward and backward via encapsulated plus and minus buttons', () => {
const onChange = vi.fn()
const { getByTestId, rerender } = render(<RulerSlider currentDegree={0} onChange={onChange} />)
const plusBtn = getByTestId('ruler-step-plus')
const minusBtn = getByTestId('ruler-step-minus')
// 0 + 15 = 15
fireEvent.click(plusBtn)
expect(onChange).toHaveBeenCalledWith(15)
// 0 - 15 wraps to 345
fireEvent.click(minusBtn)
expect(onChange).toHaveBeenCalledWith(345)
// When disabled, clicking should not trigger onChange
onChange.mockClear()
rerender(<RulerSlider currentDegree={0} onChange={onChange} disabled />)
fireEvent.click(plusBtn)
fireEvent.click(minusBtn)
expect(onChange).not.toHaveBeenCalled()
// Pointer down at x=50 -> ratio = 50/360 = 50 deg -> round(50/15)*15 = 45 deg
fireEvent.pointerDown(slider, { clientX: 50, button: 0, pointerId: 1 })
expect(onChange).toHaveBeenCalledWith(45)
})
})
@@ -1,18 +1,15 @@
import { cn } from '@/ui/lib/utils'
import { Minus, Plus } from 'lucide-react'
import React, { useCallback, useRef, useState } from 'react'
import { cn } from '@/ui/lib/utils'
export interface RulerSliderProps {
currentDegree: number // 0 to 360 (or normalized modulo 360)
interface RulerSliderProps {
currentDegree: number // 0 to 360
onChange: (degree: number) => void
className?: string
disabled?: boolean
}
const STEP = 15
const PX_PER_STEP = 20 // 20px per 15° step
const PX_PER_DEGREE = PX_PER_STEP / STEP // ~1.333px per degree
const BUFFER_DEGREE = 240 // Render buffer on each side of the active degree
const TICKS = Array.from({ length: 25 }, (_, i) => i * 15)
const MAJOR_TICKS = new Set([0, 90, 180, 270, 360])
export const RulerSlider: React.FC<RulerSliderProps> = ({
currentDegree,
@@ -20,26 +17,8 @@ export const RulerSlider: React.FC<RulerSliderProps> = ({
className,
disabled = false,
}) => {
const trackRef = useRef<HTMLDivElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
const [isDragging, setIsDragging] = useState(false)
const [dragDegree, setDragDegree] = useState<number | null>(null)
const dragStartRef = useRef<{ clientX: number; startDegree: number }>({
clientX: 0,
startDegree: 0,
})
const normalizedDegree = (((Math.round(currentDegree / STEP) * STEP) % 360) + 360) % 360
const activeDegree = isDragging && dragDegree !== null ? dragDegree : normalizedDegree
const displayedDegree = (((Math.round(activeDegree / STEP) * STEP) % 360) + 360) % 360
const handleStep = useCallback(
(delta: number) => {
if (disabled) return
const next = (((normalizedDegree + delta) % 360) + 360) % 360
onChange(next)
},
[disabled, normalizedDegree, onChange],
)
const handlePointerDown = useCallback(
(e: React.PointerEvent<HTMLDivElement>) => {
@@ -47,28 +26,28 @@ export const RulerSlider: React.FC<RulerSliderProps> = ({
e.preventDefault()
e.stopPropagation()
const target = trackRef.current
const target = containerRef.current
if (!target) return
target.setPointerCapture(e.pointerId)
dragStartRef.current = {
clientX: e.clientX,
startDegree: currentDegree,
}
setIsDragging(true)
setDragDegree(currentDegree)
const rect = target.getBoundingClientRect()
const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width))
const snapped = Math.min(360, Math.max(0, Math.round((ratio * 360) / 15) * 15))
onChange(snapped)
},
[disabled, currentDegree],
[disabled, onChange],
)
const handlePointerMove = useCallback(
(e: React.PointerEvent<HTMLDivElement>) => {
if (!isDragging || disabled) return
const deltaX = e.clientX - dragStartRef.current.clientX
// Dragging left (deltaX < 0) rotates turntable forward (angle increases)
const nextRawDegree = dragStartRef.current.startDegree - deltaX / PX_PER_DEGREE
const snapped = (((Math.round(nextRawDegree / STEP) * STEP) % 360) + 360) % 360
setDragDegree(nextRawDegree)
const target = containerRef.current
if (!target) return
const rect = target.getBoundingClientRect()
const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width))
const snapped = Math.min(360, Math.max(0, Math.round((ratio * 360) / 15) * 15))
onChange(snapped)
},
[isDragging, disabled, onChange],
@@ -78,18 +57,13 @@ export const RulerSlider: React.FC<RulerSliderProps> = ({
(e: React.PointerEvent<HTMLDivElement>) => {
if (!isDragging) return
setIsDragging(false)
if (dragDegree !== null) {
const snapped = (((Math.round(dragDegree / STEP) * STEP) % 360) + 360) % 360
onChange(snapped)
}
setDragDegree(null)
try {
trackRef.current?.releasePointerCapture(e.pointerId)
containerRef.current?.releasePointerCapture(e.pointerId)
} catch {
// pointer may have already been released
}
},
[isDragging, dragDegree, onChange],
[isDragging],
)
const handleKeyDown = useCallback(
@@ -97,132 +71,93 @@ export const RulerSlider: React.FC<RulerSliderProps> = ({
if (disabled) return
if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') {
e.preventDefault()
e.stopPropagation()
handleStep(-STEP)
onChange(Math.max(0, currentDegree - 15))
} else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') {
e.preventDefault()
e.stopPropagation()
handleStep(STEP)
onChange(Math.min(360, currentDegree + 15))
} else if (e.key === 'Home') {
e.preventDefault()
e.stopPropagation()
onChange(0)
} else if (e.key === 'End') {
e.preventDefault()
e.stopPropagation()
onChange(345)
onChange(360)
}
},
[disabled, handleStep, onChange],
[disabled, currentDegree, onChange],
)
// Compute visible ticks dynamically around activeDegree for seamless cyclic looping
const minTickIndex = Math.floor((activeDegree - BUFFER_DEGREE) / STEP)
const maxTickIndex = Math.ceil((activeDegree + BUFFER_DEGREE) / STEP)
const ticks: number[] = []
for (let i = minTickIndex; i <= maxTickIndex; i++) {
ticks.push(i * STEP)
}
const clampedDegree = Math.min(360, Math.max(0, currentDegree))
const percent = (clampedDegree / 360) * 100
return (
<div
ref={containerRef}
role="slider"
aria-label="Turntable angle"
aria-valuemin={0}
aria-valuemax={360}
aria-valuenow={clampedDegree}
aria-valuetext={`${clampedDegree}°`}
tabIndex={disabled ? -1 : 0}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={handlePointerUp}
onKeyDown={handleKeyDown}
className={cn(
'relative select-none flex items-center gap-1 sm:gap-2.5 w-full min-w-0 sm:min-w-[140px]',
disabled && 'opacity-50',
'relative select-none cursor-pointer flex flex-col justify-end h-11 px-2.5 touch-none group',
disabled && 'opacity-50 cursor-not-allowed',
className,
)}
>
{/* Minus button on left */}
<button
type="button"
onClick={() => handleStep(-STEP)}
disabled={disabled}
title="Decrease 15°"
aria-label="Decrease 15°"
data-testid="ruler-step-minus"
className="p-0.5 sm:p-1 rounded text-muted-foreground hover:text-foreground transition-colors shrink-0 disabled:opacity-40 disabled:cursor-not-allowed focus:outline-none focus-visible:ring-1 focus-visible:ring-ring"
>
<Minus className="w-3.5 h-3.5" />
</button>
{/* Center Capsule Slider Track Container */}
<div className="relative flex-1 min-w-0">
{/* Tooltip above center indicator (visible only when dragging) */}
{isDragging && (
<div
data-testid="ruler-slider-tooltip"
className="absolute -top-7 left-1/2 -translate-x-1/2 px-1.5 py-0.5 rounded bg-primary text-primary-foreground text-[10px] font-mono font-medium shadow-md whitespace-nowrap pointer-events-none z-30 animate-in fade-in zoom-in-95 duration-100"
{/* Major tick labels */}
<div className="relative w-full h-3 mb-1 pointer-events-none">
{Array.from(MAJOR_TICKS).map((deg) => (
<span
key={`label-${deg}`}
className="absolute text-[10px] leading-none font-mono text-muted-foreground -translate-x-1/2"
style={{ left: `${(deg / 360) * 100}%` }}
>
{displayedDegree}°
</div>
)}
{/* Capsule track with rounded pill shape, clipping scrolling ticks */}
<div
ref={trackRef}
role="slider"
aria-label="Turntable angle"
aria-valuemin={0}
aria-valuemax={360}
aria-valuenow={displayedDegree}
aria-valuetext={`${displayedDegree}°`}
tabIndex={disabled ? -1 : 0}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={handlePointerUp}
onKeyDown={handleKeyDown}
className={cn(
'relative w-full h-7 rounded-full bg-muted border border-border overflow-hidden cursor-ew-resize touch-none select-none group focus:outline-none focus-visible:ring-1 focus-visible:ring-ring',
disabled && 'cursor-not-allowed',
)}
>
{/* Cyclic Ticks - vertically centered */}
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
{ticks.map((tickAngle) => {
const offsetPx = (tickAngle - activeDegree) * PX_PER_DEGREE
const deg = ((tickAngle % 360) + 360) % 360
const isMajor = deg % 60 === 0
return (
<div
key={`tick-${tickAngle}`}
data-testid={`tick-${deg}`}
data-major={isMajor}
className={cn(
'absolute top-1/2 -translate-y-1/2 -translate-x-1/2 transition-colors pointer-events-none rounded-[0.5px]',
isMajor
? 'w-0.5 h-2.5 bg-foreground/75'
: 'w-px h-1.5 bg-muted-foreground/45 group-hover:bg-muted-foreground/65',
)}
style={{ left: `calc(50% + ${offsetPx}px)` }}
/>
)
})}
</div>
{/* Fixed Center Red Indicator (Pinned at 50% horizontally, spans full height) */}
<div
data-testid="ruler-center-indicator"
className="absolute inset-y-0 left-1/2 -translate-x-1/2 w-0.5 flex items-center justify-center pointer-events-none z-20"
>
<div className="w-full h-full bg-[#ea3349] rounded-full" />
</div>
</div>
{deg}°
</span>
))}
</div>
{/* Plus button on right */}
<button
type="button"
onClick={() => handleStep(STEP)}
disabled={disabled}
title="Increase 15°"
aria-label="Increase 15°"
data-testid="ruler-step-plus"
className="p-0.5 sm:p-1 rounded text-muted-foreground hover:text-foreground transition-colors shrink-0 disabled:opacity-40 disabled:cursor-not-allowed focus:outline-none focus-visible:ring-1 focus-visible:ring-ring"
>
<Plus className="w-3.5 h-3.5" />
</button>
{/* Track & Ticks */}
<div className="relative w-full h-4 flex items-end">
{/* Baseline bar */}
<div className="absolute inset-x-0 bottom-0 h-0.5 bg-muted-foreground/30 rounded-full" />
{/* Ticks */}
{TICKS.map((deg) => {
const isMajor = MAJOR_TICKS.has(deg)
return (
<div
key={`tick-${deg}`}
className={cn(
'absolute bottom-0 -translate-x-1/2 transition-colors',
isMajor
? 'w-0.5 h-3.5 bg-foreground/70'
: 'w-px h-2 bg-muted-foreground/40 group-hover:bg-muted-foreground/70',
)}
style={{ left: `${(deg / 360) * 100}%` }}
/>
)
})}
{/* Current Position Thumb */}
<div
className="absolute bottom-0 -translate-x-1/2 flex flex-col items-center pointer-events-none transition-[left] duration-75 ease-out"
style={{ left: `${percent}%` }}
>
{/* Degree Tooltip on drag/hover */}
<div className="text-[10px] font-mono font-semibold px-1 py-0.5 rounded bg-primary text-primary-foreground mb-1 shadow-xs whitespace-nowrap">
{clampedDegree}°
</div>
{/* Thumb needle */}
<div className="w-1.5 h-5 bg-primary rounded-full ring-2 ring-background shadow-md" />
</div>
</div>
</div>
)
}
@@ -1,74 +0,0 @@
import { describe, it, expect } from 'vitest'
import {
calculateFrameCenterTime,
secondToFrame,
secondToDegree,
TOTAL_FRAMES,
FPS,
FRAME_DURATION,
} from './utils'
describe('model viewer utils', () => {
describe('calculateFrameCenterTime', () => {
it('calculates the center time for frame 0', () => {
expect(calculateFrameCenterTime(0)).toBeCloseTo(0.5 / FPS)
})
it('calculates presentation times safely within frame boundaries for all frames 0 to 23', () => {
for (let i = 0; i < TOTAL_FRAMES - 1; i++) {
const center = calculateFrameCenterTime(i)
expect(center).toBeCloseTo((i + 0.5) * FRAME_DURATION)
}
// For the final frame (frame 23, 345°), ensure it is safely offset away from EOF (4.0s)
const lastCenter = calculateFrameCenterTime(TOTAL_FRAMES - 1)
expect(lastCenter).toBeCloseTo((TOTAL_FRAMES - 1) * FRAME_DURATION + FRAME_DURATION * 0.25)
expect(lastCenter).toBeLessThan(TOTAL_FRAMES * FRAME_DURATION)
})
it('handles negative and wrapping frames properly', () => {
expect(calculateFrameCenterTime(-1)).toBeCloseTo(calculateFrameCenterTime(23))
expect(calculateFrameCenterTime(24)).toBeCloseTo(calculateFrameCenterTime(0))
})
})
describe('secondToFrame', () => {
it('correctly maps frame start times to frame index without float truncation', () => {
for (let i = 0; i < TOTAL_FRAMES; i++) {
const startSec = i * FRAME_DURATION
expect(secondToFrame(startSec)).toBe(i)
}
})
it('correctly maps frame center times to frame index', () => {
for (let i = 0; i < TOTAL_FRAMES; i++) {
const centerSec = calculateFrameCenterTime(i)
expect(secondToFrame(centerSec)).toBe(i)
}
})
it('clamps values below 0 and above total duration', () => {
expect(secondToFrame(-1)).toBe(0)
expect(secondToFrame(100)).toBe(TOTAL_FRAMES - 1)
})
})
describe('secondToDegree', () => {
it('returns 0 for 0s', () => {
expect(secondToDegree(0)).toBe(0)
})
it('returns exact degrees (0..345) for every frame center', () => {
for (let i = 0; i < TOTAL_FRAMES; i++) {
const center = calculateFrameCenterTime(i)
expect(secondToDegree(center)).toBe((i * 15) % 360)
}
})
it('returns exact degrees for frame start times', () => {
for (let i = 0; i < TOTAL_FRAMES; i++) {
const start = i * FRAME_DURATION
expect(secondToDegree(start)).toBe((i * 15) % 360)
}
})
})
})
@@ -1,34 +0,0 @@
export const TOTAL_FRAMES = 24
export const FPS = 6
export const FRAME_DURATION = 1 / FPS
/**
* Calculates the presentation time within a frame.
* Seeking near the frame center avoids PTS boundary inaccuracies in browser video decoders.
* For the final frame (TOTAL_FRAMES - 1), we use a safe offset inside the frame
* to avoid grazing the EOF boundary (video duration) which can cause browser decoders
* to trigger end-of-stream or loop behavior.
*/
export function calculateFrameCenterTime(frameIndex: number): number {
const normalizedFrame = ((frameIndex % TOTAL_FRAMES) + TOTAL_FRAMES) % TOTAL_FRAMES
if (normalizedFrame === TOTAL_FRAMES - 1) {
return normalizedFrame * FRAME_DURATION + FRAME_DURATION * 0.25
}
return (normalizedFrame + 0.5) * FRAME_DURATION
}
/**
* Converts a playback second into a frame index (0..23), clamped.
* Works with frame start times, frame center times, or continuous playback seconds.
*/
export function secondToFrame(second: number): number {
return Math.min(Math.max(0, Math.floor(second * FPS + 1e-4)), TOTAL_FRAMES - 1)
}
/**
* Converts a second to turntable degree (0, 15, 30, ..., 345).
*/
export function secondToDegree(second: number): number {
const frameIndex = secondToFrame(second)
return (frameIndex * 15) % 360
}
@@ -17,7 +17,6 @@ export interface FileViewerProps {
onPlay?: () => void
onPause?: () => void
onTimeUpdate?: (time: number) => void
onSeek?: () => void
startTime?: number
shareId?: string
/** When false, the viewer hides its download affordances. Defaults to true. */
Binary file not shown.
-35
View File
@@ -192,38 +192,3 @@ export const sampleAudioAsset: AssetInfo = {
},
},
}
export const TURNTABLE_VIDEO_URL = '/turntable.mp4'
export const TURNTABLE_FRAME_RATE = 6
export const TURNTABLE_TOTAL_FRAMES = 24
export const TURNTABLE_DURATION = 4.0
export const TURNTABLE_WIDTH = 1080
export const TURNTABLE_HEIGHT = 1080
export const sampleTurntableAsset: AssetInfo = {
id: 'e2e-turntable-asset',
name: 'turntable.glb',
proxyType: '3d',
type: 'file',
status: 'ready',
sizeByte: 314488,
fileCount: 1,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
media: {
proxyType: '3d',
videoPreview: {
url: TURNTABLE_VIDEO_URL,
},
original: {
key: 'turntable.glb',
},
metadata: {
duration: TURNTABLE_DURATION,
originalWidth: TURNTABLE_WIDTH,
originalHeight: TURNTABLE_HEIGHT,
frameRate: TURNTABLE_FRAME_RATE,
totalFrames: TURNTABLE_TOTAL_FRAMES,
},
},
}
+6 -18
View File
@@ -2,7 +2,6 @@ import { type ReactElement, useCallback, useRef, useState } from 'react'
import ReactDOM from 'react-dom/client'
import type { MediaController } from '@/ui/components/viewers/types'
import VideoPlayer from '@/ui/components/viewers/video/video-viewer'
import ModelViewer from '@/ui/components/viewers/model/model-viewer'
import { calculateFrameCenterTime } from '@/ui/components/viewers/video/utils'
import { useUiStore } from '@/ui/stores/ui'
import {
@@ -11,7 +10,6 @@ import {
containerLongerVideoAsset,
longAudioVideoAsset,
sampleAudioAsset,
sampleTurntableAsset,
} from './fixture'
/**
@@ -62,7 +60,6 @@ function resolveAsset() {
if (variant === 'container-longer') return containerLongerVideoAsset
if (variant === 'long-audio') return longAudioVideoAsset
if (variant === 'audio') return sampleAudioAsset
if (variant === '3d' || variant === 'turntable') return sampleTurntableAsset
return sampleVideoAsset
}
@@ -135,21 +132,12 @@ function Harness(): ReactElement {
style={{ width: '800px', height: '600px', display: 'flex', overflow: 'hidden' }}
>
<div className="flex flex-col flex-1 h-full overflow-hidden relative">
{harnessAsset.proxyType === '3d' ? (
<ModelViewer
key={playerKey}
file={harnessAsset}
ref={playerRef}
onTimeUpdate={handleTimeUpdate}
/>
) : (
<VideoPlayer
key={playerKey}
file={harnessAsset}
ref={playerRef}
onTimeUpdate={handleTimeUpdate}
/>
)}
<VideoPlayer
key={playerKey}
file={harnessAsset}
ref={playerRef}
onTimeUpdate={handleTimeUpdate}
/>
</div>
</div>
-4
View File
@@ -34,10 +34,6 @@ const server = Bun.serve({
new Response(Bun.file(join(fixturesDir, 'sample-audio.mp4')), {
headers: { 'Content-Type': 'video/mp4' },
}),
'/turntable.mp4': () =>
new Response(Bun.file(join(fixturesDir, 'turntable.mp4')), {
headers: { 'Content-Type': 'video/mp4' },
}),
'/': index,
'/*': index,
},
@@ -1,140 +0,0 @@
import type { Locator, Page } from '@playwright/test'
const MODEL_VIDEO_SELECTOR = '[data-testid="model-viewer-surface"] video'
export interface ModelViewerSnapshot {
degree: number
currentTime: number
frameHash: string
}
export class ModelViewerPage {
readonly page: Page
readonly stage: Locator
readonly container: Locator
readonly surface: Locator
readonly video: Locator
readonly playToggle: Locator
readonly degreeReadout: Locator
readonly rulerSlider: Locator
readonly rulerStepMinus: Locator
readonly rulerStepPlus: Locator
readonly rulerTooltip: Locator
constructor(page: Page) {
this.page = page
this.stage = page.getByTestId('harness-stage')
this.container = page.getByTestId('model-viewer-container')
this.surface = page.getByTestId('model-viewer-surface')
this.video = page.locator(MODEL_VIDEO_SELECTOR).first()
this.playToggle = page.getByTestId('play-toggle')
this.degreeReadout = page.getByTestId('degree-readout')
this.rulerSlider = page.locator('[role="slider"]')
this.rulerStepMinus = page.getByTestId('ruler-step-minus')
this.rulerStepPlus = page.getByTestId('ruler-step-plus')
this.rulerTooltip = page.getByTestId('ruler-slider-tooltip')
}
async goto(): Promise<void> {
await this.page.goto('/?variant=3d')
await this.waitUntilReady()
}
async waitUntilReady(): Promise<void> {
await this.video.waitFor({ state: 'attached' })
await this.page.waitForFunction(
(selector) => {
const el = document.querySelector(selector) as HTMLVideoElement | null
return !!el && el.readyState >= 1 && Number.isFinite(el.duration)
},
MODEL_VIDEO_SELECTOR,
{ timeout: 15_000 },
)
await this.page.waitForFunction(
() => {
const readout = document.querySelector('[data-testid="degree-readout"]')
return !!readout && /\d+°\s*\/\s*360°/.test(readout.textContent ?? '')
},
undefined,
{ timeout: 15_000 },
)
}
async getDegree(): Promise<number> {
const text = (await this.degreeReadout.textContent()) ?? ''
const match = text.match(/(\d+)°\s*\/\s*360°/)
return match ? Number.parseInt(match[1], 10) : Number.NaN
}
async getCurrentTime(): Promise<number> {
return this.video.evaluate((el: HTMLVideoElement) => el.currentTime)
}
/**
* Captures a perceptual pixel hash of the video's current rendered frame.
* Two frames displaying identical visuals yield the identical hash.
*/
async captureFrameHash(): Promise<string> {
return this.video.evaluate((el: HTMLVideoElement) => {
const canvas = document.createElement('canvas')
canvas.width = 64
canvas.height = 64
const ctx = canvas.getContext('2d')
if (!ctx) return ''
ctx.drawImage(el, 0, 0, 64, 64)
const data = ctx.getImageData(0, 0, 64, 64).data
let hash = 0
for (let i = 0; i < data.length; i++) {
hash = ((hash << 5) - hash + data[i]) | 0
}
return `${hash}_${data[0]}_${data[100]}_${data[500]}_${data[1000]}`
})
}
async snapshot(): Promise<ModelViewerSnapshot> {
const [degree, currentTime, frameHash] = await Promise.all([
this.getDegree(),
this.getCurrentTime(),
this.captureFrameHash(),
])
return { degree, currentTime, frameHash }
}
async stepPlus(): Promise<void> {
await this.rulerStepPlus.click()
}
async stepMinus(): Promise<void> {
await this.rulerStepMinus.click()
}
async pressArrowRight(): Promise<void> {
await this.page.keyboard.press('ArrowRight')
}
async pressArrowLeft(): Promise<void> {
await this.page.keyboard.press('ArrowLeft')
}
async dragSurface(deltaX: number, steps = 5): Promise<void> {
const box = await this.surface.boundingBox()
if (!box) throw new Error('Surface bounding box not found')
const startX = box.x + box.width / 2
const startY = box.y + box.height / 2
await this.page.mouse.move(startX, startY)
await this.page.mouse.down()
await this.page.mouse.move(startX + deltaX, startY, { steps })
await this.page.mouse.up()
}
async dragSlider(deltaX: number, steps = 5): Promise<void> {
const box = await this.rulerSlider.boundingBox()
if (!box) throw new Error('Slider bounding box not found')
const startX = box.x + box.width / 2
const startY = box.y + box.height / 2
await this.page.mouse.move(startX, startY)
await this.page.mouse.down()
await this.page.mouse.move(startX + deltaX, startY, { steps })
await this.page.mouse.up()
}
}
@@ -1,183 +0,0 @@
import { test, expect } from '@playwright/test'
import { ModelViewerPage } from '../pages/model-viewer.page'
test.describe('3D Asset Viewer E2E Tests', () => {
/**
* ISSUE 1 VERIFICATION:
* Asserts that all 24 frames across 0° to 345° have completely unique visual scenes.
* Specifically, verifies that pairs like [0°, 15°], [45°, 60°], [90°, 105°], etc.
* decode distinct frames instead of showing the same scene.
*/
test('Issue 1: verifies all 24 degree angles render unique visual frames', async ({ page }) => {
const viewer = new ModelViewerPage(page)
await viewer.goto()
// Step through each of the 24 angles: 0°, 15°, 30°, 45°, ..., 345°
const snapshots: Array<{ degree: number; currentTime: number; frameHash: string }> = []
for (let i = 0; i < 24; i++) {
// Allow video element decoding and frame presentation to settle
await page.waitForTimeout(100)
const snap = await viewer.snapshot()
snapshots.push(snap)
if (i < 23) {
await viewer.stepPlus()
}
}
console.log('--- SNAPSHOTS ACROSS ALL 24 STEPS ---')
for (const snap of snapshots) {
console.log(
`Degree: ${snap.degree}°, currentTime: ${snap.currentTime.toFixed(6)}, frameHash: ${snap.frameHash}`,
)
}
// Verify all 24 frames have unique hashes
const uniqueHashes = new Set(snapshots.map((s) => s.frameHash))
expect(uniqueHashes.size).toBe(24)
// Verify all adjacent pairs have distinct scenes
for (let i = 0; i < 23; i++) {
const snapA = snapshots[i]
const snapB = snapshots[i + 1]
expect(snapA.frameHash).not.toBe(snapB.frameHash)
}
})
/**
* ISSUE 2 VERIFICATION (Surface):
* Asserts that at 345°, starting a drag or making small drag movements
* maintains the 345° position rather than snapping backwards to 330°.
*/
test('Issue 2: verifies drag-to-rotate on viewer surface at 345 degrees does not jitter', async ({
page,
}) => {
const viewer = new ModelViewerPage(page)
await viewer.goto()
// Step backward from 0° -> wraps to 345°
await viewer.stepMinus()
await page.waitForTimeout(100)
const initialSnap = await viewer.snapshot()
expect(initialSnap.degree).toBe(345)
const box = await viewer.surface.boundingBox()
if (!box) throw new Error('Surface box not found')
const startX = box.x + box.width / 2
const startY = box.y + box.height / 2
// Mouse down at 345°
await page.mouse.move(startX, startY)
await page.mouse.down()
// Small drag of -4px (less than 12px / 2 = 6px threshold for 1 frame)
await page.mouse.move(startX - 4, startY, { steps: 2 })
await page.waitForTimeout(50)
const degreeSmallDrag = await viewer.getDegree()
// Must remain at 345° (no jitter back to 330°)
expect(degreeSmallDrag).toBe(345)
// Drag left by -12px (rotates counterclockwise by 1 frame: 345° -> 0°)
await page.mouse.move(startX - 12, startY, { steps: 2 })
await page.waitForTimeout(50)
const degreeCcw = await viewer.getDegree()
expect(degreeCcw).toBe(0)
// Drag back to start position (0px delta relative to start)
await page.mouse.move(startX, startY, { steps: 2 })
await page.waitForTimeout(50)
const degreeBack = await viewer.getDegree()
expect(degreeBack).toBe(345)
// Drag right by +12px (rotates clockwise by 1 frame: 345° -> 330°)
await page.mouse.move(startX + 12, startY, { steps: 2 })
await page.waitForTimeout(50)
const degreeCw = await viewer.getDegree()
expect(degreeCw).toBe(330)
await page.mouse.up()
})
/**
* ISSUE 2 VERIFICATION (Slider):
* Asserts that dragging the ruler slider across 345° and 0° scrolls smoothly
* and transitions between angles cleanly.
*/
test('Issue 2 (slider): verifies dragging ruler slider across 345° and 0° transitions smoothly', async ({
page,
}) => {
const viewer = new ModelViewerPage(page)
await viewer.goto()
// Navigate to 345°
await viewer.stepMinus()
await page.waitForTimeout(100)
expect(await viewer.getDegree()).toBe(345)
const sliderBox = await viewer.rulerSlider.boundingBox()
if (!sliderBox) throw new Error('Slider box not found')
const startX = sliderBox.x + sliderBox.width / 2
const startY = sliderBox.y + sliderBox.height / 2
await page.mouse.move(startX, startY)
await page.mouse.down()
// Drag slightly left (-12px) across 345° towards 0°
await page.mouse.move(startX - 12, startY, { steps: 2 })
await page.waitForTimeout(50)
const degCross = await viewer.getDegree()
expect(degCross).toBe(0)
// Drag further left (-32px) to 15°
await page.mouse.move(startX - 32, startY, { steps: 2 })
await page.waitForTimeout(50)
const degFurther = await viewer.getDegree()
expect(degFurther).toBe(15)
// Drag back to 0px
await page.mouse.move(startX, startY, { steps: 2 })
await page.waitForTimeout(50)
const degBack = await viewer.getDegree()
expect(degBack).toBe(345)
await page.mouse.up()
})
/**
* ISSUE 3 VERIFICATION (Playback Frame Stepping):
* Asserts that auto-rotating via play/pause advances through consecutive 15° steps
* (e.g. 0° -> 15° -> 30° -> 45°) without skipping intermediate frames like 30°.
*/
test('Issue 3: verifies auto-rotation playback updates at consistent 15 degree increments', async ({
page,
}) => {
const viewer = new ModelViewerPage(page)
await viewer.goto()
// Start playback
await viewer.playToggle.click()
await page.waitForTimeout(100)
// Collect observed degree values over 1.5 seconds of playback (~9 frames at 6 FPS)
const observedDegrees = new Set<number>()
const startTime = Date.now()
while (Date.now() - startTime < 1500) {
const deg = await viewer.getDegree()
if (!Number.isNaN(deg)) {
observedDegrees.add(deg)
}
await page.waitForTimeout(30)
}
// Pause playback
await viewer.playToggle.click()
// Verify that consecutive 15° frames including 30° and 60° were captured
expect(observedDegrees.has(30)).toBe(true)
expect(observedDegrees.has(45)).toBe(true)
expect(observedDegrees.has(60)).toBe(true)
})
})

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