Compare commits

..
4 Commits
257 changed files with 2662 additions and 22816 deletions
+1 -1
View File
@@ -125,7 +125,7 @@ An **Operation** is defined once and exposed across built-in agent tools, the MC
- **Route Code-Splitting**: Split all routes into `[route].tsx` (route definition and loaders) and `[route].lazy.tsx` (UI component and heavy imports).
- **Radix / Shadcn UI**: Set `modal={false}` on `<DropdownMenu>` when triggering a `Dialog` or `AlertDialog` from inside it to prevent focus-trap UI freezes. Use `ScrollArea` (`@/ui/components/ui/scroll-area`) for scrollable containers.
- **Pagination & Infinite Scroll**: Use `useInfiniteQuery` + `react-intersection-observer` with default `limit: 20` and the API's `total` field. Backend list APIs use `paginateQuery` from `packages/core/src/pagination.ts` (default `limit: 20`).
- **Internationalization (i18n)**: Hardcoded UI text is strictly forbidden. Add `snake_case` keys to **all** locale files in `packages/webui/messages/*.json` (do not assume only `en.json` and `zh.json` exist; check the directory for all supported languages), run `bun run i18n:compile` (or `bun run i18n:watch`), and import `m` from `@/ui/paraglide/messages.js`.
- **Internationalization (i18n)**: Hardcoded UI text is strictly forbidden. Add `snake_case` keys to both `packages/webui/messages/en.json` and `packages/webui/messages/zh.json`, run `bun run i18n:compile` (or `bun run i18n:watch`), and import `m` from `@/ui/paraglide/messages.js`.
## Database & Prisma (`packages/db`)
+2 -47
View File
@@ -8,61 +8,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
### Fixed
### Changed
## [0.7.2] - 2026-11-27
### Added
- **comments**: Add Internal Comments with a Public/Internal selector in the comment composer so team and project members can have private discussions (marked with a lock icon) that never appear on public share links.
- **comments**: Allow comment authors to edit their comments inline from the comment menu, including updating text, switching between Public and Internal, removing timestamps, and adding or removing attachments.
- **comments**: Add a "Print Comments" option in the comments menu (available in both project file views and public share links) that opens a dedicated print-friendly page with asset metadata, comment thumbnails, visual markup overlays, replies, completion status, emoji reactions, and attachments.
- **share**: See view counts, last viewed times, and activity for public share links, including file and folder views, downloads, and comments.
- **share**: Add options to create a share link or add to existing share links directly from the media view dropdown menu, and open a quick share dialog with inline renaming, one-click link copying, and security settings upon creation.
### Fixed
- **video**: Pause playback while dragging the seekbar and show a lightweight preview in the player until the selected frame is ready.
- **comments**: Keep password-protected print links on the share password prompt, keep private folder names out of shared print data, and wait for thumbnails and reply drawings before printing.
- **security**: Security improvements.
### Changed
## [0.7.1] - 2026-11-23
### Added
- **search**: Find similar images and video segments from a project image, or choose, drop, or paste an image in semantic search.
### Fixed
- **storage**: Fix an issue where cached media preview and file URLs could expire and break after the host machine slept or near the end of an S3 link's lifetime.
- **search**: Video segment matches in Semantic Search and Find Similar show the segment’s first frame and let you scrub through it on hover. Matches that span the entire video reuse its full preview when available.
- **search**: Fix an issue where version stacks appeared as separate individual versions in Search and Find Similar results instead of matching only the latest version and showing a single stacked asset with its version badge.
### Changed
- **transcode**: Offload video chunk slicing for search embeddings to the transcode worker queue.
## [0.7.0] - 2026-11-18
### Added
- **agent**: Support binding external Runners per team so agents can execute shell commands and exchange files securely over WebSocket without requiring a built-in server sandbox, and allow assigning a default or dedicated Runner per agent in Team Settings.
- **i18n**: Add Korean as a display language, selectable on the sign-up page and in team settings.
### Fixed
- **video**: Fix playback stalling after tapping or clicking the progress bar on slow connections, and stop the hidden seek preview from downloading the whole video in the background.
- **cli**: Fix release publication failing to find staged standalone downloads.
### Changed
- **agent**: ⚠️ **Breaking Change**: Replaced the built-in server-side Bash sandbox with external Runners and removed the team-level sandbox domain allowlist settings. The Bash tool is now disabled by default. If your Agent or Skills require Bash execution, you'll need to set up and connect an external Runner using shumai-cli. The Shumai CLI includes built-in sandbox support, allowing you to configure filesystem access and network domain allowlists for Bash execution directly on the Runner. See [Agent Runners](https://docs.shumai.one/using-shumai/agent-sandbox) for setup instructions and configuration details. The Docker Compose configuration has also been updated to improve security following the removal of the server-side sandbox. We strongly recommend upgrading to the latest Shumai image and updating your Docker Compose file to apply these security improvements.
- **agent**: ⚠️ **Behavior Change**: Replace the built-in server-side bash sandbox and domain allowlist settings with external team Runners; agent `bash` and `download_asset` tools are enabled automatically once at least one Runner is configured for the team, while domain and OS-level sandboxing rules move to the Runner side.
- **cli**: Show copyable commands and shell configuration instructions when the standalone CLI installation directory is missing from PATH.
## [0.6.6] - 2026-11-13
-1
View File
@@ -13,7 +13,6 @@
<a href="https://github.com/shumaiOne/shumai/releases"><img alt="GitHub latest release" src="https://img.shields.io/github/v/release/shumaiOne/shumai" /></a>
<a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-blue" /></a>
<a target="_blank" href="https://deepwiki.com/shumaiOne/shumai"><img alt="Ask DeepWiki" src="https://img.shields.io/badge/Ask-DeepWiki-6E56CF" /></a>
<a target="_blank" href="https://docs.qq.com/doc/DUmJRWndFVWJPQVRI"><img alt="微信群" src="https://img.shields.io/badge/WeChat-%E5%BE%AE%E4%BF%A1%E7%BE%A4-07C160" /></a>
</p>
<p align="center">
-1
View File
@@ -13,7 +13,6 @@
<a href="https://github.com/shumaiOne/shumai/releases"><img alt="GitHub latest release" src="https://img.shields.io/github/v/release/shumaiOne/shumai" /></a>
<a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-blue" /></a>
<a target="_blank" href="https://deepwiki.com/shumaiOne/shumai"><img alt="Ask DeepWiki" src="https://img.shields.io/badge/Ask-DeepWiki-6E56CF" /></a>
<a target="_blank" href="https://docs.qq.com/doc/DUmJRWndFVWJPQVRI"><img alt="微信群" src="https://img.shields.io/badge/WeChat-%E5%BE%AE%E4%BF%A1%E7%BE%A4-07C160" /></a>
</p>
<p align="center">
+1 -39
View File
@@ -86,44 +86,6 @@ export SHUMAI_ALLOW_DELETE="true"
---
## Agent runner
Create a runner in **Settings → Agent Runners** and copy its one-time key. On macOS, Linux, or Windows, start it in an existing dedicated workspace:
```sh
export SHUMAI_API_SERVER="https://shumai.example.com"
export SHUMAI_RUNNER_KEY="your-runner-key"
shumai-cli runner start --cwd /path/to/workspace
```
For Windows PowerShell:
```powershell
$env:SHUMAI_API_SERVER = "https://shumai.example.com"
$env:SHUMAI_RUNNER_KEY = "your-runner-key"
shumai-cli runner start --cwd C:\workspace
```
Use `--url` or `--key` to override those variables. Pass `-v` or `--verbose` to log executed commands, output sizes, and file transfer paths (by default, only lifecycle events, execution IDs, exit status, and durations are printed to stderr). A runner key is separate from `SHUMAI_API_KEY`. The runner stays in the foreground; Ctrl+C stops it and its active commands. Remote servers require HTTPS; localhost and `host.docker.internal` support HTTP for development. No inbound port is opened.
Commands use `/bin/sh` on macOS and Linux. On Windows, the runner checks for Git Bash in the standard installation directories, then for `bash.exe` on PATH, then falls back to `cmd.exe`. It prints the selected shell at startup and reports it to the agent. Commands run with the local user's permissions unless SRT is requested.
[Anthropic Sandbox Runtime](https://github.com/anthropics/sandbox-runtime) is bundled with the CLI. Install its platform prerequisites (Linux: bubblewrap, socat, and ripgrep; macOS: ripgrep), then pass its native JSON settings:
```sh
shumai-cli runner start --srt sandbox.json
```
Windows sandboxing uses SRT's alpha Windows support. Use Git Bash if your selected shell is the legacy WSL Bash launcher. Run the one-time SRT setup before starting a sandboxed runner (it requests administrator permission):
```powershell
npx @anthropic-ai/sandbox-runtime windows-install
```
SRT settings are read and validated at startup. Invalid settings or unavailable sandbox prerequisites stop startup; commands never fall back to unrestricted execution. Only shell commands and their children are sandboxed. Runner connections and server-directed file transfers stay outside SRT, and no server domain is automatically allowed. The shared SRT runtime is cleaned up when the runner stops.
See [Agent Runners](../../docs/using-shumai/agent-sandbox.mdx) for configuration, Docker usage, limits, and security boundaries.
## Usage
> [!IMPORTANT]
@@ -368,7 +330,7 @@ bun run build:cli --target darwin-arm64 # or darwin-x64, linux-arm64, linux-x64,
bun run test:cli-release
```
Without `--target`, the build produces all six targets. Output defaults to `out/cli-release`. Set `--out /absolute/path` on either command to change it. Unix archives require `tar`. Creating Windows archives on Unix also requires `zip`. The test exercises installation, runner shell quoting, authenticated API calls, file transfers, and failure recovery. Install Git Bash to run the quoting check on Windows. With SRT configured, pass `--srt /absolute/path/to/settings.json` to repeat the quoting check in the sandbox.
Without `--target`, the build produces all six targets. Output defaults to `out/cli-release`; both commands accept `--out /absolute/path`. Unix archives require `tar`; creating Windows archives on Unix also requires `zip`. The test runs the generated installer against local HTTP fixtures, then authenticates, creates a folder, uploads and downloads random bytes, and checks failure recovery with no runtime on the executable's PATH.
The Native CLI workflow builds and tests each target on a matching runner. The npm release workflow assembles those tested archives, stages a draft GitHub Release, publishes npm packages, then publishes the completed release. Its `validate_only` dispatch input builds and tests without publishing. Published assets are verified and preserved on retries; draft assets can be replaced while resuming a failed run. Prerelease npm packages use the `next` tag and prerelease GitHub Releases do not become latest.
-24
View File
@@ -1,24 +0,0 @@
The Windows Bash discovery and related tests include material adapted from Pi.
https://github.com/earendil-works/pi
MIT License
Copyright (c) 2025 Mario Zechner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+1 -11
View File
@@ -1,29 +1,19 @@
{
"name": "@shumai/cli",
"version": "0.7.2",
"version": "0.6.6",
"private": true,
"type": "module",
"bin": {
"shumai-cli": "./src/index.ts"
},
"dependencies": {
"@anthropic-ai/sandbox-runtime": "0.0.83",
"@shumai/api": "workspace:*",
"@shumai/dtos": "workspace:*",
"@shumai/operations": "workspace:*",
"@shumai/tableprinter": "workspace:*",
"commander": "15.0.0",
"execa": "10.2.1",
"hono": "4.13.5",
"ulid": "3.0.2",
"ws": "8.22.2",
"yauzl": "3.4.0",
"zod": "4.5.4"
},
"devDependencies": {
"@types/adm-zip": "0.5.8",
"@types/ws": "8.18.2",
"@types/yauzl": "3.4.0",
"adm-zip": "0.6.1"
}
}
-20
View File
@@ -33,10 +33,8 @@ function setup() {
let stdout = ''
let stderr = ''
const callOperation = vi.fn<CallOperation>()
const startRunner = vi.fn(async () => {})
const program = createProgram({
callOperation,
startRunner,
output: { out: { write: (s) => void (stdout += s) }, isTty: true, columns: 120 },
})
const configure = (cmd: Command) => {
@@ -49,7 +47,6 @@ function setup() {
configure(program)
return {
callOperation,
startRunner,
run: (...argv: string[]) => program.parseAsync(['node', 'shumai-cli', ...argv]),
stdout: () => stdout,
stderr: () => stderr,
@@ -860,23 +857,6 @@ describe('shumai-cli', () => {
})
})
describe('runner start', () => {
it('documents and forwards the -v, --verbose flag', async () => {
const cli = setup()
await expect(cli.run('runner', 'start', '--help')).rejects.toThrow()
expect(cli.stdout()).toContain('-v, --verbose')
await cli.run('runner', 'start')
expect(cli.startRunner).toHaveBeenLastCalledWith({})
await cli.run('runner', 'start', '-v')
expect(cli.startRunner).toHaveBeenLastCalledWith({ verbose: true })
await cli.run('runner', 'start', '--verbose')
expect(cli.startRunner).toHaveBeenLastCalledWith({ verbose: true })
})
})
it('has no upload Operation commands: upload and create-version stream local files', () => {
const program = createProgram({ callOperation: vi.fn<CallOperation>() })
const names = program.commands.map((c) => c.name())
-15
View File
@@ -7,13 +7,10 @@ import { cliExtensions } from './operations/extensions'
import { registerOperationCommands } from './operations/generate'
import type { Output } from './operations/render'
import { version } from '../package.json'
import { startRunner } from './runner/client'
import type { RunnerOptions } from './runner/config'
export interface ProgramOptions {
callOperation?: CallOperation
output?: Output
startRunner?: (options: RunnerOptions) => Promise<void>
}
function isDeleteAllowed(): boolean {
@@ -46,18 +43,6 @@ export function createProgram(options: ProgramOptions = {}): Command {
extensions: cliExtensions,
})
program
.command('runner')
.description('Connect a local command runner to Shumai.')
.command('start')
.description('Run in the foreground using a key created in Settings → Agent Runners.')
.option('--url <url>', 'Shumai server URL (or SHUMAI_API_SERVER).')
.option('--key <key>', 'Runner key (prefer SHUMAI_RUNNER_KEY to avoid shell history).')
.option('--cwd <directory>', 'Runner workspace directory (defaults to the current directory).')
.option('--srt <file>', 'Sandbox commands with bundled SRT using this JSON settings file.')
.option('-v, --verbose', 'Show command details, output sizes, and file transfer paths.')
.action((opts: RunnerOptions) => (options.startRunner ?? startRunner)(opts))
program
.command('upload')
.description('Upload a local file or folder to a parent folder.')
-446
View File
@@ -1,446 +0,0 @@
import { createServer } from 'node:http'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { WebSocketServer, type WebSocket } from 'ws'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { runnerToServerMessageSchema, type RunnerToServerMessage } from '@shumai/dtos'
import { RunnerClient } from './client'
import { RunnerFiles } from './files'
import { RunnerShell } from './shell'
describe('runner WebSocket client', () => {
let cwd: string
let server: WebSocketServer
let runner: RunnerClient
let running: Promise<void>
let socket: WebSocket
let messages: RunnerToServerMessage[]
let welcomeInFlight: string[]
let connections: number
let replacePrevious: boolean
let connectRunner: (options?: { verbose?: boolean; log?: (line: string) => void }) => RunnerClient
beforeEach(async () => {
cwd = await mkdtemp(path.join(tmpdir(), 'shumai-client-test-'))
messages = []
welcomeInFlight = []
connections = 0
replacePrevious = false
server = new WebSocketServer({ host: '127.0.0.1', port: 0 })
await new Promise<void>((resolve) => server.once('listening', resolve))
const address = server.address()
if (!address || typeof address === 'string') throw new Error('No WebSocket address')
server.on('connection', (connection, request) => {
expect(request.headers.authorization).toBe('Bearer runner-key')
if (replacePrevious) socket.close(4000, 'Replaced by a newer connection')
socket = connection
connections++
connection.on('message', (raw) =>
messages.push(runnerToServerMessageSchema.parse(JSON.parse(raw.toString()))),
)
connection.send(
JSON.stringify({
type: 'welcome',
runnerId: 'runner',
runnerName: 'Test',
serverTime: Date.now(),
inFlightExecutionIds: welcomeInFlight,
}),
)
})
connectRunner = (options) => {
const files = new RunnerFiles(cwd)
return new RunnerClient(
{
url: new URL(`ws://127.0.0.1:${address.port}/api/runners/ws`),
key: 'runner-key',
cwd,
srt: undefined,
verbose: options?.verbose ?? false,
},
files,
new RunnerShell(files),
options?.log ?? (() => {}),
)
}
runner = connectRunner()
running = runner.run()
// Attach an error handler immediately, including for tests exercising terminal errors.
void running.catch(() => {})
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'reconcile')).toBe(true),
)
})
afterEach(async () => {
runner.stop()
await running.catch(() => {})
for (const connection of server.clients) connection.terminate()
await new Promise<void>((resolve) => server.close(() => resolve()))
await rm(cwd, { recursive: true, force: true })
})
const send = (message: unknown) => socket.send(JSON.stringify(message))
it('responds to heartbeat, executes a command once and streams byte offsets', async () => {
expect(messages).toContainEqual(
expect.objectContaining({
type: 'reconcile',
environment: { platform: process.platform, shell: '/bin/sh' },
}),
)
send({ type: 'ping', ts: 123 })
const command = {
type: 'exec.start',
executionId: 'one',
command: 'printf "世界"; printf "error" >&2',
}
send(command)
send(command)
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'exec.result')).toBe(true),
)
expect(messages).toContainEqual({ type: 'pong', ts: 123 })
expect(messages.filter((message) => message.type === 'exec.result')).toHaveLength(1)
const chunks = messages.filter((message) => message.type === 'exec.output')
expect(chunks.map((chunk) => chunk.data).join('')).toContain('世界')
let offset = 0
for (const chunk of chunks) {
expect(chunk.offset).toBe(offset)
offset += Buffer.byteLength(chunk.data)
}
})
it('cancels an active command through the protocol', async () => {
send({ type: 'exec.start', executionId: 'cancel', command: 'echo ready; sleep 30' })
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'exec.output')).toBe(true),
)
send({ type: 'exec.cancel', executionId: 'cancel' })
await vi.waitFor(() =>
expect(messages).toContainEqual(
expect.objectContaining({ type: 'exec.result', executionId: 'cancel', aborted: true }),
),
)
})
it('reconnects and replays output before completing an in-flight command', async () => {
send({
type: 'exec.start',
executionId: 'reconnect',
command: 'echo before; sleep 0.2; echo after',
})
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'exec.output')).toBe(true),
)
welcomeInFlight = ['reconnect']
socket.terminate()
messages = []
await vi.waitFor(() => expect(connections).toBe(2), { timeout: 5000 })
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'reconcile')).toBe(true),
)
const reconciliation = messages.findIndex((message) => message.type === 'reconcile')
expect(
messages
.slice(0, reconciliation)
.filter((message) => message.type === 'exec.output')
.map((message) => message.data)
.join(''),
).toContain('after')
expect(messages[reconciliation]).toMatchObject({
completedExecutions: [expect.objectContaining({ executionId: 'reconnect', exitCode: 0 })],
})
})
it('handles file requests and returns a cached result for a duplicate request', async () => {
const request = { type: 'file.stat', executionId: 'stat', srcPath: '.pi/missing' }
send(request)
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'file.stat.result')).toBe(true),
)
send(request)
await vi.waitFor(() =>
expect(messages.filter((message) => message.type === 'file.stat.result')).toHaveLength(2),
)
expect(messages.at(-1)).toMatchObject({ ok: true, exists: false })
})
it('stops instead of reconnecting when the runner key is revoked', async () => {
socket.close(1008, 'revoked')
await expect(running).rejects.toThrow('revoked')
expect(connections).toBe(1)
})
it('stops the superseded client when a second runner connects with the same key', async () => {
replacePrevious = true
let replaced: unknown
void running.catch((error: unknown) => {
replaced = error
})
const replacement = connectRunner()
const replacementRun = replacement.run()
void replacementRun.catch(() => {})
try {
await vi.waitFor(() => expect(replaced).toBeInstanceOf(Error))
await expect(running).rejects.toThrow('replaced')
expect(connections).toBe(2)
} finally {
replacement.stop()
await replacementRun.catch(() => {})
}
})
it('rejects invalid messages and path-like execution IDs', async () => {
send({ type: 'exec.start', executionId: '../escape', command: 'echo unsafe' })
await expect(running).rejects.toThrow('invalid runner protocol')
expect(messages.some((message) => message.type === 'exec.output')).toBe(false)
})
it('logs compact lifecycle, bash, and transfer summaries in default mode', async () => {
runner.stop()
await running.catch(() => {})
const logs: string[] = []
messages = []
runner = connectRunner({ verbose: false, log: (line) => logs.push(line) })
running = runner.run()
void running.catch(() => {})
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'reconcile')).toBe(true),
)
send({ type: 'exec.start', executionId: '01JTEST0000A8F2', command: 'printf "hello"' })
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'exec.result')).toBe(true),
)
send({
type: 'exec.start',
executionId: '01JTEST0000TOUT',
command: 'sleep 5',
timeoutSec: 0.1,
})
await vi.waitFor(() =>
expect(
messages.some(
(message) => message.type === 'exec.result' && message.executionId === '01JTEST0000TOUT',
),
).toBe(true),
)
send({ type: 'file.stat', executionId: '01JTEST0000STAT', srcPath: '.pi/missing' })
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'file.stat.result')).toBe(true),
)
const httpServer = createServer((_request, response) => {
response.end('payload')
})
await new Promise<void>((resolve) => httpServer.listen(0, '127.0.0.1', resolve))
try {
const httpAddress = httpServer.address()
if (!httpAddress || typeof httpAddress === 'string') throw new Error('No HTTP address')
send({
type: 'file.download',
executionId: '01JTEST0000C3D9',
url: `http://127.0.0.1:${httpAddress.port}/file`,
destPath: '.pi/assets/file.txt',
})
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'file.download.result')).toBe(true),
)
} finally {
httpServer.closeAllConnections()
await new Promise<void>((resolve) => httpServer.close(() => resolve()))
}
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} INFO {2}Runner connected: Test \(runner\)$/.test(line),
),
).toBe(true)
expect(
logs.some((line) => /^\d{2}:\d{2}:\d{2} INFO {2}Bash started \[a8f2\]$/.test(line)),
).toBe(true)
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} INFO {2}Bash completed \[a8f2\] exit=0 duration=\d+\.\ds$/.test(line),
),
).toBe(true)
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} WARN {2}Bash timed out \[tout\] duration=\d+\.\ds$/.test(line),
),
).toBe(true)
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} INFO {2}File download completed \[c3d9\] size=7B duration=\d+\.\ds$/.test(
line,
),
),
).toBe(true)
expect(logs.join('\n')).not.toContain('command=')
expect(logs.join('\n')).not.toContain('File stat')
expect(logs.join('\n')).not.toContain('.pi/assets/file.txt')
})
it('logs commands, stream sizes, and file paths in verbose mode', async () => {
runner.stop()
await running.catch(() => {})
const logs: string[] = []
messages = []
runner = connectRunner({ verbose: true, log: (line) => logs.push(line) })
running = runner.run()
void running.catch(() => {})
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'reconcile')).toBe(true),
)
send({
type: 'exec.start',
executionId: '01JTEST0000B9E1',
command: 'printf "hi"; printf "err" >&2',
})
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'exec.result')).toBe(true),
)
send({ type: 'file.stat', executionId: '01JTEST0000B1A4', srcPath: '.pi/missing' })
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'file.stat.result')).toBe(true),
)
const httpServer = createServer((_request, response) => {
response.writeHead(500)
response.end()
})
await new Promise<void>((resolve) => httpServer.listen(0, '127.0.0.1', resolve))
try {
const httpAddress = httpServer.address()
if (!httpAddress || typeof httpAddress === 'string') throw new Error('No HTTP address')
send({
type: 'file.download',
executionId: '01JTEST0000E5F1',
url: `http://127.0.0.1:${httpAddress.port}/fail`,
destPath: '.pi/assets/fail.txt',
})
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'file.download.result')).toBe(true),
)
} finally {
httpServer.closeAllConnections()
await new Promise<void>((resolve) => httpServer.close(() => resolve()))
}
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} INFO {2}Bash started \[b9e1\] command="printf \\"hi\\"; printf \\"err\\" >&2"$/.test(
line,
),
),
).toBe(true)
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} INFO {2}Bash completed \[b9e1\] exit=0 duration=\d+\.\ds stdout=2B stderr=3B$/.test(
line,
),
),
).toBe(true)
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} INFO {2}File stat \[b1a4\] path="\.pi\/missing" exists=false$/.test(
line,
),
),
).toBe(true)
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} INFO {2}File download started \[e5f1\] path="\.pi\/assets\/fail\.txt"$/.test(
line,
),
),
).toBe(true)
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} WARN {2}File download failed \[e5f1\] path="\.pi\/assets\/fail\.txt" duration=\d+\.\ds error="Download failed \(HTTP 500\)\."$/.test(
line,
),
),
).toBe(true)
})
it.each([false, true])(
'logs a single busy rejection without false starts at capacity (verbose=%s)',
async (verbose) => {
runner.stop()
await running.catch(() => {})
const logs: string[] = []
messages = []
runner = connectRunner({ verbose, log: (line) => logs.push(line) })
running = runner.run()
void running.catch(() => {})
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'reconcile')).toBe(true),
)
for (let index = 0; index < 8; index++) {
send({
type: 'exec.start',
executionId: `01JACTIVE00000${index}`,
command: 'sleep 30',
})
}
await vi.waitFor(() =>
expect(logs.filter((line) => line.includes('Bash started'))).toHaveLength(8),
)
send({
type: 'exec.start',
executionId: '01JBUSYCMD00B123',
command: 'echo rejected',
})
send({
type: 'file.upload',
executionId: '01JBUSYFILE0U456',
srcPath: '.pi/out.bin',
url: 'http://127.0.0.1:9/upload',
})
await vi.waitFor(() => {
expect(messages).toContainEqual(
expect.objectContaining({
type: 'exec.result',
executionId: '01JBUSYCMD00B123',
error: 'Runner is busy. Try again later.',
}),
)
expect(messages).toContainEqual(
expect.objectContaining({
type: 'file.upload.result',
executionId: '01JBUSYFILE0U456',
ok: false,
error: 'Runner is busy. Try again later.',
}),
)
})
const bashLogs = logs.filter((line) => line.includes('[b123]'))
const uploadLogs = logs.filter((line) => line.includes('[u456]'))
expect(bashLogs).toHaveLength(1)
expect(uploadLogs).toHaveLength(1)
if (verbose) {
expect(bashLogs[0]).toMatch(
/^\d{2}:\d{2}:\d{2} WARN {2}Bash rejected \[b123\] command="echo rejected" error="Runner is busy\. Try again later\."$/,
)
expect(uploadLogs[0]).toMatch(
/^\d{2}:\d{2}:\d{2} WARN {2}File upload rejected \[u456\] path="\.pi\/out\.bin" error="Runner is busy\. Try again later\."$/,
)
} else {
expect(bashLogs[0]).toMatch(
/^\d{2}:\d{2}:\d{2} WARN {2}Bash rejected \[b123\] \(runner is busy\)$/,
)
expect(uploadLogs[0]).toMatch(
/^\d{2}:\d{2}:\d{2} WARN {2}File upload rejected \[u456\] \(runner is busy\)$/,
)
}
},
)
})
-461
View File
@@ -1,461 +0,0 @@
import WebSocket from 'ws'
import { setTimeout as delay } from 'node:timers/promises'
import {
RUNNER_REPLACED_CLOSE_CODE,
serverToRunnerMessageSchema,
type RunnerExecOutputMessage,
type RunnerExecResultMessage,
type RunnerToServerMessage,
type ServerToRunnerMessage,
} from '@shumai/dtos'
import { CliError } from '../operations/errors'
import { resolveRunnerConfig, type RunnerConfig, type RunnerOptions } from './config'
import { RunnerFiles, type FileMessage } from './files'
import {
createRunnerLogger,
formatBytes,
formatDuration,
formatLogString,
shortId,
type RunnerLogger,
} from './log'
import { RunnerShell } from './shell'
const MAX_REPLAY_BYTES = 1024 * 1024
const MAX_COMPLETED = 16
const MAX_ACTIVE = 8
const RUNNER_BUSY_ERROR = 'Runner is busy. Try again later.'
const FILE_OPERATION_KINDS: Record<FileMessage['type'], 'download' | 'upload' | 'stat'> = {
'file.download': 'download',
'file.upload': 'upload',
'file.stat': 'stat',
}
interface Execution {
controller: AbortController
chunks: RunnerExecOutputMessage[]
bytes: number
offset: number
startedAt: number
stdoutBytes: number
stderrBytes: number
result?: RunnerExecResultMessage
}
export class RunnerClient {
private socket?: WebSocket
private ready = false
private stopped = new AbortController()
private executions = new Map<string, Execution>()
private transfers = new Map<string, AbortController>()
private completedFiles = new Map<string, RunnerToServerMessage>()
private pending = new Set<Promise<void>>()
private readonly logger: RunnerLogger
constructor(
private readonly config: RunnerConfig,
private readonly files: RunnerFiles,
private readonly shell: RunnerShell,
log: (message: string) => void = console.error,
) {
this.logger = createRunnerLogger(log, Boolean(config.verbose))
}
async run(signal?: AbortSignal): Promise<void> {
const stop = () => this.stop()
signal?.addEventListener('abort', stop, { once: true })
if (signal?.aborted) this.stop()
let attempt = 0
try {
while (!this.stopped.signal.aborted) {
const wasReady = await this.connect()
if (this.stopped.signal.aborted) break
attempt = wasReady ? 0 : Math.min(attempt + 1, 5)
this.logger.warn('Runner disconnected; reconnecting…')
await delay(Math.min(1000 * 2 ** attempt, 30_000), undefined, {
signal: this.stopped.signal,
}).catch(() => {})
}
} finally {
signal?.removeEventListener('abort', stop)
this.stop()
await Promise.allSettled(this.pending)
}
}
stop() {
this.stopped.abort()
this.ready = false
this.socket?.terminate()
for (const execution of this.executions.values()) execution.controller.abort()
for (const transfer of this.transfers.values()) transfer.abort()
}
private connect(): Promise<boolean> {
return new Promise((resolve, reject) => {
const socket = new WebSocket(this.config.url, {
headers: { authorization: `Bearer ${this.config.key}` },
handshakeTimeout: 10_000,
maxPayload: 1024 * 1024,
perMessageDeflate: false,
followRedirects: false,
})
this.socket = socket
let welcomed = false
let lastMessage = Date.now()
const heartbeat = setInterval(() => {
if (Date.now() - lastMessage > (welcomed ? 75_000 : 10_000)) socket.terminate()
}, 5_000)
socket.on('error', () => {
/* Close drives reconnect; never print credential-bearing request errors. */
})
socket.on('unexpected-response', (_request, response) => {
response.destroy()
socket.terminate()
if ([401, 403, 404, 426].includes(response.statusCode ?? 0))
reject(
new CliError(
`Runner connection rejected (HTTP ${response.statusCode}). Check the server URL and runner key.`,
),
)
})
socket.on('close', (code) => {
clearInterval(heartbeat)
this.ready = false
if ((code === 1008 || code === RUNNER_REPLACED_CLOSE_CODE) && !this.stopped.signal.aborted)
reject(
new CliError('Runner access was revoked or another connection replaced this runner.'),
)
else resolve(welcomed)
})
socket.on('message', (raw) => {
try {
const parsed = serverToRunnerMessageSchema.parse(JSON.parse(raw.toString()))
if ('executionId' in parsed && !/^[A-Za-z0-9_-]{1,128}$/.test(parsed.executionId))
throw new Error('Invalid execution ID.')
lastMessage = Date.now()
if (parsed.type === 'welcome') {
if (welcomed) throw new Error('Duplicate welcome.')
welcomed = true
this.ready = true
this.reconcile(parsed.inFlightExecutionIds)
this.logger.info(`Runner connected: ${parsed.runnerName} (${parsed.runnerId})`)
} else {
if (!welcomed) throw new Error('Expected welcome before runner requests.')
this.handle(parsed)
}
} catch {
reject(new CliError('Server sent an invalid runner protocol message.'))
socket.terminate()
}
})
if (this.stopped.signal.aborted) socket.terminate()
})
}
private send(message: RunnerToServerMessage) {
if (this.ready && this.socket?.readyState === WebSocket.OPEN)
this.socket.send(JSON.stringify(message))
}
private reconcile(inFlight: string[]) {
const expected = new Set(inFlight)
for (const [id, execution] of this.executions) {
if (!expected.has(id)) {
execution.controller.abort()
if (execution.result) this.executions.delete(id)
continue
}
// Replay before results: the server deduplicates chunks by UTF-8 byte offset.
for (const chunk of execution.chunks) this.send(chunk)
}
this.send({
type: 'reconcile',
environment: this.shell.environment,
activeExecutions: [...this.executions]
.filter(([id, execution]) => expected.has(id) && !execution.result)
.map(([executionId, execution]) => ({ executionId, nextOffset: execution.offset })),
completedExecutions: [...this.executions]
.filter(([id, execution]) => expected.has(id) && execution.result)
.map(([, execution]) => execution.result!),
})
}
private handle(message: Exclude<ServerToRunnerMessage, { type: 'welcome' }>) {
if (message.type === 'ping') {
this.send({ type: 'pong', ts: message.ts })
return
}
if (message.type === 'exec.cancel') {
this.executions.get(message.executionId)?.controller.abort()
return
}
if (message.type === 'exec.start') {
const previous = this.executions.get(message.executionId)
if (previous) {
if (previous.result) this.send(previous.result)
return
}
const id = shortId(message.executionId)
if (this.activeCount() >= MAX_ACTIVE) {
const result: RunnerExecResultMessage = {
type: 'exec.result',
executionId: message.executionId,
exitCode: null,
signal: null,
timedOut: false,
error: RUNNER_BUSY_ERROR,
}
this.recordCompletedExecution(message.executionId, result)
this.logger.warn(
this.logger.verbose
? `Bash rejected [${id}] command=${formatLogString(message.command)} error=${formatLogString(RUNNER_BUSY_ERROR)}`
: `Bash rejected [${id}] (runner is busy)`,
)
this.send(result)
return
}
const execution: Execution = {
controller: new AbortController(),
chunks: [],
bytes: 0,
offset: 0,
startedAt: performance.now(),
stdoutBytes: 0,
stderrBytes: 0,
}
this.executions.set(message.executionId, execution)
this.logger.info(
this.logger.verbose
? `Bash started [${id}] command=${formatLogString(message.command)}`
: `Bash started [${id}]`,
)
this.track(
(async () => {
const result = await this.shell.run(
message,
execution.controller.signal,
(stream, data) => {
// Small frames keep reconnect replay and WebSocket buffering bounded.
for (const part of data.match(/[\s\S]{1,8192}/gu) ?? []) {
const chunk: RunnerExecOutputMessage = {
type: 'exec.output',
executionId: message.executionId,
stream,
data: part,
offset: execution.offset,
}
const bytes = Buffer.byteLength(part)
execution.offset += bytes
execution.bytes += bytes
if (stream === 'stdout') execution.stdoutBytes += bytes
else execution.stderrBytes += bytes
execution.chunks.push(chunk)
while (execution.bytes > MAX_REPLAY_BYTES) {
const removed = execution.chunks.shift()!
execution.bytes -= Buffer.byteLength(removed.data)
if (!this.ready) execution.controller.abort()
}
if ((this.socket?.bufferedAmount ?? 0) > MAX_REPLAY_BYTES) {
this.ready = false
this.socket?.terminate()
}
this.send(chunk)
}
},
)
execution.result = result
this.logExecResult(id, execution, result)
this.send(result)
this.pruneCompletedExecutions()
})(),
)
return
}
this.handleFile(message)
}
private recordCompletedExecution(executionId: string, result: RunnerExecResultMessage) {
this.executions.set(executionId, {
controller: new AbortController(),
chunks: [],
bytes: 0,
offset: 0,
startedAt: performance.now(),
stdoutBytes: 0,
stderrBytes: 0,
result,
})
this.pruneCompletedExecutions()
}
private pruneCompletedExecutions() {
const completed = [...this.executions].filter(([, value]) => value.result)
for (const [completedId] of completed.slice(0, -MAX_COMPLETED))
this.executions.delete(completedId)
}
private logExecResult(id: string, execution: Execution, result: RunnerExecResultMessage) {
const duration = formatDuration(performance.now() - execution.startedAt)
const sizes = this.logger.verbose
? ` stdout=${formatBytes(execution.stdoutBytes)} stderr=${formatBytes(execution.stderrBytes)}`
: ''
if (result.timedOut) {
const error =
this.logger.verbose && result.error ? ` error=${formatLogString(result.error)}` : ''
this.logger.warn(`Bash timed out [${id}] duration=${duration}${sizes}${error}`)
return
}
if (result.aborted) {
this.logger.info(`Bash cancelled [${id}] duration=${duration}${sizes}`)
return
}
if (result.error) {
const error = this.logger.verbose ? ` error=${formatLogString(result.error)}` : ''
this.logger.warn(`Bash failed [${id}] duration=${duration}${sizes}${error}`)
return
}
if (result.exitCode === null && result.signal) {
this.logger.warn(`Bash killed [${id}] signal=${result.signal} duration=${duration}${sizes}`)
return
}
this.logger.info(`Bash completed [${id}] exit=${result.exitCode} duration=${duration}${sizes}`)
}
private activeCount() {
return (
[...this.executions.values()].filter((execution) => !execution.result).length +
this.transfers.size
)
}
private handleFile(message: FileMessage) {
const previous = this.completedFiles.get(message.executionId)
if (previous) {
this.send(previous)
return
}
if (this.transfers.has(message.executionId)) return
const id = shortId(message.executionId)
const transferPath = message.type === 'file.download' ? message.destPath : message.srcPath
if (this.activeCount() >= MAX_ACTIVE) {
const result = this.fileBusy(message)
this.recordCompletedFile(message.executionId, result)
const kind = FILE_OPERATION_KINDS[message.type]
this.logger.warn(
this.logger.verbose
? `File ${kind} rejected [${id}] path=${formatLogString(transferPath)} error=${formatLogString(RUNNER_BUSY_ERROR)}`
: `File ${kind} rejected [${id}] (runner is busy)`,
)
this.send(result)
return
}
const controller = new AbortController()
this.transfers.set(message.executionId, controller)
const timer = setTimeout(() => controller.abort(), 120_000)
const startedAt = performance.now()
if (this.logger.verbose && message.type !== 'file.stat') {
const kind = message.type === 'file.download' ? 'download' : 'upload'
this.logger.info(`File ${kind} started [${id}] path=${formatLogString(transferPath)}`)
}
this.track(
(async () => {
try {
const result = await this.files.handle(message, controller.signal)
this.recordCompletedFile(message.executionId, result)
this.logFileResult(id, transferPath, startedAt, result)
this.send(result)
} finally {
clearTimeout(timer)
this.transfers.delete(message.executionId)
}
})(),
)
}
private recordCompletedFile(executionId: string, result: RunnerToServerMessage) {
this.completedFiles.set(executionId, result)
if (this.completedFiles.size > MAX_COMPLETED)
this.completedFiles.delete(this.completedFiles.keys().next().value!)
}
private logFileResult(
id: string,
transferPath: string,
startedAt: number,
result: RunnerToServerMessage,
) {
if (result.type === 'file.stat.result') {
if (!this.logger.verbose) return
const pathPart = `path=${formatLogString(transferPath)}`
if (!result.ok) {
this.logger.warn(
`File stat failed [${id}] ${pathPart} error=${formatLogString(result.error ?? 'Unknown error')}`,
)
return
}
const sizePart = result.exists ? ` size=${formatBytes(result.size ?? 0)}` : ''
this.logger.info(`File stat [${id}] ${pathPart} exists=${result.exists}${sizePart}`)
return
}
if (result.type !== 'file.download.result' && result.type !== 'file.upload.result') return
const kind = result.type === 'file.download.result' ? 'download' : 'upload'
const duration = formatDuration(performance.now() - startedAt)
const pathPart = this.logger.verbose ? ` path=${formatLogString(transferPath)}` : ''
if (result.ok) {
this.logger.info(
`File ${kind} completed [${id}]${pathPart} size=${formatBytes(result.size ?? 0)} duration=${duration}`,
)
return
}
const errorPart = this.logger.verbose
? ` error=${formatLogString(result.error ?? 'Unknown error')}`
: ''
this.logger.warn(`File ${kind} failed [${id}]${pathPart} duration=${duration}${errorPart}`)
}
private fileBusy(message: FileMessage): RunnerToServerMessage {
const result = {
executionId: message.executionId,
ok: false,
error: RUNNER_BUSY_ERROR,
}
switch (message.type) {
case 'file.download':
return { ...result, type: 'file.download.result' }
case 'file.upload':
return { ...result, type: 'file.upload.result' }
case 'file.stat':
return { ...result, type: 'file.stat.result', exists: false }
}
}
private track(task: Promise<void>) {
this.pending.add(task)
void task.finally(() => this.pending.delete(task)).catch(() => this.stop())
}
}
export async function startRunner(options: RunnerOptions) {
const config = await resolveRunnerConfig(options)
const files = new RunnerFiles(config.cwd)
const shell = new RunnerShell(files, config.srt)
// SRT resolves relative policy paths against the runner workspace.
process.chdir(config.cwd)
await shell.initialize()
createRunnerLogger(console.error, Boolean(config.verbose)).info(
`Runner shell: ${shell.environment.shell}`,
)
const runner = new RunnerClient(config, files, shell)
const controller = new AbortController()
const shutdown = () => controller.abort()
process.once('SIGINT', shutdown)
process.once('SIGTERM', shutdown)
try {
await runner.run(controller.signal)
} finally {
process.removeListener('SIGINT', shutdown)
process.removeListener('SIGTERM', shutdown)
await shell.close()
}
}
-66
View File
@@ -1,66 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { commandEnv, resolveRunnerConfig } from './config'
afterEach(() => vi.unstubAllEnvs())
describe('runner configuration', () => {
it('preserves Windows OS settings, normalizes explicit overrides, and excludes credentials', () => {
vi.stubEnv('Path', 'C:\\Windows\\System32')
vi.stubEnv('SystemRoot', 'C:\\Windows')
vi.stubEnv('USERPROFILE', 'C:\\Users\\runner')
const env = commandEnv({ PATH: 'C:\\tools', ['shumai_runner_key']: 'secret' })
expect(env).toMatchObject({
PATH: 'C:\\tools',
SystemRoot: 'C:\\Windows',
USERPROFILE: 'C:\\Users\\runner',
})
expect(env).not.toHaveProperty('Path')
expect(env).not.toHaveProperty('shumai_runner_key')
})
it('uses a dedicated runner key and preserves a server path prefix', async () => {
vi.stubEnv('SHUMAI_API_SERVER', 'https://example.com/shumai/')
vi.stubEnv('SHUMAI_RUNNER_KEY', 'runner-secret')
const config = await resolveRunnerConfig({})
expect(config.url.href).toBe('wss://example.com/shumai/api/runners/ws')
expect(config.key).toBe('runner-secret')
expect(config.cwd).toBe(process.cwd())
expect(config.verbose).toBe(false)
expect((await resolveRunnerConfig({ verbose: true })).verbose).toBe(true)
})
it.each([
'http://example.com',
'ftp://localhost',
'https://user:secret@example.com',
'https://example.com/?key=secret',
'not a URL',
])('rejects unsafe server URL %s', async (url) => {
await expect(resolveRunnerConfig({ url, key: 'key' })).rejects.toThrow()
})
it('allows the Docker host development address', async () => {
expect(
(await resolveRunnerConfig({ url: 'http://host.docker.internal:3000', key: 'key' })).url.href,
).toBe('ws://host.docker.internal:3000/api/runners/ws')
})
it('does not accept a personal API token in place of a missing runner key', async () => {
vi.stubEnv('SHUMAI_RUNNER_KEY', '')
vi.stubEnv('SHUMAI_API_KEY', 'personal-secret')
await expect(resolveRunnerConfig({ url: 'https://example.com' })).rejects.toThrow(
'SHUMAI_RUNNER_KEY',
)
})
it('inherits only baseline environment and explicit skill variables', () => {
vi.stubEnv('SHUMAI_RUNNER_KEY', 'runner-secret')
vi.stubEnv('SHUMAI_API_KEY', 'personal-secret')
vi.stubEnv('AWS_SECRET_ACCESS_KEY', 'aws-secret')
vi.stubEnv('BASH_ENV', '/malicious-startup')
expect(
commandEnv({ SKILL_TOKEN: 'skill-secret', SHUMAI_RUNNER_KEY: 'injected' }),
).toMatchObject({ SKILL_TOKEN: 'skill-secret' })
for (const name of ['SHUMAI_RUNNER_KEY', 'SHUMAI_API_KEY', 'AWS_SECRET_ACCESS_KEY', 'BASH_ENV'])
expect(commandEnv()).not.toHaveProperty(name)
})
})
-84
View File
@@ -1,84 +0,0 @@
import { realpath, stat } from 'node:fs/promises'
import path from 'node:path'
import { CliError } from '../operations/errors'
export interface RunnerOptions {
url?: string
key?: string
cwd?: string
srt?: string
verbose?: boolean
}
export interface RunnerConfig {
url: URL
key: string
cwd: string
srt?: string
verbose?: boolean
}
export async function resolveRunnerConfig(options: RunnerOptions): Promise<RunnerConfig> {
const address = options.url ?? process.env.SHUMAI_API_SERVER
const key = options.key ?? process.env.SHUMAI_RUNNER_KEY
if (!address) throw new CliError('Set SHUMAI_API_SERVER or pass --url.')
if (!key?.trim()) throw new CliError('Set SHUMAI_RUNNER_KEY or pass --key with a runner key.')
let url: URL
try {
url = new URL(address)
} catch {
throw new CliError('Invalid Shumai server URL.')
}
if (
url.username ||
url.password ||
url.search ||
url.hash ||
!['http:', 'https:'].includes(url.protocol)
) {
throw new CliError(
'Use an http:// or https:// server URL without credentials, query, or fragment.',
)
}
const localHosts = ['localhost', '127.0.0.1', '[::1]', 'host.docker.internal']
if (url.protocol === 'http:' && !localHosts.includes(url.hostname)) {
throw new CliError(
'Remote runners require HTTPS. HTTP is only supported for local development.',
)
}
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
url.pathname = `${url.pathname.replace(/\/+$/, '')}/api/runners/ws`
const cwd = await realpath(path.resolve(options.cwd ?? process.cwd()))
if (!(await stat(cwd)).isDirectory()) throw new CliError('Runner workspace must be a directory.')
return {
url,
key: key.trim(),
cwd,
srt: options.srt ? path.resolve(options.srt) : undefined,
verbose: Boolean(options.verbose),
}
}
/** Commands inherit baseline OS settings and explicitly supplied skill variables, never CLI credentials. */
export function commandEnv(extra: Record<string, string> = {}, inherit = true): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = {}
for (const [key, value] of Object.entries(inherit ? process.env : {})) {
if (
/^(PATH|PATHEXT|HOME|USER|LOGNAME|LANG|TERM|TMPDIR|TEMP|TMP|SYSTEMROOT|SYSTEMDRIVE|COMSPEC|USERPROFILE|USERNAME|APPDATA|LOCALAPPDATA|PROGRAMDATA|PROGRAMFILES|PROGRAMFILES\(X86\)|LC_.*)$/i.test(
key,
)
)
env[key] = value
}
for (const [key, value] of Object.entries(extra)) {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
throw new Error('Invalid skill environment variable name.')
if (['SHUMAI_RUNNER_KEY', 'SHUMAI_API_KEY'].includes(key.toUpperCase())) continue
// Windows treats environment names as case-insensitive.
for (const existing of Object.keys(env)) {
if (existing.toUpperCase() === key.toUpperCase()) delete env[existing]
}
env[key] = value
}
return env
}
-364
View File
@@ -1,364 +0,0 @@
import { createHash } from 'node:crypto'
import { createServer, type Server } from 'node:http'
import { mkdtemp, mkdir, readFile, readdir, rm, stat, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import AdmZip from 'adm-zip'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import yauzl from 'yauzl'
import { RunnerFiles } from './files'
describe('runner workspace file transfers', () => {
let cwd: string
let files: RunnerFiles
let server: Server
let url: string
let body: Buffer
let uploaded: Buffer
beforeEach(async () => {
cwd = await mkdtemp(path.join(tmpdir(), 'shumai-files-test-'))
files = new RunnerFiles(cwd)
body = Buffer.from('download contents')
uploaded = Buffer.alloc(0)
server = createServer(async (request, response) => {
if (request.method === 'PUT') {
const chunks: Buffer[] = []
for await (const chunk of request) chunks.push(Buffer.from(chunk))
uploaded = Buffer.concat(chunks)
response.end()
} else if (request.url === '/slow') {
const timer = setInterval(() => response.write(Buffer.alloc(65536)), 20)
response.once('close', () => clearInterval(timer))
} else if (request.url === '/redirect') {
response.writeHead(302, { location: '/file' })
response.end()
} else response.end(body)
})
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
const address = server.address()
if (!address || typeof address === 'string') throw new Error('Missing test HTTP address')
url = `http://127.0.0.1:${address.port}`
})
afterEach(async () => {
server.closeAllConnections()
await new Promise<void>((resolve) => server.close(() => resolve()))
await rm(cwd, { recursive: true, force: true })
})
const signal = () => new AbortController().signal
it('downloads, checks SHA-256, stats and uploads actual bytes', async () => {
expect(
await files.handle(
{
type: 'file.download',
executionId: 'download',
url,
destPath: '.pi/input/data.bin',
expectedHash: createHash('sha256').update(body).digest('hex'),
},
signal(),
),
).toMatchObject({ ok: true, size: body.length })
expect(await readFile(path.join(cwd, '.pi/input/data.bin'))).toEqual(body)
expect(
await files.handle(
{ type: 'file.stat', executionId: 'stat', srcPath: '.pi/input/data.bin' },
signal(),
),
).toMatchObject({ ok: true, exists: true, isFile: true, size: body.length })
expect(
await files.handle(
{ type: 'file.upload', executionId: 'upload', srcPath: '.pi/input/data.bin', url },
signal(),
),
).toMatchObject({ ok: true, size: body.length, name: 'data.bin' })
expect(uploaded).toEqual(body)
expect(
await files.handle(
{ type: 'file.stat', executionId: 'absent', srcPath: '.pi/absent' },
signal(),
),
).toMatchObject({ ok: true, exists: false })
})
it('does not publish mismatched downloads or follow redirects', async () => {
expect(
await files.handle(
{
type: 'file.download',
executionId: 'bad-hash',
url,
destPath: '.pi/data',
expectedHash: 'bad',
},
signal(),
),
).toMatchObject({ ok: false, error: 'Downloaded file hash does not match.' })
await expect(readFile(path.join(cwd, '.pi/data'))).rejects.toThrow()
expect(
await files.handle(
{
type: 'file.download',
executionId: 'redirect',
url: `${url}/redirect`,
destPath: '.pi/data',
},
signal(),
),
).toHaveProperty('ok', false)
})
it.each([
'../secret',
'/etc/passwd',
'.pi/../secret',
'.pi/dir/../../secret',
'.pi\\secret',
'.pi//file',
'.pi/a:b',
'.pi/a\0b',
'.pi/.. /outside',
'.pi/folder./file',
'.pi/CON.txt',
'.pi/nul .txt',
'.pi/COM1',
'.pi/lpt¹.log',
'.pi/CONOUT$',
])('rejects unsafe protocol path %s', async (srcPath) => {
expect(
await files.handle({ type: 'file.stat', executionId: 'unsafe', srcPath }, signal()),
).toHaveProperty('ok', false)
})
it('rejects parent and final symlinks, including a replaced .pi root', async () => {
await mkdir(path.join(cwd, '.pi'))
await writeFile(path.join(cwd, 'secret'), 'secret')
await symlink(cwd, path.join(cwd, '.pi/escape'))
await symlink(path.join(cwd, 'secret'), path.join(cwd, '.pi/link'))
for (const srcPath of ['.pi/escape/secret', '.pi/link']) {
expect(
await files.handle({ type: 'file.upload', executionId: 'symlink', srcPath, url }, signal()),
).toHaveProperty('ok', false)
}
await rm(path.join(cwd, '.pi'), { recursive: true })
await symlink(cwd, path.join(cwd, '.pi'))
expect(
await files.handle(
{ type: 'file.download', executionId: 'root', destPath: '.pi/file', url },
signal(),
),
).toHaveProperty('ok', false)
})
it('extracts skills and safely replaces old contents', async () => {
const zip = new AdmZip()
zip.addFile('SKILL.md', Buffer.from('# Test skill'))
zip.addFile('scripts/run.sh', Buffer.from('echo skill'))
body = zip.toBuffer()
for (let attempt = 0; attempt < 2; attempt++) {
expect(
await files.handle(
{
type: 'file.download',
executionId: `zip-${attempt}`,
url,
destPath: '.pi/skills/test',
extractZip: true,
},
signal(),
),
).toHaveProperty('ok', true)
}
expect(await readFile(path.join(cwd, '.pi/skills/test/SKILL.md'), 'utf8')).toBe('# Test skill')
})
it('rejects symlink ZIP entries and zip-slip paths without publishing them', async () => {
const zip = new AdmZip()
zip.addFile('link', Buffer.from('/etc/passwd'))
const entry = zip.getEntry('link')!
entry.header.attr = (0o120777 << 16) >>> 0
body = zip.toBuffer()
expect(
await files.handle(
{
type: 'file.download',
executionId: 'zip-link',
url,
destPath: '.pi/skills/bad',
extractZip: true,
},
signal(),
),
).toHaveProperty('ok', false)
const normal = new AdmZip()
normal.addFile('aa/secret', Buffer.from('escape'))
body = Buffer.from(
normal.toBuffer().toString('latin1').replaceAll('aa/secret', '../secret'),
'latin1',
)
expect(
await files.handle(
{
type: 'file.download',
executionId: 'zip-slip',
url,
destPath: '.pi/skills/bad',
extractZip: true,
},
signal(),
),
).toHaveProperty('ok', false)
await expect(readFile(path.join(cwd, '.pi/skills/bad/link'))).rejects.toThrow()
})
it('preserves executable script permissions and rejects oversized ZIP entries', async () => {
const zip = new AdmZip()
zip.addFile('run.sh', Buffer.from('#!/bin/sh\necho executable\n'))
zip.getEntry('run.sh')!.header.attr = (0o100755 << 16) >>> 0
body = zip.toBuffer()
expect(
await files.handle(
{
type: 'file.download',
executionId: 'exec-zip',
url,
destPath: '.pi/skills/executable',
extractZip: true,
},
signal(),
),
).toHaveProperty('ok', true)
expect((await stat(path.join(cwd, '.pi/skills/executable/run.sh'))).mode & 0o7777).toBe(0o755)
const central = body.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02]))
body.writeUInt32LE(256 * 1024 * 1024 + 1, central + 24)
expect(
await files.handle(
{
type: 'file.download',
executionId: 'large-zip',
url,
destPath: '.pi/skills/large',
extractZip: true,
},
signal(),
),
).toMatchObject({ ok: false, error: 'Extracted ZIP exceeds 256 MiB.' })
})
it('cancels a streaming download without publishing partial bytes or leaving staging files', async () => {
await mkdir(path.join(cwd, '.pi/input'), { recursive: true })
await writeFile(path.join(cwd, '.pi/input/data'), 'original')
const controller = new AbortController()
const transfer = files.handle(
{
type: 'file.download',
executionId: 'stream-cancel',
url: `${url}/slow`,
destPath: '.pi/input/data',
},
controller.signal,
)
await vi.waitFor(async () =>
expect(
(await readdir(path.join(cwd, '.pi/input'))).some((name) => name.startsWith('.shumai-')),
).toBe(true),
)
controller.abort()
expect(await transfer).toHaveProperty('ok', false)
expect(await readFile(path.join(cwd, '.pi/input/data'), 'utf8')).toBe('original')
expect(await readdir(path.join(cwd, '.pi/input'))).toEqual(['data'])
})
it('cancels extraction without deleting the installed skill or leaving staging trees', async () => {
await mkdir(path.join(cwd, '.pi/skills/installed'), { recursive: true })
await writeFile(path.join(cwd, '.pi/skills/installed/SKILL.md'), 'original')
const zip = new AdmZip()
for (let index = 0; index < 2000; index++)
zip.addFile(`file-${index}.txt`, Buffer.alloc(32768, 65))
body = zip.toBuffer()
const controller = new AbortController()
const transfer = files.handle(
{
type: 'file.download',
executionId: 'extract-cancel',
url,
destPath: '.pi/skills/installed',
extractZip: true,
},
controller.signal,
)
await vi.waitFor(
async () => {
const temporary = (await readdir(path.join(cwd, '.pi/skills'))).find((name) =>
name.startsWith('.shumai-'),
)
expect(temporary).toBeDefined()
expect(
(await readdir(path.join(cwd, '.pi/skills', temporary!, 'extracted'))).length,
).toBeGreaterThan(0)
},
{ interval: 5, timeout: 5000 },
)
controller.abort()
expect(await transfer).toHaveProperty('ok', false)
expect(await readFile(path.join(cwd, '.pi/skills/installed/SKILL.md'), 'utf8')).toBe('original')
expect(await readdir(path.join(cwd, '.pi/skills'))).toEqual(['installed'])
}, 10000)
it('waits for an in-flight ZIP entry read before closing on cancellation', async () => {
const zip = new AdmZip()
zip.addFile('SKILL.md', Buffer.from('skill'))
body = zip.toBuffer()
const controller = new AbortController()
const pendingRead = Promise.withResolvers<() => void>()
const readEntry = yauzl.ZipFile.prototype.readEntry
const read = vi.spyOn(yauzl.ZipFile.prototype, 'readEntry').mockImplementationOnce(function (
this: yauzl.ZipFile,
) {
pendingRead.resolve(() => readEntry.call(this))
})
const close = vi.spyOn(yauzl.ZipFile.prototype, 'close')
try {
const transfer = files.handle(
{
type: 'file.download',
executionId: 'zip-entry-cancel',
url,
destPath: '.pi/skills/new',
extractZip: true,
},
controller.signal,
)
const finishRead = await pendingRead.promise
controller.abort()
await new Promise<void>((resolve) => setImmediate(resolve))
const closedDuringRead = close.mock.calls.length > 0
if (!closedDuringRead) finishRead()
expect(await transfer).toHaveProperty('ok', false)
expect(closedDuringRead).toBe(false)
expect(await readdir(path.join(cwd, '.pi/skills'))).toEqual([])
} finally {
read.mockRestore()
close.mockRestore()
}
})
it('handles cancelled transfers and refuses uploads of directories', async () => {
const controller = new AbortController()
controller.abort()
expect(
await files.handle(
{ type: 'file.download', executionId: 'cancelled', url, destPath: '.pi/data' },
controller.signal,
),
).toHaveProperty('ok', false)
expect(
await files.handle(
{ type: 'file.upload', executionId: 'directory', url, srcPath: '.pi/transfers' },
signal(),
),
).toHaveProperty('ok', false)
expect(uploaded).toHaveLength(0)
})
})
-282
View File
@@ -1,282 +0,0 @@
import { createHash } from 'node:crypto'
import { constants, createWriteStream } from 'node:fs'
import { lstat, mkdir, mkdtemp, open, rename, rm } from 'node:fs/promises'
import path from 'node:path'
import { Readable, Transform } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import yauzl from 'yauzl'
import type {
RunnerFileDownloadMessage,
RunnerFileUploadMessage,
RunnerFileStatMessage,
RunnerToServerMessage,
} from '@shumai/dtos'
const MAX_FILE_BYTES = 256 * 1024 * 1024
const MAX_ZIP_ENTRIES = 10_000
export type FileMessage =
RunnerFileDownloadMessage | RunnerFileUploadMessage | RunnerFileStatMessage
function pathParts(value: string): string[] {
const parts = value.split('/')
if (
value.includes('\\') ||
value.includes('\0') ||
parts.some(
(part) =>
!part ||
part === '.' ||
part === '..' ||
part.includes(':') ||
/[. ]$/.test(part) ||
/^(?:con|prn|aux|nul|conin\$|conout\$|com[1-9¹²³]|lpt[1-9¹²³])(?: *\.|$)/i.test(part),
)
)
throw new Error('Invalid workspace path.')
return parts
}
function isMissing(error: unknown): boolean {
return error instanceof Error && 'code' in error && error.code === 'ENOENT'
}
function transferUrl(address: string): URL {
const url = new URL(address)
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
throw new Error('Invalid transfer URL.')
return url
}
export class RunnerFiles {
constructor(readonly cwd: string) {}
/** Basic workspace validation. Concurrent hostile filesystem mutation is outside v1's scope. */
private async resolve(relative: string, createParents = false): Promise<string> {
const parts = pathParts(relative)
if (parts[0] !== '.pi' || parts.length < 2) throw new Error('File paths must stay inside .pi/.')
let current = this.cwd
for (let index = 0; index < parts.length; index++) {
current = path.join(current, parts[index])
const parent = index < parts.length - 1
if (parent && createParents) await mkdir(current, { recursive: true, mode: 0o700 })
try {
const info = await lstat(current)
if (info.isSymbolicLink() || (parent && !info.isDirectory()))
throw new Error('Workspace paths cannot contain symlinks or non-directory parents.')
} catch (error) {
if (!isMissing(error)) throw error
}
}
return current
}
async createWriter(relative: string) {
const file = await open(
await this.resolve(relative, true),
constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW,
0o600,
)
return {
write: async (data: string) => {
await file.writeFile(data)
},
close: () => file.close(),
}
}
async handle(message: FileMessage, signal: AbortSignal): Promise<RunnerToServerMessage> {
try {
signal.throwIfAborted()
if (message.type === 'file.download')
return {
type: 'file.download.result',
executionId: message.executionId,
ok: true,
...(await this.download(message, signal)),
}
const filename = await this.resolve(message.srcPath)
if (message.type === 'file.upload') return await this.upload(message, filename, signal)
try {
const info = await lstat(filename)
return {
type: 'file.stat.result',
executionId: message.executionId,
ok: true,
exists: true,
isFile: info.isFile(),
size: info.size,
name: path.basename(filename),
}
} catch (error) {
if (!isMissing(error)) throw error
return {
type: 'file.stat.result',
executionId: message.executionId,
ok: true,
exists: false,
}
}
} catch (error) {
const result = {
executionId: message.executionId,
ok: false,
error: error instanceof Error ? error.message : 'File operation failed.',
}
switch (message.type) {
case 'file.download':
return { ...result, type: 'file.download.result' }
case 'file.upload':
return { ...result, type: 'file.upload.result' }
case 'file.stat':
return { ...result, type: 'file.stat.result', exists: false }
}
}
}
private async upload(
message: RunnerFileUploadMessage,
filename: string,
signal: AbortSignal,
): Promise<RunnerToServerMessage> {
const file = await open(
filename,
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
)
try {
const info = await file.stat()
if (!info.isFile() || info.size > MAX_FILE_BYTES)
throw new Error('Upload must be a regular file no larger than 256 MiB.')
// Node and Bun declare different DOM stream types for the same fetch-compatible stream.
const body = info.size
? (Readable.toWeb(
file.createReadStream({ autoClose: false, end: info.size - 1 }),
) as unknown as ReadableStream<Uint8Array>)
: new Uint8Array()
const response = await fetch(transferUrl(message.url), {
method: 'PUT',
body,
...{ duplex: 'half' },
headers: {
'content-type': message.contentType ?? 'application/octet-stream',
'content-length': String(info.size),
},
signal,
redirect: 'error',
})
await response.body?.cancel()
if (!response.ok) throw new Error(`Upload failed (HTTP ${response.status}).`)
return {
type: 'file.upload.result',
executionId: message.executionId,
ok: true,
size: info.size,
name: path.basename(filename),
}
} finally {
await file.close()
}
}
private async download(message: RunnerFileDownloadMessage, signal: AbortSignal) {
const destination = await this.resolve(message.destPath, true)
const temporary = await mkdtemp(path.join(path.dirname(destination), '.shumai-'))
let preserveBackup = false
try {
const response = await fetch(transferUrl(message.url), { signal, redirect: 'error' })
if (!response.ok || !response.body) {
await response.body?.cancel()
throw new Error(`Download failed (HTTP ${response.status}).`)
}
const hash = createHash('sha256')
let size = 0
const archive = path.join(temporary, 'download')
await pipeline(
response.body,
new Transform({
transform(chunk: Buffer, _encoding, callback) {
size += chunk.length
if (size > MAX_FILE_BYTES) {
callback(new Error('Download exceeds 256 MiB.'))
return
}
hash.update(chunk)
callback(null, chunk)
},
}),
createWriteStream(archive, { flags: 'wx', mode: 0o600 }),
{ signal },
)
if (message.expectedHash && hash.digest('hex') !== message.expectedHash)
throw new Error('Downloaded file hash does not match.')
let source = archive
if (message.extractZip) {
source = path.join(temporary, 'extracted')
await mkdir(source, { mode: 0o700 })
await this.extract(archive, source, signal)
}
signal.throwIfAborted()
await this.resolve(message.destPath)
if (message.extractZip) {
const backup = path.join(temporary, 'previous')
let backedUp = false
try {
await rename(destination, backup)
backedUp = true
} catch (error) {
if (!isMissing(error)) throw error
}
try {
await rename(source, destination)
} catch (error) {
if (backedUp) {
preserveBackup = true
await rename(backup, destination)
preserveBackup = false
}
throw error
}
} else await rename(source, destination)
return { size, cached: false }
} finally {
if (!preserveBackup) await rm(temporary, { recursive: true, force: true })
}
}
private async extract(archive: string, directory: string, signal: AbortSignal) {
const zip = await yauzl.openPromise(archive, {
lazyEntries: true,
strictFileNames: true,
autoClose: false,
})
let size = 0
let count = 0
try {
signal.throwIfAborted()
// Let each metadata read finish before cancellation can close the ZIP descriptor.
for await (const entry of zip.eachEntry()) {
signal.throwIfAborted()
if (++count > MAX_ZIP_ENTRIES) throw new Error('ZIP contains too many entries.')
const parts = pathParts(entry.fileName.replace(/\/$/, ''))
const mode = entry.externalFileAttributes >>> 16
const kind = mode & 0o170000
if (kind && kind !== 0o100000 && kind !== 0o040000)
throw new Error('ZIP links and special files are forbidden.')
size += entry.uncompressedSize
if (size > MAX_FILE_BYTES) throw new Error('Extracted ZIP exceeds 256 MiB.')
const destination = path.join(directory, ...parts)
if (entry.fileName.endsWith('/')) await mkdir(destination, { recursive: true, mode: 0o700 })
else {
await mkdir(path.dirname(destination), { recursive: true, mode: 0o700 })
const input = await zip.openReadStreamPromise(entry)
await pipeline(
input,
createWriteStream(destination, { flags: 'wx', mode: 0o600 | (mode & 0o155) }),
{ signal },
)
}
}
} finally {
zip.close()
}
}
}
-44
View File
@@ -1,44 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
createRunnerLogger,
formatBytes,
formatDuration,
formatLogString,
formatTimestamp,
shortId,
} from './log'
describe('runner log helpers', () => {
it('formats timestamps and aligned log levels', () => {
const fixed = new Date(2026, 0, 1, 9, 4, 5)
expect(formatTimestamp(fixed)).toBe('09:04:05')
const lines: string[] = []
const logger = createRunnerLogger(
(line) => lines.push(line),
false,
() => fixed,
)
logger.info('Bash started [a8f2]')
logger.warn('Runner disconnected; reconnecting…')
logger.error('Fatal error')
expect(lines).toEqual([
'09:04:05 INFO Bash started [a8f2]',
'09:04:05 WARN Runner disconnected; reconnecting…',
'09:04:05 ERROR Fatal error',
])
})
it('formats short IDs, durations, byte counts, and single-line quoted strings', () => {
expect(shortId('01JABCDEF1234567890A8F2')).toBe('a8f2')
expect(shortId('one')).toBe('one')
expect(formatDuration(1840)).toBe('1.8s')
expect(formatDuration(-10)).toBe('0.0s')
expect(formatBytes(0)).toBe('0')
expect(formatBytes(512)).toBe('512B')
expect(formatBytes(1536)).toBe('1.5KB')
expect(formatBytes(12 * 1024)).toBe('12KB')
expect(formatBytes(Math.round(2.4 * 1024 * 1024))).toBe('2.4MB')
expect(formatLogString('echo "hi"\nls')).toBe('"echo \\"hi\\"\\nls"')
expect(formatLogString('x'.repeat(210))).toBe(`"${'x'.repeat(200)}…"`)
})
})
-59
View File
@@ -1,59 +0,0 @@
export type RunnerLogLevel = 'INFO' | 'WARN' | 'ERROR'
export interface RunnerLogger {
readonly verbose: boolean
info(message: string): void
warn(message: string): void
error(message: string): void
}
/** Formats a local wall-clock timestamp as HH:MM:SS for runner stderr logs. */
export function formatTimestamp(date = new Date()): string {
const pad = (value: number) => String(value).padStart(2, '0')
return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}
/** Builds a prefixed runner logger writing uniform timestamped lines to stderr. */
export function createRunnerLogger(
write: (message: string) => void = console.error,
verbose = false,
now: () => Date = () => new Date(),
): RunnerLogger {
const emit = (level: RunnerLogLevel, message: string) => {
write(`${formatTimestamp(now())} ${level.padEnd(5)} ${message}`)
}
return {
verbose,
info: (message) => emit('INFO', message),
warn: (message) => emit('WARN', message),
error: (message) => emit('ERROR', message),
}
}
/** Extracts the trailing 4-character tail of an execution ID for compact log labels. */
export function shortId(executionId: string): string {
return executionId.slice(-4).toLowerCase()
}
/** Formats a millisecond duration as seconds with one decimal place (e.g. `1.8s`). */
export function formatDuration(ms: number): string {
return `${(Math.max(0, ms) / 1000).toFixed(1)}s`
}
/** Formats a byte count concisely for runner logs (`0`, `128B`, `12KB`, `2.4MB`). */
export function formatBytes(bytes: number): string {
if (bytes <= 0) return '0'
if (bytes < 1024) return `${bytes}B`
if (bytes < 1024 * 1024) {
const kb = bytes / 1024
return kb < 10 ? `${kb.toFixed(1).replace(/\.0$/, '')}KB` : `${Math.round(kb)}KB`
}
const mb = bytes / (1024 * 1024)
return `${mb.toFixed(1).replace(/\.0$/, '')}MB`
}
/** Formats an arbitrary string (command, path, error) as a bounded single-line JSON string. */
export function formatLogString(value: string, maxLength = 200): string {
const text = value.length > maxLength ? `${value.slice(0, maxLength)}…` : value
return JSON.stringify(text)
}
-106
View File
@@ -1,106 +0,0 @@
import { spawnSync, type SpawnSyncReturns } from 'node:child_process'
import { accessSync, constants } from 'node:fs'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { resolveRunnerShell } from './shell-config'
vi.mock('node:child_process', () => ({ spawnSync: vi.fn() }))
vi.mock('node:fs', { spy: true })
const access = vi.mocked(accessSync)
const where = vi.mocked(spawnSync)
const gitBash = 'D:\\Program Files\\Git\\bin\\bash.exe'
const gitBashX86 = 'D:\\Program Files (x86)\\Git\\bin\\bash.exe'
function whereResult(stdout = '', status = 0): SpawnSyncReturns<string> {
return { stdout, stderr: '', status, output: [null, stdout, ''], pid: 1, signal: null }
}
function available(...paths: string[]) {
access.mockImplementation((executable) => {
if (!paths.some((path) => executable === path)) throw new Error('File not found')
})
}
beforeEach(() => {
vi.stubEnv('ProgramFiles', 'D:\\Program Files')
vi.stubEnv('ProgramFiles(x86)', 'D:\\Program Files (x86)')
vi.stubEnv('SystemRoot', 'E:\\WinNT')
available()
where.mockReturnValue(whereResult('', 1))
})
afterEach(() => {
vi.resetAllMocks()
vi.unstubAllEnvs()
})
describe('runner shell selection', () => {
it.each(['linux', 'darwin'] as const)('uses /bin/sh on %s', (platform) => {
expect(resolveRunnerShell(platform)).toEqual({
executable: '/bin/sh',
commandTransport: 'shell',
})
expect(where).not.toHaveBeenCalled()
})
it.each([
[gitBash, [gitBash, gitBashX86]],
[gitBashX86, [gitBashX86]],
] as const)('prefers installed Git Bash at %s before PATH', (executable, paths) => {
available(...paths)
expect(resolveRunnerShell('win32')).toEqual({ executable, commandTransport: 'argv' })
expect(where).not.toHaveBeenCalled()
})
// Adapted from Pi's shell-path-exists.test.ts. See apps/cli/THIRD-PARTY-NOTICES.txt.
it('accepts a Windows Store Bash alias found on PATH via access(F_OK)', () => {
const alias = 'D:\\Users\\runner\\AppData\\Local\\Microsoft\\WindowsApps\\bash.exe'
available(alias)
where.mockReturnValue(whereResult(alias + '\r\n'))
expect(resolveRunnerShell('win32')).toEqual({ executable: alias, commandTransport: 'argv' })
expect(access).toHaveBeenCalledWith(alias, constants.F_OK)
expect(where).toHaveBeenCalledWith('E:\\WinNT\\System32\\where.exe', ['$PATH:bash.exe'], {
encoding: 'utf8',
timeout: 5000,
windowsHide: true,
})
})
it('skips relative and inaccessible PATH results', () => {
const executable = 'D:\\MSYS2\\usr\\bin\\bash.exe'
available(executable)
where.mockReturnValue(
whereResult(['bash.exe', 'D:\\missing\\bash.exe', executable].join('\r\n')),
)
expect(resolveRunnerShell('win32')).toEqual({ executable, commandTransport: 'argv' })
})
it.each([
['E:\\WinNT', 'E:\\WinNT\\System32\\cmd.exe'],
[undefined, 'C:\\Windows\\System32\\cmd.exe'],
] as const)(
'falls back to cmd.exe when no Bash is available (SystemRoot %s)',
(root, executable) => {
vi.stubEnv('SystemRoot', root)
expect(resolveRunnerShell('win32')).toEqual({ executable, commandTransport: 'shell' })
},
)
// Adapted from Pi's windows-shell-config.test.ts.
it.each([
['D:\\WinNT\\', 'd:/WINNT/System32/BASH.EXE', 'stdin'],
['D:\\WinNT', 'D:\\WinNT\\Sysnative\\bash.exe', 'stdin'],
[undefined, 'E:\\Windows\\System32\\bash.exe', 'stdin'],
['D:\\WinNT', 'D:\\Git\\bin\\bash.exe', 'argv'],
['D:\\WinNT', 'E:\\Windows\\System32\\bash.exe', 'argv'],
['WinNT', 'C:\\Windows\\System32\\bash.exe', 'argv'],
] as const)(
'uses the correct command transport for SystemRoot %s and %s',
(root, executable, commandTransport) => {
vi.stubEnv('SystemRoot', root)
available(executable)
where.mockReturnValue(whereResult(executable + '\r\n'))
expect(resolveRunnerShell('win32')).toEqual({ executable, commandTransport })
},
)
})
-64
View File
@@ -1,64 +0,0 @@
import { spawnSync } from 'node:child_process'
import { accessSync, constants } from 'node:fs'
import { win32 } from 'node:path'
export interface RunnerShellConfig {
executable: string
commandTransport: 'shell' | 'argv' | 'stdin'
}
// Windows Bash discovery and legacy WSL detection adapted from pi-mono.
// See apps/cli/THIRD-PARTY-NOTICES.txt.
function isLegacyWslBashPath(executable: string, systemRoot: string | undefined): boolean {
const normalized = win32.normalize(executable).toLowerCase()
if (systemRoot) {
if (!/^[a-z]:[\\/]/i.test(systemRoot)) return false
return ['System32', 'Sysnative'].some(
(directory) => normalized === win32.join(systemRoot, directory, 'bash.exe').toLowerCase(),
)
}
return /^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized)
}
function shellPathExists(executable: string): boolean {
// access(F_OK) accepts runnable Windows Store aliases that fail an extra stat check.
try {
accessSync(executable, constants.F_OK)
return true
} catch {
return false
}
}
function findWindowsBash(system32: string): string | undefined {
for (const directory of [process.env.ProgramFiles, process.env['ProgramFiles(x86)']]) {
if (!directory || !win32.isAbsolute(directory)) continue
const executable = win32.join(directory, 'Git', 'bin', 'bash.exe')
if (shellPathExists(executable)) return executable
}
// Use the system tool and limit its search to PATH. The workspace may contain a bash.exe.
const found = spawnSync(win32.join(system32, 'where.exe'), ['$PATH:bash.exe'], {
encoding: 'utf8',
timeout: 5000,
windowsHide: true,
})
if (found.status !== 0 || !found.stdout) return
return found.stdout
.trim()
.split(/\r?\n/)
.find((executable) => win32.isAbsolute(executable) && shellPathExists(executable))
}
export function resolveRunnerShell(platform = process.platform): RunnerShellConfig {
if (platform !== 'win32') return { executable: '/bin/sh', commandTransport: 'shell' }
const systemRoot = process.env.SystemRoot
const system32 = win32.join(systemRoot ?? 'C:\\Windows', 'System32')
const executable = findWindowsBash(system32)
if (!executable) return { executable: win32.join(system32, 'cmd.exe'), commandTransport: 'shell' }
return {
executable,
commandTransport: isLegacyWslBashPath(executable, systemRoot) ? 'stdin' : 'argv',
}
}
-352
View File
@@ -1,352 +0,0 @@
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import { RunnerFiles } from './files'
import { RunnerShell } from './shell'
describe('runner bash execution', () => {
let cwd: string
let shell: RunnerShell
beforeEach(async () => {
cwd = await mkdtemp(path.join(tmpdir(), 'shumai-shell-test-'))
shell = new RunnerShell(new RunnerFiles(cwd))
vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
vi.spyOn(SandboxManager, 'reset').mockResolvedValue()
vi.spyOn(SandboxManager, 'wrapWithSandboxArgv').mockImplementation(async (command) => ({
argv: ['/bin/sh', '-c', command],
env: process.env,
}))
})
afterEach(async () => {
await shell.close()
vi.restoreAllMocks()
vi.unstubAllEnvs()
await rm(cwd, { recursive: true, force: true })
})
const request = (command: string, executionId = 'test') => ({
type: 'exec.start' as const,
executionId,
command,
})
it('runs with no executables on PATH when SRT is not requested', async () => {
vi.stubEnv('PATH', '')
await shell.initialize()
let output = ''
const result = await shell.run(
request('printf no-extra-runtime'),
new AbortController().signal,
(_stream, data) => {
output += data
},
)
expect(result).toMatchObject({ exitCode: 0 })
expect(output).toBe('no-extra-runtime')
})
// Adapted from Pi's tools.test.ts. See apps/cli/THIRD-PARTY-NOTICES.txt.
it('sends the complete command over stdin for the legacy Bash launcher', async () => {
shell = new RunnerShell(new RunnerFiles(cwd), undefined, {
executable: '/bin/sh',
commandTransport: 'stdin',
})
const command = [
'name="Hello, 世界"',
'for choice in "one two" \'three "four"\'; do',
' printf \'%s / %s\\n\' "$name" "$choice"',
'done',
].join('\n')
let output = ''
const result = await shell.run(
request(command),
new AbortController().signal,
(_stream, data) => {
output += data
},
)
expect(result).toMatchObject({ exitCode: 0 })
expect(output).toBe('Hello, 世界 / one two\nHello, 世界 / three "four"\n')
})
it('passes a command with shell quoting directly to the selected executable', async () => {
shell = new RunnerShell(new RunnerFiles(cwd), undefined, {
executable: '/bin/sh',
commandTransport: 'argv',
})
const command = "printf '%s' '$literal \"quotes\"'"
let output = ''
const result = await shell.run(
request(command),
new AbortController().signal,
(_stream, data) => {
output += data
},
)
expect(result).toMatchObject({ exitCode: 0 })
expect(output).toBe('$literal "quotes"')
})
it('rejects the legacy WSL launcher before starting SRT', async () => {
shell = new RunnerShell(new RunnerFiles(cwd), path.join(cwd, 'sandbox.json'), {
executable: 'C:\\Windows\\System32\\bash.exe',
commandTransport: 'stdin',
})
await expect(shell.initialize()).rejects.toThrow('SRT cannot run the legacy WSL Bash launcher')
expect(SandboxManager.initialize).not.toHaveBeenCalled()
})
it('streams both outputs, returns the exit code, and saves a log in the runner workspace', async () => {
const output: string[] = []
const result = await shell.run(
request('printf "hello 世界"; printf "failure" >&2; exit 7'),
new AbortController().signal,
(stream, data) => output.push(`${stream}:${data}`),
)
expect(result).toMatchObject({
exitCode: 7,
signal: null,
timedOut: false,
fullOutputPath: '.pi/logs/bash-test.log',
})
expect(output.join('|')).toContain('stdout:hello 世界')
expect(output.join('|')).toContain('stderr:failure')
expect(await readFile(path.join(cwd, result.fullOutputPath!), 'utf8')).toContain('hello 世界')
})
it('passes skill env without inheriting runner or unrelated credentials', async () => {
vi.stubEnv('SHUMAI_RUNNER_KEY', 'runner-secret')
vi.stubEnv('AWS_SECRET_ACCESS_KEY', 'aws-secret')
let output = ''
await shell.run(
{
...request(
'printf "%s|%s|%s" "$SKILL_TOKEN" "$SHUMAI_RUNNER_KEY" "$AWS_SECRET_ACCESS_KEY"',
),
env: { SKILL_TOKEN: 'skill-secret' },
},
new AbortController().signal,
(_stream, data) => {
output += data
},
)
expect(output).toBe('skill-secret||')
})
it('times out and terminates background children', async () => {
const result = await shell.run(
{ ...request('sleep 30 & echo $!; wait'), timeoutSec: 0.1 },
new AbortController().signal,
() => {},
)
expect(result).toMatchObject({ timedOut: true, signal: 'SIGKILL' })
const pid = Number((await readFile(path.join(cwd, '.pi/logs/bash-test.log'), 'utf8')).trim())
expect(() => process.kill(pid, 0)).toThrow()
})
it('cancels a running command and never starts an already cancelled one', async () => {
const controller = new AbortController()
const running = shell.run(request('echo ready; sleep 30'), controller.signal, () =>
controller.abort(),
)
expect(await running).toMatchObject({ aborted: true, signal: 'SIGKILL' })
expect(
await shell.run(request('touch unwanted', 'cancelled'), controller.signal, () => {}),
).toMatchObject({ aborted: true })
await expect(readFile(path.join(cwd, 'unwanted'))).rejects.toThrow()
})
it('finishes draining after a timely root exit even if a background process holds the pipes', async () => {
const source = `const {spawn} = require('node:child_process'); const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 30000)'], {detached: true, stdio: ['ignore', 1, 2]}); console.log(child.pid); child.unref()`
const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`
const result = await shell.run(
{ ...request(`${quote(process.execPath)} -e ${quote(source)}`), timeoutSec: 0.5 },
new AbortController().signal,
() => {},
)
const pid = Number((await readFile(path.join(cwd, '.pi/logs/bash-test.log'), 'utf8')).trim())
try {
expect(result).toMatchObject({ exitCode: 0, timedOut: false, aborted: false })
expect(result.error).toBeUndefined()
} finally {
if (pid > 0) process.kill(pid, 'SIGKILL')
}
})
it('reports launch failure without including command text or skill secrets', async () => {
shell = new RunnerShell(new RunnerFiles(cwd), undefined, {
executable: path.join(cwd, 'missing-shell'),
commandTransport: 'shell',
})
const result = await shell.run(
request('echo private-command'),
new AbortController().signal,
() => {},
)
expect(result).toMatchObject({
exitCode: null,
signal: null,
error: 'Command execution failed (ENOENT).',
})
expect(result.error).not.toContain('private-command')
})
it('terminates a running process if the output consumer fails', async () => {
let pid = 0
const result = await shell.run(
request('printf "%s\\n" "$$"; sleep 30'),
new AbortController().signal,
(_stream, data) => {
pid = Number(data.trim())
throw new Error('Output consumer failed')
},
)
expect(result.error).toBe('Output consumer failed')
expect(pid).toBeGreaterThan(0)
expect(() => process.kill(pid, 0)).toThrow()
})
it('rejects invalid timeouts and caps runaway output', async () => {
expect(
await shell.run(
{ ...request('sleep 30'), timeoutSec: -1 },
new AbortController().signal,
() => {},
),
).toHaveProperty('error')
expect(
await shell.run(
request('head -c 70000000 /dev/zero', 'large'),
new AbortController().signal,
() => {},
),
).toMatchObject({ error: 'Command exceeded the 64 MiB output limit.' })
})
it('uses the exact SRT JSON snapshot and validates SRT before connecting', async () => {
const settings = path.join(cwd, 'sandbox.json')
const config = {
network: { allowedDomains: [], deniedDomains: [] },
filesystem: { denyRead: [], allowWrite: ['.pi'], denyWrite: [] },
}
const json = JSON.stringify(config)
await writeFile(settings, json)
vi.stubEnv('PATH', '')
shell = new RunnerShell(new RunnerFiles(cwd), settings)
await shell.initialize()
await writeFile(settings, '{}')
expect(
await shell.run(request('echo sandboxed'), new AbortController().signal, () => {}),
).toMatchObject({ exitCode: 0 })
expect(SandboxManager.initialize).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining(config),
)
expect(SandboxManager.wrapWithSandboxArgv).toHaveBeenCalledWith(
expect.stringContaining('echo sandboxed'),
'/bin/sh',
undefined,
expect.any(AbortSignal),
cwd,
{ commandId: 'test', commandText: 'echo sandboxed' },
)
expect(SandboxManager.reset).not.toHaveBeenCalled()
})
it('keeps skill PATH and Node startup settings out of the SRT launcher', async () => {
const settings = path.join(cwd, 'sandbox.json')
const marker = path.join(cwd, 'injected')
const evil = path.join(cwd, 'evil.cjs')
await writeFile(
settings,
JSON.stringify({
network: { allowedDomains: [], deniedDomains: [] },
filesystem: { denyRead: [], allowWrite: ['.pi'], denyWrite: [] },
}),
)
await writeFile(evil, `require('node:fs').writeFileSync('${marker}', 'escaped')`)
shell = new RunnerShell(new RunnerFiles(cwd), settings)
await shell.initialize()
const result = await shell.run(
{
...request('printf secure'),
env: { PATH: '/evil-srt', NODE_OPTIONS: `--require=${evil}` },
},
new AbortController().signal,
() => {},
)
expect(result).toMatchObject({ exitCode: 0 })
await expect(readFile(marker)).rejects.toThrow()
})
it('initializes one sandbox for parallel commands and resets only at shutdown', async () => {
const settings = path.join(cwd, 'sandbox.json')
await writeFile(
settings,
JSON.stringify({
network: { allowedDomains: [], deniedDomains: [] },
filesystem: { denyRead: [], allowWrite: ['.pi'], denyWrite: [] },
}),
)
shell = new RunnerShell(new RunnerFiles(cwd), settings)
await shell.initialize()
const value = "quoted ' value\n$(echo should-not-expand)"
let output = ''
const results = await Promise.all(
['one', 'two'].map((id) =>
shell.run(
{ ...request('printf "%s" "$SKILL_TOKEN"', id), env: { SKILL_TOKEN: value } },
new AbortController().signal,
(_stream, data) => {
output += data
},
),
),
)
expect(results.every((result) => result.exitCode === 0)).toBe(true)
expect(output).toBe(value.repeat(2))
expect(SandboxManager.initialize).toHaveBeenCalledTimes(1)
expect(SandboxManager.reset).not.toHaveBeenCalled()
await shell.close()
expect(SandboxManager.reset).toHaveBeenCalledTimes(1)
})
it('fails startup and cleans up if sandbox initialization or execution fails', async () => {
const settings = path.join(cwd, 'sandbox.json')
await writeFile(
settings,
JSON.stringify({
network: { allowedDomains: [], deniedDomains: [] },
filesystem: { denyRead: [], allowWrite: ['.pi'], denyWrite: [] },
}),
)
shell = new RunnerShell(new RunnerFiles(cwd), settings)
vi.mocked(SandboxManager.initialize).mockRejectedValueOnce(
new Error('Run windows-install first'),
)
await expect(shell.initialize()).rejects.toThrow('windows-install')
expect(SandboxManager.reset).toHaveBeenCalledTimes(1)
expect(
await shell.run(request('echo unsafe'), new AbortController().signal, () => {}),
).toHaveProperty('error', 'SRT has not been initialized.')
vi.mocked(SandboxManager.wrapWithSandboxArgv).mockRejectedValueOnce(
new Error('sandbox unavailable'),
)
await expect(shell.initialize()).rejects.toThrow('SRT preflight failed: sandbox unavailable')
})
it('fails closed for missing or malformed SRT settings', async () => {
const settings = path.join(cwd, 'sandbox.json')
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow()
await writeFile(settings, 'invalid json')
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow()
await writeFile(settings, '[]')
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow(
/object/,
)
await writeFile(settings, JSON.stringify({ network: { allowedDomains: 42 } }))
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow()
expect(SandboxManager.initialize).not.toHaveBeenCalled()
})
})
-232
View File
@@ -1,232 +0,0 @@
import { randomUUID } from 'node:crypto'
import { execa } from 'execa'
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import {
runnerEnvironmentSchema,
type RunnerEnvironment,
type RunnerExecResultMessage,
type RunnerExecStartMessage,
} from '@shumai/dtos'
import { commandEnv } from './config'
import { RunnerFiles } from './files'
import { resolveRunnerShell } from './shell-config'
import { loadSandbox } from './srt'
const MAX_OUTPUT_BYTES = 64 * 1024 * 1024
const MAX_TIMEOUT_SEC = 3600
export class RunnerShell {
readonly environment: RunnerEnvironment
private sandbox?: Awaited<ReturnType<typeof loadSandbox>>
private initialized = false
private active = 0
constructor(
private readonly files: RunnerFiles,
private readonly srtPath?: string,
private readonly config = resolveRunnerShell(),
) {
this.environment = runnerEnvironmentSchema.parse({
platform: process.platform,
shell: config.executable,
})
}
async initialize() {
if (!this.srtPath) return
if (this.config.commandTransport === 'stdin')
throw new Error(
'SRT cannot run the legacy WSL Bash launcher. Install Git for Windows to use Bash with SRT.',
)
// Read and validate once; commands cannot weaken the policy by editing the file.
this.sandbox = await loadSandbox(this.srtPath)
try {
await SandboxManager.initialize(this.sandbox.config)
this.initialized = true
let diagnostic = ''
const probe = await this.run(
{ type: 'exec.start', executionId: randomUUID(), command: 'exit 0', timeoutSec: 15 },
new AbortController().signal,
(_stream, data) => {
diagnostic = (diagnostic + data).slice(-4096)
},
)
if (probe.exitCode !== 0 || probe.error || probe.timedOut)
throw new Error(
`SRT preflight failed: ${probe.error || diagnostic.trim() || 'Check settings and local SRT prerequisites.'}`,
)
} catch (error) {
await this.close()
throw error
}
}
async close() {
if (!this.sandbox) return
try {
await SandboxManager.reset()
} finally {
await this.sandbox.cleanup()
this.sandbox = undefined
this.initialized = false
}
}
async run(
message: RunnerExecStartMessage,
signal: AbortSignal,
output: (stream: 'stdout' | 'stderr', data: string) => void,
): Promise<RunnerExecResultMessage> {
const result: RunnerExecResultMessage = {
type: 'exec.result',
executionId: message.executionId,
exitCode: null,
signal: null,
timedOut: false,
aborted: false,
}
if (this.srtPath) this.active++
try {
if (signal.aborted) return { ...result, aborted: true }
const timeout = message.timeoutSec ?? 120
if (!Number.isFinite(timeout) || timeout <= 0 || timeout > MAX_TIMEOUT_SEC)
throw new Error(`Command timeout must be between 0 and ${MAX_TIMEOUT_SEC} seconds.`)
const logPath = `.pi/logs/bash-${message.executionId}.log`
const log = await this.files.createWriter(logPath)
try {
const windows = process.platform === 'win32'
const { commandTransport } = this.config
const useShell = commandTransport === 'shell'
const sendCommandOnStdin = commandTransport === 'stdin'
let executable = useShell ? message.command : this.config.executable
let args = useShell ? [] : sendCommandOnStdin ? ['-s'] : ['-c', message.command]
let shell: string | false = useShell && this.config.executable
let env = commandEnv(message.env)
if (this.srtPath) {
if (!this.initialized) throw new Error('SRT has not been initialized.')
const skillEnv = commandEnv(message.env, false)
const command = windows
? message.command
: [
...Object.entries(skillEnv).map(
([key, value]) => `export ${key}='${value!.replaceAll("'", "'\\''")}'`,
),
message.command,
].join('\n')
const wrapped = await SandboxManager.wrapWithSandboxArgv(
command,
this.config.executable,
undefined,
signal,
this.files.cwd,
{ commandId: message.executionId, commandText: message.command },
)
;[executable, ...args] = wrapped.argv
shell = false
if (windows) {
// SRT's broker starts a fresh sandbox-user environment. Explicit skill
// values belong in its child overlay, never in the broker's startup env.
const separator = args.indexOf('--')
if (separator < 0) throw new Error('SRT returned an invalid Windows launch command.')
args.splice(
separator,
0,
...Object.entries(skillEnv).flatMap(([key, value]) => ['--env', `${key}=${value}`]),
)
env = wrapped.env
} else env = commandEnv()
}
if (signal.aborted) return { ...result, aborted: true }
const deadline = Date.now() + Math.ceil(timeout * 1000)
const child = execa(executable, args, {
cwd: this.files.cwd,
env,
extendEnv: false,
shell,
stdin: sendCommandOnStdin ? [Buffer.from(message.command)] : 'ignore',
buffer: false,
reject: false,
stripFinalNewline: false,
verbose: 'none',
windowsHide: true,
killDescendants: true,
killSignal: 'SIGKILL',
cancelSignal: signal,
timeout: Math.ceil(timeout * 1000),
})
let bytes = 0
let writes = Promise.resolve()
let drainTimer: ReturnType<typeof setTimeout> | undefined
let drainExpired = false
let exitedWithinDeadline = false
child.nodeChildProcess.once('exit', (exitCode) => {
exitedWithinDeadline = exitCode !== null && Date.now() < deadline
// Execa cleans up descendants where the OS still permits it. Bound
// draining if a background child keeps inherited output pipes open.
child.kill('SIGKILL')
drainTimer = setTimeout(() => {
drainExpired = true
child.stdout.destroy()
child.stderr.destroy()
}, 1000)
})
try {
const readers = (['stdout', 'stderr'] as const).map(async (stream) => {
child[stream].setEncoding('utf8')
try {
for await (const data of child[stream]) {
bytes += Buffer.byteLength(data)
if (bytes > MAX_OUTPUT_BYTES)
throw new Error('Command exceeded the 64 MiB output limit.')
await (writes = writes.then(async () => {
await log.write(data)
output(stream, data)
}))
}
} catch (error) {
if (
drainExpired &&
error instanceof Error &&
'code' in error &&
error.code === 'ERR_STREAM_PREMATURE_CLOSE'
)
return
result.error ??= error instanceof Error ? error.message : 'Output streaming failed.'
child.kill('SIGKILL')
}
})
const [completed] = await Promise.all([child, Promise.all(readers)])
await writes
result.exitCode = completed.exitCode ?? null
result.signal = completed.signal ?? null
// Execa's timeout includes stream draining. Report the command's
// runtime, so a timely exit does not become a timeout while draining.
result.timedOut = completed.timedOut && !exitedWithinDeadline
result.aborted = completed.isCanceled
if (
completed.failed &&
completed.exitCode === undefined &&
!result.timedOut &&
!result.aborted &&
!completed.signal
)
result.error = `Command execution failed (${completed.code ?? 'unknown error'}).`
result.fullOutputPath = logPath
} finally {
clearTimeout(drainTimer)
}
} finally {
await log.close()
}
} catch (error) {
result.aborted = signal.aborted
result.error = error instanceof Error ? error.message : 'Command execution failed.'
} finally {
// SRT's temporary mount resources are shared: clean up only after every
// concurrent command has finished, and keep the proxies until shutdown.
if (this.srtPath && --this.active === 0 && this.initialized)
SandboxManager.cleanupAfterCommand()
}
return result
}
}
-2
View File
@@ -1,2 +0,0 @@
// Release builds embed SRT's native helpers through scripts/srt-bundle.ts.
export const bundledSrtVendor: Record<string, string> | undefined = undefined
-59
View File
@@ -1,59 +0,0 @@
import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { loadSandbox } from './srt'
describe('runner SRT configuration', () => {
let directory: string
let settings: string
const config = {
network: { allowedDomains: [], deniedDomains: [] },
filesystem: { denyRead: [], allowWrite: ['.pi'], denyWrite: [] },
}
beforeEach(async () => {
directory = await mkdtemp(path.join(tmpdir(), 'shumai-srt-settings-'))
settings = path.join(directory, 'sandbox.json')
})
afterEach(() => rm(directory, { recursive: true, force: true }))
it('validates upstream settings, supplies packaged helpers, and removes them on cleanup', async () => {
await writeFile(settings, JSON.stringify(config))
const sandbox = await loadSandbox(settings)
const helper = sandbox.config.javaAgentJarPath!
expect(sandbox.config).toMatchObject(config)
expect((await readFile(helper)).subarray(0, 2).toString()).toBe('PK')
if (process.platform === 'linux')
expect(await stat(sandbox.config.seccomp!.applyPath!)).toHaveProperty(
'size',
expect.any(Number),
)
if (process.platform === 'win32')
expect(await stat(sandbox.config.windows!.srtWin!.path!)).toHaveProperty(
'size',
expect.any(Number),
)
await sandbox.cleanup()
await expect(stat(helper)).rejects.toThrow()
})
it('preserves explicit upstream helper paths', async () => {
await writeFile(
settings,
JSON.stringify({
...config,
javaAgentJarPath: '/custom/proxy.jar',
seccomp: { applyPath: '/custom/seccomp' },
windows: { srtWin: { path: 'C:\\custom\\srt-win.exe' } },
}),
)
const sandbox = await loadSandbox(settings)
try {
expect(sandbox.config.javaAgentJarPath).toBe('/custom/proxy.jar')
expect(sandbox.config.seccomp?.applyPath).toBe('/custom/seccomp')
expect(sandbox.config.windows?.srtWin?.path).toBe('C:\\custom\\srt-win.exe')
} finally {
await sandbox.cleanup()
}
})
})
-59
View File
@@ -1,59 +0,0 @@
import { createRequire } from 'node:module'
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import {
SandboxRuntimeConfigSchema,
type SandboxRuntimeConfig,
} from '@anthropic-ai/sandbox-runtime'
import { bundledSrtVendor } from './srt-vendor'
/** Load the upstream JSON format and supply the helpers bundled with this CLI. */
export async function loadSandbox(configPath: string) {
const config = SandboxRuntimeConfigSchema.parse(JSON.parse(await readFile(configPath, 'utf8')))
const directory = await mkdtemp(path.join(tmpdir(), 'shumai-srt-'))
const cleanup = () => rm(directory, { recursive: true, force: true })
const asset = async (name: string) => {
const encoded = bundledSrtVendor?.[name]
const bytes =
encoded !== undefined
? Buffer.from(encoded, 'base64')
: await readFile(
path.join(
path.dirname(
createRequire(import.meta.url).resolve(
'@anthropic-ai/sandbox-runtime/package.json',
),
),
'vendor',
name,
),
)
const destination = path.join(directory, path.basename(name))
await writeFile(destination, bytes, { mode: 0o500 })
return destination
}
try {
if (process.platform === 'linux' && !config.seccomp?.applyPath) {
config.seccomp = {
...config.seccomp,
applyPath: await asset(`seccomp/${process.arch}/apply-seccomp`),
}
}
if (process.platform === 'win32' && !config.windows?.srtWin?.path) {
config.windows = {
...config.windows,
srtWin: {
...config.windows?.srtWin,
path: await asset(`srt-win/${process.arch}/srt-win.exe`),
},
}
}
if (!config.javaAgentJarPath)
config.javaAgentJarPath = await asset('java-proxy-agent/srt-proxy-agent.jar')
return { config: config satisfies SandboxRuntimeConfig, cleanup }
} catch (error) {
await cleanup()
throw error
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/premiere-uxp",
"version": "0.7.2",
"version": "0.6.6",
"private": true,
"type": "commonjs",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/transcode-app",
"version": "0.7.2",
"version": "0.6.6",
"private": true,
"type": "module",
"bin": {
+1 -11
View File
@@ -77,13 +77,8 @@ apps/web/e2e/
| Owner deletes a file, finds it in recently deleted, and restores it | `tests/project/delete-restore.spec.ts` |
| Owner deletes a folder and still sees its contents preview and countdown in recently deleted | `tests/project/delete-restore.spec.ts` |
| Owner deletes a version stack and restores it from recently deleted | `tests/project/delete-restore.spec.ts` |
| Owner creates a share link from a file context menu, edits it in the quick dialog, and opens advanced settings | `tests/project/create-share-link.spec.ts` |
| Owner creates a share link and adds to an existing share link from media view | `tests/project/create-share-link.spec.ts` |
| Owner creates a share link from a file context menu and lands on the share page | `tests/project/create-share-link.spec.ts` |
| Owner protects a share with a password; guests must enter it to view | `tests/project/share-password.spec.ts` |
| Guests can unlock a protected printable comments link directly | `tests/project/share-password.spec.ts` |
| Public page views and share activity appear in both management sidebars | `tests/project/share-activity.spec.ts` |
| Opening a direct historical version link records the selected version | `tests/project/share-activity.spec.ts` |
| Concurrent public opens count every view and deduplicate matching activity | `tests/project/share-activity.spec.ts` |
| Owner creates a collection from the sidebar; the collection shows project files | `tests/project/create-collection.spec.ts` |
| Owner invites a member to a project; the member only sees the invited project | `tests/project/invite-member.spec.ts` |
| Owner changes a project member role in the members dialog and permissions update | `tests/project/change-member-role.spec.ts` |
@@ -100,9 +95,6 @@ apps/web/e2e/
| Owner searches the file list by an English name keyword | `tests/project/search-file-list.spec.ts` |
| Owner searches the file list by Chinese, Japanese, and Korean name keywords | `tests/project/search-file-list.spec.ts` |
| Owner searches the file list with a keyword and a filter condition | `tests/project/search-file-list.spec.ts` |
| Owner finds similar media and filters the results by type | `tests/project/search-file-list.spec.ts` |
| Owner previews matched video ranges in both search dialogs | `tests/project/search-file-list.spec.ts` |
| Owner submits a resized image with filters and can remove the attachment | `tests/project/search-file-list.spec.ts` |
| Owner saves a search result as a collection | `tests/project/save-search-collection.spec.ts` |
| Image share with watermark + download disabled: no download buttons on public list/detail pages, watermarked proxy served, download-url rejected | `tests/project/share-watermark-no-download.spec.ts` |
| Video share with watermark + download disabled: no download buttons on public list/detail pages, watermarked proxy served, download-url rejected | `tests/project/share-watermark-no-download.spec.ts` |
@@ -118,8 +110,6 @@ apps/web/e2e/
| Upload an image file, wait for transcode, and create a comment with draw | `tests/file/image-draw-comment.spec.ts` |
| Upload a video file, wait for transcode, and create a comment with draw at a non-zero timestamp | `tests/file/video-draw-comment.spec.ts` |
| Upload an audio file, wait for transcode, and create a comment at a non-zero timestamp | `tests/file/audio-timestamp-comment.spec.ts` |
| Create internal and public comments, verify internal comments are hidden on public share links | `tests/file/internal-comment-and-edit.spec.ts` |
| Author edits comment text, switches to internal, removes timestamp, and updates attachments | `tests/file/internal-comment-and-edit.spec.ts` |
| Show a breathing poster preview and "Preparing..." while a video is still transcoding | `tests/file/processing-preview.spec.ts` |
| Show a preparing circle before the poster is generated | `tests/file/processing-preview.spec.ts` |
@@ -1,206 +0,0 @@
import { expect, test } from '../../fixtures'
import { apiAddAssetsToShare, apiCreateShare, fileCard } from '../../helpers/files'
test('internal comments show lock icon in workspace and are hidden on public share pages', async ({
browser,
file,
prisma,
}) => {
const { context, page, projectId, fileId, fileName } = file
const publicText = `Public note ${Date.now()}`
const internalText = `Internal secret ${Date.now()}`
await page.goto(`/projects/${projectId}/files/${fileId}`)
const editor = page.locator('[contenteditable="true"]').first()
const sendBtn = page.locator('button:has(svg.lucide-arrow-up)').last()
const visibilityTrigger = page.getByTestId('comment-visibility-trigger')
// Default visibility is Public
await expect(visibilityTrigger).toBeVisible()
await expect(visibilityTrigger).toContainText('Public')
// Post a public comment
await editor.fill(publicText)
await sendBtn.click()
await expect(page.getByText(publicText)).toBeVisible()
// Switch to Internal and post an internal comment
await visibilityTrigger.click()
await page.getByTestId('comment-visibility-internal').click()
await expect(visibilityTrigger).toContainText('Internal')
await editor.fill(internalText)
await sendBtn.click()
await expect(page.getByText(internalText)).toBeVisible()
// Visibility pill resets to Public after sending
await expect(visibilityTrigger).toContainText('Public')
// Internal comment shows lock icon, public comment does not
await expect(page.getByTestId('internal-comment-icon')).toHaveCount(1)
// Verify DB persisted isInternal flags
await expect
.poll(async () => {
const comments = await prisma.assetComment.findMany({
where: { assetId: fileId },
orderBy: { id: 'asc' },
})
return comments.map((c) => ({ message: c.message, isInternal: c.isInternal }))
})
.toEqual([
{ message: publicText, isInternal: false },
{ message: internalText, isInternal: true },
])
// Create a public share link for this file
const share = await apiCreateShare(context.request, projectId, 'External Review Share')
await apiAddAssetsToShare(context.request, share.id, [fileId])
// Open public share page as an unauthenticated guest
const guestContext = await browser.newContext()
try {
const guestPage = await guestContext.newPage()
await guestPage.goto(`/share/${share.id}`)
// File card comment badge should only count the 1 public comment
const card = fileCard(guestPage, fileName)
await expect(card).toBeVisible()
await expect(card).toContainText('1')
// Open the shared file
await card.dblclick()
await expect(guestPage.getByText(publicText)).toBeVisible()
await expect(guestPage.getByText(internalText)).toHaveCount(0)
await expect(guestPage.getByTestId('comment-visibility-trigger')).toHaveCount(0)
} finally {
await guestContext.close()
}
})
test.describe('author edits comment with timestamp and attachments', () => {
test.use({ fileOptions: { mediaType: 'audio' } })
test('author edits comment text, switches to internal, removes timestamp, and updates attachments', async ({
file,
prisma,
}) => {
const { page, projectId, fileId } = file
const originalText = `Initial audio note ${Date.now()}`
const editedText = `Edited private note ${Date.now()}`
// Wait for audio transcode completion
await expect
.poll(
async () => {
const asset = await prisma.asset.findUnique({ where: { id: fileId } })
return asset?.status
},
{ timeout: 30_000 },
)
.toBe('processed')
await page.goto(`/projects/${projectId}/files/${fileId}`)
const mediaEl = page.locator('audio, video').first()
await expect(mediaEl).toBeVisible({ timeout: 30_000 })
// Seek to non-zero timestamp
await page.evaluate(() => {
const el = document.querySelector('audio, video') as HTMLMediaElement | null
if (el) el.currentTime = 1
})
await page.waitForTimeout(500)
// Attach initial file in composer
const composerFileInput = page.locator('input[type="file"]').last()
await composerFileInput.setInputFiles({
name: 'old-attachment.txt',
mimeType: 'text/plain',
buffer: Buffer.from('old attachment content'),
})
await expect(page.getByText('old-attachment.txt')).toBeVisible()
// Submit public comment with timestamp and attachment
const editor = page.locator('[contenteditable="true"]').first()
await editor.fill(originalText)
const sendBtn = page.locator('button:has(svg.lucide-arrow-up)').last()
await expect(sendBtn).toBeEnabled()
await sendBtn.click()
await expect(page.getByText(originalText)).toBeVisible()
await expect(page.getByText('old-attachment.txt')).toBeVisible()
// Wait for DB persistence
await expect
.poll(async () => {
return prisma.assetComment.findFirst({
where: { assetId: fileId, message: originalText },
})
})
.not.toBeNull()
// Open three-dot menu on comment card and click Edit
const moreBtn = page.getByRole('button', { name: 'More options' }).last()
await moreBtn.click({ force: true })
await page.getByRole('menuitem', { name: 'Edit' }).click()
const editForm = page.getByTestId('comment-edit-form')
await expect(editForm).toBeVisible()
// Remove timestamp
await expect(editForm.getByTestId('edit-comment-timestamp')).toBeVisible()
await editForm.getByTestId('edit-comment-remove-timestamp').click()
await expect(editForm.getByTestId('edit-comment-timestamp')).toHaveCount(0)
// Remove existing attachment
await editForm.getByTestId('edit-existing-attachment').locator('button').click()
await expect(editForm.getByTestId('edit-existing-attachment')).toHaveCount(0)
// Add a new attachment
await editForm.getByTestId('edit-comment-file-input').setInputFiles({
name: 'new-attachment.txt',
mimeType: 'text/plain',
buffer: Buffer.from('new attachment content'),
})
await expect(editForm.getByText('new-attachment.txt')).toBeVisible()
// Switch Public -> Internal
await editForm.getByTestId('comment-visibility-trigger').click()
await page.getByTestId('comment-visibility-internal').click()
await expect(editForm.getByTestId('comment-visibility-trigger')).toContainText('Internal')
// Change comment text
const editInput = editForm.getByTestId('edit-comment-input')
await editInput.click()
await page.keyboard.press('ControlOrMeta+a')
await page.keyboard.type(editedText)
// Save
const saveBtn = editForm.getByTestId('edit-comment-save')
await expect(saveBtn).toBeEnabled()
await saveBtn.click()
await expect(editForm).toHaveCount(0)
await expect(page.getByText(editedText)).toBeVisible()
await expect(page.getByText('new-attachment.txt')).toBeVisible()
await expect(page.getByText('old-attachment.txt')).toHaveCount(0)
await expect(page.getByTestId('internal-comment-icon')).toHaveCount(1)
// Reload and verify persistence in UI and DB
await page.reload()
await expect(page.getByText(editedText)).toBeVisible()
await expect(page.getByText('new-attachment.txt')).toBeVisible()
await expect(page.getByTestId('internal-comment-icon')).toHaveCount(1)
const updated = await prisma.assetComment.findFirst({
where: { assetId: fileId, message: editedText },
include: { attachments: { include: { asset: true } } },
})
expect(updated).not.toBeNull()
expect(updated?.isInternal).toBe(true)
expect(updated?.second).toBeNull()
expect(updated?.attachments.map((a) => a.asset.name)).toEqual(['new-attachment.txt'])
})
})
@@ -1,7 +1,7 @@
import { expect, test } from '../../fixtures'
import { apiCreateShare, fileCard } from '../../helpers/files'
import { fileCard } from '../../helpers/files'
test('owner creates a share link from a file context menu, edits it in the quick dialog, and opens advanced settings', async ({
test('owner creates a share link from a file context menu and lands on the share page', async ({
file,
prisma,
}) => {
@@ -14,38 +14,19 @@ test('owner creates a share link from a file context menu, edits it in the quick
await fileCard(page, fileName).click({ button: 'right' })
await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
// Quick share dialog opens with share name, URL, security controls, and footer actions
const dialog = page.getByRole('dialog')
await expect(dialog).toBeVisible()
await expect(dialog.getByText(fileName)).toBeVisible()
await expect(dialog.getByRole('button', { name: 'Copy Link' }).last()).toBeVisible()
await expect(dialog.getByRole('button', { name: 'Done' })).toBeVisible()
// The toast offers a "View" action that navigates to the share page
const toast = page.locator('[data-sonner-toast]').filter({ hasText: 'Share link created' })
await expect(toast).toBeVisible()
await toast.getByRole('button', { name: 'View' }).click()
// Rename share link inline via the pen icon
await dialog.getByRole('button', { name: 'Rename Share Link' }).click()
const nameInput = dialog.getByRole('textbox', { name: 'Rename Share Link' })
await expect(nameInput).toBeVisible()
await nameInput.fill('Client Review Cut')
await nameInput.press('Enter')
await expect(dialog.getByText('Client Review Cut')).toBeVisible()
// Toggle Allow download off in quick security settings
const allowDownloadRow = dialog.getByText('Allow download').locator('..')
await allowDownloadRow.getByRole('switch').click()
await expect(page.getByText('Settings updated')).toBeVisible()
// Navigate to full settings via Advanced settings
await dialog.getByRole('button', { name: 'Advanced settings' }).click()
await expect(page).toHaveURL(/\/projects\/[^/]+\/shares\/[^/]+/)
// The shared file is listed in the share contents
await expect(fileCard(page, fileName)).toBeVisible()
// DB: the share exists with updated settings and the file is symlinked under the share root
// DB: the share exists and the file is symlinked under the share root
const share = await prisma.shareLink.findFirst({ where: { projectId } })
expect(share).not.toBeNull()
expect(share?.name).toBe('Client Review Cut')
expect(share?.allowDownload).toBe(false)
const symlink = await prisma.asset.findFirst({
where: { parentId: share?.rootFolderId, targetId: fileId },
@@ -53,58 +34,3 @@ test('owner creates a share link from a file context menu, edits it in the quick
expect(symlink).not.toBeNull()
expect(symlink?.type).toBe('symlink')
})
test('owner creates a share link and adds to an existing share link from media view', async ({
file,
prisma,
}) => {
const { context, page, projectId, fileName, fileId } = file
// Seed an existing share link so "Add to Share Links" submenu is available
const existingShare = await apiCreateShare(context.request, projectId, 'Existing Client Share')
await page.goto(`/projects/${projectId}/files/${fileId}`)
const headerTrigger = page.getByRole('button', { name: fileName })
await expect(headerTrigger).toBeVisible()
// Open the media view header arrow dropdown and create a new share link
await headerTrigger.click()
await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
const dialog = page.getByRole('dialog')
await expect(dialog).toBeVisible()
await expect(dialog.getByText(fileName)).toBeVisible()
await expect(page).toHaveURL(new RegExp(`/projects/${projectId}/files/${fileId}$`))
// Close the dialog with Done and stay on the media view
await dialog.getByRole('button', { name: 'Done' }).click()
await expect(dialog).toBeHidden()
await expect(page).toHaveURL(new RegExp(`/projects/${projectId}/files/${fileId}$`))
// DB: new share link created with symlink to the file
const createdShare = await prisma.shareLink.findFirst({
where: { projectId, id: { not: existingShare.id } },
})
expect(createdShare).not.toBeNull()
expect(createdShare?.name).toBe(fileName)
const createdSymlink = await prisma.asset.findFirst({
where: { parentId: createdShare?.rootFolderId, targetId: fileId },
})
expect(createdSymlink).not.toBeNull()
expect(createdSymlink?.type).toBe('symlink')
// Open the header dropdown again and add the file to the existing share link
await headerTrigger.click()
await page.getByRole('menuitem', { name: 'Add to Share Links' }).hover()
await page.getByRole('menuitem', { name: 'Existing Client Share' }).click()
const addedToast = page.locator('[data-sonner-toast]').filter({ hasText: 'Added to share link' })
await expect(addedToast).toBeVisible()
const addedSymlink = await prisma.asset.findFirst({
where: { parentId: existingShare.rootFolderId, targetId: fileId },
})
expect(addedSymlink).not.toBeNull()
expect(addedSymlink?.type).toBe('symlink')
})
@@ -28,7 +28,7 @@ test('owner saves a search result as a collection', async ({ project, prisma })
await expect(dialog).toBeVisible()
await dialog.getByPlaceholder('Search records by name...').fill('report')
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
await dialog.getByRole('button', { name: 'Search' }).click()
await expect(dialog.getByText(matching, { exact: true })).toBeVisible()
await expect(dialog.getByText(other, { exact: true })).not.toBeVisible()
@@ -1,5 +1,4 @@
import type { APIRequestContext, Locator } from '@playwright/test'
import type { AssetInfo, ImageSearchRequest, SearchRequest } from '@shumai/dtos'
import type { APIRequestContext } from '@playwright/test'
import { expect, test } from '../../fixtures'
import { apiUploadFile, fileCard } from '../../helpers/files'
@@ -39,7 +38,7 @@ test('owner searches the file list by an English name keyword', async ({ project
// Keyword-only search (no filter conditions)
await dialog.getByPlaceholder('Search records by name...').fill('report')
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
await dialog.getByRole('button', { name: 'Search' }).click()
await expect(dialog.getByText(report2024, { exact: true })).toBeVisible()
await expect(dialog.getByText(report2025, { exact: true })).toBeVisible()
@@ -76,7 +75,7 @@ test('owner searches the file list by Chinese, Japanese, and Korean name keyword
const dialog = page.getByRole('dialog')
await expect(dialog).toBeVisible()
await dialog.getByPlaceholder('Search records by name...').fill(keyword)
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
await dialog.getByRole('button', { name: 'Search' }).click()
for (const name of visible) {
await expect(dialog.getByText(name, { exact: true })).toBeVisible()
}
@@ -150,7 +149,7 @@ test('owner searches the file list with a keyword and a filter condition', async
// confirms the filter became active before we run the search.
await expect(dialog.getByText('1 active')).toBeVisible()
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
await dialog.getByRole('button', { name: 'Search' }).click()
await expect(dialog.getByText(bigReport, { exact: true })).toBeVisible()
await expect(dialog.getByText(smallReport, { exact: true })).not.toBeVisible()
@@ -161,290 +160,3 @@ test('owner searches the file list with a keyword and a filter condition', async
await expect(fileCard(page, bigReport)).toBeVisible()
await expect(fileCard(page, smallReport)).not.toBeVisible()
})
test.describe('image search', () => {
test.use({ fileOptions: { mediaType: 'image' } })
test('owner previews matched video ranges in both search dialogs', async ({ file }) => {
const { page, teamId, projectId, rootFolderId, fileName } = file
const layout = { columns: 5, rows: 2, frameCount: 7 }
const video: AssetInfo = {
id: 'video-result',
name: 'result.mp4',
type: 'file',
sizeByte: 100,
fileCount: 1,
status: 'processed',
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
proxyType: 'video',
preview: {
thumbnailUrl: '/test-sprites/poster.svg',
spriteUrl: '/test-sprites/full.svg',
originalWidth: 100,
originalHeight: 40,
},
startTime: 0,
endTime: 30,
matchedSprite: { ...layout, url: '/test-sprites/chunk.svg' },
}
const brokenMatch: AssetInfo = {
...video,
startTime: 55,
endTime: 85,
matchedSprite: { ...layout, url: '/test-sprites/broken.svg' },
}
const secondMatch: AssetInfo = {
...video,
startTime: 25,
endTime: 55,
matchedSprite: { ...layout, url: '/test-sprites/second.svg' },
}
await page.route(`**/api/teams/${teamId}/settings`, async (route) => {
const response = await route.fetch()
await route.fulfill({
response,
json: { ...(await response.json()), semanticSearchEnabled: true },
})
})
const results = { json: { data: [video, secondMatch, brokenMatch], pageInfo: { total: 3 } } }
await page.route(`**/api/folders/${rootFolderId}/image-search`, (route) =>
route.fulfill(results),
)
await page.route(`**/api/folders/${rootFolderId}/search`, (route) => {
const request = route.request().postDataJSON() as SearchRequest | null
return request?.isSemantic ? route.fulfill(results) : route.continue()
})
await page.route('**/test-sprites/*.svg', (route) =>
route.request().url().endsWith('/broken.svg')
? route.fulfill({ status: 404 })
: route.fulfill({
contentType: 'image/svg+xml',
body: '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="40"/>',
}),
)
async function verifyPreviews(dialog: Locator) {
const heading = dialog.getByRole('heading').first()
await heading.hover()
const cards = dialog.getByTestId('sprite-scrubber')
const firstFrame = cards.nth(0).locator('.opacity-100 > [style*="/test-sprites/chunk.svg"]')
const secondFrame = cards.nth(1).locator('.opacity-100 > [style*="/test-sprites/second.svg"]')
await expect(firstFrame).toHaveCSS('background-position', '0px 0px')
await expect(secondFrame).toHaveCSS('background-position', '0px 0px')
await expect(cards.nth(2).getByAltText('Thumbnail')).toHaveClass(/opacity-100/)
await expect(dialog.locator('[style*="/test-sprites/full.svg"]')).toHaveCount(0)
await cards.nth(0).hover()
await expect(cards.nth(0)).not.toHaveAttribute('data-frame', '0')
await heading.hover()
await expect(firstFrame).toHaveCSS('background-position', '0px 0px')
await cards.nth(2).hover()
await expect(
cards.nth(2).locator('.opacity-100 > [style*="/test-sprites/full.svg"]'),
).toBeVisible()
await heading.hover()
await expect(cards.nth(2).getByAltText('Thumbnail')).toHaveClass(/opacity-100/)
}
await page.goto(`/projects/${projectId}`)
await fileCard(page, fileName).click({ button: 'right' })
await page.getByRole('menuitem', { name: 'Find similar' }).click()
await verifyPreviews(page.getByRole('dialog', { name: 'Find similar' }))
await page.keyboard.press('Escape')
await page.getByRole('button', { name: 'Search' }).click()
const semanticSearch = page.getByRole('dialog', { name: 'Search', exact: true })
await semanticSearch.getByRole('switch', { name: 'Semantic Search' }).click()
const searchInput = semanticSearch.getByPlaceholder('Search records by content...')
await searchInput.fill('video scene')
await searchInput.press('Enter')
await verifyPreviews(semanticSearch)
})
test('owner finds similar media and filters the results by type', async ({ file }) => {
const { page, teamId, projectId, rootFolderId, fileId, fileName } = file
const source = fileCard(page, fileName)
await page.goto(`/projects/${projectId}`)
await source.click({ button: 'right' })
await expect(page.getByRole('menu')).toBeVisible()
await expect(page.getByRole('menuitem', { name: 'Find similar' })).toHaveCount(0)
await page.route(`**/api/teams/${teamId}/settings`, async (route) => {
const response = await route.fetch()
await route.fulfill({
response,
json: { ...(await response.json()), semanticSearchEnabled: true },
})
})
const image: AssetInfo = {
id: 'image-result',
name: 'result.jpg',
type: 'file',
sizeByte: 100,
fileCount: 1,
status: 'processed',
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
proxyType: 'image',
}
const video: AssetInfo = {
...image,
id: 'video-result',
name: 'result.mp4',
proxyType: 'video',
startTime: 65,
endTime: 120,
}
const requests: ImageSearchRequest[] = []
await page.route(`**/api/folders/${rootFolderId}/image-search`, async (route) => {
const request = route.request().postDataJSON() as ImageSearchRequest
requests.push(request)
const data =
request.mediaType === 'image'
? [image]
: request.mediaType === 'video'
? [video]
: [image, video]
await route.fulfill({ json: { data, pageInfo: { total: data.length } } })
})
const settingsLoaded = page.waitForResponse(`**/api/teams/${teamId}/settings`)
await page.reload()
await settingsLoaded
await source.click({ button: 'right' })
await page.getByRole('menuitem', { name: 'Find similar' }).click()
const dialog = page.getByRole('dialog', { name: 'Find similar' })
await expect(dialog.getByText(image.name)).toBeVisible()
await expect(dialog.getByText(video.name)).toBeVisible()
await expect(dialog.getByTestId('file-preview-matched-duration')).toHaveText('01:05 - 02:00')
expect(requests.at(-1)).toMatchObject({ sourceAssetId: fileId, first: 20 })
await dialog.getByText('Videos', { exact: true }).click()
await expect(dialog.getByText(video.name)).toBeVisible()
await expect(dialog.getByText(image.name)).toHaveCount(0)
expect(requests.at(-1)).toMatchObject({ sourceAssetId: fileId, mediaType: 'video' })
await dialog.getByText('Images', { exact: true }).click()
await expect(dialog.getByText(image.name)).toBeVisible()
await expect(dialog.getByText(video.name)).toHaveCount(0)
expect(requests.at(-1)).toMatchObject({ sourceAssetId: fileId, mediaType: 'image' })
})
test('owner submits a resized image with filters and can remove the attachment', async ({
project,
browserName,
}) => {
const { page, teamId, projectId, rootFolderId } = project
await page.route(`**/api/teams/${teamId}/settings`, async (route) => {
const response = await route.fetch()
await route.fulfill({
response,
json: { ...(await response.json()), semanticSearchEnabled: true },
})
})
const requests: ImageSearchRequest[] = []
await page.route(`**/api/folders/${rootFolderId}/image-search`, async (route) => {
requests.push(route.request().postDataJSON() as ImageSearchRequest)
await route.fulfill({ json: { data: [], pageInfo: { total: 0 } } })
})
await page.goto(`/projects/${projectId}`)
await page.getByRole('button', { name: 'Search' }).click()
const dialog = page.getByRole('dialog', { name: 'Search', exact: true })
const semantic = dialog.getByRole('switch', { name: 'Semantic Search' })
await expect(semantic).toBeEnabled()
await semantic.click()
await dialog.getByPlaceholder('Search records by content...').fill('text draft')
await dialog.getByRole('button', { name: '+ Add condition' }).click()
const comboboxes = dialog.getByRole('combobox')
await comboboxes.first().click()
await page.getByRole('option', { name: 'Size', exact: true }).click()
await comboboxes.nth(1).click()
await page.getByRole('option', { name: '>', exact: true }).click()
await dialog.locator('input[type="number"]').fill('100')
await expect(dialog.getByText('1 active')).toBeVisible()
await dialog.getByRole('button', { name: 'Attach an image' }).click()
const picker = page.getByRole('dialog', { name: 'Attach an image' })
await expect(picker).toBeVisible()
const png = await page.evaluate(() => {
const canvas = document.createElement('canvas')
canvas.width = 2560
canvas.height = 1440
return canvas.toDataURL('image/png').split(',')[1]
})
const chooser = page.waitForEvent('filechooser')
await picker.getByRole('button', { name: 'Choose image' }).click()
await (
await chooser
).setFiles({ name: 'reference.png', mimeType: 'image/png', buffer: Buffer.from(png, 'base64') })
await expect(dialog.getByText('reference.png')).toBeVisible()
await expect(dialog.getByPlaceholder('Search records by content...')).toHaveCount(0)
const thumbnail = dialog.locator('img').first()
await expect
.poll(() =>
thumbnail.evaluate((image: HTMLImageElement) => ({
width: image.naturalWidth,
height: image.naturalHeight,
})),
)
.toEqual({ width: 1280, height: 720 })
expect(requests).toHaveLength(0)
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
await expect.poll(() => requests.length).toBe(1)
expect(requests[0]).toMatchObject({
image: expect.stringMatching(/^\/9j\//),
conditions: [{ field: 'sizeByte', operator: 'gt', value: 100 }],
})
expect(requests[0]).not.toHaveProperty('query')
await dialog.getByRole('button', { name: 'Attach an image' }).click()
const transfer = await page.evaluateHandle(() => {
const canvas = document.createElement('canvas')
canvas.width = 720
canvas.height = 1280
const png = atob(canvas.toDataURL('image/png').split(',')[1])
const bytes = Uint8Array.from(png, (byte) => byte.charCodeAt(0))
const transfer = new DataTransfer()
transfer.items.add(new File([bytes], 'dropped.png', { type: 'image/png' }))
return transfer
})
await picker
.getByRole('button', { name: 'Choose image' })
.dispatchEvent('drop', { dataTransfer: transfer })
await transfer.dispose()
await expect(dialog.getByText('dropped.png')).toBeVisible()
if (browserName === 'chromium') {
await page.context().grantPermissions(['clipboard-read', 'clipboard-write'])
await page.evaluate(async (base64) => {
const bytes = Uint8Array.from(atob(base64), (byte) => byte.charCodeAt(0))
const image = new Blob([bytes], { type: 'image/png' })
await navigator.clipboard.write([new ClipboardItem({ 'image/png': image })])
}, png)
await dialog.getByRole('button', { name: 'Attach an image' }).click()
await expect(picker).toBeVisible()
await page.keyboard.press('ControlOrMeta+V')
await expect(picker).toBeHidden()
await expect(dialog.getByText('dropped.png')).toHaveCount(0)
await expect(thumbnail).toHaveJSProperty('naturalWidth', 1280)
await expect(thumbnail).toHaveJSProperty('naturalHeight', 720)
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
await expect.poll(() => requests.length).toBe(2)
expect(requests[1]).toMatchObject({
image: expect.stringMatching(/^\/9j\//),
conditions: [{ field: 'sizeByte', operator: 'gt', value: 100 }],
})
}
await dialog.getByRole('button', { name: 'Remove image' }).click()
await expect(dialog.getByPlaceholder('Search records by content...')).toBeVisible()
await expect(dialog.getByText('1 active')).toBeVisible()
await dialog.getByRole('button', { name: 'Close', exact: true }).last().click()
await expect(page.getByText('This folder is empty')).toBeVisible()
})
})
@@ -1,163 +0,0 @@
import { expect, test } from '../../fixtures'
import { apiAddAssetsToShare, apiCreateShare, fileCard } from '../../helpers/files'
test('counts public page views and shows activity in both share management sidebars', async ({
file,
browser,
prisma,
}) => {
const { context, page, projectId, rootFolderId, fileId, fileName } = file
const folder = await prisma.asset.create({
data: {
name: 'Review Folder',
projectId,
parentId: rootFolderId,
type: 'folder',
status: 'processed',
},
})
await prisma.asset.update({ where: { id: fileId }, data: { parentId: folder.id } })
const share = await apiCreateShare(context.request, projectId, 'Client Review')
await apiAddAssetsToShare(context.request, share.id, [folder.id])
const password = 'review-password'
const lock = await context.request.put(`/api/shares/${share.id}`, { data: { password } })
expect(lock.ok()).toBe(true)
const readShare = () => prisma.shareLink.findUniqueOrThrow({ where: { id: share.id } })
await page.goto(`/projects/${projectId}/shares`)
await expect(page.getByText('Never viewed')).toBeVisible()
const guest = await browser.newContext()
try {
const guestPage = await guest.newPage()
await guestPage.goto(`/share/${share.id}`)
await guestPage.getByPlaceholder('Enter password').fill(password)
await guestPage.getByRole('button', { name: 'Access Share' }).click()
await expect(fileCard(guestPage, folder.name)).toBeVisible()
await expect.poll(async () => (await readShare()).views).toBe(1)
await fileCard(guestPage, folder.name).click()
await expect(fileCard(guestPage, fileName)).toBeVisible()
await expect.poll(async () => (await readShare()).views).toBe(2)
await fileCard(guestPage, fileName).click()
await expect.poll(async () => (await readShare()).views).toBe(3)
const beforeReload = (await readShare()).lastViewedAt
await guestPage.reload()
await expect.poll(async () => (await readShare()).views).toBe(4)
expect((await readShare()).lastViewedAt!.getTime()).toBeGreaterThan(beforeReload!.getTime())
const downloadResponse = guestPage.waitForResponse((response) =>
response.url().endsWith('/download-url'),
)
await guestPage.getByTestId('default-viewer-download-button').click()
const download = await downloadResponse
expect(download.status()).toBe(200)
const comment = await context.request.post(`/api/shares/${share.id}/files/${fileId}/comments`, {
headers: { 'x-share-password': password },
data: { message: 'Ready for review', attachmentIds: [] },
})
expect(comment.status()).toBe(201)
} finally {
await guest.close()
}
await page.reload()
const row = page.getByRole('row').filter({ hasText: share.name })
await expect(row.getByRole('cell', { name: '4', exact: true })).toBeVisible()
await expect(row.locator('time')).toContainText('Today')
await row.getByRole('button', { name: 'View Activity' }).click()
const sidebar = page.getByRole('dialog', { name: 'Activity' })
await expect(sidebar.getByText('Opened Share Link')).toHaveCount(1)
await expect(sidebar.getByText('Viewed Asset')).toHaveCount(2)
await expect(sidebar.getByText(folder.name)).toBeVisible()
await expect(sidebar.getByText('Downloaded')).toBeVisible()
await expect(sidebar.getByText('Commented')).toBeVisible()
await expect(sidebar.getByText('Someone').first()).toBeVisible()
await page.goto(`/projects/${projectId}/shares/${share.id}`)
await expect(page.getByRole('tab', { name: 'Settings' })).toHaveAttribute('aria-selected', 'true')
await page.getByRole('tab', { name: 'Activity' }).click()
const tab = page.getByRole('tabpanel', { name: 'Activity' })
await expect(tab.getByText('Opened Share Link')).toHaveCount(1)
await expect(tab.getByText('Viewed Asset')).toHaveCount(2)
await expect(tab.getByText('Commented')).toBeVisible()
})
test('a direct historical version link records the version as the viewed asset', async ({
file,
browser,
prisma,
}) => {
const { context, projectId, rootFolderId, fileId } = file
const stack = await prisma.asset.create({
data: {
name: 'Review Versions',
projectId,
parentId: rootFolderId,
type: 'version_stack',
status: 'processed',
},
})
await prisma.asset.update({
where: { id: fileId },
data: { parentId: stack.id, sortIndex: 'a' },
})
const oldVersion = await prisma.asset.create({
data: {
name: 'Earlier Cut',
projectId,
parentId: stack.id,
sortIndex: 'b',
type: 'file',
status: 'processed',
},
})
const share = await apiCreateShare(context.request, projectId, 'Version Review')
await apiAddAssetsToShare(context.request, share.id, [stack.id])
const guest = await browser.newContext()
try {
const page = await guest.newPage()
await page.goto(`/share/${share.id}/files/${stack.id}?version=${oldVersion.id}`)
await expect
.poll(() => prisma.shareActivity.count({ where: { shareLinkId: share.id } }))
.toBe(2)
const activities = await prisma.shareActivity.findMany({ where: { shareLinkId: share.id } })
expect(activities).toEqual(
expect.arrayContaining([
expect.objectContaining({ kind: 'share_viewed', assetId: null }),
expect.objectContaining({ kind: 'asset_viewed', assetId: oldVersion.id }),
]),
)
const link = await prisma.shareLink.findUniqueOrThrow({ where: { id: share.id } })
expect(link.views).toBe(1)
} finally {
await guest.close()
}
})
test('concurrent authorized page opens add every view and one matching activity', async ({
project,
browser,
prisma,
}) => {
const share = await apiCreateShare(
project.context.request,
project.projectId,
'Concurrent Review',
)
const guest = await browser.newContext()
try {
const responses = await Promise.all(
Array.from({ length: 8 }, () =>
guest.request.post(`/api/shares/${share.id}/views`, { data: {} }),
),
)
expect(responses.map((response) => response.status())).toEqual(Array(8).fill(204))
const link = await prisma.shareLink.findUniqueOrThrow({ where: { id: share.id } })
expect(link).toMatchObject({ views: 8, lastViewedAt: expect.any(Date) })
const activities = await prisma.shareActivity.findMany({ where: { shareLinkId: share.id } })
expect(activities).toMatchObject([{ kind: 'share_viewed', userId: null, assetId: null }])
} finally {
await guest.close()
}
})
@@ -49,33 +49,3 @@ test('owner protects a share with a password and guests must enter it to view',
await guestContext.close()
}
})
test('a guest can unlock a protected printable comments link directly', async ({
file,
browser,
}) => {
const { context, projectId, fileName, fileId } = file
const share = await apiCreateShare(context.request, projectId, 'Shared Print')
await apiAddAssetsToShare(context.request, share.id, [fileId])
const res = await context.request.put(`/api/shares/${share.id}`, {
data: { password: 'secret123' },
})
expect(res.ok()).toBe(true)
const guestContext = await browser.newContext()
const page = await guestContext.newPage()
try {
await page.goto(`/print/comments/${fileId}?shareId=${share.id}`)
const passwordInput = page.getByPlaceholder('Enter password')
await expect(passwordInput).toBeVisible()
await passwordInput.fill('wrong-password')
await page.getByRole('button', { name: 'Confirm' }).click()
await expect(page.getByText('Incorrect password. Please try again.')).toBeVisible()
await passwordInput.fill('secret123')
await page.getByRole('button', { name: 'Confirm' }).click()
await expect(page.getByTitle(fileName)).toBeVisible()
await expect(page).toHaveURL(`/print/comments/${fileId}?shareId=${share.id}`)
} finally {
await guestContext.close()
}
})
@@ -147,10 +147,8 @@ test('dissolving a shared version stack renders the remaining standalone file na
// Share the version stack
await fileCard(page, fileB.name).click({ button: 'right' })
await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
const shareDialog = page.getByRole('dialog')
await expect(shareDialog).toBeVisible()
await shareDialog.getByRole('button', { name: 'Done' }).click()
await expect(shareDialog).toBeHidden()
const toast = page.locator('[data-sonner-toast]').filter({ hasText: 'Share link created' })
await expect(toast).toBeVisible()
const share = await prisma.shareLink.findFirstOrThrow({
where: { projectId },
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/web-app",
"version": "0.7.2",
"version": "0.6.6",
"private": true,
"type": "module",
"dependencies": {
-11
View File
@@ -81,16 +81,6 @@ if (regenCmdIndex !== -1) {
async function run() {
validateArchiveStorageConfig()
const runnerLease = await runnerService.startServerTopology()
runnerLease.addEventListener(
'abort',
() => {
console.error('Lost the runner server lease:', runnerLease.reason)
process.exit(1)
},
{ once: true },
)
runnerLease.throwIfAborted()
// Initialize workflows and activities for local executor mode
initAgentWorkflows()
initTranscodeWorkflows()
@@ -232,7 +222,6 @@ async function run() {
await workflowService.shutdownWorkers().catch(() => {})
assetService.stopCleanupJob()
server.stop(true)
await runnerService.stopServerTopology().catch(console.error)
process.exit(0)
}
+25 -97
View File
@@ -32,34 +32,24 @@
},
"apps/cli": {
"name": "@shumai/cli",
"version": "0.7.2",
"version": "0.6.6",
"bin": {
"shumai-cli": "./src/index.ts",
},
"dependencies": {
"@anthropic-ai/sandbox-runtime": "0.0.83",
"@shumai/api": "workspace:*",
"@shumai/dtos": "workspace:*",
"@shumai/operations": "workspace:*",
"@shumai/tableprinter": "workspace:*",
"commander": "15.0.0",
"execa": "10.2.1",
"hono": "4.13.5",
"ulid": "3.0.2",
"ws": "8.22.2",
"yauzl": "3.4.0",
"zod": "4.5.4",
},
"devDependencies": {
"@types/adm-zip": "0.5.8",
"@types/ws": "8.18.2",
"@types/yauzl": "3.4.0",
"adm-zip": "0.6.1",
},
},
"apps/premiere-uxp": {
"name": "@shumai/premiere-uxp",
"version": "0.7.2",
"version": "0.6.6",
"dependencies": {
"@shumai/api": "workspace:*",
"@shumai/dtos": "workspace:*",
@@ -113,7 +103,7 @@
},
"apps/transcode": {
"name": "@shumai/transcode-app",
"version": "0.7.2",
"version": "0.6.6",
"bin": {
"shumai-transcode": "./src/index.ts",
},
@@ -125,7 +115,7 @@
},
"apps/web": {
"name": "@shumai/web-app",
"version": "0.7.2",
"version": "0.6.6",
"dependencies": {
"@shumai/agent": "workspace:*",
"@shumai/api": "workspace:*",
@@ -145,7 +135,7 @@
},
"packages/agent": {
"name": "@shumai/agent",
"version": "0.7.2",
"version": "0.6.6",
"dependencies": {
"@earendil-works/chord": "1.5.0",
"@earendil-works/pi-ai": "1.5.0",
@@ -169,7 +159,7 @@
},
"packages/api": {
"name": "@shumai/api",
"version": "0.7.2",
"version": "0.6.6",
"dependencies": {
"@better-auth/mcp": "1.7.12",
"@earendil-works/pi-durable": "1.5.0",
@@ -190,7 +180,7 @@
},
"packages/core": {
"name": "@shumai/core",
"version": "0.7.2",
"version": "0.6.6",
"dependencies": {
"@ai-sdk/alibaba": "2.0.38",
"@ai-sdk/amazon-bedrock": "5.0.67",
@@ -254,7 +244,7 @@
},
"packages/db": {
"name": "@shumai/db",
"version": "0.7.2",
"version": "0.6.6",
"dependencies": {
"@prisma/adapter-pg": "7.10.0",
"@prisma/client": "7.10.0",
@@ -269,7 +259,7 @@
},
"packages/dtos": {
"name": "@shumai/dtos",
"version": "0.7.2",
"version": "0.6.6",
"dependencies": {
"@earendil-works/pi-ai": "1.5.0",
"@earendil-works/pi-durable": "1.5.0",
@@ -278,7 +268,7 @@
},
"packages/e2e": {
"name": "@shumai/e2e",
"version": "0.7.2",
"version": "0.6.6",
"dependencies": {
"@earendil-works/pi-ai": "1.5.0",
"@earendil-works/pi-durable": "1.5.0",
@@ -294,18 +284,18 @@
},
"packages/operations": {
"name": "@shumai/operations",
"version": "0.7.2",
"version": "0.6.6",
"dependencies": {
"zod": "4.5.4",
},
},
"packages/tableprinter": {
"name": "@shumai/tableprinter",
"version": "0.7.2",
"version": "0.6.6",
},
"packages/transcode": {
"name": "@shumai/transcode",
"version": "0.7.2",
"version": "0.6.6",
"dependencies": {
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
@@ -316,7 +306,7 @@
},
"packages/webui": {
"name": "@shumai/webui",
"version": "0.7.2",
"version": "0.6.6",
"dependencies": {
"@base-ui/react": "1.7.0",
"@better-auth/oauth-provider": "1.7.12",
@@ -421,7 +411,7 @@
},
"packages/workflow-core": {
"name": "@shumai/workflow-core",
"version": "0.7.2",
"version": "0.6.6",
"dependencies": {
"@dbos-inc/dbos-sdk": "5.2.11",
"@shumai/core": "workspace:*",
@@ -484,8 +474,6 @@
"@alloc/quick-lru": ["@alloc/quick-lru@5.2.0", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="],
"@anthropic-ai/sandbox-runtime": ["@anthropic-ai/sandbox-runtime@0.0.83", "", { "dependencies": { "@pondwader/socks5-server": "^1.0.10", "commander": "^12.1.0", "node-forge": "^1.4.0", "zod": "^3.25.0" }, "peerDependencies": { "@microsoft/mxc-sdk": "^1.0.1" }, "optionalPeers": ["@microsoft/mxc-sdk"], "bin": { "srt": "dist/cli.js" } }, "sha512-yEusORnVJrNseF/9fvjVYyk6tr79/aFbIB3T/X8p2puLZdaaiGNeYN50v0CE+1DT70v7XuzKOAnTivh1f5cksA=="],
"@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.129.0", "", { "dependencies": { "json-schema-to-ts": "^3.1.1", "standardwebhooks": "^1.0.0" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-MH7LB20kNpGLUpPTe2OG5XvL/KhX8HUO9XyBaFjgFk6TLS4Xjt0VPIuMKywe7POKKPslX+QxSlVok9e+8kG5Nw=="],
"@aws-sdk/checksums": ["@aws-sdk/checksums@3.1000.29", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-Dtu0gr4dnATZAPwEYbpCsG+MpLM7OAliy2gTepEFQwl1vZ6DL3QMH2FveMa3HLvPsOdhJsPRB3KtxVhph9T75A=="],
@@ -898,8 +886,6 @@
"@playwright/test": ["@playwright/test@1.61.1", "", { "dependencies": { "playwright": "1.61.1" }, "bin": { "playwright": "cli.js" } }, "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig=="],
"@pondwader/socks5-server": ["@pondwader/socks5-server@1.0.10", "", {}, "sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg=="],
"@preact/signals-core": ["@preact/signals-core@1.14.4", "", {}, "sha512-HNB6HYeYKhQbJ1aKl+YRjrS4+QWHLKX6qKoUsfS/m0vqzsVaEBiZiaKbG/e+NKk2ch5ALQr/ihWaMHxiCuuWHA=="],
"@prisma/adapter-pg": ["@prisma/adapter-pg@7.10.0", "", { "dependencies": { "@prisma/driver-adapter-utils": "7.10.0", "@types/pg": "^8.16.0", "pg": "^8.16.3", "postgres-array": "3.0.4" } }, "sha512-N7nwSor0HO1Kz6xBv0TPAjAPysKK0fac6p4fVN3ensLOuzc/83Fgmln5k92eK/cvzqdkSR/2kkAqlbcdwVrwpw=="],
@@ -1108,8 +1094,6 @@
"@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="],
"@sec-ant/readable-stream": ["@sec-ant/readable-stream@0.4.1", "", {}, "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg=="],
"@shumai/agent": ["@shumai/agent@workspace:packages/agent"],
"@shumai/api": ["@shumai/api@workspace:packages/api"],
@@ -1146,8 +1130,6 @@
"@sindresorhus/is": ["@sindresorhus/is@4.6.0", "", {}, "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw=="],
"@sindresorhus/merge-streams": ["@sindresorhus/merge-streams@4.0.0", "", {}, "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ=="],
"@smithy/core": ["@smithy/core@3.33.3", "", { "dependencies": { "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-CsOeKq/9kA3y6VJHt+/+VTCtBaxJ4OTFpgrjIUhPpDIKxBci1k2bJaQASF2h/ELWrulGp+t97DZ0mevfAD8idg=="],
"@smithy/credential-provider-imds": ["@smithy/credential-provider-imds@4.5.2", "", { "dependencies": { "@smithy/core": "^3.33.2", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg=="],
@@ -1532,9 +1514,9 @@
"@types/whatwg-mimetype": ["@types/whatwg-mimetype@3.0.2", "", {}, "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA=="],
"@types/ws": ["@types/ws@8.18.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w=="],
"@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
"@types/yauzl": ["@types/yauzl@3.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-NRPn5w6h8dhcnmx3YIRQcqMywY/+nND/uOkJessedcrowO3C0AssHp3tMJpxKAwOhFOo0OV1y9VtsC5hbKKBAw=="],
"@types/yauzl": ["@types/yauzl@2.10.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="],
"@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.68.0", "", { "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.68.0", "@typescript-eslint/type-utils": "8.68.0", "@typescript-eslint/utils": "8.68.0", "@typescript-eslint/visitor-keys": "8.68.0", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.68.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-WASHDpCm6qO5jj9g1a+8NiW5+GCkAyLReR56/4VruYmNgfUmqpxOfZ2Yfb8xGfJPWv5Qi6LSD8sXdces3vbp/Q=="],
@@ -1992,8 +1974,6 @@
"eventsource-parser": ["eventsource-parser@3.1.1", "", {}, "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ=="],
"execa": ["execa@10.2.1", "", { "dependencies": { "@sindresorhus/merge-streams": "^4.0.0", "figures": "^6.1.0", "get-stream": "^9.0.1", "human-signals": "^8.0.1", "is-plain-obj": "^4.1.0", "is-stream": "^4.0.1", "npm-run-path": "^6.0.0", "pretty-ms": "^9.3.1", "signal-exit": "^4.1.0", "strip-final-newline": "^4.0.0", "which-command": "^0.1.0", "yoctocolors": "^2.2.0" } }, "sha512-/Bofl3ZBh2Q4/PG0W63qFzP5vDAypi8Zc90UWTBzaDNIYiX7apPOd0N6L8hG8CojUdq4V51adu8BObP+iVsSTw=="],
"exiftool-vendored": ["exiftool-vendored@38.1.0", "", { "dependencies": { "@photostructure/tz-lookup": "^11.7.0", "@types/luxon": "^3.7.5", "batch-cluster": "^19.2.0", "he": "^1.2.0", "luxon": "^3.7.2" }, "optionalDependencies": { "exiftool-vendored.exe": "13.59.2", "exiftool-vendored.pl": "13.59.2" } }, "sha512-LIERqM/Qb0oqJlSswLFKWsxGVH81skp7omsX2BPKA/dEzfLP5syNO5KL7k5UlMCf+m0jqEXrKTQr/xV5vScPow=="],
"exiftool-vendored.exe": ["exiftool-vendored.exe@13.59.2", "", { "os": "win32" }, "sha512-U0l0CApIGO+AjpFYCiNCApQsMdlf6sqCyEl4wlKKqvwVAEVcvMRw91k7zj32OPFZE+/+XlLFsc6876MpOqBLiw=="],
@@ -2038,8 +2018,6 @@
"fflate": ["fflate@0.8.3", "", {}, "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA=="],
"figures": ["figures@6.1.0", "", { "dependencies": { "is-unicode-supported": "^2.0.0" } }, "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg=="],
"file-entry-cache": ["file-entry-cache@8.0.0", "", { "dependencies": { "flat-cache": "^4.0.0" } }, "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ=="],
"find-my-way": ["find-my-way@9.7.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-querystring": "^1.0.0", "safe-regex2": "^5.0.0" } }, "sha512-f2JHn75x2JlwUwLenZypgczR7YWMb/uO9BvUXtus+JMgkbIkLADd38cI4EiV+OQqrGo1Zlq6V8wnqMJ8e62wUQ=="],
@@ -2096,7 +2074,7 @@
"get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
"get-stream": ["get-stream@9.0.1", "", { "dependencies": { "@sec-ant/readable-stream": "^0.4.1", "is-stream": "^4.0.1" } }, "sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA=="],
"get-stream": ["get-stream@5.2.0", "", { "dependencies": { "pump": "^3.0.0" } }, "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA=="],
"get-symbol-description": ["get-symbol-description@1.1.0", "", { "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6" } }, "sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg=="],
@@ -2156,8 +2134,6 @@
"https-proxy-agent": ["https-proxy-agent@9.1.0", "", { "dependencies": { "agent-base": "9.0.0", "debug": "^4.3.4", "proxy-agent-negotiate": "1.1.0" } }, "sha512-ag87y7cJJ9/3+GxFr8Oy4O5faDsGRGnBGsJj/YjOSsSx/5eadKLYTMPlzuR6obgoCDDm0abAAZitXXQkMOPSpA=="],
"human-signals": ["human-signals@8.0.1", "", {}, "sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ=="],
"iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="],
"ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
@@ -2232,7 +2208,7 @@
"is-shared-array-buffer": ["is-shared-array-buffer@1.0.4", "", { "dependencies": { "call-bound": "^1.0.3" } }, "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A=="],
"is-stream": ["is-stream@4.0.1", "", {}, "sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A=="],
"is-stream": ["is-stream@2.0.1", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="],
"is-string": ["is-string@1.1.1", "", { "dependencies": { "call-bound": "^1.0.3", "has-tostringtag": "^1.0.2" } }, "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA=="],
@@ -2240,8 +2216,6 @@
"is-typed-array": ["is-typed-array@1.1.15", "", { "dependencies": { "which-typed-array": "^1.1.16" } }, "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ=="],
"is-unicode-supported": ["is-unicode-supported@2.1.0", "", {}, "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ=="],
"is-weakmap": ["is-weakmap@2.0.2", "", {}, "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w=="],
"is-weakref": ["is-weakref@1.1.1", "", { "dependencies": { "call-bound": "^1.0.3" } }, "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew=="],
@@ -2466,16 +2440,12 @@
"node-fetch": ["node-fetch@3.3.2", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="],
"node-forge": ["node-forge@1.4.3", "", {}, "sha512-P6wzfh6t70avmV8FrVEAd/36sOPJQ+hkaJVX1Laap9J/77m7M0eyozDvc8SwnDf4P7MP94gwbAAo0rg3YVXT+g=="],
"node-releases": ["node-releases@2.0.54", "", {}, "sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ=="],
"nodemailer": ["nodemailer@10.0.10", "", {}, "sha512-He9XskOFms62SyAKkLu8CcGcYHAo+BSHSsORI8s4PJH8qZgZY4L4lDfvyN0twvmbpyG+eGrxpyBlskj9d9rJ8A=="],
"normalize-path": ["normalize-path@3.0.0", "", {}, "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA=="],
"npm-run-path": ["npm-run-path@6.0.0", "", { "dependencies": { "path-key": "^4.0.0", "unicorn-magic": "^0.3.0" } }, "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA=="],
"object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
"object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],
@@ -2520,8 +2490,6 @@
"parse-entities": ["parse-entities@4.0.2", "", { "dependencies": { "@types/unist": "^2.0.0", "character-entities-legacy": "^3.0.0", "character-reference-invalid": "^2.0.0", "decode-named-character-reference": "^1.0.0", "is-alphanumerical": "^2.0.0", "is-decimal": "^2.0.0", "is-hexadecimal": "^2.0.0" } }, "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw=="],
"parse-ms": ["parse-ms@4.0.0", "", {}, "sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw=="],
"partial-json": ["partial-json@0.1.7", "", {}, "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA=="],
"path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="],
@@ -2604,8 +2572,6 @@
"pretty-format": ["pretty-format@27.5.1", "", { "dependencies": { "ansi-regex": "^5.0.1", "ansi-styles": "^5.0.0", "react-is": "^17.0.1" } }, "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ=="],
"pretty-ms": ["pretty-ms@9.3.1", "", { "dependencies": { "parse-ms": "^4.0.0" } }, "sha512-HzMy3Geq23nVALD/M2LliU+F+M+gVNsvkQWWqeBZ8HDiCgzo6YPJ/Omrmtq24EFrIsk0a3EkQGEd7bDOo+IhGA=="],
"prisma": ["prisma@7.10.0", "", { "dependencies": { "@prisma/config": "7.10.0", "@prisma/dev": "0.24.17", "@prisma/engines": "7.10.0", "@prisma/studio-core": "0.33.0", "mysql2": "3.15.3", "postgres": "3.4.7" }, "peerDependencies": { "better-sqlite3": ">=9.0.0", "typescript": ">=5.4.0" }, "optionalPeers": ["better-sqlite3", "typescript"], "bin": { "prisma": "build/index.js" } }, "sha512-o0ornyJOWgygVAzGCpr8PdXV8EJLHyVGDDUr/voBQt8Azzw8cYTByzzPGcA/m4tCkPcnJA8raEOv2CslsKhPEw=="],
"prisma-json-types-generator": ["prisma-json-types-generator@5.1.1", "", { "dependencies": { "@prisma/generator-helper": "^7.8.0", "semver": "^7.8.5", "try": "^1.0.3", "tslib": "^2.8.1", "typescript": "npm:typescript@^6.0.3" }, "peerDependencies": { "@prisma/client": "^7.8.0", "prisma": "^7.8.0" }, "bin": { "prisma-json-types-generator": "index.js" } }, "sha512-vtj68YkCla7bEnblC54xzKU3w+H/1uoKxtLU3F2eC9LL8j1Dz8GadVagKhQqQd03KGfHmO7o83Tf3yXxCKQwzQ=="],
@@ -2768,7 +2734,7 @@
"siginfo": ["siginfo@2.0.0", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="],
"signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
"signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
"skin-tone": ["skin-tone@2.0.0", "", { "dependencies": { "unicode-emoji-modifier-base": "^1.0.0" } }, "sha512-kUMbT1oBJCpgrnKoSr0o6wPtvRWT9W9UKvGLwfJYO2WuahZRHOpEyL1ckyMGgMWh0UdpmaoFqKKD29WTomNEGA=="],
@@ -2824,8 +2790,6 @@
"strip-ansi-cjs": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"strip-final-newline": ["strip-final-newline@4.0.0", "", {}, "sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw=="],
"strip-json-comments": ["strip-json-comments@5.0.3", "", {}, "sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw=="],
"style-to-js": ["style-to-js@1.1.21", "", { "dependencies": { "style-to-object": "1.0.14" } }, "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ=="],
@@ -2924,8 +2888,6 @@
"unicode-trie": ["unicode-trie@2.0.0", "", { "dependencies": { "pako": "^0.2.5", "tiny-inflate": "^1.0.0" } }, "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ=="],
"unicorn-magic": ["unicorn-magic@0.3.0", "", {}, "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA=="],
"unified": ["unified@11.0.5", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="],
"unist-util-is": ["unist-util-is@6.0.1", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g=="],
@@ -2988,8 +2950,6 @@
"which-collection": ["which-collection@1.0.2", "", { "dependencies": { "is-map": "^2.0.3", "is-set": "^2.0.3", "is-weakmap": "^2.0.2", "is-weakset": "^2.0.3" } }, "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw=="],
"which-command": ["which-command@0.1.0", "", { "bin": { "which-command": "cli.js" } }, "sha512-XZyoF5/5hZtXitIwzrU4NKK+Wtbb9aB9CezUEw2Q0wlYK8NUYQxC1rRXgNueYLtBAJwXIb+/tFVk4dozciNJMA=="],
"which-typed-array": ["which-typed-array@1.1.22", "", { "dependencies": { "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.9", "call-bound": "^1.0.4", "for-each": "^0.3.5", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-tostringtag": "^1.0.2" } }, "sha512-fvO4ExWMFsqyhG3AiPAObMuY1lxaqgYcxbc49CNdWDDECOJNgQyvsOWVwbZc+qf3rzRtxojBK+CMEv0Ld5CYpw=="],
"why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="],
@@ -3004,7 +2964,7 @@
"wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
"ws": ["ws@8.22.2", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA=="],
"ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
"xtend": ["xtend@4.0.2", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="],
@@ -3018,14 +2978,12 @@
"yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
"yauzl": ["yauzl@3.4.0", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw=="],
"yauzl": ["yauzl@2.10.0", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="],
"yjs": ["yjs@13.6.32", "", { "dependencies": { "lib0": "^0.2.99" } }, "sha512-lfiJIIC4Xayt5ItynE407ehlE03pCjeOc4hkR4yxxvvNJ4kuiN25B0g+Qp8XagYz361LLL7DCzR5bvFJ81QKtQ=="],
"yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="],
"yoctocolors": ["yoctocolors@2.2.0", "", {}, "sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg=="],
"zeptomatch": ["zeptomatch@2.1.0", "", { "dependencies": { "grammex": "^3.1.11", "graphmatch": "^1.1.0" } }, "sha512-KiGErG2J0G82LSpniV0CtIzjlJ10E04j02VOudJsPyPwNZgGnRKQy7I1R7GMyg/QswnE4l7ohSGrQbQbjXPPDA=="],
"zip-stream": ["zip-stream@6.0.1", "", { "dependencies": { "archiver-utils": "^5.0.0", "compress-commons": "^6.0.2", "readable-stream": "^4.0.0" } }, "sha512-zK7YHHz4ZXpW89AHXUPbQVGKI7uvkd3hzusTdotCg1UxyaVtg0zFJSTfW/Dq5f7OBBVnq6cZIaC8Ti4hb6dtCA=="],
@@ -3038,10 +2996,6 @@
"@ai-sdk/provider-utils/undici": ["undici@7.29.0", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="],
"@anthropic-ai/sandbox-runtime/commander": ["commander@12.1.0", "", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="],
"@anthropic-ai/sandbox-runtime/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.92", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.80", "@aws-sdk/credential-provider-http": "^3.972.82", "@aws-sdk/credential-provider-ini": "^3.973.25", "@aws-sdk/credential-provider-process": "^3.972.80", "@aws-sdk/credential-provider-sso": "^3.973.24", "@aws-sdk/credential-provider-web-identity": "^3.972.86", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-jC3zmOo7Qxlk+oBivvSsS1Ph7sFGm0QfuhqDGbqgRXi4cxUYMG+dWtBwS2XYYXgc8TIVXJiwgQ65sbNpbYupTA=="],
"@aws-sdk/client-bedrock-runtime/@smithy/node-http-handler": ["@smithy/node-http-handler@4.11.3", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-2jY1tSpERfPfWqyBV2pH+iGFaghVsIJszJNsT7hxtQYhVJpWDyc0LqOWI+nXOxOAHaEfZ4PXXtp1wW1TGpHhkA=="],
@@ -3058,16 +3012,10 @@
"@dbos-inc/dbos-sdk/commander": ["commander@12.1.0", "", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="],
"@dbos-inc/dbos-sdk/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
"@earendil-works/chord/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
"@earendil-works/pi-ai/@google/genai": ["@google/genai@2.21.0", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"], "hasInstallScript": true }, "sha512-+PDtco2/Z0ONdzCGekCoCT+O1VJS9xJQNN4XzQpXG/t3El/SWWMkCWlFRO1KmivOHPa4Q0VjUYu1HBKCZ/v33Q=="],
"@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],
"@google/genai/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
"@grpc/grpc-js/@grpc/proto-loader": ["@grpc/proto-loader@0.8.1", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.5.5", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg=="],
"@inlang/paraglide-js/commander": ["commander@11.1.0", "", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="],
@@ -3094,8 +3042,6 @@
"@reduxjs/toolkit/reselect": ["reselect@5.3.0", "", {}, "sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg=="],
"@shumai/cli/adm-zip": ["adm-zip@0.6.1", "", {}, "sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ=="],
"@shumai/webui/@types/react-dom": ["@types/react-dom@19.2.5", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-fMPwH9v7r/pp43yUd2/Mbiex5KouJwwR3dzHkhLREUC6764VyDsqxhAxv6OFEYR1RhjOyD1naqba8ECDBe7ZQg=="],
"@smithy/node-http-handler/@smithy/types": ["@smithy/types@4.19.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q=="],
@@ -3242,8 +3188,6 @@
"@visx/vendor/d3-format": ["d3-format@3.1.0", "", {}, "sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA=="],
"archiver-utils/is-stream": ["is-stream@2.0.1", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="],
"bcrypt-pbkdf/tweetnacl": ["tweetnacl@0.14.5", "", {}, "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA=="],
"better-call/@better-fetch/fetch": ["@better-fetch/fetch@1.3.1", "", {}, "sha512-ABkD1WhyfPZprKRQI3bhATjeiFuNWC9PXhfGWqL+sg/gKrM977oFrYkdb4msM3hgUGonr7KlOsOFT5TU2rht9g=="],
@@ -3252,19 +3196,13 @@
"bl/readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
"compress-commons/is-stream": ["is-stream@2.0.1", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="],
"docker-modem/readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
"dockerode/tar-fs": ["tar-fs@2.1.5", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw=="],
"eslint-plugin-react/minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="],
"extract-zip/@types/yauzl": ["@types/yauzl@2.10.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="],
"extract-zip/get-stream": ["get-stream@5.2.0", "", { "dependencies": { "pump": "^3.0.0" } }, "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA=="],
"extract-zip/yauzl": ["yauzl@2.10.0", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="],
"foreground-child/signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
"gaxios/https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="],
@@ -3272,10 +3210,6 @@
"glob/minimatch": ["minimatch@9.0.9", "", { "dependencies": { "brace-expansion": "^2.0.2" } }, "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg=="],
"happy-dom/@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
"happy-dom/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
"its-fine/@types/react-reconciler": ["@types/react-reconciler@0.28.9", "", { "peerDependencies": { "@types/react": "*" } }, "sha512-HHM3nxyUZ3zAylX8ZEyrDNd2XZOnQ0D5XfunJF5FLQnZbHHYq4UWvW1QfelQNXv1ICNkwYhfxjwfnqivYB6bFg=="],
"lazystream/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
@@ -3286,8 +3220,6 @@
"lit-element/@lit/reactive-element": ["@lit/reactive-element@1.6.3", "", { "dependencies": { "@lit-labs/ssr-dom-shim": "^1.0.0" } }, "sha512-QuTgnG52Poic7uM1AN5yJ09QMe0O28e10XzSvWDz02TJiiKee4stsiownEIadWm8nYzyDAyT+gKzUoZmiWQtsQ=="],
"npm-run-path/path-key": ["path-key@4.0.0", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="],
"p-retry/retry": ["retry@0.13.1", "", {}, "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg=="],
"parse-entities/@types/unist": ["@types/unist@2.0.11", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
@@ -3306,8 +3238,6 @@
"prop-types/react-is": ["react-is@16.13.1", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="],
"proper-lockfile/signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
"readdir-glob/minimatch": ["minimatch@5.1.9", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw=="],
"sharp/semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
@@ -3320,6 +3250,8 @@
"wrap-ansi-cjs/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
"yauzl/buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.80", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-uO5TiSvb6j1w9RTe5z28OaOmsrOxVQUPaC5+wZl50RfOXcrYD/KgnS8I9lfyGXc7sGbkCopK6VnhNIAoLqfewQ=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.82", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.14.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-vQzlDHlC24Yz42p+rT4NBoP/5VdetkBoujbOLq9h6QYWC8THuZSPYnXIR9OP3XcOrdMgPBBipOrdssfxnIiWUg=="],
@@ -3338,8 +3270,6 @@
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@smithy/types": ["@smithy/types@4.19.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q=="],
"@earendil-works/pi-ai/@google/genai/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
"@isaacs/cliui/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="],
"@isaacs/cliui/strip-ansi/ansi-regex": ["ansi-regex@6.3.0", "", {}, "sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ=="],
@@ -3442,8 +3372,6 @@
"eslint-plugin-react/minimatch/brace-expansion": ["brace-expansion@1.1.18", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw=="],
"extract-zip/yauzl/buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
"gaxios/https-proxy-agent/agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="],
"glob/minimatch/brace-expansion": ["brace-expansion@2.1.4", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg=="],
-59
View File
@@ -3,65 +3,6 @@ title: "Changelog"
description: "Recent updates, new features, and improvements in Shumai"
---
<Update label="v0.7.2" description="November 27, 2026">
### Added
- **comments**: Add Internal Comments with a Public/Internal selector in the comment composer so team and project members can have private discussions (marked with a lock icon) that never appear on public share links.
- **comments**: Allow comment authors to edit their comments inline from the comment menu, including updating text, switching between Public and Internal, removing timestamps, and adding or removing attachments.
- **comments**: Add a "Print Comments" option in the comments menu (available in both project file views and public share links) that opens a dedicated print-friendly page with asset metadata, comment thumbnails, visual markup overlays, replies, completion status, emoji reactions, and attachments.
- **share**: See view counts, last viewed times, and activity for public share links, including file and folder views, downloads, and comments.
- **share**: Add options to create a share link or add to existing share links directly from the media view dropdown menu, and open a quick share dialog with inline renaming, one-click link copying, and security settings upon creation.
### Fixed
- **video**: Pause playback while dragging the seekbar and show a lightweight preview in the player until the selected frame is ready.
- **comments**: Keep password-protected print links on the share password prompt, keep private folder names out of shared print data, and wait for thumbnails and reply drawings before printing.
- **security**: Security improvements.
### Changed
</Update>
<Update label="v0.7.1" description="November 23, 2026">
### Added
- **search**: Find similar images and video segments from a project image, or choose, drop, or paste an image in semantic search.
### Fixed
- **storage**: Fix an issue where cached media preview and file URLs could expire and break after the host machine slept or near the end of an S3 link's lifetime.
- **search**: Video segment matches in Semantic Search and Find Similar show the segment’s first frame and let you scrub through it on hover. Matches that span the entire video reuse its full preview when available.
- **search**: Fix an issue where version stacks appeared as separate individual versions in Search and Find Similar results instead of matching only the latest version and showing a single stacked asset with its version badge.
### Changed
- **transcode**: Offload video chunk slicing for search embeddings to the transcode worker queue.
</Update>
<Update label="v0.7.0" description="November 18, 2026">
### Added
- **i18n**: Add Korean as a display language, selectable on the sign-up page and in team settings.
### Fixed
- **video**: Fix playback stalling after tapping or clicking the progress bar on slow connections, and stop the hidden seek preview from downloading the whole video in the background.
- **cli**: Fix release publication failing to find staged standalone downloads.
### Changed
- **agent**: ⚠️ **Breaking Change**: Replaced the built-in server-side Bash sandbox with external Runners and removed the team-level sandbox domain allowlist settings. The Bash tool is now disabled by default. If your Agent or Skills require Bash execution, you'll need to set up and connect an external Runner using shumai-cli. The Shumai CLI includes built-in sandbox support, allowing you to configure filesystem access and network domain allowlists for Bash execution directly on the Runner. See [Agent Runners](https://docs.shumai.one/using-shumai/agent-sandbox) for setup instructions and configuration details. The Docker Compose configuration has also been updated to improve security following the removal of the server-side sandbox. We strongly recommend upgrading to the latest Shumai image and updating your Docker Compose file to apply these security improvements.
- **cli**: Show copyable commands and shell configuration instructions when the standalone CLI installation directory is missing from PATH.
</Update>
<Update label="v0.6.6" description="November 13, 2026">
### Added
-2
View File
@@ -72,8 +72,6 @@ When running multiple replicas of the transcode workers or main servers across m
- **Custom Worker ID**: Set `SHUMAI_WORKERS_ID` (or `SHUMAI_WORKER_ID`) if you wish to assign an explicit identifier.
- **Kubernetes**: In Kubernetes Pods, set `POD_NAME` (via Downward API `fieldRef: { fieldPath: metadata.name }`) to provide stable, unique per-pod identity across pod restarts.
Agent runners require a single main server per database. With runners configured, stop the old main server before starting its replacement. For Kubernetes, use a single main server replica with the Recreate deployment strategy. Transcode workers can still scale independently.
---
## Scalable Deployment on Kubernetes & AWS EKS
+10 -10
View File
@@ -38,16 +38,16 @@ Shumai is configured via environment variables. You can define these variables i
Shumai supports storing files locally or on S3-compatible endpoints.
| Variable | Description | Example / Default |
| :-------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------ |
| `STORAGE_BACKEND` | Storage type. Use `local` for local file system storage, or `s3` for S3-compatible cloud storage. | `local` (default) or `s3` |
| `AWS_ENDPOINT_URL_S3` | Endpoint for S3 storage or local storage. Used by the browser to build file upload URLs. Must include port if deploying remotely or using custom ports. | `http://localhost:3000` (respects `SHUMAI_SERVER_PORT` fallback if unset) |
| `S3_BUCKET` | S3 bucket name. | `shumai` (default) |
| `S3_ACCESS_KEY_ID` | Access key credentials for S3. | `minioadmin` (default) |
| `S3_SECRET_ACCESS_KEY` | Secret key credentials for S3. | `minioadmin` (default) |
| `S3_REGION` | S3 storage region. | `auto` (default) |
| `PRESIGNED_URL_EXPIRES_IN` | Number of hours (decimals supported, e.g. `0.5`) for which generated presigned download links are valid. Applies to both local and S3 storage. | `12` (default) |
| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | Number of hours (decimals supported, e.g. `0.5`) for which generated presigned upload links are valid. Falls back to `PRESIGNED_URL_EXPIRES_IN` if unset. Applies to both local and S3. | `12` (default) |
| Variable | Description | Example / Default |
| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------ |
| `STORAGE_BACKEND` | Storage type. Use `local` for local file system storage, or `s3` for S3-compatible cloud storage. | `local` (default) or `s3` |
| `AWS_ENDPOINT_URL_S3` | Endpoint for S3 storage or local storage. Used by the browser to build file upload URLs. Must include port if deploying remotely or using custom ports. | `http://localhost:3000` (respects `SHUMAI_SERVER_PORT` fallback if unset) |
| `S3_BUCKET` | S3 bucket name. | `shumai` (default) |
| `S3_ACCESS_KEY_ID` | Access key credentials for S3. | `minioadmin` (default) |
| `S3_SECRET_ACCESS_KEY` | Secret key credentials for S3. | `minioadmin` (default) |
| `S3_REGION` | S3 storage region. | `auto` (default) |
| `PRESIGNED_URL_EXPIRES_IN` | Number of hours for which generated presigned download links are valid. | `5` (default) |
| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | Number of hours for which generated presigned upload links are valid. Falls back to `PRESIGNED_URL_EXPIRES_IN` if unset. | `12` (default) |
### Local Storage Port Configuration
+10 -10
View File
@@ -13,16 +13,16 @@ Using external S3 storage is highly recommended for production teams. It allows
To enable S3-compatible storage, update the following environment variables in your `.env` file or Docker Compose configuration:
| Variable | Description | Required | Default / Example |
| :-------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------- | :------- | :----------------------------------- |
| `STORAGE_BACKEND` | Set to `s3` to enable S3 compatible storage. | Yes | `s3` |
| `S3_BUCKET` | The name of the S3 bucket where files will be stored. | Yes | `shumai-bucket` |
| `S3_REGION` | The region of your S3 bucket. | No | `auto` |
| `S3_ACCESS_KEY_ID` | The access key ID for your storage service. | Yes | `your-access-key-id` |
| `S3_SECRET_ACCESS_KEY` | The secret access key for your storage service. | Yes | `your-secret-access-key` |
| `AWS_ENDPOINT_URL_S3` | The endpoint URL of your S3 compatible storage provider. | Yes | `https://s3.us-east-1.amazonaws.com` |
| `PRESIGNED_URL_EXPIRES_IN` | Duration in hours (decimals supported, e.g. `0.5`) before generated presigned download URLs expire. | No | `12` |
| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | Duration in hours (decimals supported, e.g. `0.5`) before generated presigned upload URLs expire. Falls back to `PRESIGNED_URL_EXPIRES_IN` if unset. | No | `12` |
| Variable | Description | Required | Default / Example |
| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------ | :------- | :----------------------------------- |
| `STORAGE_BACKEND` | Set to `s3` to enable S3 compatible storage. | Yes | `s3` |
| `S3_BUCKET` | The name of the S3 bucket where files will be stored. | Yes | `shumai-bucket` |
| `S3_REGION` | The region of your S3 bucket. | No | `auto` |
| `S3_ACCESS_KEY_ID` | The access key ID for your storage service. | Yes | `your-access-key-id` |
| `S3_SECRET_ACCESS_KEY` | The secret access key for your storage service. | Yes | `your-secret-access-key` |
| `AWS_ENDPOINT_URL_S3` | The endpoint URL of your S3 compatible storage provider. | Yes | `https://s3.us-east-1.amazonaws.com` |
| `PRESIGNED_URL_EXPIRES_IN` | Duration in hours before generated presigned download URLs expire. | No | `5` |
| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | Duration in hours before generated presigned upload URLs expire. Falls back to `PRESIGNED_URL_EXPIRES_IN` if unset. | No | `12` |
---
+25 -81
View File
@@ -1,101 +1,45 @@
---
title: Agent Runners
description: Connect an optional command runner and configure sandboxing on its machine.
title: Agent Sandbox
description: Secure execution environment and network domain restrictions for AI agent scripts.
---
Agents use Shumai's built-in tools without a runner. To execute shell commands or download assets into a shell workspace, connect a **runner** on a machine you control. The runner opens an authenticated outbound WebSocket connection; no inbound port is needed.
Running automated scripts poses security risks. Shumai resolves this by executing all agent skills inside a secure, isolated **Sandbox** environment.
Agent runners require one main Shumai server per database. Multiple main servers can share a database while it has no configured runners. Stop the other main servers before creating a runner. Transcode workers can run separately.
---
## Connect a runner
## Sandbox Security
1. In **Settings → Agent Runners**, create a runner and copy its one-time key. Only team owners can manage runners and rotate their keys.
2. Install [Shumai CLI](https://github.com/shumaiOne/shumai/tree/main/apps/cli#installation) on macOS, Linux, or Windows.
3. Start it in a dedicated, existing workspace:
The sandbox restricts the execution process from accessing the host filesystem, system processes, and internal networks:
```bash
export SHUMAI_API_SERVER="https://shumai.example.com"
export SHUMAI_RUNNER_KEY="your-runner-key"
shumai-cli runner start --cwd /path/to/workspace
```
- **Isolation**: Scripts run in a virtualized workspace container that prevents them from modifying critical system files or reading other project data.
- **Network Bridging**: External network calls from inside the sandbox are strictly monitored.
On Windows, set the variables in PowerShell:
### File System Restrictions
```powershell
$env:SHUMAI_API_SERVER = "https://shumai.example.com"
$env:SHUMAI_RUNNER_KEY = "your-runner-key"
shumai-cli runner start --cwd C:\workspace
```
To protect your workspace environments and sensitive data, the sandbox enforces strict file-level access controls:
Use a runner key, not a personal API token. Prefer the environment variable over `--key` to keep the key out of shell history. The runner stays in the foreground; Ctrl+C stops it and its active commands. Temporary connection losses trigger reconnection. Revoked or replaced connections stop instead of reconnecting.
- **Read Access**: The sandbox is allowed to read files within the workspace, with a strict exception for sensitive environment and certificate files. It cannot read: `['.env', '.env.*', '*.pem', '*.key']`.
- **Write Access**: The sandbox is heavily restricted and may only write to the `.pi` folder located in the current working directory (cwd). Even within this allowed directory, the sandbox is explicitly blocked from writing or creating sensitive files matching: `['.env', '.env.*', '*.pem', '*.key']`.
The first runner becomes the team default. Each agent can use that default or a dedicated runner selected in its settings. Without a configured runner, `bash` and `download_asset` are hidden. With one configured, authorized editors and reviewers can run commands immediately without reading a skill first. Disabled-tool policies still apply. An offline runner produces an execution error.
---
The `bash` tool uses `/bin/sh` on macOS and Linux. On Windows, the runner looks for Git Bash in the standard installation directories, then for `bash.exe` on PATH, and falls back to `cmd.exe`. The runner prints its selected shell at startup and reports it to the agent so it can use compatible syntax. For Bash with SRT on Windows, use Git Bash in place of the legacy WSL Bash launcher.
## Domain Whitelisting
Commands start in the workspace directory. Skills, downloaded assets, generated files, and output logs live under `.pi`. Commands inherit baseline OS settings and explicit skill variables, rather than the runner's full environment, including its runner key and personal API token.
By default, Network Sandbox is **disabled** (allowing all outbound network requests). Team Owners can toggle Network Sandbox **ON** in Sandbox Settings to enforce strict domain whitelisting:
Everyone with shell access to the same runner can read files left in its workspace, including assets and logs from other projects. Shumai project permissions apply when assets are downloaded. Share a runner only among users who may read all files in that workspace. For separate trust groups, use separate runner accounts or virtual machines and restrict access to the agents bound to each runner.
### Allowed Domains
## Optional SRT sandbox
A list of domains that sandboxed scripts are permitted to access.
Without `--srt`, commands have the runner operating-system user's permissions. Connect only to a trusted Shumai server; use a dedicated container, VM, or account when appropriate.
- Default whitelisted domains include standard package registries (like npm or python package hosts) and repository hosts (like `github.com`).
- If a script needs to call an external API (e.g. `api.slack.com`), the administrator must add it to the allowed list.
[Anthropic Sandbox Runtime](https://github.com/anthropics/sandbox-runtime) is bundled as a library in Shumai CLI. Install its platform prerequisites on the runner machine (Linux: bubblewrap, socat, and ripgrep; macOS: ripgrep), then start with its JSON settings:
### Pending Domains
```bash
shumai-cli runner start --cwd /path/to/workspace --srt sandbox.json
```
When an agent script attempts to reach a domain that is not currently authorized:
Windows uses SRT's alpha Windows support. Run the one-time setup before starting a sandboxed runner; it requests administrator permission:
1. The network connection is blocked immediately.
2. The target domain is logged and added to the **Pending Domains** list.
3. Admins can review this list and click **Approve** to authorize the domain, or **Reject** to keep it blocked.
```powershell
npx @anthropic-ai/sandbox-runtime windows-install
```
SRT verifies the setup at startup and reports an error if it is missing. A runner without `--srt` does not need this setup.
The JSON uses upstream SRT settings directly. For example:
```json
{
"filesystem": {
"denyRead": ["~/.ssh", "~/.aws", ".env", ".env.*"],
"allowWrite": [".pi"],
"denyWrite": []
},
"network": {
"allowedDomains": [],
"deniedDomains": []
}
}
```
This example allows writes only in `.pi`, denies reads of the listed credential locations, and blocks command network access. Review read permissions and network rules for your environment using SRT's documentation. Relative filesystem paths use the runner workspace. Settings are snapshotted at startup; restart after changing them. Missing or invalid settings, missing SRT prerequisites, and sandbox initialization failures stop startup. Commands never fall back to unrestricted execution.
SRT wraps shell commands and their child processes. One shared SRT runtime handles concurrent commands and is reset when the runner stops. The runner's WebSocket and server-directed file transfers operate outside SRT. **The Shumai server address is not automatically added to allowed domains.** If a script itself needs network access, explicitly allow its destination in the JSON.
Shumai has no server-side sandbox or domain settings. SRT is initialized only on runners that opt into it. SRT in Docker may require namespace permissions on that dedicated runner container; these permissions are not needed by the Shumai server.
## Runner in Docker
An ordinary runner can run in its own container without extra capabilities or an exposed port:
```bash
docker run --rm --init --name shumai-runner \
--cap-drop ALL --security-opt no-new-privileges \
-e SHUMAI_API_SERVER -e SHUMAI_RUNNER_KEY \
-v shumai-runner-workspace:/workspace -w /workspace \
node:22-bookworm sh -c \
'npm install -g @shumai-one/shumai-cli && exec shumai-cli runner start'
```
For development, HTTP is accepted for `localhost`, `127.0.0.1`, `[::1]`, and Docker's `host.docker.internal`. Remote servers require HTTPS. Avoid mounting sensitive host directories or the Docker socket into the runner workspace.
## Limits and lifecycle
Commands default to 120 seconds and accept a maximum timeout of one hour. Timeout and cancellation attempt to terminate the command and its process tree. Each command saves up to 64 MiB of output in `.pi/logs`; manage retained logs as part of workspace maintenance. Transfers and extracted archives are limited to 256 MiB. Protocol file operations reject paths outside `.pi`, existing symlinks, and unsafe archive entries. V1 assumes commands do not deliberately change workspace paths while transfers are running.
Temporary reconnects reconcile active and recently completed commands without deliberately executing them again. Restarting the runner process does not resume commands from the previous process.
Up to eight commands and file transfers can run concurrently in the shared workspace. Additional requests return a busy error. On Windows without SRT, background processes may survive after the command's shell exits; remaining output pipes are closed after one second. Use foreground commands for predictable timeout and cancellation. SRT manages the sandboxed Windows process tree.
![Agent Sandbox Settings](../sandbox.webp)
+1 -11
View File
@@ -11,7 +11,7 @@ Shumai allows you to collaborate with external stakeholders who do not have acco
1. Select the files or folders you want to share, then right-click and choose **Create New Share Link**.
2. Click the newly created **Share Link** in the project sidebar to open its settings page.
3. Use the **Settings** tab in the right sidebar to configure the share link.
3. Configure the share link in the right sidebar. You can:
- Add password protection
- Set an expiration date
- Allow or disallow downloads
@@ -33,16 +33,6 @@ Once a share link is created, you can easily add more files or folders to it wit
---
## Viewing Share Activity
Open **All Share Links** in the project sidebar to see **Views** and **Last Viewed** for each link. Click **View Activity** on a link’s row to open its history, or select the **Activity** tab on that link’s settings page.
The history groups share opens, file and folder views, downloads, and comments by day. It shows the visitor’s name when available and **Someone** for anonymous activity. A download entry appears when a visitor starts an authorized download.
Every successful open of the share, a shared folder, or a shared file adds one view and updates **Last Viewed**, including reloads. The history shows matching actions once within 30 minutes. A match uses the share link, action, visitor, and asset when there is one. For this check, all anonymous visitors are treated as the same visitor. For example, if a visitor opens the same file twice in ten minutes, **Views** increases by two and the history shows one **Viewed Asset** entry.
---
## Security and Settings
### Expiration Date
-2
View File
@@ -53,8 +53,6 @@ Worker 根据可配置的并发上限从 PostgreSQL 队列中拉取任务:
- **自定义 Worker ID**:若需显式指定标识符,可设置 `SHUMAI_WORKERS_ID`(或 `SHUMAI_WORKER_ID`)。
- **Kubernetes 环境**:在 Kubernetes Pod 中,可通过 Downward API(`fieldRef: { fieldPath: metadata.name }`)设置 `POD_NAME`,以在 Pod 重启期间保持稳定且唯一的单 Pod 身份标识。
使用智能体运行器时,每个数据库只允许运行一个主服务器。已配置运行器时,请先停止旧主服务器,再启动替换实例。在 Kubernetes 中,主服务器应使用单副本和 Recreate 部署策略。转码 Worker 仍可独立扩展。
---
## 基于 Kubernetes 与 AWS EKS 的弹性扩展部署
+10 -10
View File
@@ -38,16 +38,16 @@ Shumai 通过环境变量配置。可以在应用工作区根目录的 `.env`
Shumai 支持将文件存储在本地文件系统或兼容 S3 的对象存储中。
| 变量 | 说明 | 示例 / 默认值 |
| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------- |
| `STORAGE_BACKEND` | 存储类型。使用 `local` 表示本地文件系统存储,使用 `s3` 表示兼容 S3 的云对象存储。 | `local`(默认)或 `s3` |
| `AWS_ENDPOINT_URL_S3` | S3 存储或本地存储的服务端点。浏览器据此生成文件上传链接。在远程部署或使用自定义端口时,必须包含端口号。 | `http://localhost:3000`(未设置时回退至 `SHUMAI_SERVER_PORT`) |
| `S3_BUCKET` | S3 存储桶名称。 | `shumai`(默认) |
| `S3_ACCESS_KEY_ID` | S3 访问凭据 Access Key ID。 | `minioadmin`(默认) |
| `S3_SECRET_ACCESS_KEY` | S3 访问凭据 Secret Access Key。 | `minioadmin`(默认) |
| `S3_REGION` | S3 存储区域。 | `auto`(默认) |
| `PRESIGNED_URL_EXPIRES_IN` | 生成的预签名下载链接的有效时长(单位:小时,支持小数如 `0.5`),同时适用于本地与 S3 存储。 | `12`(默认) |
| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | 生成的预签名上传链接的有效时长(单位:小时,支持小数如 `0.5`)。未设置时回退至 `PRESIGNED_URL_EXPIRES_IN`,同时适用于本地与 S3 存储。 | `12`(默认) |
| 变量 | 说明 | 示例 / 默认值 |
| :-------------------------------- | :------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------- |
| `STORAGE_BACKEND` | 存储类型。使用 `local` 表示本地文件系统存储,使用 `s3` 表示兼容 S3 的云对象存储。 | `local`(默认)或 `s3` |
| `AWS_ENDPOINT_URL_S3` | S3 存储或本地存储的服务端点。浏览器据此生成文件上传链接。在远程部署或使用自定义端口时,必须包含端口号。 | `http://localhost:3000`(未设置时回退至 `SHUMAI_SERVER_PORT`) |
| `S3_BUCKET` | S3 存储桶名称。 | `shumai`(默认) |
| `S3_ACCESS_KEY_ID` | S3 访问凭据 Access Key ID。 | `minioadmin`(默认) |
| `S3_SECRET_ACCESS_KEY` | S3 访问凭据 Secret Access Key。 | `minioadmin`(默认) |
| `S3_REGION` | S3 存储区域。 | `auto`(默认) |
| `PRESIGNED_URL_EXPIRES_IN` | 生成的预签名下载链接的有效时长(单位:小时)。 | `5`(默认) |
| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | 生成的预签名上传链接的有效时长(单位:小时)。未设置时回退至 `PRESIGNED_URL_EXPIRES_IN`。 | `12`(默认) |
### 本地存储端口配置
+10 -10
View File
@@ -13,16 +13,16 @@ Shumai 采用 Bun 原生高性能 S3 客户端存储与分发创意资产。借
若要启用兼容 S3 的存储,请在 `.env` 文件或 Docker Compose 配置中更新以下环境变量:
| 变量名 | 说明 | 必填 | 默认值 / 示例 |
| :-------------------------------- | :------------------------------------------------------------------------------------------------------------ | :--- | :----------------------------------- |
| `STORAGE_BACKEND` | 设为 `s3` 以启用兼容 S3 的存储后端。 | 是 | `s3` |
| `S3_BUCKET` | 存放文件的 S3 存储桶名称。 | 是 | `shumai-bucket` |
| `S3_REGION` | S3 存储桶所在地域(Region)。 | 否 | `auto` |
| `S3_ACCESS_KEY_ID` | 存储服务的访问密钥 ID(Access Key ID)。 | 是 | `your-access-key-id` |
| `S3_SECRET_ACCESS_KEY` | 存储服务的私有访问密钥(Secret Access Key)。 | 是 | `your-secret-access-key` |
| `AWS_ENDPOINT_URL_S3` | 兼容 S3 的存储服务端点 URL。 | 是 | `https://s3.us-east-1.amazonaws.com` |
| `PRESIGNED_URL_EXPIRES_IN` | 生成的预签名下载链接有效期(单位:小时,支持小数如 `0.5`)。 | 否 | `12` |
| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | 生成的预签名上传链接有效期(单位:小时,支持小数如 `0.5`)。若未指定,则回退继承 `PRESIGNED_URL_EXPIRES_IN`。 | 否 | `12` |
| 变量名 | 说明 | 必填 | 默认值 / 示例 |
| :-------------------------------- | :------------------------------------------------------------------------------------------ | :--- | :----------------------------------- |
| `STORAGE_BACKEND` | 设为 `s3` 以启用兼容 S3 的存储后端。 | 是 | `s3` |
| `S3_BUCKET` | 存放文件的 S3 存储桶名称。 | 是 | `shumai-bucket` |
| `S3_REGION` | S3 存储桶所在地域(Region)。 | 否 | `auto` |
| `S3_ACCESS_KEY_ID` | 存储服务的访问密钥 ID(Access Key ID)。 | 是 | `your-access-key-id` |
| `S3_SECRET_ACCESS_KEY` | 存储服务的私有访问密钥(Secret Access Key)。 | 是 | `your-secret-access-key` |
| `AWS_ENDPOINT_URL_S3` | 兼容 S3 的存储服务端点 URL。 | 是 | `https://s3.us-east-1.amazonaws.com` |
| `PRESIGNED_URL_EXPIRES_IN` | 生成的预签名下载链接有效期(单位:小时)。 | 否 | `5` |
| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | 生成的预签名上传链接有效期(单位:小时)。若未指定,则回退继承 `PRESIGNED_URL_EXPIRES_IN`。 | 否 | `12` |
---
+25 -79
View File
@@ -1,99 +1,45 @@
---
title: 智能体运行器
description: 连接可选的命令运行器,并在运行器机器上配置沙箱。
title: 智能体沙箱
description: AI 智能体脚本的安全执行环境与网络域名限制规范。
---
智能体无需运行器即可使用内置工具。如需执行命令或将素材下载到命令工作区,请在自己管理的机器上连接**运行器**。运行器主动通过经过身份验证的 WebSocket 连接 Shumai,无需开放入站端口。
运行自动化脚本存在潜在的安全风险。Shumai 通过在安全且隔离的**沙箱(Sandbox)**环境中执行所有智能体技能来化解这一隐患。
每个数据库只支持一台主 Shumai 服务器使用智能体运行器。未配置运行器时,多台主服务器可以共享数据库。创建运行器前,请停止其他主服务器副本。转码 Worker 可以独立运行。
---
## 连接运行器
## 沙箱安全机制
1. 在 **设置 → 智能体运行器** 中创建运行器,复制仅显示一次的密钥。只有团队所有者可以管理运行器和轮换密钥。
2. 在 macOS、Linux 或 Windows 机器上安装 [Shumai CLI](https://github.com/shumaiOne/shumai/tree/main/apps/cli#installation)。
3. 在已有的专用工作目录中启动:
沙箱严格限制执行进程访问宿主机文件系统、系统进程及内部网络:
```bash
export SHUMAI_API_SERVER="https://shumai.example.com"
export SHUMAI_RUNNER_KEY="your-runner-key"
shumai-cli runner start --cwd /path/to/workspace
```
- **环境隔离**:脚本在虚拟化的工作区容器中运行,无法篡改系统核心文件或读取其他项目数据。
- **网络桥接管控**:来自沙箱内部的外部网络请求会受到严格监控。
Windows 用户可在 PowerShell 中设置变量:
### 文件系统访问限制
```powershell
$env:SHUMAI_API_SERVER = "https://shumai.example.com"
$env:SHUMAI_RUNNER_KEY = "your-runner-key"
shumai-cli runner start --cwd C:\workspace
```
为保障工作区环境与敏感数据安全,沙箱实施了严密的文件级访问控制策略:
使用运行器密钥,而非个人 API 令牌。建议通过环境变量传入,避免 `--key` 将密钥留在命令历史中。运行器在前台执行,Ctrl+C 会停止运行器及其活动命令。临时断线后自动重连;密钥撤销或连接被替换时退出。
- **读取权限**:沙箱允许读取工作区内的普通文件,但严格禁止访问敏感环境配置与证书密钥文件。禁止读取的文件模式包括:`['.env', '.env.*', '*.pem', '*.key']`。
- **写入权限**:沙箱的写入权限受到极为严苛的限制,仅允许写入当前工作目录(cwd)下的 `.pi` 文件夹。即便在该受信任的目录内部,沙箱也严禁写入或创建匹配以下模式的敏感文件:`['.env', '.env.*', '*.pem', '*.key']`。
第一个运行器是团队默认运行器,也可在智能体设置中指定专用运行器。未配置运行器时隐藏 `bash` 和 `download_asset`。配置后,具有智能体使用权限的编辑者和审阅者可立即使用 Bash,无需先读取技能;禁用工具设置仍然生效。运行器离线时执行命令会返回错误。
---
命令从工作目录启动,技能、下载素材、生成文件和日志位于 `.pi` 中。子进程只继承基础系统环境及明确配置的技能变量,不自动继承运行器密钥、个人 API 令牌或其他任意环境变量。
## 域名白名单
所有有权在同一运行器执行命令的用户都可以读取工作区中保留的文件,包括其他项目的素材和日志。Shumai 下载素材时会检查项目权限。请仅在有权读取工作区内所有文件的用户之间共享运行器。不同信任范围应使用独立的运行器账号或虚拟机,并限制对应智能体的访问权限。
默认情况下,网络沙箱处于**关闭**状态(允许所有出站网络请求)。团队所有者可在沙箱设置中开启网络沙箱,以强制推行严格的域名白名单管控:
## 可选 SRT 沙箱
### 允许的域名 (Allowed Domains)
未使用 `--srt` 时,命令具有运行器系统用户的权限。只连接可信 Shumai 服务器,可按需使用独立容器、虚拟机或账号。
允许沙箱内脚本正常访问的域名清单。
[Anthropic Sandbox Runtime](https://github.com/anthropics/sandbox-runtime) 已作为库内置于 Shumai CLI。安装平台依赖(Linux:bubblewrap、socat 和 ripgrep;macOS:ripgrep)后传入 JSON 配置:
- 默认白名单包含标准软件包注册表(如 npm、Python 官方源等)以及代码托管平台(如 `github.com`)。
- 若脚本需要调用外部 API(如 `api.slack.com`),管理员须预先将其添加至白名单中。
```bash
shumai-cli runner start --cwd /path/to/workspace --srt sandbox.json
```
### 待审批域名 (Pending Domains)
Windows 使用 SRT 的实验性 Windows 支持。启用沙箱前执行一次初始化;此命令会请求管理员权限:
当智能体脚本尝试访问未经授权的域名时:
```powershell
npx @anthropic-ai/sandbox-runtime windows-install
```
1. 网络连接将被即刻拦截。
2. 系统会记录目标域名并将其加入**待审批域名**列表。
3. 管理员可审阅该列表,点击**批准**将其加白,或点击**拒绝**保持拦截。
SRT 会在启动时检查安装状态,缺少初始化时返回错误。未使用 `--srt` 的运行器不需要此步骤。`bash` 工具在 macOS 和 Linux 上使用 `/bin/sh`。在 Windows 上,运行器先在标准安装目录查找 Git Bash,再在 PATH 中查找 `bash.exe`,找不到时使用 `cmd.exe`。运行器在启动时显示所选 Shell,并将其报告给智能体,让智能体使用匹配的命令语法。在 Windows 上搭配 SRT 使用 Bash 时,请用 Git Bash 代替旧版 WSL Bash 启动器。
直接使用上游 SRT JSON 格式,例如:
```json
{
"filesystem": {
"denyRead": ["~/.ssh", "~/.aws", ".env", ".env.*"],
"allowWrite": [".pi"],
"denyWrite": []
},
"network": {
"allowedDomains": [],
"deniedDomains": []
}
}
```
此例只允许写入 `.pi`,禁止读取所列凭证位置,并禁止命令访问网络。请参考 SRT 文档审查适合自己环境的读取权限和域名规则。相对路径以运行器工作目录为基准。配置在启动时读取并保存快照,修改后需要重启。配置缺失或无效、SRT 依赖缺失、沙箱初始化失败都会阻止启动,不会回退到无沙箱执行。
SRT 只包裹 Shell 命令及其子进程。并发命令共享同一个 SRT 运行时,运行器停止时统一清理。运行器 WebSocket 和服务器发起的文件传输在 SRT 外运行。**不会自动将 Shumai 服务器地址添加到允许域名中。** 如果脚本自身需要网络,请在 JSON 中明确允许目标域名。
Shumai 服务器不管理沙箱和域名规则。只有启用沙箱的运行器才初始化 SRT。在 Docker 中使用 SRT 可能需要为专用运行器容器增加命名空间权限,Shumai 服务器不需要这些权限。
## Docker 运行器
普通运行器可在独立容器中执行,无需额外权限或暴露端口:
```bash
docker run --rm --init --name shumai-runner \
--cap-drop ALL --security-opt no-new-privileges \
-e SHUMAI_API_SERVER -e SHUMAI_RUNNER_KEY \
-v shumai-runner-workspace:/workspace -w /workspace \
node:22-bookworm sh -c \
'npm install -g @shumai-one/shumai-cli && exec shumai-cli runner start'
```
本地开发允许 `localhost`、`127.0.0.1`、`[::1]`、Docker 的 `host.docker.internal` HTTP 地址;远程连接必须使用 HTTPS。不要将敏感宿主机目录或 Docker socket 挂载到运行器工作区。
## 限制与生命周期
默认超时 120 秒,最长一小时。超时或取消会尝试终止命令及其子进程。单条命令最多在 `.pi/logs` 保存 64 MiB 输出,请按工作区维护需求清理日志。文件传输和技能解压限制为 256 MiB。协议文件操作拒绝 `.pi` 外路径、已有符号链接及不安全的压缩包条目。V1 假定命令不会在文件传输期间故意修改工作区路径。
临时重连会同步执行中及近期完成的命令,避免主动重复执行。重启运行器进程不会恢复旧进程中的命令。
共享工作区最多同时执行八个命令或文件传输,超出时返回繁忙错误。Windows 未启用 SRT 时,后台进程可能在命令 Shell 退出后继续运行,剩余输出管道会在一秒后关闭。请使用前台命令,以确保超时和取消可预测。启用 SRT 时由 SRT 管理 Windows 沙箱进程树。
![智能体沙箱设置](/sandbox.webp)
+1 -11
View File
@@ -11,7 +11,7 @@ Shumai 支持与未注册工作区账号的外部利益相关者协作。借助*
1. 选中要分享的文件或文件夹,右键单击并选择**创建新分享链接**。
2. 在项目侧边栏中点击刚创建的**分享链接**,进入其配置页面。
3. 在右侧边栏的**设置**选项卡中配置分享链接。
3. 在右侧边栏中配置分享链接参数:
- 添加密码保护
- 设置过期时间
- 开启或禁止文件下载
@@ -33,16 +33,6 @@ Shumai 支持与未注册工作区账号的外部利益相关者协作。借助*
---
## 查看分享活动
在项目侧边栏打开**所有分享链接**,即可看到每条链接的**浏览次数**和**最近浏览**时间。点击对应行的**查看活动**,或在该链接的配置页面切换到**活动**选项卡,即可查看活动记录。
活动按天分组,包括打开分享链接、浏览文件和文件夹、下载以及发表评论。可以识别访客时显示其姓名,匿名活动显示为**有人**。访客开始下载且通过权限验证后,系统会记录下载活动。
每次成功打开分享页面、共享文件夹或共享文件(包括刷新页面)都会增加一次**浏览次数**,并更新**最近浏览**时间。系统根据分享链接、操作、访客和相关资产(如有)判断活动是否重复,30 分钟内的重复活动只显示一次。判断时,所有匿名访客视为同一位访客。例如,同一位访客在十分钟内两次打开同一文件,**浏览次数**会增加两次,活动列表显示一条**浏览了素材**的记录。
---
## 安全与权限配置
### 有效期
+1 -1
View File
@@ -22,7 +22,7 @@ const baseNamingConvention = [
filter: {
// Allow CSS variables, common HTTP headers, library-specific names, paths, and hyphenated/numeric keys
regex:
'^(Authorization|Content-Type|Accept|--.*|string_contains|disableCSRFCheck|X-Frameio-.*|/.*|field-.*|class-name|icon-.*|[0-9]+|@typescript-eslint/.*|Variables|Read|Edit|Admin|Bucket|Key|Body|ContentLength|ContentType|Prefix|ContinuationToken|Signature|Expires|CopySource|Delete|Objects|Quiet|ResponseContentDisposition|UploadId|PartNumber)$',
'^(Authorization|Content-Type|Accept|--.*|string_contains|disableCSRFCheck|X-Frameio-.*|/.*|field-.*|class-name|icon-.*|[0-9]+|@typescript-eslint/.*|Variables|Read|Edit|Admin|Bucket|Key|Body|ContentLength|ContentType|Prefix|ContinuationToken|Signature|CopySource|Delete|Objects|Quiet|ResponseContentDisposition|UploadId|PartNumber)$',
match: false,
},
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "shumai",
"version": "0.7.2",
"version": "0.6.6",
"private": true,
"type": "module",
"repository": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/agent",
"version": "0.7.2",
"version": "0.6.6",
"private": true,
"type": "module",
"main": "./src/index.ts",
-2
View File
@@ -601,7 +601,6 @@ export const createCommentActivity = defineStep(
sessionId?: string | null
agentId?: string | null
replyToId?: string | null
isInternal?: boolean
}) {
if (params.sessionId) {
const agentId = params.agentId && params.agentId !== 'default' ? params.agentId : 'default'
@@ -670,7 +669,6 @@ export const createCommentActivity = defineStep(
sessionId: params.sessionId ?? null,
creatorId: params.agentId && params.agentId !== 'default' ? params.agentId : null,
replyToId: params.replyToId,
isInternal: params.isInternal ?? false,
},
})
},
+121 -334
View File
@@ -1,25 +1,37 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import {
generateTextEmbeddingActivity,
extractAiMetadataActivity,
getEmbeddingContextActivity,
saveAssetEmbeddingsActivity,
deleteAssetEmbeddingsActivity,
generateImageEmbeddingActivity,
generateVideoChunkEmbeddingActivity,
getGemmaEmbeddingTargetFrameCount,
transcodeVideoChunksActivity,
} from './ai'
import { s3Service } from '@shumai/core/src/s3/s3'
import { prisma, AssetType, AssetStatus, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import { transcodeService } from '@shumai/core'
import { prisma, AssetType, AssetStatus } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import {
DBOSError,
registerLocalTaskAbortController,
unregisterLocalTaskAbortController,
workflowService,
} from '@shumai/workflow-core'
import sharp from 'sharp'
vi.mock('fs', async (importOriginal) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- importOriginal returns the raw fs module, typed dynamically as any here
const actual = await importOriginal<any>()
const mockRead = vi.fn((path, options) => {
if (typeof path === 'string' && (path.includes('video-chunk') || path.includes('out1.webp'))) {
return Buffer.from('chunk-data')
}
return actual.readFileSync(path, options)
})
return {
...actual,
writeFileSync: vi.fn(),
readFileSync: mockRead,
unlinkSync: vi.fn(),
}
})
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
getObject: vi.fn(),
@@ -27,11 +39,35 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
headObject: vi.fn(),
listObjects: vi.fn(),
downloadToFile: vi.fn(),
deleteObject: vi.fn(),
resolveInput: vi.fn().mockImplementation(async (_bucket, key) => `https://mock-storage/${key}`),
},
}))
vi.mock('@shumai/core/src/transcode/transcode', () => ({
transcodeService: {
extractVideoFrames: vi.fn(),
createTempDir: vi.fn().mockReturnValue('/tmp'),
removeDir: vi.fn(),
},
}))
vi.mock('child_process', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock functions dynamically return varying types based on test command calls
const execFileMock: any = vi.fn((file: any, args: any, cb: any) => {
cb(null, '120.0\n', '')
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock functions dynamically return varying types based on test command calls
execFileMock[Symbol.for('nodejs.util.promisify.custom')] = vi.fn(async (file: any) => {
if (file === 'ffprobe') {
return { stdout: '120.0\n', stderr: '' }
}
return { stdout: '', stderr: '' }
})
return {
execFile: execFileMock,
}
})
const mockEmbedContent = vi.fn().mockResolvedValue({
embeddings: [
{
@@ -467,6 +503,82 @@ describe('AI Activities Unit Tests', () => {
}),
).rejects.toThrow('is empty (0 bytes)')
})
describe('extractAiMetadataActivity', () => {
it('should return existing images if they are already in S3 storage', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock returned object cast as any due to partial implementation
vi.mocked(s3Service.headObject).mockResolvedValue({} as any)
vi.mocked(s3Service.listObjects).mockResolvedValue([
'project/ai_metadata/1.webp',
'project/ai_metadata/2.webp',
])
const res = await extractAiMetadataActivity({
assetKey: 'project/video.mp4',
filePath: '/tmp/video.mp4',
type: 'autofill',
isImage: false,
})
expect(res).toEqual(['project/ai_metadata/1.webp', 'project/ai_metadata/2.webp'])
expect(s3Service.headObject).toHaveBeenCalledWith('shumai', 'project/ai_metadata/1.webp')
expect(transcodeService.extractVideoFrames).not.toHaveBeenCalled()
})
it('should extract frames and upload to S3 if not already present', async () => {
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not Found'))
vi.mocked(transcodeService.extractVideoFrames).mockResolvedValue(['/tmp/out1.webp'])
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock returned object cast as any due to partial implementation
vi.mocked(s3Service.putObject).mockResolvedValue({} as any)
const res = await extractAiMetadataActivity({
assetKey: 'project/video.mp4',
filePath: '/tmp/video.mp4',
type: 'autofill',
isImage: false,
})
expect(res).toEqual(['project/ai_metadata/out1.webp'])
expect(transcodeService.extractVideoFrames).toHaveBeenCalledWith({
inputFile: '/tmp/video.mp4',
outputDir: '/tmp',
numFrames: 30,
frameHeight: 720,
isImage: false,
})
expect(s3Service.putObject).toHaveBeenCalledWith(
'shumai',
'project/ai_metadata/out1.webp',
expect.any(Buffer),
expect.any(Number),
'image/webp',
)
})
it('should resolveInput from s3Service when filePath is not provided', async () => {
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not Found'))
vi.mocked(s3Service.resolveInput).mockResolvedValue('https://mock-storage/project/video.mp4')
vi.mocked(transcodeService.extractVideoFrames).mockResolvedValue(['/tmp/out1.webp'])
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(s3Service.putObject).mockResolvedValue({} as any)
const res = await extractAiMetadataActivity({
assetKey: 'project/video.mp4',
type: 'autofill',
isImage: false,
})
expect(res).toEqual(['project/ai_metadata/out1.webp'])
expect(s3Service.resolveInput).toHaveBeenCalledWith('shumai', 'project/video.mp4')
expect(transcodeService.extractVideoFrames).toHaveBeenCalledWith({
inputFile: 'https://mock-storage/project/video.mp4',
outputDir: expect.any(String),
numFrames: 30,
frameHeight: 720,
isImage: false,
})
})
})
})
describe('AI Database Activities Integration', () => {
@@ -775,329 +887,4 @@ describe('AI Database Activities Integration', () => {
expect(after).toHaveLength(0)
})
})
describe('transcodeVideoChunksActivity', () => {
afterEach(() => {
delete process.env.EMBEDDING_TRANSCODE_WAIT_TIMEOUT_MS
})
it('should create a transcode_video_chunks WorkflowTask and await completion', async () => {
const waitForSpy = vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => ({
done: true,
task: {
...task,
status: WorkflowTaskStatus.completed,
output: {
chunks: [
{
startTime: 0,
endTime: 60,
chunkKey: `files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
},
],
},
},
}))
const res = await transcodeVideoChunksActivity({
parentTaskId: 'parent-123',
teamId: team.id,
projectId: 'proj-123',
assetId: asset.id,
assetKey: 'media/video.mp4',
format: 'video',
chunks: [{ startTime: 0, endTime: 60 }],
})
expect(res.chunks).toEqual([
{
startTime: 0,
endTime: 60,
chunkKey: `files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
},
])
expect(waitForSpy).toHaveBeenCalledTimes(1)
expect(waitForSpy).toHaveBeenCalledWith(
expect.objectContaining({
assetId: asset.id,
type: WorkflowTaskType.transcode_video_chunks,
}),
60 * 60 * 1000,
)
const createdTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode_video_chunks },
})
expect(createdTask).toBeDefined()
expect(createdTask?.payload?.videoChunks).toEqual({
parentTaskId: 'parent-123',
assetKey: 'media/video.mp4',
format: 'video',
chunks: [{ startTime: 0, endTime: 60 }],
})
})
it('should honor custom EMBEDDING_TRANSCODE_WAIT_TIMEOUT_MS env var', async () => {
process.env.EMBEDDING_TRANSCODE_WAIT_TIMEOUT_MS = '12345'
const waitForSpy = vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => ({
done: true,
task: {
...task,
status: WorkflowTaskStatus.completed,
output: {
chunks: [
{
startTime: 0,
endTime: 60,
chunkKey: `files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
},
],
},
},
}))
await transcodeVideoChunksActivity({
parentTaskId: 'parent-timeout-env',
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
})
expect(waitForSpy).toHaveBeenCalledWith(expect.anything(), 12345)
})
it('should reuse an existing transcode_video_chunks task with the same parentTaskId on retry', async () => {
const existingChild = await prisma.workflowTask.create({
data: {
assetId: asset.id,
teamId: team.id,
type: WorkflowTaskType.transcode_video_chunks,
status: WorkflowTaskStatus.processing,
payload: {
projectId: '',
videoChunks: {
parentTaskId: 'parent-retry-1',
assetKey: 'media/video.mp4',
format: 'video',
chunks: [{ startTime: 0, endTime: 60 }],
},
},
},
})
const waitForSpy = vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => ({
done: true,
task: {
...task,
status: WorkflowTaskStatus.completed,
output: {
chunks: [
{
startTime: 0,
endTime: 60,
chunkKey: `files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
},
],
},
},
}))
await transcodeVideoChunksActivity({
parentTaskId: 'parent-retry-1',
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
format: 'video',
chunks: [{ startTime: 0, endTime: 60 }],
})
expect(waitForSpy).toHaveBeenCalledWith(
expect.objectContaining({ id: existingChild.id }),
expect.any(Number),
)
const count = await prisma.workflowTask.count({
where: { assetId: asset.id, type: WorkflowTaskType.transcode_video_chunks },
})
expect(count).toBe(1)
})
it('should return empty chunks immediately when chunks array is empty', async () => {
const waitForSpy = vi.spyOn(workflowService, 'waitFor')
const res = await transcodeVideoChunksActivity({
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [],
})
expect(res.chunks).toEqual([])
expect(waitForSpy).not.toHaveBeenCalled()
})
it('should throw non-retryable ApplicationFailure when assetKey is empty', async () => {
await expect(
transcodeVideoChunksActivity({
assetId: asset.id,
assetKey: '',
chunks: [{ startTime: 0, endTime: 60 }],
}),
).rejects.toThrow('assetKey is required for video chunks transcoding')
})
it('should wrap child task failure as non-retryable ApplicationFailure to avoid duplicate child tasks', async () => {
vi.spyOn(workflowService, 'waitFor').mockRejectedValue(
new Error(
'Original video file is archived and no proxy is available. Restore the asset to generate embeddings.',
),
)
expect.assertions(2)
try {
await transcodeVideoChunksActivity({
parentTaskId: 'parent-child-fail',
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
})
} catch (err: unknown) {
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
expect((err as Error).message).toContain('Original video file is archived')
}
})
it('should cancel child task and throw non-retryable ApplicationFailure on timeout', async () => {
const cancelSpy = vi.spyOn(workflowService, 'cancel').mockResolvedValue(undefined)
vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => ({
done: false,
task,
}))
expect.assertions(4)
try {
await transcodeVideoChunksActivity({
parentTaskId: 'parent-timeout-fail',
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
})
} catch (err: unknown) {
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
expect((err as Error).message).toContain('timed out')
}
const childTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode_video_chunks },
})
expect(cancelSpy).toHaveBeenCalledWith(childTask!.id)
expect(childTask?.status).toBe(WorkflowTaskStatus.failed)
})
it('should throw non-retryable ApplicationFailure when completed child task has invalid chunks output', async () => {
vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => ({
done: true,
task: {
...task,
status: WorkflowTaskStatus.completed,
output: {},
},
}))
expect.assertions(2)
try {
await transcodeVideoChunksActivity({
parentTaskId: 'parent-invalid-output',
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
})
} catch (err: unknown) {
expect((err as { nonRetryable?: boolean }).nonRetryable).toBe(true)
expect((err as Error).message).toContain('completed without valid chunks output')
}
})
it('should cancel child transcode_video_chunks task when parent workflow is cancelled', async () => {
const parentTaskId = 'parent-cancel-test'
const abortController = new AbortController()
registerLocalTaskAbortController(parentTaskId, abortController)
const cancelSpy = vi.spyOn(workflowService, 'cancel').mockResolvedValue(undefined)
vi.spyOn(workflowService, 'waitFor').mockImplementation(async () => {
abortController.abort()
throw new DBOSError.DBOSWorkflowCancelledError(parentTaskId)
})
try {
await expect(
transcodeVideoChunksActivity({
parentTaskId,
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
}),
).rejects.toThrow()
const childTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode_video_chunks },
})
expect(childTask).toBeDefined()
expect(cancelSpy).toHaveBeenCalledWith(childTask!.id)
expect(childTask?.status).toBe(WorkflowTaskStatus.failed)
} finally {
unregisterLocalTaskAbortController(parentTaskId)
}
})
it('should clean up uploaded chunks from S3 if parent workflow is cancelled just as child completes', async () => {
const parentTaskId = 'parent-cancel-race'
const abortController = new AbortController()
registerLocalTaskAbortController(parentTaskId, abortController)
vi.spyOn(workflowService, 'cancel').mockResolvedValue(undefined)
vi.spyOn(workflowService, 'waitFor').mockImplementation(async (task) => {
abortController.abort()
return {
done: true,
task: {
...task,
status: WorkflowTaskStatus.completed,
output: {
chunks: [
{
startTime: 0,
endTime: 60,
chunkKey: `files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
},
],
},
},
}
})
try {
await expect(
transcodeVideoChunksActivity({
parentTaskId,
teamId: team.id,
assetId: asset.id,
assetKey: 'media/video.mp4',
chunks: [{ startTime: 0, endTime: 60 }],
}),
).rejects.toThrow('Parent embedding workflow was cancelled before transcode completed')
expect(s3Service.deleteObject).toHaveBeenCalledWith(
'shumai',
`files/${asset.id}/tmp-embedding-chunks/chunk-0-60.mp4`,
)
} finally {
unregisterLocalTaskAbortController(parentTaskId)
}
})
})
})
+215 -165
View File
@@ -1,16 +1,18 @@
import { GoogleGenAI } from '@google/genai'
import { s3Service } from '@shumai/core/src/s3/s3'
import { textEmbeddingService } from '@shumai/core/src/search/text-embedding'
import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import {
ApplicationFailure,
defineStep,
getLocalTaskAbortSignal,
isDbosWorkflowCancelledError,
workflowService,
} from '@shumai/workflow-core'
import { transcodeService } from '@shumai/core'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import { execFile } from 'child_process'
import { promisify } from 'util'
import { ulid } from 'ulid'
import { ApplicationFailure, defineStep } from '@shumai/workflow-core'
import { prisma } from '@shumai/db'
import sharp from 'sharp'
const execFileAsync = promisify(execFile)
export interface Usage {
inputTokens: number
outputTokens: number
@@ -109,6 +111,8 @@ async function callGemmaEmbeddingServer(input: string | OpenAiEmbeddingItem[]):
}
}
import { textEmbeddingService } from '@shumai/core/src/search/text-embedding'
export interface GenerateTextEmbeddingParams {
text: string
teamId: string
@@ -153,6 +157,66 @@ export const generateTextEmbeddingActivity = defineStep(
},
)
export interface ExtractAiMetadataParams {
assetKey: string
filePath?: string
type: 'autofill'
isImage: boolean
}
export const extractAiMetadataActivity = defineStep(async function extractAiMetadataActivity(
params: ExtractAiMetadataParams,
): Promise<string[]> {
const bucket = process.env.S3_BUCKET || 'shumai'
const assetDir = path.dirname(params.assetKey)
const aiDir = path.join(assetDir, 'ai_metadata')
const generatedFiles: string[] = []
let tmpDir = params.filePath ? path.dirname(params.filePath) : ''
let cleanupTmp = false
if (!tmpDir) {
tmpDir = transcodeService.createTempDir('ai-meta-')
cleanupTmp = true
}
try {
if (params.type === 'autofill') {
const targetKey = path.join(aiDir, '1.webp')
try {
await s3Service.headObject(bucket, targetKey)
const keys = await s3Service.listObjects(bucket, aiDir)
return keys.filter((k) => k.toLowerCase().endsWith('.webp'))
} catch {
// Not found
}
const inputSource = params.filePath || (await s3Service.resolveInput(bucket, params.assetKey))
const files = await transcodeService.extractVideoFrames({
inputFile: inputSource,
outputDir: tmpDir,
numFrames: 30,
frameHeight: 720,
isImage: params.isImage,
})
for (const file of files) {
const name = path.basename(file)
const buffer = fs.readFileSync(file)
const key = path.join(aiDir, name)
await s3Service.putObject(bucket, key, buffer, buffer.length, 'image/webp')
generatedFiles.push(key)
}
}
} finally {
if (cleanupTmp && tmpDir) {
transcodeService.removeDir(tmpDir)
}
}
return generatedFiles
})
export const getEmbeddingContextActivity = defineStep(
async function getEmbeddingContextActivity(params: { teamId: string; assetId: string }) {
const team = await prisma.team.findUnique({
@@ -251,7 +315,6 @@ export const saveAssetEmbeddingsActivity = defineStep(
embedding: number[]
startTime?: number
endTime?: number
sprite?: PrismaJson.VideoChunkSprite
}>
}) {
for (const item of params.embeddings) {
@@ -259,16 +322,15 @@ export const saveAssetEmbeddingsActivity = defineStep(
const is768 = item.embedding.length === 768
if (item.startTime !== undefined && item.endTime !== undefined) {
const sprite = item.sprite ? JSON.stringify(item.sprite) : null
if (is768) {
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding_768, start_time, end_time, sprite, updated_at)
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, ${sprite}::jsonb, NOW())
INSERT INTO asset_embeddings (id, asset_id, embedding_768, start_time, end_time, updated_at)
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, NOW())
`
} else {
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, sprite, updated_at)
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, ${sprite}::jsonb, NOW())
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, updated_at)
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, NOW())
`
}
} else {
@@ -507,180 +569,168 @@ export const generateVideoChunkEmbeddingActivity = defineStep(
},
)
export interface VideoChunkRange {
export interface TranscodeVideoChunkParams {
assetId: string
assetKey?: string
filePath?: string
startTime: number
endTime: number
}
export interface TranscodedVideoChunk extends VideoChunkRange {
chunkKey: string
sprite?: PrismaJson.VideoChunkSprite
}
export interface TranscodeVideoChunksParams {
parentTaskId?: string
teamId?: string | null
projectId?: string | null
assetId: string
assetKey: string
format?: 'video' | 'frames'
chunks: VideoChunkRange[]
}
const DEFAULT_TRANSCODE_WAIT_TIMEOUT_MS = 60 * 60 * 1000 // 60 minutes
function getTranscodeWaitTimeoutMs(): number {
const parsed = parseInt(process.env.EMBEDDING_TRANSCODE_WAIT_TIMEOUT_MS || '', 10)
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_TRANSCODE_WAIT_TIMEOUT_MS
}
async function cancelChildTranscodeTask(childTaskId: string): Promise<void> {
try {
await workflowService.cancel(childTaskId)
} catch {
// Ignore DBOS cancel errors during cleanup
}
try {
await prisma.workflowTask.updateMany({
where: {
id: childTaskId,
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
data: {
status: WorkflowTaskStatus.failed,
output: { error: 'Parent embedding workflow was cancelled' },
},
})
} catch {
// Ignore DB update errors during cleanup
}
}
export const transcodeVideoChunksActivity = defineStep(async function transcodeVideoChunksActivity(
params: TranscodeVideoChunksParams,
): Promise<{ chunks: TranscodedVideoChunk[] }> {
if (!params.assetKey) {
export const transcodeVideoChunkActivity = defineStep(async function transcodeVideoChunkActivity(
params: TranscodeVideoChunkParams,
): Promise<{ chunkKey: string }> {
if (!params.filePath && !params.assetKey) {
throw ApplicationFailure.create({
message: 'assetKey is required for video chunks transcoding',
message: 'Neither filePath nor assetKey was provided for video chunk transcoding',
nonRetryable: true,
})
}
if (!params.chunks || params.chunks.length === 0) {
return { chunks: [] }
}
let childTask = null
if (params.parentTaskId) {
childTask = await prisma.workflowTask.findFirst({
where: {
assetId: params.assetId,
type: WorkflowTaskType.transcode_video_chunks,
status: {
in: [
WorkflowTaskStatus.pending,
WorkflowTaskStatus.processing,
WorkflowTaskStatus.completed,
],
},
payload: {
path: ['videoChunks', 'parentTaskId'],
equals: params.parentTaskId,
},
},
orderBy: { id: 'desc' },
})
}
if (!childTask) {
childTask = await prisma.workflowTask.create({
data: {
assetId: params.assetId,
teamId: params.teamId ?? null,
projectId: params.projectId ?? null,
type: WorkflowTaskType.transcode_video_chunks,
status: WorkflowTaskStatus.pending,
payload: {
projectId: params.projectId ?? '',
videoChunks: {
parentTaskId: params.parentTaskId,
assetKey: params.assetKey,
format: params.format,
chunks: params.chunks,
},
},
},
})
}
const abortSignal = getLocalTaskAbortSignal(params.parentTaskId)
if (abortSignal?.aborted) {
await cancelChildTranscodeTask(childTask.id)
throw ApplicationFailure.create({
message: 'Parent embedding workflow was cancelled before transcode completed',
nonRetryable: true,
})
}
const onAbort = () => {
void cancelChildTranscodeTask(childTask.id)
}
abortSignal?.addEventListener('abort', onAbort, { once: true })
try {
const { task: completedTask, done } = await workflowService.waitFor(
childTask,
getTranscodeWaitTimeoutMs(),
)
if (!done) {
await cancelChildTranscodeTask(childTask.id)
throw ApplicationFailure.create({
message: `Transcode video chunks task ${childTask.id} timed out`,
nonRetryable: true,
})
}
const output = completedTask.output as { chunks?: TranscodedVideoChunk[] } | null
if (!output?.chunks || !Array.isArray(output.chunks)) {
throw ApplicationFailure.create({
message: `Transcode video chunks task ${childTask.id} completed without valid chunks output`,
nonRetryable: true,
})
}
if (abortSignal?.aborted) {
if (params.format === 'frames') {
const tmpDir = transcodeService.createTempDir('video-chunk-frames-')
try {
const bucket = process.env.S3_BUCKET || 'shumai'
for (const chunk of output.chunks) {
try {
await s3Service.deleteObject(bucket, chunk.chunkKey)
} catch {
// Best-effort cleanup on cancellation race
}
const inputSource =
params.filePath ||
(params.assetKey ? await s3Service.resolveInput(bucket, params.assetKey) : '')
if (!inputSource) {
throw ApplicationFailure.create({
message: 'Neither filePath nor assetKey was provided for video chunk transcoding',
nonRetryable: true,
})
}
const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://')
const duration = Math.max(0.1, params.endTime - params.startTime)
const fpsFilter = duration > 16 ? `fps=${16 / duration}` : 'fps=1'
const vframesArgs = duration > 16 ? ['-vframes', '16'] : []
await execFileAsync('ffmpeg', [
'-y',
'-loglevel',
'warning',
...(isRemote
? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5']
: []),
'-ss',
params.startTime.toString(),
'-i',
inputSource,
'-map',
'0:V:0',
'-t',
duration.toString(),
'-vf',
fpsFilter,
...vframesArgs,
'-q:v',
'2',
path.join(tmpDir, 'frame_%04d.jpg'),
])
const frameFiles = fs
.readdirSync(tmpDir)
.filter((f) => /\.(jpe?g|png|webp)$/i.test(f))
.sort()
const archiveEntries: Record<string, Buffer> = {}
for (const file of frameFiles) {
archiveEntries[file] = fs.readFileSync(path.join(tmpDir, file))
}
const archive = new Bun.Archive(archiveEntries)
const archiveBytes = await archive.bytes()
const archiveData = Buffer.from(
archiveBytes.buffer,
archiveBytes.byteOffset,
archiveBytes.byteLength,
)
const key = `files/${params.assetId}/tmp-embedding-chunks/frames-${params.startTime}-${params.endTime}-${ulid()}.tar`
await s3Service.putObject(bucket, key, archiveData, archiveData.length, 'application/x-tar')
return { chunkKey: key }
} catch (err) {
if (err instanceof ApplicationFailure) {
throw err
}
throw ApplicationFailure.create({
message: 'Parent embedding workflow was cancelled before transcode completed',
message: `Failed to extract video chunk frames for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
nonRetryable: false,
})
} finally {
transcodeService.removeDir(tmpDir)
}
}
const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}-${ulid()}.mp4`)
try {
const bucket = process.env.S3_BUCKET || 'shumai'
const inputSource =
params.filePath ||
(params.assetKey ? await s3Service.resolveInput(bucket, params.assetKey) : '')
if (!inputSource) {
throw ApplicationFailure.create({
message: 'Neither filePath nor assetKey was provided for video chunk transcoding',
nonRetryable: true,
})
}
const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://')
return { chunks: output.chunks }
// Slice video segment using ffmpeg, force 1fps and remove audio for gemini-embedding-2 optimization
// Note: -ss placed before -i for fast input seeking via demuxer Range requests
await execFileAsync('ffmpeg', [
'-y',
'-loglevel',
'warning',
...(isRemote
? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5']
: []),
'-ss',
params.startTime.toString(),
'-i',
inputSource,
'-map',
'0:V:0',
'-t',
(params.endTime - params.startTime).toString(),
'-vf',
'fps=1',
'-c:v',
'libx264',
'-preset',
'ultrafast',
'-crf',
'28',
'-an',
chunkTmp,
])
const chunkData = fs.readFileSync(chunkTmp)
// Upload to S3
const key = `files/${params.assetId}/tmp-embedding-chunks/chunk-${params.startTime}-${params.endTime}-${ulid()}.mp4`
await s3Service.putObject(bucket, key, chunkData, chunkData.length, 'video/mp4')
return { chunkKey: key }
} catch (err) {
if (abortSignal?.aborted || isDbosWorkflowCancelledError(err)) {
await cancelChildTranscodeTask(childTask.id)
throw err
}
if (err instanceof ApplicationFailure) {
throw err
}
// The child transcode workflow already applies its own step retry policy;
// fail fast here instead of spawning duplicate child tasks on parent retries.
throw ApplicationFailure.create({
message: err instanceof Error ? err.message : String(err),
nonRetryable: true,
cause: err instanceof Error ? err : undefined,
message: `Failed to transcode video chunk for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
nonRetryable: false,
})
} finally {
abortSignal?.removeEventListener('abort', onAbort)
if (fs.existsSync(chunkTmp)) {
try {
fs.unlinkSync(chunkTmp)
} catch (e) {
console.error('Failed to cleanup local chunk file:', e)
}
}
}
})
@@ -5,7 +5,7 @@ import { setupTestDbHooks } from '@shumai/db/test'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createAgentSession, type DbProviderInfo } from './index'
import { closeAgentSessions } from './runtime'
import { createRunnerBashTool } from './tools/runner-bash'
import { createSandboxedBashTool } from './tools/sandboxed-bash'
const mockProviders: DbProviderInfo[] = [
{
@@ -43,19 +43,6 @@ function createMockWs() {
}
}
function reconcile(runnerId: string, ws: RunnerSocket) {
runnerService.handleMessage(
runnerId,
ws,
JSON.stringify({
type: 'reconcile',
environment: { platform: 'linux', shell: '/bin/sh' },
activeExecutions: [],
completedExecutions: [],
}),
)
}
describe('Concurrent Runner Sessions', () => {
setupTestDbHooks()
@@ -77,7 +64,6 @@ describe('Concurrent Runner Sessions', () => {
{ id: runner.id, teamId: team.id, name: runner.name, keyHash: hashRunnerKey(key) },
conn.ws,
)
reconcile(runner.id, conn.ws)
await prisma.user.create({
data: {
@@ -106,17 +92,19 @@ describe('Concurrent Runner Sessions', () => {
providers: mockProviders,
})
const tool = createRunnerBashTool({}, { teamId: team.id })
const tool = createSandboxedBashTool('/mock/cwd', {}, { teamId: team.id })
// Note: registerConnection sends a 'welcome' message first (conn.sent[0])
const execA = invokeTool(tool, 'call-a', {
command: 'echo session-a',
source: 'skill',
})
await vi.waitFor(() => expect(conn.sent.length).toBe(2))
const msgA = JSON.parse(conn.sent[1])
const execB = invokeTool(tool, 'call-b', {
command: 'echo session-b',
source: 'skill',
})
await vi.waitFor(() => expect(conn.sent.length).toBe(3))
const msgB = JSON.parse(conn.sent[2])
@@ -172,12 +160,10 @@ describe('Concurrent Runner Sessions', () => {
)
const [resA, resB] = await Promise.all([execA, execB])
expect(resA.content).toContainEqual(
expect.objectContaining({ text: expect.stringContaining('out-a') }),
)
expect(resB.content).toContainEqual(
expect.objectContaining({ text: expect.stringContaining('out-b') }),
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ToolResponse content blocks
expect((resA as any).content[0].text).toContain('out-a')
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ToolResponse content blocks
expect((resB as any).content[0].text).toContain('out-b')
runnerService.handleDisconnect(runner.id, conn.ws)
})
@@ -215,17 +201,17 @@ describe('Concurrent Runner Sessions', () => {
},
gpuConn.ws,
)
reconcile(defaultRunner.id, defaultConn.ws)
reconcile(gpuRunner.id, gpuConn.ws)
const defaultTool = createRunnerBashTool(
const defaultTool = createSandboxedBashTool(
'/mock/cwd',
{},
{
teamId: team.id,
agentRunnerId: null,
},
)
const gpuTool = createRunnerBashTool(
const gpuTool = createSandboxedBashTool(
'/mock/cwd',
{},
{
teamId: team.id,
@@ -233,8 +219,8 @@ describe('Concurrent Runner Sessions', () => {
},
)
const pDefault = invokeTool(defaultTool, '1', { command: 'uname -a' })
const pGpu = invokeTool(gpuTool, '2', { command: 'nvidia-smi' })
const pDefault = invokeTool(defaultTool, '1', { command: 'uname -a', source: 'user' })
const pGpu = invokeTool(gpuTool, '2', { command: 'nvidia-smi', source: 'user' })
await vi.waitFor(() => {
expect(defaultConn.lastSentJson()?.type).toBe('exec.start')
+26 -12
View File
@@ -10,6 +10,7 @@ import { type TSchema } from 'typebox'
import { Value } from 'typebox/value'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
buildRestrictedUserInstructions,
createAgentSession,
formatSkillsForPrompt,
getModelFromDb,
@@ -170,7 +171,20 @@ describe('Runner tool availability & skill staging integration', () => {
})
})
describe('createAgentSession runner bash policy', () => {
describe('buildRestrictedUserInstructions', () => {
it('should describe the restricted user bash rules', () => {
const instructions = buildRestrictedUserInstructions()
expect(instructions).toContain('# Restricted User Context')
expect(instructions).toContain(
'NEVER execute a bash command that the user asks you to run directly',
)
expect(instructions).toContain('loaded via the `read_skill` tool')
expect(instructions).toContain('parameter to "skill"')
expect(instructions).toContain('source="user" will be rejected')
})
})
describe('createAgentSession bash restriction for non-owner users', () => {
setupTestDbHooks()
afterEach(() => {
@@ -248,21 +262,21 @@ describe('createAgentSession runner bash policy', () => {
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(true)
})
it('does not use skill history as authorization for a session', async () => {
it('should treat a user who is not a team member as restricted (fail-closed)', async () => {
const { harness } = await setupSession({ role: 'non-member' })
const tools = await getAgentTools(harness)
expect(tools.some((t) => t.name === 'bash')).toBe(true)
expect(tools.some((t) => t.name === 'bash')).toBe(false)
expect(tools.some((t) => t.name === 'read_skill')).toBe(true)
const prompt = await await getAgentPrompt(harness)
expect(prompt).not.toContain('# Restricted User Context')
expect(prompt).toContain('# Restricted User Context')
})
it.each(['editor', 'reviewer'] as const)(
'exposes bash immediately for %s users without reading a skill',
'should exclude the bash tool initially for %s users',
async (role) => {
const { harness } = await setupSession({ role })
const tools = await getAgentTools(harness)
expect(tools.some((t) => t.name === 'bash')).toBe(true)
expect(tools.some((t) => t.name === 'bash')).toBe(false)
expect(tools.some((t) => t.name === 'read_skill')).toBe(true)
},
)
@@ -332,7 +346,7 @@ describe('createAgentSession runner bash policy', () => {
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(true)
})
it('keeps bash available before and after reading a skill', async () => {
it('should inject the bash tool after a skill is loaded via read_skill for restricted users', async () => {
const { team, harness } = await setupSession({ role: 'reviewer' })
const skill = await prisma.skill.create({
data: { name: 'Inject Skill', assetId: 'asset1', hash: 'inject-hash', teamId: team.id },
@@ -342,14 +356,14 @@ describe('createAgentSession runner bash policy', () => {
const readSkillTool = (await getAgentTools(harness)).find((t) => t.name === 'read_skill')
expect(readSkillTool).toBeDefined()
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(true)
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(false)
await invokeTool(readSkillTool!, '1', { skillId: skill.id }, undefined, undefined)
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(true)
})
it('keeps bash disabled by agent policy after reading a skill', async () => {
it('should not inject the bash tool for restricted users when bash is in deniedTools', async () => {
const { team, harness } = await setupSession({ role: 'editor', deniedTools: ['bash'] })
const skill = await prisma.skill.create({
data: { name: 'Denied Skill', assetId: 'asset1', hash: 'denied-hash', teamId: team.id },
@@ -365,11 +379,11 @@ describe('createAgentSession runner bash policy', () => {
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(false)
})
it('omits skill-first bash instructions for editors', async () => {
it('should include restricted user instructions in the system prompt for non-owners', async () => {
const { harness } = await setupSession({ role: 'editor' })
const prompt = await await getAgentPrompt(harness)
expect(prompt).not.toContain('# Restricted User Context')
expect(prompt).not.toContain('source="user" will be rejected')
expect(prompt).toContain('# Restricted User Context')
expect(prompt).toContain('source="user" will be rejected')
})
it('should not include restricted user instructions in the system prompt for owners', async () => {
+2 -4
View File
@@ -13,17 +13,15 @@ export function initAgentWorkflows() {
export * from './activities/agent'
export {
deleteAssetEmbeddingsActivity,
extractAiMetadataActivity,
generateImageEmbeddingActivity,
generateTextEmbeddingActivity,
generateVideoChunkEmbeddingActivity,
saveAssetEmbeddingsActivity,
transcodeVideoChunksActivity,
type ExistingAssetEmbeddingInfo,
type ExtractAiMetadataParams,
type GeneratedEmbedding,
type GenerateTextEmbeddingParams,
type TranscodedVideoChunk,
type TranscodeVideoChunksParams,
type VideoChunkRange,
} from './activities/ai'
export * from './context/serialize-context'
export * from './operation-tools'
@@ -29,7 +29,7 @@ async function resolveTargetRunnerId(ctx: AgentOperationContext): Promise<string
if (ctx.runnerId && !ctx.teamId) {
if (!runnerService.isRunnerConnected(ctx.runnerId)) {
throw new Error(
'Runner is currently offline. Please start your runner with "shumai-cli runner start" and try again.',
'Runner is currently offline. Please start your runner with "shumai runner start" and try again.',
)
}
return ctx.runnerId
@@ -68,7 +68,7 @@ async function resolveTargetRunnerId(ctx?: AgentOperationContext): Promise<strin
if (ctx?.runnerId && !ctx.teamId) {
if (!runnerService.isRunnerConnected(ctx.runnerId)) {
throw new Error(
'Runner is currently offline. Please start your runner with "shumai-cli runner start" and try again.',
'Runner is currently offline. Please start your runner with "shumai runner start" and try again.',
)
}
return ctx.runnerId
+46 -6
View File
@@ -44,7 +44,7 @@ import { createGenerateImageTool } from './tools/generate-image'
import { createGenerateVideoTool } from './tools/generate-video'
import { createReadSkillTool } from './tools/read-skill'
import { createReadThreadTool } from './tools/read-thread'
import { createRunnerBashTool, type LoadedSkillRef } from './tools/runner-bash'
import { createSandboxedBashTool, type LoadedSkillRef } from './tools/sandboxed-bash'
const activeHarnesses = new Set<Harness>()
@@ -152,6 +152,21 @@ export interface CreateAgentSessionParams {
baseDelayMs?: number
}
/**
* Security instructions appended to the system prompt when the requesting user is not a team
* owner (i.e. editor/reviewer). These complement the hard enforcement in the bash tool itself
* (source="user" is blocked) and the delayed bash tool injection after a skill is loaded.
*/
export function buildRestrictedUserInstructions(): string {
return [
'# Restricted User Context',
'The current user is NOT a team owner. You must follow these security rules:',
'1. NEVER execute a bash command that the user asks you to run directly. Direct user bash requests are not permitted for this user role. Politely decline and explain that they need a team owner or an approved skill.',
'2. You may ONLY use the `bash` tool to execute commands that are explicitly required by a skill you have loaded via the `read_skill` tool.',
'3. When calling `bash`, you MUST set the `source` parameter to "skill". Calls with source="user" will be rejected by the system.',
].join('\n')
}
export async function createAgentSession(params: CreateAgentSessionParams) {
const {
teamId,
@@ -188,6 +203,8 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
getModelFromDb(params.providers, providerName, modelId)
const role = userId ? await resolveEffectiveRole(teamId, projectId, userId) : undefined
const isOwner = !userId || role === 'owner'
const restricted = !isOwner
const wrapToolWithQuota = (tool: AgentTool): AgentTool => {
const originalExecute = tool.execute
@@ -245,6 +262,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
const loadedSkills = new Map<string, LoadedSkillRef>()
// Restore env variables and loaded skill refs from previously loaded skills in this session
let skillLoadedInSession = false
if (sessionId) {
try {
const entries = await agentSessionService.getEntries(record.id)
@@ -263,6 +281,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
'skillId' in details &&
typeof details.skillId === 'string'
) {
skillLoadedInSession = true
onEnvsAdded(await agentService.getSkillEnvs(details.skillId))
const dbSkill = await prisma.skill.findUnique({
where: { id: details.skillId },
@@ -316,18 +335,23 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
}
}
const runnerBash = createRunnerBashTool(skillEnvs, {
const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs, {
teamId,
agentRunnerId: agent?.runnerId,
environment: resolvedRunner.runner
? runnerService.getRunnerEnvironment(resolvedRunner.runner.id)
: undefined,
userId,
role,
// Non-owner users can only run bash commands required by a loaded skill
restrictedUser: restricted,
getLoadedSkills: () => loadedSkills.values(),
})
// When a team has no Runner configured in DB, bash and download_asset are omitted.
// For non-owner users, the bash tool is not injected initially. It becomes available
// only after a skill is successfully loaded via the read_skill tool (or immediately when
// a skill was already loaded earlier in this session).
const registry = createRegistry()
const bashIncludedFromStart = hasRunner && (isOwner || skillLoadedInSession)
let bashInjected = bashIncludedFromStart
const onSkillLoaded = async (skill: LoadedSkillRef) => {
loadedSkills.set(skill.id, skill)
if (resolvedRunner.runner && runnerService.isRunnerConnected(resolvedRunner.runner.id)) {
@@ -338,6 +362,18 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
)
})
}
if (!restricted || !hasRunner || bashInjected || deniedTools.includes('bash')) return
bashInjected = true
registry.install(
defineExtension({ name: 'shumai.bash', tools: [wrapToolWithQuota(sandboxedBash)] }),
)
await session?.configure(
{
tools: [...enabledTools, wrapToolWithQuota(sandboxedBash)],
modelTools: { add: [sandboxedBash] },
},
piContext,
)
}
const readSkill = createReadSkillTool(
userId,
@@ -368,7 +404,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
...mediaTools,
readSkill,
readThread,
...(hasRunner ? [runnerBash] : []),
...(bashIncludedFromStart ? [sandboxedBash] : []),
...systemTools,
...customTools,
]
@@ -436,6 +472,10 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
return prompt
}
if (restricted) {
prompt += `\n\n${buildRestrictedUserInstructions()}`
}
if (hasRunner && !deniedTools.includes('bash')) {
prompt +=
'\n\n' +
+1 -1
View File
@@ -67,7 +67,7 @@ export const createReadSkillTool = (
// Retrieve skill content using agentService
const skillMdContent = await agentService.getSkillContent(params.skillId)
// Notify that a skill was successfully loaded (e.g. to stage the skill on the runner)
// Notify that a skill was successfully loaded (e.g. to enable restricted tools and stage skill on runner)
await onSkillLoaded?.({ id: skill.id, assetId: skill.assetId, hash: skill.hash })
return {
@@ -1,7 +1,8 @@
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { runnerService } from '@shumai/core/src/runner'
import { EventEmitter } from 'node:events'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createRunnerBashTool } from './runner-bash'
import { createSandboxedBashTool } from './sandboxed-bash'
vi.mock('@shumai/core/src/runner', () => ({
runnerService: {
@@ -13,7 +14,8 @@ vi.mock('@shumai/core/src/runner', () => ({
},
}))
describe('createRunnerBashTool', () => {
describe('createSandboxedBashTool', () => {
const mockCwd = '/mock/cwd'
const mockTeamId = 'team-1'
const mockRunner = {
id: 'runner-1',
@@ -36,22 +38,24 @@ describe('createRunnerBashTool', () => {
)
})
const createMockSignal = () => new AbortController().signal
const createMockSignal = () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- signal needs to be partially compatible with AbortSignal
const signal = new EventEmitter() as any
signal.addEventListener = vi.fn((event: string, cb: (ev: Event) => unknown) => {
signal.on(event, cb)
})
signal.removeEventListener = vi.fn((event: string, cb: (ev: Event) => unknown) => {
signal.off(event, cb)
})
signal.aborted = false
return signal
}
const createMockOnUpdate = () => vi.fn()
it.each(['C:\\Windows\\System32\\cmd.exe', 'C:\\Program Files\\Git\\bin\\bash.exe'])(
'tells the agent to use the runner OS and shell syntax for %s',
(shell) => {
const tool = createRunnerBashTool({}, { environment: { platform: 'win32', shell } })
expect(tool.description).toContain('Runner OS: win32')
expect(tool.description).toContain(shell)
expect(tool.description).toContain('Use syntax and programs compatible with this environment')
},
)
it('should execute a command on the runner with injected env vars', async () => {
const tool = createRunnerBashTool(
const tool = createSandboxedBashTool(
mockCwd,
{ TEST_ENV: 'test-value' },
{
teamId: mockTeamId,
@@ -74,7 +78,13 @@ describe('createRunnerBashTool', () => {
const onUpdate = createMockOnUpdate()
const signal = createMockSignal()
const result = await invokeTool(tool, '1', { command: 'echo hello' }, signal, onUpdate)
const result = await invokeTool(
tool,
'1',
{ command: 'echo hello', source: 'user' },
signal,
onUpdate,
)
expect(runnerService.requireOnlineRunner).toHaveBeenCalledWith(mockTeamId, null)
expect(runnerService.exec).toHaveBeenCalledWith(
@@ -85,15 +95,15 @@ describe('createRunnerBashTool', () => {
collectOutput: false,
}),
)
expect(result.content).toContainEqual(
expect.objectContaining({ text: expect.stringContaining('hello output') }),
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ToolResponse content is an array of content blocks
expect((result as any).content[0].text).toContain('hello output')
expect(onUpdate).toHaveBeenCalled()
})
it('should stage loaded skills and inputFiles before executing', async () => {
const loadedSkills = [{ id: 'skill-1', assetId: 'asset-1', hash: 'hash-1' }]
const tool = createRunnerBashTool(
const tool = createSandboxedBashTool(
mockCwd,
{},
{
teamId: mockTeamId,
@@ -116,6 +126,7 @@ describe('createRunnerBashTool', () => {
'1',
{
command: 'ffmpeg -i .pi/generated/gen1/input.png out.mp4',
source: 'user',
inputFiles: ['.pi/generated/gen1/input.png'],
},
createMockSignal(),
@@ -129,12 +140,31 @@ describe('createRunnerBashTool', () => {
)
})
it('allows editor commands without a source classification', async () => {
const tool = createRunnerBashTool(
it('should block user-requested commands when restrictedUser is enabled', async () => {
const tool = createSandboxedBashTool(
mockCwd,
{},
{
teamId: mockTeamId,
role: 'editor',
restrictedUser: true,
},
)
const signal = createMockSignal()
await expect(
invokeTool(tool, '1', { command: 'echo hack', source: 'user' }, signal, createMockOnUpdate()),
).rejects.toThrow(/not permitted for your role/)
expect(runnerService.exec).not.toHaveBeenCalled()
})
it('should allow skill-requested commands when restrictedUser is enabled', async () => {
const tool = createSandboxedBashTool(
mockCwd,
{},
{
teamId: mockTeamId,
restrictedUser: true,
},
)
@@ -151,25 +181,24 @@ describe('createRunnerBashTool', () => {
})
const signal = createMockSignal()
const result = await invokeTool(tool, '1', { command: 'echo skill' }, signal)
expect(result.content).toContainEqual(
expect.objectContaining({ text: expect.stringContaining('skill output') }),
)
const result = await invokeTool(tool, '1', { command: 'echo skill', source: 'skill' }, signal)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ToolResponse content is an array of content blocks
expect((result as any).content[0].text).toContain('skill output')
})
it('should handle runner execution errors', async () => {
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
const tool = createSandboxedBashTool(mockCwd, {}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockRejectedValue(new Error('Runner disconnected'))
const signal = createMockSignal()
await expect(
invokeTool(tool, '1', { command: 'fail' }, signal, createMockOnUpdate()),
invokeTool(tool, '1', { command: 'fail', source: 'user' }, signal, createMockOnUpdate()),
).rejects.toThrow('Runner disconnected')
})
it('should handle non-zero exit codes', async () => {
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
const tool = createSandboxedBashTool(mockCwd, {}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockResolvedValue({
executionId: 'exec-1',
@@ -182,27 +211,12 @@ describe('createRunnerBashTool', () => {
const signal = createMockSignal()
await expect(
invokeTool(tool, '1', { command: 'exit 1' }, signal, createMockOnUpdate()),
invokeTool(tool, '1', { command: 'exit 1', source: 'user' }, signal, createMockOnUpdate()),
).rejects.toThrow(/exited with code 1/)
})
it('reports signal termination as a command failure', async () => {
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockResolvedValue({
executionId: 'signaled',
output: '',
exitCode: null,
signal: 'SIGTERM',
timedOut: false,
aborted: false,
})
await expect(invokeTool(tool, '1', { command: 'command' }, createMockSignal())).rejects.toThrow(
'terminated by SIGTERM',
)
})
it('should handle timeouts', async () => {
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
const tool = createSandboxedBashTool(mockCwd, {}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
opts.onOutput?.('output before timeout\n', 'stdout')
@@ -220,7 +234,7 @@ describe('createRunnerBashTool', () => {
const executePromise = invokeTool(
tool,
'1',
{ command: 'sleep 10', timeout: 2 },
{ command: 'sleep 10', timeout: 2, source: 'user' },
signal,
createMockOnUpdate(),
)
@@ -230,7 +244,7 @@ describe('createRunnerBashTool', () => {
})
it('should handle abort signals', async () => {
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
const tool = createSandboxedBashTool(mockCwd, {}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockResolvedValue({
executionId: 'exec-1',
@@ -243,12 +257,12 @@ describe('createRunnerBashTool', () => {
const signal = createMockSignal()
await expect(
invokeTool(tool, '1', { command: 'long-run' }, signal, createMockOnUpdate()),
invokeTool(tool, '1', { command: 'long-run', source: 'user' }, signal, createMockOnUpdate()),
).rejects.toThrow(/aborted/)
})
it('should truncate output exceeding max lines (2000 lines) and report runner log file path', async () => {
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
const tool = createSandboxedBashTool(mockCwd, {}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
const lines: string[] = []
@@ -269,8 +283,14 @@ describe('createRunnerBashTool', () => {
})
const signal = createMockSignal()
const result = await invokeTool(tool, '1', { command: 'generate lines' }, signal)
const text = result.content.map((block) => (block.type === 'text' ? block.text : '')).join('')
const result = await invokeTool(
tool,
'1',
{ command: 'generate lines', source: 'user' },
signal,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- content block array
const text = (result as any).content[0].text
expect(text).toContain('line-3000')
expect(text).toContain(
'[Showing lines 1001-3000 of 3000. Full output: .pi/logs/bash-exec1.log]',
@@ -285,7 +305,7 @@ describe('createRunnerBashTool', () => {
})
it('should truncate output exceeding max bytes (50KB) and report partial line size', async () => {
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
const tool = createSandboxedBashTool(mockCwd, {}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
const longLine = 'a'.repeat(60000)
@@ -302,8 +322,14 @@ describe('createRunnerBashTool', () => {
})
const signal = createMockSignal()
const result = await invokeTool(tool, '1', { command: 'long single line' }, signal)
const text = result.content.map((block) => (block.type === 'text' ? block.text : '')).join('')
const result = await invokeTool(
tool,
'1',
{ command: 'long single line', source: 'user' },
signal,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- content block array
const text = (result as any).content[0].text
expect(text).toMatch(
/Showing last 50\.0KB of line 1 \(line is 58\.6KB\)\. Full output: \.pi\/logs\/bash-exec2\.log/,
)
@@ -6,7 +6,6 @@ import { logger } from '@shumai/core/src/logger'
import { quotaService } from '@shumai/core/src/quota/quota-service'
import { runnerService } from '@shumai/core/src/runner'
import type { TeamMemberRole } from '@shumai/db'
import type { RunnerEnvironment } from '@shumai/dtos'
import { Type } from 'typebox'
import { OutputAccumulator } from '../utils/output-accumulator'
import {
@@ -16,9 +15,19 @@ import {
type TruncationResult,
} from '../utils/truncate'
const BashSource = Type.String({
enum: ['user', 'skill'],
description:
'Indicates who requested this bash command. Set to "user" when the end user directly ' +
'requested the command. Set to "skill" when the command is required by a skill you loaded ' +
'via the read_skill tool. Users without the owner role can only execute commands with ' +
'source="skill"; source="user" will be blocked.',
})
const BashParameters = Type.Object({
command: Type.String({ description: "The command to execute using the runner's shell." }),
command: Type.String({ description: 'The bash command to execute.' }),
timeout: Type.Optional(Type.Number({ description: 'Maximum execution time in seconds.' })),
source: BashSource,
inputFiles: Type.Optional(
Type.Union([
Type.Array(Type.String(), {
@@ -42,31 +51,42 @@ export interface LoadedSkillRef {
hash: string
}
export interface RunnerBashOptions {
export interface SandboxedBashOptions {
teamId?: string
agentRunnerId?: string | null
runnerId?: string
userId?: string
role?: TeamMemberRole | null
environment?: RunnerEnvironment
/**
* When true, the tool only allows commands requested by a loaded skill (source="skill").
* Commands requested directly by the end user (source="user") are blocked.
*/
restrictedUser?: boolean
getLoadedSkills?: () => Iterable<LoadedSkillRef>
}
export const createRunnerBashTool = (
export const createSandboxedBashTool = (
_cwd: string,
skillEnvs: Record<string, string> = {},
options?: RunnerBashOptions,
options?: SandboxedBashOptions,
): AgentTool<typeof BashParameters, BashDetails> => {
return {
name: 'bash',
description: `Execute a shell command on the configured runner. ${options?.environment ? `Runner OS: ${options.environment.platform}. Shell: ${options.environment.shell}. Use syntax and programs compatible with this environment.` : 'The runner reports its OS and shell when connected.'} Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a log file in .pi/logs/ on the runner. Optionally provide a timeout in seconds, or inputFiles to stage generated files (.pi/generated/...) into the runner workspace before running.`,
description: `Execute a bash command on the configured runner environment. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a log file in .pi/logs/ on the runner. Optionally provide a timeout in seconds, or inputFiles to stage generated files (.pi/generated/...) into the runner workspace before running. When in a restricted (non-owner) user context, only commands required by a skill loaded via the read_skill tool are allowed, and you must set source="skill".`,
parameters: BashParameters,
outputLimits: { maxBytes: DEFAULT_MAX_BYTES, maxLines: DEFAULT_MAX_LINES, retain: 'tail' },
execute: async (
{ command, timeout, inputFiles },
{ command, timeout, source, inputFiles },
api,
context,
): Promise<AgentToolResult<BashDetails>> => {
const signal = context.abortSignal
if (options?.restrictedUser && source !== 'skill') {
throw new Error(
'Bash commands requested directly by the user (source="user") are not permitted for your role. ' +
'Only commands required by a loaded skill (source="skill") can be executed.',
)
}
if (options?.teamId) {
await quotaService.checkQuota(
{
@@ -84,7 +104,7 @@ export const createRunnerBashTool = (
if (options?.runnerId) {
if (!runnerService.isRunnerConnected(options.runnerId)) {
throw new Error(
'Runner is currently offline. Please start your runner with "shumai-cli runner start" and try again.',
'Runner is currently offline. Please start your runner with "shumai runner start" and try again.',
)
}
targetRunnerId = options.runnerId
@@ -191,38 +211,35 @@ export const createRunnerBashTool = (
}
if (signal?.aborted || execResult.aborted) {
logger.error({ command, outputText }, 'Bash command aborted')
logger.error({ command, outputText }, 'Sandboxed bash command aborted')
throw new Error(appendStatus(outputText, 'Command aborted'))
}
if (execResult.timedOut) {
logger.error({ timeout, command, outputText }, 'Bash command timed out')
throw new Error(appendStatus(outputText, `Bash command timed out after ${timeout} seconds`))
logger.error({ timeout, command, outputText }, 'Sandboxed bash command timed out')
throw new Error(
appendStatus(outputText, `Sandboxed bash command timed out after ${timeout} seconds`),
)
}
if (execResult.error) {
logger.error(
{ error: execResult.error, command, outputText },
'Bash command encountered runner error',
'Sandboxed bash command encountered runner error',
)
throw new Error(appendStatus(outputText, execResult.error))
}
if (execResult.signal) {
logger.error(
{ signal: execResult.signal, command, outputText },
'Bash command was terminated',
)
throw new Error(appendStatus(outputText, 'Bash command terminated by ' + execResult.signal))
}
if (execResult.exitCode !== 0 && execResult.exitCode !== null) {
logger.error(
{ exitCode: execResult.exitCode, command, outputText },
'Bash command exited with failure code',
'Sandboxed bash command exited with failure code',
)
throw new Error(
appendStatus(outputText, `Bash command exited with code ${execResult.exitCode}`),
appendStatus(
outputText,
`Sandboxed bash command exited with code ${execResult.exitCode}`,
),
)
}
@@ -205,43 +205,6 @@ describe('Agent Chat Workflow', () => {
})
})
it('marks agent placeholder reply as internal when user comment is internal', async () => {
mockActivities.getCommentActivity.mockResolvedValue({
id: 'c-internal',
message: 'hello agent privately',
assetId: 'a1',
creatorId: 'user-c1',
second: null,
annotation: null,
replyToId: null,
isInternal: true,
attachments: [],
})
const task = await prisma.workflowTask.create({
data: {
type: 'chat',
status: 'pending',
assetId: 'a1',
payload: {
projectId: 'p1',
agent: { userCommentId: 'c-internal', agentId: 'b1' },
},
},
})
await agentChat(task)
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
assetId: 'a1',
message: '__CHAT__',
sessionId: 'pending',
agentId: 'b1',
replyToId: 'c-internal',
isInternal: true,
})
})
it('should skip session initialization if sessionId is already provided', async () => {
const task = await prisma.workflowTask.create({
data: {
@@ -85,7 +85,6 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
sessionId: sessionId || 'pending',
agentId: agentId,
replyToId: userComment.replyToId ?? userComment.id,
...(userComment.isInternal ? { isInternal: true } : {}),
})
placeholderCommentId = placeholder.id
@@ -34,7 +34,7 @@ vi.mock('../activities/ai', async () => {
generateVideoChunkEmbeddingActivity: vi.fn(),
saveAssetEmbeddingsActivity: vi.fn(),
deleteAssetEmbeddingsActivity: vi.fn(),
transcodeVideoChunksActivity: vi.fn(),
transcodeVideoChunkActivity: vi.fn(),
deleteS3ObjectActivity: vi.fn(),
}
})
@@ -60,7 +60,9 @@ describe('Agent Embedding Workflow', () => {
updateTaskUsageActivity: vi.mocked(workflowCore.updateTaskUsageActivity),
createCommentActivity: vi.mocked(agentActivities.createCommentActivity),
updateCommentActivity: vi.mocked(agentActivities.updateCommentActivity),
transcodeVideoChunksActivity: vi.mocked(aiActivities.transcodeVideoChunksActivity),
downloadMediaToTmpActivity: vi.fn(),
cleanupTmpDirActivity: vi.fn(),
transcodeVideoChunkActivity: vi.mocked(aiActivities.transcodeVideoChunkActivity),
deleteS3ObjectActivity: vi.mocked(aiActivities.deleteS3ObjectActivity),
}
@@ -84,21 +86,19 @@ describe('Agent Embedding Workflow', () => {
embedding: [0.3, 0.4],
usage: { inputTokens: 3, outputTokens: 3, model: 'gpt' },
})
mockActivities.transcodeVideoChunksActivity.mockImplementation(
async (params: {
assetId: string
chunks: Array<{ startTime: number; endTime: number }>
}) => {
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
filePath: '/tmp/test.mp4',
tmpDir: '/tmp/test-dir',
})
mockActivities.transcodeVideoChunkActivity.mockImplementation(
async (params: { assetId: string; startTime: number; endTime: number }) => {
return {
chunks: params.chunks.map((c) => ({
startTime: c.startTime,
endTime: c.endTime,
chunkKey: `files/${params.assetId}/tmp-embedding-chunks/chunk-${c.startTime}-${c.endTime}.mp4`,
})),
chunkKey: `files/${params.assetId}/tmp-embedding-chunks/chunk-${params.startTime}-${params.endTime}.mp4`,
}
},
)
mockActivities.deleteS3ObjectActivity.mockResolvedValue(undefined)
mockActivities.cleanupTmpDirActivity.mockResolvedValue(undefined)
})
it('should run agent embedding workflow successfully for image', async () => {
@@ -256,7 +256,7 @@ describe('Agent Embedding Workflow', () => {
)
})
it('should run agent embedding workflow successfully for video in chunks via single batch transcode task', async () => {
it('should run agent embedding workflow successfully for video in chunks', async () => {
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: {
@@ -278,7 +278,6 @@ describe('Agent Embedding Workflow', () => {
status: 'pending',
assetId: 'a1',
teamId: 't1',
projectId: 'p1',
payload: {
projectId: 'p1',
agent: { sessionId: 's1', agentId: 'agent-1' },
@@ -288,20 +287,28 @@ describe('Agent Embedding Workflow', () => {
await agentEmbeddingMedia(task)
// Verify batch video chunk slicing activity called once on transcode queue with all 3 chunks
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledTimes(1)
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledWith({
parentTaskId: task.id,
teamId: 't1',
projectId: 'p1',
// Verify video chunk slicing activity called 3 times on transcode queue
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(3)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(1, {
assetId: 'a1',
assetKey: 'test-transcoded.mp4',
startTime: 0,
endTime: 60,
format: 'video',
})
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(2, {
assetId: 'a1',
assetKey: 'test-transcoded.mp4',
startTime: 55,
endTime: 115,
format: 'video',
})
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(3, {
assetId: 'a1',
assetKey: 'test-transcoded.mp4',
startTime: 110,
endTime: 150,
format: 'video',
chunks: [
{ startTime: 0, endTime: 60 },
{ startTime: 55, endTime: 115 },
{ startTime: 110, endTime: 150 },
],
})
// Verify video chunk embedding generation (3 chunks) on agent queue
@@ -394,7 +401,6 @@ describe('Agent Embedding Workflow', () => {
await agentEmbeddingMedia(task)
expect(mockActivities.transcodeVideoChunksActivity).not.toHaveBeenCalled()
expect(mockActivities.saveAssetEmbeddingsActivity).not.toHaveBeenCalled()
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: task.id,
@@ -463,7 +469,7 @@ describe('Agent Embedding Workflow', () => {
})
})
it('should save completed chunks to DB immediately and clean up all remaining temporary S3 chunks on failure', async () => {
it('should save completed chunks to DB immediately before subsequent chunk failure', async () => {
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: {
@@ -504,18 +510,6 @@ describe('Agent Embedding Workflow', () => {
assetId: 'a1',
embeddings: [{ embedding: [0.1, 0.2], startTime: 0, endTime: 60 }],
})
// All 3 temporary chunks (chunk 1 after success, chunk 2 and chunk 3 in finally) MUST be deleted from S3
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenCalledTimes(3)
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenNthCalledWith(1, {
key: 'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
})
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenNthCalledWith(2, {
key: 'files/a1/tmp-embedding-chunks/chunk-55-115.mp4',
})
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenNthCalledWith(3, {
key: 'files/a1/tmp-embedding-chunks/chunk-110-150.mp4',
})
})
it('should not create redundant chunks when video exactly matches chunk duration', async () => {
@@ -544,11 +538,12 @@ describe('Agent Embedding Workflow', () => {
await agentEmbeddingMedia(task)
// Verify only 1 chunk was requested instead of 2 (0-60 and 55-60)
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledTimes(1)
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledWith(
// Verify only 1 chunk was created instead of 2 (0-60 and 55-60)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(1)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledWith(
expect.objectContaining({
chunks: [{ startTime: 0, endTime: 60 }],
startTime: 0,
endTime: 60,
}),
)
})
@@ -580,10 +575,11 @@ describe('Agent Embedding Workflow', () => {
await agentEmbeddingMedia(task)
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledWith(
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledWith(
expect.objectContaining({
startTime: 0,
endTime: 30,
format: 'frames',
chunks: [{ startTime: 0, endTime: 30 }],
}),
)
expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith(
@@ -630,14 +626,14 @@ describe('Agent Embedding Workflow', () => {
await agentEmbeddingMedia(task)
// Chunk 1 (0-60) should be skipped; only chunk 2 (55-115) and chunk 3 (110-150) should be transcoded and embedded
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledTimes(1)
expect(mockActivities.transcodeVideoChunksActivity).toHaveBeenCalledWith(
expect.objectContaining({
chunks: [
{ startTime: 55, endTime: 115 },
{ startTime: 110, endTime: 150 },
],
}),
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(2)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(
1,
expect.objectContaining({ startTime: 55, endTime: 115 }),
)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(
2,
expect.objectContaining({ startTime: 110, endTime: 150 }),
)
expect(mockActivities.saveAssetEmbeddingsActivity).toHaveBeenCalledTimes(2)
+47 -66
View File
@@ -1,4 +1,3 @@
import { logger } from '@shumai/core/src/logger'
import type { WorkflowTask } from '@shumai/db'
import {
ApplicationFailure,
@@ -13,9 +12,8 @@ import {
generateVideoChunkEmbeddingActivity,
getEmbeddingContextActivity,
saveAssetEmbeddingsActivity,
transcodeVideoChunksActivity,
transcodeVideoChunkActivity,
type ExistingAssetEmbeddingInfo,
type VideoChunkRange,
} from '../activities/ai'
export interface GeneratedEmbedding {
@@ -150,7 +148,6 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
const overlap = chunkOverlap ?? 5.0
const step = Math.max(1, limit - overlap)
const missingChunks: VideoChunkRange[] = []
for (let start = 0.0; start < duration; start += step) {
let end = start + limit
if (end >= duration) {
@@ -166,8 +163,52 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
Math.abs(c.endTime - end) < 0.1,
)
if (!chunkExists) {
missingChunks.push({ startTime: start, endTime: end })
if (chunkExists) {
// If this chunk reached the end of the video, stop
if (end >= duration) {
break
}
continue
}
// Step A: Slice chunk on transcode worker and upload to S3
const chunkRes = await transcodeVideoChunkActivity({
assetId: asset.id,
assetKey: embeddingKey,
startTime: start,
endTime: end,
format: isGemmaProvider ? 'frames' : 'video',
})
const { chunkKey } = chunkRes
try {
// Step B: Generate embedding on agent worker
const chunkResult = await generateVideoChunkEmbeddingActivity({
teamId: task.teamId,
chunkKey,
})
// Step C: Save chunk embedding to database immediately
await saveAssetEmbeddingsActivity({
assetId: task.assetId,
embeddings: [
{
embedding: chunkResult.embedding,
startTime: start,
endTime: end,
},
],
})
if (chunkResult.usage) {
usage.inputTokens += chunkResult.usage.inputTokens || 0
usage.outputTokens += chunkResult.usage.outputTokens || 0
}
} finally {
// Step D: Delete temporary chunk from S3
await deleteS3ObjectActivity({
key: chunkKey,
})
}
// If this chunk reached the end of the video, stop to avoid redundant overlapping chunks
@@ -175,66 +216,6 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
break
}
}
if (missingChunks.length > 0) {
// Step A: Slice all missing chunks via batch task on transcode queue and upload to S3
const { chunks: transcodedChunks } = await transcodeVideoChunksActivity({
parentTaskId: task.id,
teamId: task.teamId,
projectId: task.projectId,
assetId: asset.id,
assetKey: embeddingKey,
format: isGemmaProvider ? 'frames' : 'video',
chunks: missingChunks,
})
const remainingChunkKeys = new Set(transcodedChunks.map((c) => c.chunkKey))
try {
for (const chunk of transcodedChunks) {
// Step B: Generate embedding on agent worker
const chunkResult = await generateVideoChunkEmbeddingActivity({
teamId: task.teamId,
chunkKey: chunk.chunkKey,
})
// Step C: Save chunk embedding to database immediately
await saveAssetEmbeddingsActivity({
assetId: task.assetId,
embeddings: [
{
embedding: chunkResult.embedding,
startTime: chunk.startTime,
endTime: chunk.endTime,
...(chunk.sprite && { sprite: chunk.sprite }),
},
],
})
if (chunkResult.usage) {
usage.inputTokens += chunkResult.usage.inputTokens || 0
usage.outputTokens += chunkResult.usage.outputTokens || 0
}
// Step D: Delete temporary chunk from S3 as soon as it is embedded
await deleteS3ObjectActivity({
key: chunk.chunkKey,
})
remainingChunkKeys.delete(chunk.chunkKey)
}
} finally {
for (const key of remainingChunkKeys) {
try {
await deleteS3ObjectActivity({ key })
} catch (cleanupErr) {
logger.error(
{ taskId: task.id, chunkKey: key, err: cleanupErr },
'Failed to delete temporary chunk from S3',
)
}
}
}
}
}
// Update Usage
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/api",
"version": "0.7.2",
"version": "0.6.6",
"private": true,
"type": "module",
"main": "./src/index.ts",
-25
View File
@@ -6,7 +6,6 @@ import { AssetType } from '@shumai/db'
import { authMiddleware } from './middleware/auth'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { s3Service } from '@shumai/core/src/s3/s3'
vi.mock('./middleware/auth', () => ({
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock
@@ -85,28 +84,4 @@ describe('Attachment API', () => {
itemId: 'asset1',
})
})
it('keeps the upload key inside the attachment folder', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(assetService.createAsset).mockResolvedValue({ id: 'asset1' } as any)
vi.mocked(s3Service.presign).mockResolvedValue('http://mock-s3-url')
const fileName = '../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov'
const res = await app.request('/projects/project1/attachments', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
body: JSON.stringify({ fileName, contentType: 'video/quicktime', size: 100 }),
})
expect(res.status).toBe(200)
const key = vi.mocked(assetService.createAsset).mock.lastCall?.[0].key as string
const parts = key.split('/')
expect(parts[0]).toBe('attachments')
expect(parts).toHaveLength(3)
expect(parts).not.toContain('..')
expect(s3Service.presign).toHaveBeenCalledWith(expect.any(String), key, 'PUT')
expect(assetService.createAsset).toHaveBeenCalledWith(
expect.objectContaining({ name: fileName }),
)
})
})
+1 -2
View File
@@ -7,7 +7,6 @@ import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { projectService } from '@shumai/core/src/project/project'
import { AssetType } from '@shumai/db'
import { ulid } from 'ulid'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import type { Prisma } from '@shumai/db'
@@ -28,7 +27,7 @@ const route = new Hono<{ Variables: { user: User } }>().post(
id: projectId,
})
const key = `attachments/${ulid()}/${sanitizeFilename(req.fileName)}`
const key = `attachments/${ulid()}/${req.fileName}`
const assetInfo = await assetService.createAsset({
name: req.fileName,
-199
View File
@@ -3,7 +3,6 @@ import { Hono, type Context, type Next } from 'hono'
import { HTTPException } from 'hono/http-exception'
import fileRoute from './file'
import { assetService } from '@shumai/core/src/asset/asset'
import { commentFrameService } from '@shumai/core/src/comment/comment-frame'
import { projectService } from '@shumai/core/src/project/project'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { notificationService } from '@shumai/core/src/notification/notification'
@@ -82,7 +81,6 @@ describe('file api', () => {
vi.spyOn(assetService, 'updateAssetName').mockImplementation(vi.fn())
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
vi.spyOn(assetService, 'createComment').mockImplementation(vi.fn())
vi.spyOn(assetService, 'updateComment').mockImplementation(vi.fn())
vi.spyOn(assetService, 'completeComment').mockImplementation(vi.fn())
vi.spyOn(assetService, 'deleteComment').mockImplementation(vi.fn())
vi.spyOn(assetService, 'addCommentReaction').mockImplementation(vi.fn())
@@ -92,10 +90,7 @@ describe('file api', () => {
assetId: 'file1',
} as unknown as Awaited<ReturnType<typeof assetService.getComment>>)
vi.spyOn(assetService, 'listComments').mockImplementation(vi.fn())
vi.spyOn(assetService, 'listAllComments').mockImplementation(vi.fn())
vi.spyOn(assetService, 'getProjectNameForAsset').mockResolvedValue('Demo Project')
vi.spyOn(assetService, 'exportComments').mockImplementation(vi.fn())
vi.spyOn(commentFrameService, 'extractFrame').mockImplementation(vi.fn())
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn())
vi.spyOn(notificationService, 'create').mockImplementation(vi.fn())
@@ -292,7 +287,6 @@ describe('file api', () => {
updatedAt: new Date().toISOString(),
sessionId: null,
isCompleted: false,
isInternal: false,
completionLastChangedBy: null,
reactionCounts: [],
})
@@ -353,7 +347,6 @@ describe('file api', () => {
updatedAt: new Date().toISOString(),
sessionId: null,
isCompleted: false,
isInternal: false,
completionLastChangedBy: null,
reactionCounts: [],
})
@@ -411,7 +404,6 @@ describe('file api', () => {
updatedAt: new Date().toISOString(),
sessionId: null,
isCompleted: false,
isInternal: false,
completionLastChangedBy: null,
reactionCounts: [],
},
@@ -557,7 +549,6 @@ describe('file api', () => {
updatedAt: new Date().toISOString(),
sessionId: null,
isCompleted: true,
isInternal: false,
completionLastChangedBy: { id: 'user1', name: 'Test User' },
reactionCounts: [],
})
@@ -584,110 +575,6 @@ describe('file api', () => {
expect(assetService.getComment).toHaveBeenCalledWith('comment-id', 'user1')
})
it('POST /files/:fileId/comments forwards isInternal', async () => {
vi.mocked(assetService.createComment).mockResolvedValue({
id: 'comment-internal-id',
assetId: 'test-id',
message: 'internal note',
annotations: null,
second: null,
creator: { id: 'user1', name: 'Test User' },
replies: [],
attachments: [],
mentions: [],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
sessionId: null,
isCompleted: false,
isInternal: true,
completionLastChangedBy: null,
reactionCounts: [],
})
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/files/test-id/comments', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'internal note', attachmentIds: [], isInternal: true }),
})
expect(res.status).toBe(201)
const json = await res.json()
expect(json.isInternal).toBe(true)
expect(assetService.createComment).toHaveBeenCalledWith(
expect.objectContaining({
assetId: 'test-id',
userId: 'user1',
message: 'internal note',
isInternal: true,
}),
expect.anything(),
)
})
it('PATCH /comments/:commentId updates comment and logs comment_update audit entry', async () => {
vi.mocked(assetService.updateComment).mockResolvedValue({
id: 'comment-id',
assetId: 'file-id',
message: 'edited text',
annotations: null,
second: null,
creator: { id: 'user1', name: 'Test User' },
replies: [],
attachments: [],
mentions: [],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
sessionId: null,
isCompleted: false,
isInternal: true,
completionLastChangedBy: null,
reactionCounts: [],
})
vi.mocked(assetService.getAssetContext).mockResolvedValue({
teamId: 'test-team',
projectId: 'proj-1',
})
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/comments/comment-id', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: 'edited text',
isInternal: true,
second: null,
attachmentIds: ['att-1'],
}),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json.message).toBe('edited text')
expect(json.isInternal).toBe(true)
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user1', name: 'Test User' },
permission: Permission.Read,
type: ResourceType.Comment,
id: 'comment-id',
})
expect(assetService.updateComment).toHaveBeenCalledWith({
commentId: 'comment-id',
userId: 'user1',
message: 'edited text',
isInternal: true,
second: null,
attachmentIds: ['att-1'],
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'comment_update',
teamId: 'test-team',
userId: 'user1',
projectId: 'proj-1',
itemId: 'comment-id',
})
})
it('POST /comments/:commentId/complete reopens with isCompleted false', async () => {
vi.mocked(runOperation).mockResolvedValue({ commentId: 'comment-id', resolved: false })
vi.mocked(assetService.getComment).mockResolvedValue({
@@ -1208,90 +1095,4 @@ describe('file api', () => {
)
})
})
describe('GET /files/:fileId/comments/print and /frame routes', () => {
it('returns asset, top-down breadcrumbs, and all comments for printing', async () => {
vi.mocked(assetService.getAsset).mockResolvedValue({
id: 'file-1',
name: 'demo.mp4',
sizeByte: 100,
fileCount: 1,
type: 'file',
status: 'active',
proxyType: 'video',
ancestorFolders: [
{ id: 'f2', name: 'Inner' },
{ id: 'f1', name: 'Outer' },
],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
vi.mocked(assetService.getProjectNameForAsset).mockResolvedValue('My Project')
vi.mocked(assetService.listAllComments).mockResolvedValue([
{
id: 'c1',
assetId: 'file-1',
message: 'Looks great',
annotations: null,
second: 1.5,
creator: { id: 'u1', name: 'Alice' },
replies: [],
attachments: [],
mentions: [],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
sessionId: null,
isCompleted: false,
isInternal: false,
completionLastChangedBy: null,
reactionCounts: [],
},
])
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/files/file-1/comments/print')
expect(res.status).toBe(200)
const body = await res.json()
expect(body.breadcrumbs).toEqual(['My Project', 'Outer', 'Inner'])
expect(body.comments).toHaveLength(1)
expect(body.asset.id).toBe('file-1')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user1', name: 'Test User' },
permission: Permission.Read,
type: ResourceType.Asset,
id: 'file-1',
})
})
it('streams extracted frame image with cache headers', async () => {
const buf = Buffer.from('mock-webp-bytes')
vi.mocked(commentFrameService.extractFrame).mockResolvedValue({
buffer: buf,
mimeType: 'image/webp',
})
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/files/file-1/comments/frame?second=2.5&width=400')
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('image/webp')
expect(res.headers.get('cache-control')).toBe('private, max-age=300')
const arr = new Uint8Array(await res.arrayBuffer())
expect(Buffer.from(arr).toString()).toBe('mock-webp-bytes')
expect(commentFrameService.extractFrame).toHaveBeenCalledWith({
assetId: 'file-1',
second: 2.5,
width: 400,
signal: expect.any(AbortSignal),
})
})
it('rejects invalid second query parameter with 400', async () => {
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/files/file-1/comments/frame?second=-5')
expect(res.status).toBe(400)
expect(commentFrameService.extractFrame).not.toHaveBeenCalled()
})
})
})
-90
View File
@@ -3,7 +3,6 @@ import { assetService } from '@shumai/core/src/asset/asset'
import { projectService } from '@shumai/core/src/project/project'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { commentService } from '@shumai/core/src/comment/comment'
import { commentFrameService } from '@shumai/core/src/comment/comment-frame'
import { s3Service } from '@shumai/core/src/s3/s3'
import type { Prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
@@ -18,7 +17,6 @@ import {
import {
archiveAssetsRequestSchema,
createCommentRequestSchema,
updateCommentRequestSchema,
deleteFilesRequestSchema,
batchGetFilesRequestSchema,
paginationParamsSchema,
@@ -31,7 +29,6 @@ import {
getDownloadLinksRequestSchema,
getStoragePathsRequestSchema,
completeCommentRequestSchema,
commentFrameQuerySchema,
exportCommentsRequestSchema,
addCommentReactionRequestSchema,
removeCommentReactionRequestSchema,
@@ -200,7 +197,6 @@ const route = new Hono<{ Variables: { user: User } }>()
annotations: req.annotations,
second: req.second,
attachmentIds: req.attachmentIds,
isInternal: req.isInternal,
})
const context = await assetService.getAssetContext(fileId)
@@ -252,60 +248,6 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.body(result.content)
},
)
.get('/files/:fileId/comments/print', async (c) => {
const fileId = c.req.param('fileId')
const user = c.get('user')
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Asset,
id: fileId,
})
const [asset, projectName, comments] = await Promise.all([
assetService.getAsset({ assetId: fileId }),
assetService.getProjectNameForAsset(fileId),
assetService.listAllComments(fileId, user.id),
])
const folderNames = (asset.ancestorFolders ?? [])
.slice()
.reverse()
.map((f) => f.name)
.filter((name): name is string => Boolean(name))
const breadcrumbs = projectName ? [projectName, ...folderNames] : folderNames
return c.json({
asset,
breadcrumbs,
comments,
})
})
.get('/files/:fileId/comments/frame', zValidator('query', commentFrameQuerySchema), async (c) => {
const fileId = c.req.param('fileId')
const user = c.get('user')
const { second, width } = c.req.valid('query')
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Asset,
id: fileId,
})
const result = await commentFrameService.extractFrame({
assetId: fileId,
second,
width,
signal: c.req.raw.signal,
})
return c.body(new Uint8Array(result.buffer), 200, {
'Content-Type': result.mimeType,
'Cache-Control': 'private, max-age=300',
})
})
.post(
'/comments/:commentId/reactions',
zValidator('json', addCommentReactionRequestSchema),
@@ -363,38 +305,6 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(await assetService.getComment(commentId, user.id))
},
)
.patch('/comments/:commentId', zValidator('json', updateCommentRequestSchema), async (c) => {
const commentId = c.req.param('commentId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Comment,
id: commentId,
})
const updated = await assetService.updateComment({
commentId,
userId: user.id,
message: req.message,
isInternal: req.isInternal,
second: req.second,
attachmentIds: req.attachmentIds,
})
const context = await assetService.getAssetContext(updated.assetId)
await auditLogService.logAction({
action: AuditAction.comment_update,
teamId: context.teamId,
userId: user.id,
projectId: context.projectId,
itemId: commentId,
})
return c.json(updated)
})
.delete('/comments/:commentId', async (c) => {
const commentId = c.req.param('commentId')
const user = c.get('user')
-78
View File
@@ -60,7 +60,6 @@ describe('folder api', () => {
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
vi.spyOn(assetService, 'listChildren').mockImplementation(vi.fn())
vi.spyOn(searchService, 'search').mockImplementation(vi.fn())
vi.spyOn(searchService, 'searchByImage').mockResolvedValue({ data: [], pageInfo: { total: 0 } })
})
afterEach(() => {
@@ -330,83 +329,6 @@ describe('folder api', () => {
)
})
describe('POST /folders/:folderId/image-search', () => {
function request(body: Record<string, unknown>) {
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
return app.request('/folders/scope-id/image-search', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
it('checks both permissions and passes a stored image search to Core', async () => {
const res = await request({ sourceAssetId: 'image-id', mediaType: 'video', first: 20 })
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ data: [], pageInfo: { total: 0 } })
expect(vi.mocked(authzService.hasPermission).mock.calls.map(([input]) => input.id)).toEqual([
'scope-id',
'image-id',
])
expect(authzService.hasPermission).toHaveBeenLastCalledWith(
expect.objectContaining({
id: 'image-id',
permission: Permission.Read,
type: ResourceType.Asset,
}),
)
expect(searchService.searchByImage).toHaveBeenCalledWith('scope-id', {
sourceAssetId: 'image-id',
mediaType: 'video',
first: 20,
operator: 'AND',
conditions: [],
})
})
it('checks folder read access before passing image data to Core', async () => {
const conditions = [{ field: 'status', operator: 'eq', value: 'approved' }]
const res = await request({ image: 'aW1hZ2U=', conditions })
expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledTimes(1)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
id: 'scope-id',
permission: Permission.Read,
type: ResourceType.Asset,
}),
)
expect(searchService.searchByImage).toHaveBeenCalledWith('scope-id', {
image: 'aW1hZ2U=',
conditions,
operator: 'AND',
})
})
it('rejects a denied folder or source before running the search', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new HTTPException(403))
expect((await request({ image: 'aW1hZ2U=' })).status).toBe(403)
vi.mocked(authzService.hasPermission)
.mockResolvedValueOnce(undefined)
.mockRejectedValueOnce(new HTTPException(403))
expect((await request({ sourceAssetId: 'image-id' })).status).toBe(403)
expect(searchService.searchByImage).not.toHaveBeenCalled()
})
it('rejects incomplete, ambiguous, and invalid search inputs', async () => {
for (const body of [
{},
{ image: 'aW1hZ2U=', sourceAssetId: 'both' },
{ image: 'invalid!' },
{ sourceAssetId: 'image-id', mediaType: 'audio' },
]) {
expect((await request(body)).status).toBe(400)
}
expect((await request({ image: 'A'.repeat(1_600_000) })).status).toBe(413)
expect(searchService.searchByImage).not.toHaveBeenCalled()
})
})
it('PATCH /folders/:folderId/order', async () => {
vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({
id: 'test-id',
+1 -33
View File
@@ -1,6 +1,5 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { bodyLimit } from 'hono/body-limit'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { assetService } from '@shumai/core/src/asset/asset'
import { searchService } from '@shumai/core/src/search/search'
@@ -12,11 +11,7 @@ import {
updateAgentsMdRequestSchema,
} from '@shumai/dtos'
import { listChildrenRequestSchema, updateAssetOrderRequestSchema, AuditAction } from '@shumai/dtos'
import {
imageSearchRequestSchema,
MAX_SEARCH_IMAGE_BASE64_LENGTH,
searchRequestSchema,
} from '@shumai/dtos'
import { searchRequestSchema } from '@shumai/dtos'
import type { Prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import {
@@ -159,33 +154,6 @@ const route = new Hono<{ Variables: { user: User } }>()
const result = await searchService.search(folderId, req)
return c.json(result)
})
.post(
'/folders/:folderId/image-search',
bodyLimit({ maxSize: MAX_SEARCH_IMAGE_BASE64_LENGTH + 64 * 1024 }),
zValidator('json', imageSearchRequestSchema),
async (c) => {
const folderId = c.req.param('folderId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Asset,
id: folderId,
})
if (req.sourceAssetId) {
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Asset,
id: req.sourceAssetId,
})
}
return c.json(await searchService.searchByImage(folderId, req))
},
)
.get('/folders/:folderId/agentsmd', async (c) => {
const { content } = await runOperation(
getFolderInstructionsOp,
+2 -2
View File
@@ -30,7 +30,7 @@ const route = new Hono<{ Variables: { user: User } }>()
id: teamId,
})
const attachment = await kanbanService.createAttachment(teamId, user.id, req)
const attachment = await kanbanService.createAttachment(teamId, req)
return c.json(attachment)
},
)
@@ -123,7 +123,7 @@ const route = new Hono<{ Variables: { user: User } }>()
id: taskId,
})
const events = await kanbanService.listEvents(taskId, user.id)
const events = await kanbanService.listEvents(taskId)
return c.json({ data: events })
})
+4 -77
View File
@@ -4,8 +4,6 @@ import { kanbanService } from '@shumai/core/src/kanban/kanban'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { notificationService } from '@shumai/core/src/notification/notification'
import { KanbanTaskStatus, KanbanTaskPriority } from '@shumai/db/enums'
import { HTTPException } from 'hono/http-exception'
import { authzService } from '@shumai/core/src/authz/authz'
import kanbanRoute from './index'
vi.mock('@shumai/core/src/authz/authz', () => ({
@@ -21,7 +19,6 @@ vi.mock('@shumai/core/src/authz/authz', () => ({
ResourceType: {
Team: 'team',
Project: 'project',
Asset: 'asset',
KanbanGoal: 'kanbanGoal',
KanbanTask: 'kanbanTask',
},
@@ -54,7 +51,6 @@ describe('Kanban API Routes', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
vi.mocked(auditLogService.logAction).mockResolvedValue({} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
vi.mocked(notificationService.notifyKanbanTaskEvent).mockResolvedValue(undefined as any) // eslint-disable-line @typescript-eslint/no-explicit-any
app = new Hono()
@@ -222,7 +218,6 @@ describe('Kanban API Routes', () => {
status: 'READY',
goalId: 'goal-1',
}),
'user-1',
)
})
@@ -253,7 +248,7 @@ describe('Kanban API Routes', () => {
expect(res.status).toBe(200)
const json = await res.json()
expect(json.id).toBe(taskId)
expect(mockGet).toHaveBeenCalledWith(taskId, 'user-1')
expect(mockGet).toHaveBeenCalledWith(taskId)
})
it('PATCH /teams/:teamId/kanban/tasks/:taskId', async () => {
@@ -498,74 +493,6 @@ describe('Kanban API Routes', () => {
expect(mockLinkAssets).toHaveBeenCalledWith(teamId, taskId, ['asset-1', 'asset-2'])
})
describe('linking files the caller cannot read', () => {
const denyAsset = (deniedAssetId: string) =>
vi.mocked(authzService.hasPermission).mockImplementation(async (req) => {
if (req.type === 'asset' && req.id === deniedAssetId) {
throw new HTTPException(403, { message: 'User has only project scope' })
}
})
it('checks Read on every file linked to a task', async () => {
const mockLinkAssets = vi.spyOn(kanbanService, 'linkAssets').mockResolvedValue(undefined)
denyAsset('asset-2')
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}/assets`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ assetIds: ['asset-1', 'asset-2'] }),
})
expect(res.status).toBe(403)
expect(mockLinkAssets).not.toHaveBeenCalled()
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({ type: 'asset', id: 'asset-1', permission: 'Read' }),
)
})
it('checks Read on the file when linking it from the file side', async () => {
const mockLinkAsset = vi.spyOn(kanbanService, 'linkAsset').mockResolvedValue(undefined)
denyAsset('asset-1')
const res = await app.request(`/teams/${teamId}/kanban/assets/asset-1/tasks`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ taskId }),
})
expect(res.status).toBe(403)
expect(mockLinkAsset).not.toHaveBeenCalled()
})
it('checks Read on files passed when updating a task', async () => {
const mockUpdate = vi.spyOn(kanbanService, 'updateTask')
denyAsset('asset-9')
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ assetIds: ['asset-9'] }),
})
expect(res.status).toBe(403)
expect(mockUpdate).not.toHaveBeenCalled()
})
it('checks Read on files passed when creating a task', async () => {
const mockCreate = vi.spyOn(kanbanService, 'createTask')
denyAsset('asset-9')
const res = await app.request(`/teams/${teamId}/kanban/tasks`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Task', assetIds: ['asset-9'] }),
})
expect(res.status).toBe(403)
expect(mockCreate).not.toHaveBeenCalled()
})
})
it('DELETE /teams/:teamId/kanban/tasks/:taskId/assets/:assetId', async () => {
const mockUnlinkAsset = vi.spyOn(kanbanService, 'unlinkAsset').mockResolvedValue(undefined)
@@ -603,7 +530,7 @@ describe('Kanban API Routes', () => {
const json = await res.json()
expect(json.total).toBe(1)
expect(json.data).toHaveLength(1)
expect(mockListTasksForAsset).toHaveBeenCalledWith(teamId, 'asset-1', 'user-1')
expect(mockListTasksForAsset).toHaveBeenCalledWith(teamId, 'asset-1')
})
it('POST /teams/:teamId/kanban/assets/:assetId/tasks', async () => {
@@ -658,7 +585,7 @@ describe('Kanban API Routes', () => {
expect(res.status).toBe(200)
const json = await res.json()
expect(json.id).toBe('att-1')
expect(mockAttachment).toHaveBeenCalledWith(teamId, 'user-1', {
expect(mockAttachment).toHaveBeenCalledWith(teamId, {
fileName: 'test.png',
size: 1024,
contentType: 'image/png',
@@ -756,7 +683,7 @@ describe('Kanban API Routes', () => {
expect(res.status).toBe(200)
const json = await res.json()
expect(json.data).toHaveLength(1)
expect(mockEvents).toHaveBeenCalledWith(taskId, 'user-1')
expect(mockEvents).toHaveBeenCalledWith(taskId)
})
})
})
+3 -26
View File
@@ -22,21 +22,6 @@ import { HTTPException } from 'hono/http-exception'
type User = Prisma.UserGetPayload<Record<string, never>>
/**
* Linking a file to a task shows its name, folder path and thumbnail to everyone
* who can read the task, so the caller must be able to read each linked file.
*/
async function assertCanReadAssets(user: User, assetIds: string[] | undefined) {
for (const id of new Set(assetIds ?? [])) {
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Asset,
id,
})
}
}
const route = new Hono<{ Variables: { user: User } }>()
.post('/teams/:teamId/kanban/tasks', zValidator('json', createKanbanTaskSchema), async (c) => {
const { teamId } = c.req.param()
@@ -55,8 +40,6 @@ const route = new Hono<{ Variables: { user: User } }>()
throw new HTTPException(403, { message: 'User is not a member of the team' })
}
await assertCanReadAssets(user, req.assetIds)
const task = await kanbanService.createTask(teamId, req, user.id, role)
await auditLogService.logAction({
@@ -106,7 +89,7 @@ const route = new Hono<{ Variables: { user: User } }>()
id: teamId,
})
const result = await kanbanService.listTasks(teamId, req, user.id)
const result = await kanbanService.listTasks(teamId, req)
return c.json(result)
},
)
@@ -121,7 +104,7 @@ const route = new Hono<{ Variables: { user: User } }>()
id: taskId,
})
const task = await kanbanService.getTask(taskId, user.id)
const task = await kanbanService.getTask(taskId)
return c.json(task)
})
.patch(
@@ -139,8 +122,6 @@ const route = new Hono<{ Variables: { user: User } }>()
id: taskId,
})
await assertCanReadAssets(user, req.assetIds)
const existing = await kanbanService.getTask(taskId)
const role = await resolveEffectiveRole(teamId, existing.projectId ?? undefined, user.id)
const task = await kanbanService.updateTask(taskId, req, user.id, role)
@@ -281,8 +262,6 @@ const route = new Hono<{ Variables: { user: User } }>()
id: taskId,
})
await assertCanReadAssets(user, req.assetIds)
await kanbanService.linkAssets(teamId, taskId, req.assetIds)
return c.json({ success: true })
},
@@ -312,7 +291,7 @@ const route = new Hono<{ Variables: { user: User } }>()
id: teamId,
})
const tasks = await kanbanService.listTasksForAsset(teamId, assetId, user.id)
const tasks = await kanbanService.listTasksForAsset(teamId, assetId)
return c.json({ data: tasks, total: tasks.length })
})
.post(
@@ -330,8 +309,6 @@ const route = new Hono<{ Variables: { user: User } }>()
id: req.taskId,
})
await assertCanReadAssets(user, [assetId])
await kanbanService.linkAsset(teamId, req.taskId, assetId)
return c.json({ success: true })
},
-166
View File
@@ -1,166 +0,0 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import publicShareRoute from './public-share'
import { shareService } from '@shumai/core/src/share/share'
import { assetService } from '@shumai/core/src/asset/asset'
import { commentFrameService } from '@shumai/core/src/comment/comment-frame'
import { watermarkService } from '@shumai/core/src/watermark/watermark'
import { auth } from '@shumai/core/src/auth/auth'
import { ShareLinkPasswordInvalidError } from '@shumai/core/src/share/errors'
describe('public share print comments and frame api', () => {
beforeEach(() => {
vi.spyOn(auth.api, 'getSession').mockResolvedValue(null)
})
afterEach(() => {
vi.restoreAllMocks()
})
it('GET /shares/:shareId/files/:fileId/comments/print returns share-scoped breadcrumbs and comments', async () => {
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
id: 'share-1',
name: 'Client Review',
rootFolderId: 'share-root',
projectId: 'proj-1',
watermarkConfigId: null,
fieldVisibility: { status: true, internalNote: false },
} as never)
vi.spyOn(assetService, 'getAsset').mockResolvedValue({
id: 'file-1',
name: 'spot.mp4',
sizeByte: 100,
fileCount: 1,
type: 'file',
status: 'active',
proxyType: 'video',
fieldValues: [
{ fieldId: 'status', value: 'Approved' },
{ fieldId: 'internalNote', value: 'Private note' },
{ fieldId: 'rating', value: 3 },
],
ancestorFolders: [
{ id: 'inner', name: 'Inner Folder' },
{ id: 'share-root', name: 'Share Root' },
{ id: 'private-parent', name: 'Secret Project Folder' },
],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
vi.spyOn(assetService, 'resolveLatestVersionId').mockResolvedValue('file-1')
vi.spyOn(assetService, 'resolveTargetAssetId').mockResolvedValue('file-1')
vi.spyOn(assetService, 'listAllComments').mockResolvedValue([
{
id: 'c1',
assetId: 'file-1',
message: 'Great cut!',
annotations: null,
second: 3,
creator: { id: 'u1', name: 'Guest' },
replies: [],
attachments: [],
mentions: [],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
sessionId: null,
isCompleted: false,
isInternal: false,
completionLastChangedBy: null,
reactionCounts: [],
},
])
const app = new Hono().route('/', publicShareRoute)
const res = await app.request('/shares/share-1/files/file-1/comments/print', {
headers: { 'x-share-password': 'secret' },
})
expect(res.status).toBe(200)
expect(assetService.listAllComments).toHaveBeenCalledWith('file-1', undefined, {
excludeInternal: true,
})
const body = await res.json()
expect(body.breadcrumbs).toEqual(['Client Review', 'Inner Folder'])
expect(body.asset.ancestorFolders).toEqual([{ id: 'inner', name: 'Inner Folder' }])
expect(body.asset.fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }])
expect(JSON.stringify(body)).not.toContain('Secret Project Folder')
expect(JSON.stringify(body)).not.toContain('private-parent')
expect(body.comments).toHaveLength(1)
})
it('GET /shares/:shareId/files/:fileId/comments/print returns 401 on invalid password', async () => {
vi.spyOn(shareService, 'verifyPublicAccess').mockRejectedValue(
new ShareLinkPasswordInvalidError('Invalid password'),
)
const app = new Hono().route('/', publicShareRoute)
const res = await app.request('/shares/share-1/files/file-1/comments/print')
expect(res.status).toBe(401)
})
it('GET /shares/:shareId/files/:fileId/comments/frame passes watermarkConfigId and password query param', async () => {
const verifySpy = vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
id: 'share-1',
name: 'Watermarked Review',
rootFolderId: 'share-root',
projectId: 'proj-1',
watermarkConfigId: 'wm-1',
} as never)
vi.spyOn(assetService, 'resolveTargetAssetId').mockResolvedValue('target-file-1')
const extractSpy = vi.spyOn(commentFrameService, 'extractFrame').mockResolvedValue({
buffer: Buffer.from('wm-webp'),
mimeType: 'image/webp',
})
vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map())
const app = new Hono().route('/', publicShareRoute)
const res = await app.request(
'/shares/share-1/files/file-1/comments/frame?second=4.2&width=400&p=pw123',
)
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('image/webp')
expect(verifySpy).toHaveBeenCalledWith('share-1', 'file-1', 'pw123')
expect(extractSpy).toHaveBeenCalledWith({
assetId: 'target-file-1',
second: 4.2,
width: 400,
watermarkConfigId: 'wm-1',
signal: expect.any(AbortSignal),
})
})
it('GET /shares/:shareId/files/:fileId/comments excludes internal comments', async () => {
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
id: 'share-1',
rootFolderId: 'share-root',
projectId: 'proj-1',
} as never)
vi.spyOn(assetService, 'resolveTargetAssetId').mockResolvedValue('file-1')
const listSpy = vi.spyOn(assetService, 'listComments').mockResolvedValue({
data: [],
pageInfo: { cursor: undefined, total: 0 },
})
const app = new Hono().route('/', publicShareRoute)
const res = await app.request('/shares/share-1/files/file-1/comments')
expect(res.status).toBe(200)
expect(listSpy).toHaveBeenCalledWith('file-1', expect.anything(), undefined, {
excludeInternal: true,
})
})
it('POST /shares/:shareId/files/:fileId/comments rejects isInternal=true with 400', async () => {
const app = new Hono().route('/', publicShareRoute)
const res = await app.request('/shares/share-1/files/file-1/comments', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'secret', attachmentIds: [], isInternal: true }),
})
expect(res.status).toBe(400)
})
})
+64 -203
View File
@@ -1,19 +1,11 @@
import { Hono } from 'hono'
import type { Context } from 'hono'
import { HTTPException } from 'hono/http-exception'
import { getCookie } from 'hono/cookie'
import { zValidator } from '@hono/zod-validator'
import { shareService } from '@shumai/core/src/share/share'
import { shareActivityService } from '@shumai/core/src/share/share-activity'
import { assetService } from '@shumai/core/src/asset/asset'
import { commentFrameService } from '@shumai/core/src/comment/comment-frame'
import { watermarkService } from '@shumai/core/src/watermark/watermark'
import {
paginationParamsSchema,
assetTypeFilterSchema,
commentFrameQuerySchema,
recordShareViewRequestSchema,
} from '@shumai/dtos'
import { paginationParamsSchema, assetTypeFilterSchema } from '@shumai/dtos'
import { z } from 'zod'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { FieldInfo } from '@shumai/dtos'
@@ -123,20 +115,6 @@ async function applyWatermarkToAssetMedia(
}
}
/**
* Keeps only the custom field values the share link is configured to show.
* Fields are hidden by default; `fieldVisibility` lists the keys turned on
* for this share, matching what `GET /shares/:shareId/fields` returns.
*/
function filterSharedFieldValues(asset: AssetInfo, fieldVisibility: unknown): AssetInfo {
if (!asset.fieldValues) return asset
const visibility = (fieldVisibility || {}) as Record<string, boolean>
return {
...asset,
fieldValues: asset.fieldValues.filter((fv) => Boolean(visibility[fv.fieldId])),
}
}
const app = new Hono()
function toFieldInfo(
@@ -155,9 +133,6 @@ function toFieldInfo(
}
export function handlePublicShareError(c: Context, err: unknown) {
if (err instanceof HTTPException) {
throw err
}
if (err instanceof ShareLinkPasswordInvalidError) {
return c.json({ error: 'Unauthorized' }, 401)
}
@@ -181,36 +156,7 @@ const sharedChildrenRequestSchema = paginationParamsSchema.extend({
assetType: assetTypeFilterSchema.optional().default('file'),
})
async function getPublicShareUserId(c: Context, shareId: string) {
const session = await auth.api.getSession({ headers: c.req.raw.headers })
if (session?.user) return session.user.id
const token = getCookie(c, `shumai_guest_${shareId}`) || getCookie(c, 'shumai_guest')
const verified = token && verifyGuestToken(token, shareId)
if (!verified) return undefined
const guestUser = await userService.getUserById(verified.userId)
return guestUser?.guestEmail ? guestUser.id : undefined
}
const route = app
.post('/shares/:shareId/views', zValidator('json', recordShareViewRequestSchema), async (c) => {
const shareId = c.req.param('shareId')
const password = c.req.header('x-share-password')
const { assetId, isShareEntry } = c.req.valid('json')
try {
const share = await shareService.verifyPublicAccess(shareId, assetId, password)
const targetId =
assetId && assetId !== share.rootFolderId
? await assetService.resolveLatestVersionId(assetId)
: undefined
const userId = await getPublicShareUserId(c, shareId)
await shareActivityService.recordView(shareId, { assetId: targetId, isShareEntry, userId })
return c.body(null, 204)
} catch (err) {
return handlePublicShareError(c, err)
}
})
.get('/shares/:shareId/info', async (c) => {
const shareId = c.req.param('shareId')
const password = c.req.header('x-share-password')
@@ -276,16 +222,13 @@ const route = app
order = parts[1]
}
const res = await assetService.listChildren(
{
...req,
assetId: folderId,
assetType: req.assetType || 'file',
sort,
order,
},
{ excludeInternalComments: true },
)
const res = await assetService.listChildren({
...req,
assetId: folderId,
assetType: req.assetType || 'file',
sort,
order,
})
if (shareLink.watermarkConfigId && res.data.length > 0) {
// Resolve symlink targets once and reuse for the media lookup, so each
@@ -317,8 +260,6 @@ const route = app
}
}
res.data = res.data.map((item) => filterSharedFieldValues(item, shareLink.fieldVisibility))
return c.json(res)
} catch (err) {
return handlePublicShareError(c, err)
@@ -333,10 +274,7 @@ const route = app
try {
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
let asset = await assetService.getAsset(
{ assetId: fileId },
{ excludeInternalComments: true },
)
let asset = await assetService.getAsset({ assetId: fileId })
// Only video/image/3d assets are subject to watermark protection; skip the
// watermark lookup entirely for other media types (pdf, audio, ...).
@@ -360,25 +298,19 @@ const route = app
asset.media.hls.url = `/api/shares/${shareLink.id}/files/${asset.id}/m3u8/master.m3u8${pwQuery}`
}
return c.json(filterSharedFieldValues(asset, shareLink.fieldVisibility))
return c.json(asset)
} catch (err) {
return handlePublicShareError(c, err)
}
})
.post(
'/shares/:shareId/files/:fileId/download-url',
zValidator(
'json',
z.object({
key: z.string().min(1),
purpose: z.enum(['download', 'prepare', 'clipboard']).default('download'),
}),
),
zValidator('json', z.object({ key: z.string().min(1) })),
async (c) => {
const shareId = c.req.param('shareId')
const fileId = c.req.param('fileId')
const password = c.req.header('x-share-password')
const { key, purpose } = c.req.valid('json')
const { key } = c.req.valid('json')
try {
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
@@ -391,16 +323,7 @@ const route = app
return c.json({ error: 'Invalid key' }, 400)
}
const { url, assetId } = await assetService.getDownloadUrlWithAsset(fileId, key)
if (assetId !== fileId) await shareService.verifyPublicAccess(shareId, assetId, password)
if (purpose === 'download') {
const userId = await getPublicShareUserId(c, shareId)
await shareActivityService.recordEvent(shareId, {
kind: 'asset_downloaded',
assetId,
userId,
})
}
const url = await assetService.getDownloadUrl(fileId, key)
return c.json({ url })
} catch (err) {
return handlePublicShareError(c, err)
@@ -420,107 +343,32 @@ const route = app
await shareService.verifyPublicAccess(shareId, fileId, password)
const targetFileId = await assetService.resolveTargetAssetId(fileId)
const userId = await getPublicShareUserId(c, shareId)
const res = await assetService.listComments(targetFileId, req, userId, {
excludeInternal: true,
let userId: string | undefined
const session = await auth.api.getSession({
headers: c.req.raw.headers,
})
if (session?.user) {
userId = session.user.id
} else {
const cookieName = `shumai_guest_${shareId}`
const token = getCookie(c, cookieName) || getCookie(c, 'shumai_guest')
if (token) {
const verified = verifyGuestToken(token, shareId)
if (verified) {
const guestUser = await userService.getUserById(verified.userId)
if (guestUser && guestUser.guestEmail) {
userId = guestUser.id
}
}
}
}
const res = await assetService.listComments(targetFileId, req, userId)
return c.json(res)
} catch (err) {
return handlePublicShareError(c, err)
}
},
)
.get('/shares/:shareId/files/:fileId/comments/print', async (c) => {
const shareId = c.req.param('shareId')
const fileId = c.req.param('fileId')
const password = c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
try {
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
let asset = await assetService.getAsset(
{ assetId: fileId },
{ excludeInternalComments: true },
)
const targetAssetId = await assetService.resolveLatestVersionId(fileId)
if (
shareLink.watermarkConfigId &&
(asset.proxyType === 'video' || asset.proxyType === 'image' || asset.proxyType === '3d')
) {
const wfMap = await watermarkService.getCompletedWatermarkMediaMap(
[targetAssetId],
shareLink.watermarkConfigId,
)
asset = await applyWatermarkToAssetMedia(
asset,
wfMap.get(targetAssetId) ?? null,
shareLink.id,
password,
)
}
const targetFileId = await assetService.resolveTargetAssetId(fileId)
const userId = await getPublicShareUserId(c, shareId)
const comments = await assetService.listAllComments(targetFileId, userId, {
excludeInternal: true,
})
// Scope breadcrumbs strictly to folders inside the share link root so private
// project and parent folder names are never leaked.
const ancestors = asset.ancestorFolders ?? []
const rootIndex = ancestors.findIndex((f) => f.id === shareLink.rootFolderId)
const scopedAncestors = rootIndex !== -1 ? ancestors.slice(0, rootIndex) : []
const scopedFolders = [...scopedAncestors]
.reverse()
.map((f) => f.name)
.filter((name): name is string => Boolean(name))
const breadcrumbs = shareLink.name ? [shareLink.name, ...scopedFolders] : scopedFolders
return c.json({
asset: {
...filterSharedFieldValues(asset, shareLink.fieldVisibility),
ancestorFolders: scopedAncestors,
},
breadcrumbs,
comments,
})
} catch (err) {
return handlePublicShareError(c, err)
}
})
.get(
'/shares/:shareId/files/:fileId/comments/frame',
zValidator('query', commentFrameQuerySchema),
async (c) => {
const shareId = c.req.param('shareId')
const fileId = c.req.param('fileId')
const password =
c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
const { second, width } = c.req.valid('query')
try {
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
const targetFileId = await assetService.resolveTargetAssetId(fileId)
const result = await commentFrameService.extractFrame({
assetId: targetFileId,
second,
width,
watermarkConfigId: shareLink.watermarkConfigId,
signal: c.req.raw.signal,
})
return c.body(new Uint8Array(result.buffer), 200, {
'Content-Type': result.mimeType,
'Cache-Control': 'private, max-age=300',
})
} catch (err) {
if (err instanceof HTTPException) {
throw err
}
return handlePublicShareError(c, err)
}
},
)
.post(
'/shares/:shareId/files/:fileId/comments',
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })),
@@ -534,36 +382,49 @@ const route = app
return c.json({ error: 'Attachments are not allowed on public share comments' }, 400)
}
if (req.isInternal) {
return c.json({ error: 'Internal comments are not allowed on public share links' }, 400)
}
try {
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
const shareLink = await shareService.getShareLink(shareId)
await shareService.verifyPublicAccess(shareId, fileId, password)
const targetFileId = await assetService.resolveTargetAssetId(fileId)
const teamId = await projectService.getProjectTeam(shareLink.projectId)
const userId = await getPublicShareUserId(c, shareId)
// Identify user
let userId: string | null = null
const session = await auth.api.getSession({
headers: c.req.raw.headers,
})
if (session?.user) {
userId = session.user.id
} else {
const cookieName = `shumai_guest_${shareId}`
const token = getCookie(c, cookieName) || getCookie(c, 'shumai_guest')
if (token) {
const verified = verifyGuestToken(token, shareId)
if (verified) {
const guestUser = await userService.getUserById(verified.userId)
if (guestUser && guestUser.guestEmail) {
userId = guestUser.id
}
}
}
}
if (!userId) {
return c.json({ error: 'Unauthorized' }, 401)
}
const comment = await assetService.createComment(
{
assetId: targetFileId,
userId,
replyToId: req.replyToId,
message: req.message,
annotations: req.annotations,
second: req.second,
attachmentIds: req.attachmentIds,
isInternal: false,
},
{ shareLinkId: shareId },
)
const comment = await assetService.createComment({
assetId: targetFileId,
userId: userId,
replyToId: req.replyToId,
message: req.message,
annotations: req.annotations,
second: req.second,
attachmentIds: req.attachmentIds,
})
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
+5 -274
View File
@@ -4,15 +4,9 @@ import shareRoute from './share'
import publicShareRoute from './public-share'
import { authMiddleware } from './middleware/auth'
import { shareService } from '@shumai/core/src/share/share'
import { shareActivityService } from '@shumai/core/src/share/share-activity'
import { HTTPException } from 'hono/http-exception'
import { assetService } from '@shumai/core/src/asset/asset'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import {
ShareLinkPasswordInvalidError,
ShareLinkExpiredError,
ShareLinkNotFoundError,
} from '@shumai/core/src/share/errors'
import { ShareLinkPasswordInvalidError, ShareLinkExpiredError } from '@shumai/core/src/share/errors'
import { createGuestToken } from '@shumai/core/src/auth/guest-token'
import { userService } from '@shumai/core/src/user/user'
import { notificationService } from '@shumai/core/src/notification/notification'
@@ -99,82 +93,6 @@ describe('Share API', () => {
})
// Public Routes
describe('POST /shares/:shareId/views', () => {
test('attributes an authorized asset view to a verified guest', async () => {
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
rootFolderId: 'folder1',
} as Awaited<ReturnType<typeof shareService.verifyPublicAccess>>)
vi.spyOn(assetService, 'resolveLatestVersionId').mockResolvedValue('asset1')
vi.spyOn(userService, 'getUserById').mockResolvedValue({
id: 'guest1',
guestEmail: 'alice@example.com',
} as Awaited<ReturnType<typeof userService.getUserById>>)
const record = vi.spyOn(shareActivityService, 'recordView').mockResolvedValue(undefined)
const token = createGuestToken({ userId: 'guest1', shareId: 'share1' })
const res = await app.request('/shares/share1/views', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-share-password': 'pass',
Cookie: `shumai_guest_share1=${token}`,
},
body: JSON.stringify({ assetId: 'alias1', isShareEntry: true }),
})
expect(res.status).toBe(204)
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'alias1', 'pass')
expect(record).toHaveBeenCalledWith('share1', {
assetId: 'asset1',
isShareEntry: true,
userId: 'guest1',
})
})
test('a rejected view leaves the counter and history alone', async () => {
vi.spyOn(shareService, 'verifyPublicAccess').mockRejectedValue(
new ShareLinkPasswordInvalidError('Incorrect password'),
)
const record = vi.spyOn(shareActivityService, 'recordView').mockResolvedValue(undefined)
const res = await app.request('/shares/share1/views', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: '{}',
})
expect(res.status).toBe(401)
expect(record).not.toHaveBeenCalled()
})
})
describe('GET /shares/:shareId/activities', () => {
test('returns the requested page to a share reader', async () => {
const list = vi.spyOn(shareActivityService, 'list').mockResolvedValue({
data: [],
pageInfo: { total: 0 },
})
const res = await app.request('/shares/share1/activities?first=20')
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ data: [], pageInfo: { total: 0 } })
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
id: 'share1',
permission: Permission.Read,
type: ResourceType.Share,
}),
)
expect(list).toHaveBeenCalledWith('share1', { first: 20 })
})
test('denies access to activity without share read permission', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new HTTPException(403))
const list = vi.spyOn(shareActivityService, 'list')
const res = await app.request('/shares/share1/activities')
expect(res.status).toBe(403)
expect(list).not.toHaveBeenCalled()
})
})
describe('GET /shares/:shareId/info', () => {
test('Success', async () => {
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
@@ -183,8 +101,6 @@ describe('Share API', () => {
isDisabled: false,
allowDownload: false,
isExpired: false,
views: 0,
lastViewedAt: null,
hasPassword: true,
rootFolderId: 'folder1',
projectId: 'project1',
@@ -218,8 +134,6 @@ describe('Share API', () => {
isDisabled: false,
allowDownload: false,
isExpired: false,
views: 0,
lastViewedAt: null,
hasPassword: true,
rootFolderId: 'folder1',
projectId: 'project1',
@@ -247,8 +161,6 @@ describe('Share API', () => {
isDisabled: false,
allowDownload: false,
isExpired: false,
views: 0,
lastViewedAt: null,
hasPassword: true,
rootFolderId: 'folder1',
projectId: 'project1',
@@ -305,7 +217,6 @@ describe('Share API', () => {
sort: 'name',
order: 'asc',
}),
{ excludeInternalComments: true },
)
})
@@ -439,119 +350,6 @@ describe('Share API', () => {
})
})
describe('public share field values', () => {
const shareLinkWithFields = {
id: 'share1',
name: 'My Share',
isDisabled: false,
allowDownload: false,
rootFolderId: 'folder1',
projectId: 'project1',
password: null,
expireAt: null,
watermarkConfigId: null,
fieldVisibility: { status: true, internalNote: false },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any
const assetWithFields = {
id: 'file1',
name: 'a.png',
sizeByte: 1,
fileCount: 0,
type: 'file',
status: 'processed',
proxyType: 'pdf',
fieldValues: [
{ fieldId: 'status', value: 'Approved' },
{ fieldId: 'internalNote', value: 'not for guests' },
{ fieldId: 'rating', value: 3 },
],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any
test('children only include field values visible on the share', async () => {
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithFields)
vi.spyOn(assetService, 'listChildren').mockResolvedValue({
data: [assetWithFields],
pageInfo: { total: 1, cursor: undefined },
})
const res = await app.request('/shares/share1/folders/folder1/children?assetType=file')
expect(res.status).toBe(200)
const body = await res.json()
expect(body.data[0].fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }])
})
test('children with watermark only include field values visible on the share', async () => {
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
...shareLinkWithFields,
watermarkConfigId: 'cfg1',
})
vi.spyOn(assetService, 'listChildren').mockResolvedValue({
data: [assetWithFields],
pageInfo: { total: 1, cursor: undefined },
})
vi.spyOn(assetService, 'resolveLatestVersionId').mockImplementation(async (id) => id)
vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map())
const res = await app.request('/shares/share1/folders/folder1/children?assetType=file')
expect(res.status).toBe(200)
const body = await res.json()
expect(body.data[0].fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }])
})
test('children include no field values when the share shows no fields', async () => {
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
...shareLinkWithFields,
fieldVisibility: null,
})
vi.spyOn(assetService, 'listChildren').mockResolvedValue({
data: [assetWithFields],
pageInfo: { total: 1, cursor: undefined },
})
const res = await app.request('/shares/share1/folders/folder1/children?assetType=file')
expect(res.status).toBe(200)
const body = await res.json()
expect(body.data[0].fieldValues).toEqual([])
})
test('file detail only includes field values visible on the share', async () => {
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithFields)
vi.spyOn(assetService, 'getAsset').mockResolvedValue(assetWithFields)
const res = await app.request('/shares/share1/files/file1')
expect(res.status).toBe(200)
const body = await res.json()
expect(body.fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }])
})
test('file detail with watermark only includes field values visible on the share', async () => {
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
...shareLinkWithFields,
watermarkConfigId: 'cfg1',
})
vi.spyOn(assetService, 'getAsset').mockResolvedValue({
...assetWithFields,
proxyType: 'image',
media: { proxyType: 'image', videoTranscodes: [], imageTranscodes: [] },
})
vi.spyOn(assetService, 'resolveLatestVersionId').mockResolvedValue('file1')
vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map())
const res = await app.request('/shares/share1/files/file1')
expect(res.status).toBe(200)
const body = await res.json()
expect(body.fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }])
})
})
describe('GET /shares/:shareId/files/:fileId', () => {
const shareLinkWithWatermark = {
id: 'share1',
@@ -914,8 +712,6 @@ describe('Share API', () => {
rootFolderId: 'root1',
projectId: 'project1',
isExpired: false,
views: 0,
lastViewedAt: null,
hasPassword: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
@@ -960,8 +756,6 @@ describe('Share API', () => {
rootFolderId: 'root1',
projectId: 'project1',
isExpired: false,
views: 0,
lastViewedAt: null,
hasPassword: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
@@ -1019,8 +813,6 @@ describe('Share API', () => {
rootFolderId: 'root1',
projectId: 'project1',
isExpired: false,
views: 0,
lastViewedAt: null,
hasPassword: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
@@ -1052,8 +844,6 @@ describe('Share API', () => {
rootFolderId: 'root1',
projectId: 'project1',
isExpired: false,
views: 0,
lastViewedAt: null,
hasPassword: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
@@ -1098,8 +888,6 @@ describe('Share API', () => {
rootFolderId: 'root1',
projectId: 'project1',
isExpired: false,
views: 0,
lastViewedAt: null,
hasPassword: false,
watermarkStatus: 'processing',
watermarkConfigId: 'cfg1',
@@ -1188,60 +976,12 @@ describe('Share API', () => {
})
describe('POST /shares/:shareId/files/:fileId/download-url', () => {
test('requires share access to the concrete asset selected for download', async () => {
vi.spyOn(shareService, 'verifyPublicAccess')
.mockResolvedValueOnce({
allowDownload: true,
} as Awaited<ReturnType<typeof shareService.verifyPublicAccess>>)
.mockRejectedValueOnce(new ShareLinkNotFoundError('Asset is not shared'))
vi.spyOn(assetService, 'getDownloadUrlWithAsset').mockResolvedValue({
url: 'https://s3.example.com/download',
assetId: 'unshared',
})
const record = vi.spyOn(shareActivityService, 'recordEvent').mockResolvedValue(undefined)
const res = await app.request('/shares/share1/files/file1/download-url', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'files/download.png' }),
})
expect(res.status).toBe(404)
expect(await res.json()).toEqual({ error: 'Asset is not shared' })
expect(record).not.toHaveBeenCalled()
})
test.each(['prepare', 'clipboard'])(
'does not count a URL requested for %s',
async (purpose) => {
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
allowDownload: true,
} as Awaited<ReturnType<typeof shareService.verifyPublicAccess>>)
vi.spyOn(assetService, 'getDownloadUrlWithAsset').mockResolvedValue({
url: 'https://s3.example.com/download',
assetId: 'target1',
})
const record = vi.spyOn(shareActivityService, 'recordEvent').mockResolvedValue(undefined)
const res = await app.request('/shares/share1/files/symlink1/download-url', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'files/target1/fly.png', purpose }),
})
expect(res.status).toBe(200)
expect(record).not.toHaveBeenCalled()
},
)
test('Success for symlink asset in share', async () => {
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
allowDownload: true,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
vi.spyOn(assetService, 'getDownloadUrlWithAsset').mockResolvedValue({
url: 'https://s3.example.com/download',
assetId: 'target1',
})
const record = vi.spyOn(shareActivityService, 'recordEvent').mockResolvedValue(undefined)
vi.spyOn(assetService, 'getDownloadUrl').mockResolvedValue('https://s3.example.com/download')
const res = await app.request('/shares/share1/files/symlink1/download-url', {
method: 'POST',
@@ -1253,15 +993,7 @@ describe('Share API', () => {
const body = await res.json()
expect(body.url).toBe('https://s3.example.com/download')
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'symlink1', undefined)
expect(assetService.getDownloadUrlWithAsset).toHaveBeenCalledWith(
'symlink1',
'files/target1/fly.png',
)
expect(record).toHaveBeenCalledWith('share1', {
kind: 'asset_downloaded',
assetId: 'target1',
userId: undefined,
})
expect(assetService.getDownloadUrl).toHaveBeenCalledWith('symlink1', 'files/target1/fly.png')
})
test('Rejects when allowDownload is disabled', async () => {
@@ -1272,8 +1004,8 @@ describe('Share API', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
const getDownloadUrlSpy = vi
.spyOn(assetService, 'getDownloadUrlWithAsset')
.mockResolvedValue({ url: 'https://s3.example.com/download', assetId: 'target1' })
.spyOn(assetService, 'getDownloadUrl')
.mockResolvedValue('https://s3.example.com/download')
const res = await app.request('/shares/share1/files/symlink1/download-url', {
method: 'POST',
@@ -1441,7 +1173,6 @@ describe('Share API', () => {
userId: 'guest1',
message: 'hello from alice',
}),
{ shareLinkId: 'share1' },
)
})
-12
View File
@@ -2,13 +2,11 @@ import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { shareService } from '@shumai/core/src/share/share'
import { shareActivityService } from '@shumai/core/src/share/share-activity'
import { projectService } from '@shumai/core/src/project/project'
import {
createShareLinkRequestSchema,
updateShareLinkRequestSchema,
listShareLinksRequestSchema,
paginationParamsSchema,
addAssetToShareRequestSchema,
updateShareLinkWatermarkRequestSchema,
AuditAction,
@@ -92,16 +90,6 @@ const route = new Hono<{ Variables: { user: User } }>()
const shareLink = await shareService.getShareLink(shareId)
return c.json(shareLink)
})
.get('/shares/:shareId/activities', zValidator('query', paginationParamsSchema), async (c) => {
const shareId = c.req.param('shareId')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Read,
type: ResourceType.Share,
id: shareId,
})
return c.json(await shareActivityService.list(shareId, c.req.valid('query')))
})
.put('/shares/:shareId', zValidator('json', updateShareLinkRequestSchema), async (c) => {
const shareId = c.req.param('shareId')
const user = c.get('user')
-62
View File
@@ -254,67 +254,5 @@ describe('Upload API', () => {
})
expect(res.status).toBe(404)
})
it('accepts a valid signed local upload URL', async () => {
vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('local')
const putObjectSpy = vi.spyOn(s3Module.s3Service, 'putObject').mockResolvedValue(undefined)
const signedPath = s3Module.signLocalUrl('test-bucket', 'files/test.txt')
const localPath = signedPath.replace(/^\/api/, '')
const localApp = new Hono().route('/', localUploadRoute)
const res = await localApp.request(localPath, {
method: 'PUT',
headers: { 'Content-Type': 'text/plain', 'Content-Length': '5' },
body: 'hello',
})
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ success: true })
expect(putObjectSpy).toHaveBeenCalledWith(
'test-bucket',
'files/test.txt',
expect.anything(),
5,
'text/plain',
)
})
it('returns 403 when local upload URL signature is expired', async () => {
vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('local')
const putObjectSpy = vi.spyOn(s3Module.s3Service, 'putObject').mockResolvedValue(undefined)
const signedPath = s3Module.signLocalUrl('test-bucket', 'files/test.txt', -10)
const localPath = signedPath.replace(/^\/api/, '')
const localApp = new Hono().route('/', localUploadRoute)
const res = await localApp.request(localPath, {
method: 'PUT',
body: 'hello',
})
expect(res.status).toBe(403)
expect(putObjectSpy).not.toHaveBeenCalled()
})
it('returns 403 when Expires query param is missing or invalid', async () => {
vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('local')
const putObjectSpy = vi.spyOn(s3Module.s3Service, 'putObject').mockResolvedValue(undefined)
const localApp = new Hono().route('/', localUploadRoute)
const missingRes = await localApp.request('/upload/local?bucket=b&key=k&Signature=sig', {
method: 'PUT',
body: 'hello',
})
expect(missingRes.status).toBe(403)
const invalidRes = await localApp.request(
'/upload/local?bucket=b&key=k&Signature=sig&Expires=not-a-number',
{
method: 'PUT',
body: 'hello',
},
)
expect(invalidRes.status).toBe(403)
expect(putObjectSpy).not.toHaveBeenCalled()
})
})
})
+3 -3
View File
@@ -27,10 +27,10 @@ export const localUploadRoute = new Hono().put(
return c.text('Not found', 404)
}
const { bucket, key, Signature, Expires } = c.req.valid('query')
const { bucket, key, Signature } = c.req.valid('query')
if (!verifyLocalUrlSignature(bucket, key, Signature, Expires)) {
return c.text('Invalid or expired signature', 403)
if (!verifyLocalUrlSignature(bucket, key, Signature)) {
return c.text('Invalid signature', 403)
}
const contentType = c.req.header('Content-Type')
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/core",
"version": "0.7.2",
"version": "0.6.6",
"private": true,
"type": "module",
"main": "./src/index.ts",
-1
View File
@@ -137,7 +137,6 @@ export class AssetArchiveService {
WorkflowTaskType.transcode_screenshot,
WorkflowTaskType.transcode_image_annotation,
WorkflowTaskType.transcode_watermark,
WorkflowTaskType.transcode_video_chunks,
],
},
},
+7 -697
View File
@@ -1,5 +1,5 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { getPrismaTestingHelper, prisma } from '@shumai/db'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { HTTPException } from 'hono/http-exception'
@@ -8,7 +8,6 @@ import { s3Service, getStorageBackend } from '@shumai/core/src/s3/s3'
import * as archiveStorageModule from '@shumai/core/src/s3/archive-storage'
import { uploadService } from '@shumai/core/src/upload/upload'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { watermarkService } from '@shumai/core/src/watermark/watermark'
import { AssetService } from './asset'
import { ensureJpegInStorage } from '@shumai/core/src/s3/preview-converter'
@@ -23,7 +22,6 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
deletePrefix: vi.fn().mockResolvedValue(1),
copyObject: vi.fn().mockResolvedValue(undefined),
getStoragePath: vi.fn((bucket: string, key: string) => `/mock/data/${bucket}/${key}`),
listObjects: vi.fn().mockResolvedValue([]),
},
getStorageBackend: vi.fn().mockReturnValue('local'),
}))
@@ -49,31 +47,6 @@ describe('AssetService', () => {
vi.clearAllMocks()
})
it('checks generated file expiration hourly while continuing regular cleanup', async () => {
vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] })
const startedAt = Date.now()
const regularCleanup = vi
.spyOn(watermarkService, 'purgeOrphanWatermarkConfigs')
.mockResolvedValue(0)
try {
await assetService.startCleanupJob()
await vi.waitFor(() => expect(s3Service.listObjects).toHaveBeenCalledTimes(1))
expect(s3Service.listObjects).toHaveBeenCalledWith(expect.any(String), 'temp/generated/')
await vi.advanceTimersByTimeAsync(5_000)
await vi.waitFor(() => expect(regularCleanup).toHaveBeenCalledTimes(2))
expect(s3Service.listObjects).toHaveBeenCalledTimes(1)
vi.setSystemTime(startedAt + 60 * 60 * 1000)
await vi.advanceTimersByTimeAsync(5_000)
await vi.waitFor(() => expect(s3Service.listObjects).toHaveBeenCalledTimes(2))
} finally {
assetService.stopCleanupJob()
regularCleanup.mockRestore()
vi.useRealTimers()
}
})
const setupBasicAssets = async () => {
const user = await prisma.user.create({
data: {
@@ -941,7 +914,7 @@ describe('AssetService', () => {
).resolves.not.toThrow()
})
it('cleans up deleted comment attachments through the asset cleanup job', async () => {
it('deleteComment cleans up S3 attachment files and database records', async () => {
const { user, project, assets } = await setupBasicAssets()
// 1. Create StorageKey and Asset for attachment
@@ -949,15 +922,15 @@ describe('AssetService', () => {
data: {
key: 'attachments/test-attachment-file.png',
status: 'active',
createdAt: new Date(Date.now() - 60_000),
},
})
const attachmentAsset = await prisma.asset.create({
data: {
name: 'test-attachment-file.png',
type: AssetType.attachment,
type: AssetType.file,
projectId: project.id,
parentId: assets.root.id,
creatorId: user.id,
storageKeyId: storageKey.id,
sizeByte: 100,
@@ -988,278 +961,18 @@ describe('AssetService', () => {
// 5. Verify the comment is deleted from DB
await expect(prisma.assetComment.findUnique({ where: { id: comment.id } })).resolves.toBeNull()
// 6. The attachment is removed immediately; the storage cleanup owns object deletion.
// 6. Verify that the attachment Asset and StorageKey are deleted from DB
await expect(prisma.asset.findUnique({ where: { id: attachmentAsset.id } })).resolves.toBeNull()
expect(s3Service.deleteObject).not.toHaveBeenCalled()
await assetService.emptyTrash(project.id)
await expect(prisma.storageKey.findUnique({ where: { id: storageKey.id } })).resolves.toBeNull()
// 7. Verify S3 deletion was called
const { s3Service } = await import('@shumai/core/src/s3/s3')
expect(s3Service.deleteObject).toHaveBeenCalledWith(
'shumai',
'attachments/test-attachment-file.png',
)
})
describe('comment attachments', () => {
const addProjectReviewer = async (teamId: string) => {
const reviewer = await prisma.user.create({
data: { name: 'Reviewer', type: 'human', email: `reviewer-${Date.now()}@example.com` },
})
await prisma.teamMember.create({
data: { teamId, userId: reviewer.id, role: 'reviewer' },
})
return reviewer
}
const createUpload = async (projectId: string, creatorId: string, name: string) => {
const storageKey = await prisma.storageKey.create({
data: { key: `attachments/${name}`, status: 'active' },
})
return await prisma.asset.create({
data: {
name,
type: AssetType.attachment,
projectId,
creatorId,
sizeByte: 1,
status: 'uploaded',
storageKeyId: storageKey.id,
},
})
}
it('only attaches comment uploads made by the commenter', async () => {
const { user, project, assets } = await setupBasicAssets()
const reviewer = await addProjectReviewer(project.teamId)
const ownerUpload = await createUpload(project.id, user.id, 'owner-upload.png')
const reviewerUpload = await createUpload(project.id, reviewer.id, 'reviewer-upload.png')
const comment = await assetService.createComment({
assetId: assets.fileA1.id,
userId: reviewer.id,
message: 'looks good',
attachmentIds: [assets.fileA2.id, ownerUpload.id, reviewerUpload.id],
})
const links = await prisma.assetCommentAttachment.findMany({
where: { commentId: comment.id },
})
expect(links.map((l) => l.assetId)).toEqual([reviewerUpload.id])
})
it('does not attach an upload that already belongs to another comment', async () => {
const { user, assets, project } = await setupBasicAssets()
const upload = await createUpload(project.id, user.id, 'shared.png')
await assetService.createComment({
assetId: assets.fileA1.id,
userId: user.id,
message: 'first',
attachmentIds: [upload.id],
})
const second = await assetService.createComment({
assetId: assets.fileA1.id,
userId: user.id,
message: 'second',
attachmentIds: [upload.id],
})
const links = await prisma.assetCommentAttachment.findMany({
where: { commentId: second.id },
})
expect(links).toHaveLength(0)
})
it('allows only one concurrent comment to claim an upload', async () => {
// The normal test proxy serializes transactions on a single connection.
const db = getPrismaTestingHelper().getUnderlyingClient() as typeof prisma
const service = new AssetService(db)
const { user, team, project, file, upload } = await db.$transaction(async (tx) => {
const user = await tx.user.create({
data: { name: 'Commenter', email: `attachment-race-${crypto.randomUUID()}@example.com` },
})
const team = await tx.team.create({ data: { name: 'Attachment race' } })
const project = await tx.project.create({ data: { name: 'Project', teamId: team.id } })
const file = await tx.asset.create({
data: {
name: 'File',
type: AssetType.file,
status: AssetStatus.processed,
projectId: project.id,
creatorId: user.id,
},
})
const upload = await tx.asset.create({
data: {
name: 'Upload',
type: AssetType.attachment,
status: AssetStatus.uploaded,
projectId: project.id,
creatorId: user.id,
},
})
return { user, team, project, file, upload }
})
let claims: Promise<PromiseSettledResult<unknown>[]> | undefined
try {
await db.$transaction(async (tx) => {
await tx.$queryRaw`SELECT id FROM assets WHERE id = ${upload.id} FOR UPDATE`
claims = Promise.allSettled(
['First comment', 'Second comment'].map((message) =>
service.createComment(
{ assetId: file.id, userId: user.id, message, attachmentIds: [upload.id] },
{ triggerAgents: false },
),
),
)
// Release the upload only after both requests are waiting on its row lock.
await vi.waitFor(
async () => {
const [waiters] = await tx.$queryRaw<{ count: number }[]>`
WITH RECURSIVE waiters(pid) AS (
SELECT pg_backend_pid()
UNION
SELECT pending.pid
FROM waiters
JOIN (SELECT DISTINCT pid FROM pg_locks WHERE NOT granted) pending
ON waiters.pid = ANY(pg_blocking_pids(pending.pid))
)
SELECT count(*)::int - 1 AS count FROM waiters
`
expect(waiters.count).toBe(2)
},
{ timeout: 3_000 },
)
})
expect(await claims).toEqual([
expect.objectContaining({ status: 'fulfilled' }),
expect.objectContaining({ status: 'fulfilled' }),
])
await expect(
db.assetCommentAttachment.count({ where: { assetId: upload.id } }),
).resolves.toBe(1)
} finally {
await claims
await db.asset.deleteMany({ where: { projectId: project.id } })
await db.project.delete({ where: { id: project.id } })
await db.team.delete({ where: { id: team.id } })
await db.user.delete({ where: { id: user.id } })
}
})
it('deleteComment keeps project files that are linked to the comment', async () => {
const { project, assets } = await setupBasicAssets()
const reviewer = await addProjectReviewer(project.teamId)
const fileKey = await prisma.storageKey.create({
data: { key: 'files/01JAAAAAAAAAAAAAAAAAAAAAAA/deliverable.mov', status: 'active' },
})
await prisma.asset.update({
where: { id: assets.fileA2.id },
data: { storageKeyId: fileKey.id },
})
const comment = await assetService.createComment({
assetId: assets.fileA1.id,
userId: reviewer.id,
message: 'note',
attachmentIds: [],
})
// A link to a project file, as comments created before attachment checks could hold.
await prisma.assetCommentAttachment.create({
data: { commentId: comment.id, assetId: assets.fileA2.id },
})
await assetService.deleteComment({ commentId: comment.id, userId: reviewer.id })
await expect(
prisma.assetComment.findUnique({ where: { id: comment.id } }),
).resolves.toBeNull()
await expect(
prisma.asset.findUnique({ where: { id: assets.fileA2.id } }),
).resolves.not.toBeNull()
await expect(
prisma.storageKey.findUnique({ where: { id: fileKey.id } }),
).resolves.not.toBeNull()
expect(s3Service.deleteObject).not.toHaveBeenCalledWith(
expect.anything(),
'files/01JAAAAAAAAAAAAAAAAAAAAAAA/deliverable.mov',
)
})
it('keeps an attachment object until the original and copied comments are deleted', async () => {
const { user, project, assets } = await setupBasicAssets()
const upload = await createUpload(project.id, user.id, 'copied-upload.png')
const originalComment = await assetService.createComment({
assetId: assets.fileA1.id,
userId: user.id,
message: 'Original comment',
attachmentIds: [upload.id],
})
const [copiedFileId] = await assetService.copyAssets({
assetIds: [assets.fileA1.id],
newParentId: assets.root3.id,
creatorId: user.id,
withComments: true,
})
const copiedComment = await prisma.assetComment.findFirstOrThrow({
where: { assetId: copiedFileId },
})
const storageKey = await prisma.storageKey.findFirstOrThrow({
where: { key: 'attachments/copied-upload.png' },
})
await prisma.storageKey.update({
where: { id: storageKey.id },
data: { createdAt: new Date(Date.now() - 60_000) },
})
await assetService.deleteComment({ commentId: copiedComment.id, userId: user.id })
await assetService.emptyTrash(project.id)
const survivingUpload = await prisma.asset.findUniqueOrThrow({ where: { id: upload.id } })
expect(survivingUpload.storageKeyId).toBe(storageKey.id)
expect(s3Service.deleteObject).not.toHaveBeenCalledWith(expect.any(String), storageKey.key)
await assetService.deleteComment({ commentId: originalComment.id, userId: user.id })
await assetService.emptyTrash(project.id)
await expect(
prisma.storageKey.findUnique({ where: { id: storageKey.id } }),
).resolves.toBeNull()
expect(s3Service.deleteObject).toHaveBeenCalledWith(expect.any(String), storageKey.key)
})
it('keeps a legacy attachment asset while another comment still links to it', async () => {
const { user, project, assets } = await setupBasicAssets()
const upload = await createUpload(project.id, user.id, 'legacy-upload.png')
const first = await assetService.createComment({
assetId: assets.fileA1.id,
userId: user.id,
message: 'First comment',
attachmentIds: [upload.id],
})
const second = await assetService.createComment({
assetId: assets.fileA1.id,
userId: user.id,
message: 'Second comment',
attachmentIds: [],
})
await prisma.assetCommentAttachment.create({
data: { assetId: upload.id, commentId: second.id },
})
await assetService.deleteComment({ commentId: first.id, userId: user.id })
await expect(prisma.asset.findUnique({ where: { id: upload.id } })).resolves.not.toBeNull()
await assetService.deleteComment({ commentId: second.id, userId: user.id })
await expect(prisma.asset.findUnique({ where: { id: upload.id } })).resolves.toBeNull()
})
})
it('can create and retrieve comments with video timestamp', async () => {
const { user, assets } = await setupBasicAssets()
@@ -5816,46 +5529,6 @@ describe('AssetService — natural sort by name', () => {
expect(restored?.isDeleted).toBe(false)
expect(restored?.status).toBe(AssetStatus.processed)
})
it('should restore asset with status "processed" even if an auxiliary transcode_video_chunks task is active', async () => {
const team = await prisma.team.create({ data: { name: 'Restore Video Chunks Team' } })
const project = await prisma.project.create({
data: { name: 'Restore Video Chunks Project', teamId: team.id },
})
const rootFolder = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
projectId: project.id,
status: AssetStatus.uploaded,
},
})
const file = await prisma.asset.create({
data: {
name: 'embedding-chunks-video.mp4',
type: AssetType.file,
projectId: project.id,
parentId: rootFolder.id,
status: AssetStatus.trashed,
isDeleted: true,
deletedAt: new Date(),
},
})
await prisma.workflowTask.create({
data: {
assetId: file.id,
type: WorkflowTaskType.transcode_video_chunks,
status: WorkflowTaskStatus.processing,
},
})
await assetService.restoreAssets([file.id])
const restored = await prisma.asset.findUnique({ where: { id: file.id } })
expect(restored?.isDeleted).toBe(false)
expect(restored?.status).toBe(AssetStatus.processed)
})
})
describe('HLS playlists', () => {
@@ -5964,367 +5637,4 @@ describe('AssetService — natural sort by name', () => {
expect(variant).toContain('http://mock-s3-url')
})
})
describe('internal comments and comment editing', () => {
async function setupCommentFixture() {
const team = await prisma.team.create({ data: { name: 'Comment Team' } })
const author = await prisma.user.create({
data: { name: 'Author', email: `author-${Date.now()}-${Math.random()}@test.com` },
})
const owner = await prisma.user.create({
data: { name: 'Owner', email: `owner-${Date.now()}-${Math.random()}@test.com` },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: author.id, role: 'editor' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: owner.id, role: 'owner' },
})
const project = await prisma.project.create({
data: { name: 'Comment Project', teamId: team.id },
})
const rootFolder = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
projectId: project.id,
status: AssetStatus.uploaded,
},
})
const file = await prisma.asset.create({
data: {
name: 'clip.mp4',
type: AssetType.file,
projectId: project.id,
parentId: rootFolder.id,
creatorId: author.id,
status: AssetStatus.uploaded,
},
})
return { team, author, owner, project, rootFolder, file }
}
async function createAttachmentAsset(projectId: string, creatorId: string, name: string) {
const storageKey = await prisma.storageKey.create({
data: { key: `files/attachments/${Date.now()}-${Math.random()}-${name}` },
})
return prisma.asset.create({
data: {
name,
type: AssetType.attachment,
projectId,
creatorId,
status: AssetStatus.uploaded,
storageKeyId: storageKey.id,
},
})
}
it('creates public (default) and internal comments, and enforces internal replies on internal parents', async () => {
const { author, owner, file } = await setupCommentFixture()
const pub = await assetService.createComment(
{ assetId: file.id, userId: author.id, message: 'Public feedback', attachmentIds: [] },
{ triggerAgents: false },
)
expect(pub.isInternal).toBe(false)
const internal = await assetService.createComment(
{
assetId: file.id,
userId: author.id,
message: 'Internal note',
attachmentIds: [],
isInternal: true,
},
{ triggerAgents: false },
)
expect(internal.isInternal).toBe(true)
// Replying to an internal parent forces isInternal: true even if false is passed
const replyToInternal = await assetService.createComment(
{
assetId: file.id,
userId: owner.id,
replyToId: internal.id,
message: 'Internal reply',
attachmentIds: [],
isInternal: false,
},
{ triggerAgents: false },
)
expect(replyToInternal.isInternal).toBe(true)
// Replying internally to a public parent is allowed
const internalReplyOnPublic = await assetService.createComment(
{
assetId: file.id,
userId: owner.id,
replyToId: pub.id,
message: 'Private side note',
attachmentIds: [],
isInternal: true,
},
{ triggerAgents: false },
)
expect(internalReplyOnPublic.isInternal).toBe(true)
const publicReplyOnPublic = await assetService.createComment(
{
assetId: file.id,
userId: author.id,
replyToId: pub.id,
message: 'Public reply',
attachmentIds: [],
isInternal: false,
},
{ triggerAgents: false },
)
expect(publicReplyOnPublic.isInternal).toBe(false)
// Authenticated list includes everything
const allListed = await assetService.listComments(file.id, { first: 20 }, author.id)
expect(allListed.data).toHaveLength(2)
expect(allListed.data[0].replies).toHaveLength(2)
expect(allListed.data[1].replies).toHaveLength(1)
// Public share list excludes internal comments and internal replies
const publicListed = await assetService.listComments(file.id, { first: 20 }, undefined, {
excludeInternal: true,
})
expect(publicListed.data).toHaveLength(1)
expect(publicListed.data[0].id).toBe(pub.id)
expect(publicListed.data[0].replies.map((r) => r.id)).toEqual([publicReplyOnPublic.id])
// listAllComments with excludeInternal matches
const publicAll = await assetService.listAllComments(file.id, undefined, {
excludeInternal: true,
})
expect(publicAll).toHaveLength(1)
expect(publicAll[0].replies.map((r) => r.id)).toEqual([publicReplyOnPublic.id])
})
it('excludes internal comments and replies under internal parents from public share commentsCount', async () => {
const { author, rootFolder, file } = await setupCommentFixture()
const pub = await assetService.createComment(
{ assetId: file.id, userId: author.id, message: 'Public', attachmentIds: [] },
{ triggerAgents: false },
)
await assetService.createComment(
{
assetId: file.id,
userId: author.id,
replyToId: pub.id,
message: 'Internal reply on public',
attachmentIds: [],
isInternal: true,
},
{ triggerAgents: false },
)
const internal = await assetService.createComment(
{
assetId: file.id,
userId: author.id,
message: 'Internal root',
attachmentIds: [],
isInternal: true,
},
{ triggerAgents: false },
)
await assetService.createComment(
{
assetId: file.id,
userId: author.id,
replyToId: internal.id,
message: 'Reply on internal',
attachmentIds: [],
isInternal: true,
},
{ triggerAgents: false },
)
const allChildren = await assetService.listChildren({
assetId: rootFolder.id,
assetType: 'file',
})
expect(allChildren.data.find((a) => a.id === file.id)?.commentsCount).toBe(4)
const publicChildren = await assetService.listChildren(
{ assetId: rootFolder.id, assetType: 'file' },
{ excludeInternalComments: true },
)
expect(publicChildren.data.find((a) => a.id === file.id)?.commentsCount).toBe(1)
const publicFile = await assetService.getAsset(
{ assetId: file.id },
{ excludeInternalComments: true },
)
expect(publicFile.commentsCount).toBe(1)
})
it('rejects replying to an internal comment from a public share link', async () => {
const { author, file } = await setupCommentFixture()
const internal = await assetService.createComment(
{
assetId: file.id,
userId: author.id,
message: 'Internal only',
attachmentIds: [],
isInternal: true,
},
{ triggerAgents: false },
)
await expect(
assetService.createComment(
{
assetId: file.id,
userId: author.id,
replyToId: internal.id,
message: 'Guest reply attempt',
attachmentIds: [],
},
{ triggerAgents: false, shareLinkId: 'share-1' },
),
).rejects.toMatchObject({ status: 404 })
})
it('allows author to edit text, visibility, remove timestamp, and add/delete attachments', async () => {
const { author, project, file } = await setupCommentFixture()
const att1 = await createAttachmentAsset(project.id, author.id, 'old.png')
const att2 = await createAttachmentAsset(project.id, author.id, 'keep.pdf')
const att3 = await createAttachmentAsset(project.id, author.id, 'new.png')
const created = await assetService.createComment(
{
assetId: file.id,
userId: author.id,
message: 'Original message',
second: 12.5,
attachmentIds: [att1.id, att2.id],
isInternal: false,
},
{ triggerAgents: false },
)
const updated = await assetService.updateComment({
commentId: created.id,
userId: author.id,
message: 'Updated message',
isInternal: true,
second: null,
attachmentIds: [att2.id, att3.id],
})
expect(updated.message).toBe('Updated message')
expect(updated.isInternal).toBe(true)
expect(updated.second).toBeNull()
expect(updated.attachments.map((a) => a.assetId).sort()).toEqual([att2.id, att3.id].sort())
// Removed attachment asset should be cleaned up since no comment references it anymore
expect(await prisma.asset.findUnique({ where: { id: att1.id } })).toBeNull()
expect(await prisma.asset.findUnique({ where: { id: att2.id } })).not.toBeNull()
expect(await prisma.asset.findUnique({ where: { id: att3.id } })).not.toBeNull()
})
it('enforces author-only edit, parent-internal reply constraint, non-empty validation, and preserves reply flags', async () => {
const { author, owner, file } = await setupCommentFixture()
const parent = await assetService.createComment(
{
assetId: file.id,
userId: author.id,
message: 'Parent comment',
attachmentIds: [],
isInternal: true,
},
{ triggerAgents: false },
)
const reply = await assetService.createComment(
{
assetId: file.id,
userId: author.id,
replyToId: parent.id,
message: 'Internal reply',
attachmentIds: [],
isInternal: true,
},
{ triggerAgents: false },
)
// Non-author (even team owner) cannot edit
await expect(
assetService.updateComment({
commentId: parent.id,
userId: owner.id,
message: 'Owner edit attempt',
}),
).rejects.toMatchObject({ status: 403 })
// Reply cannot be made public while parent is internal
await expect(
assetService.updateComment({
commentId: reply.id,
userId: author.id,
isInternal: false,
}),
).rejects.toMatchObject({ status: 400 })
// Empty comment without attachments or annotations is rejected
await expect(
assetService.updateComment({
commentId: parent.id,
userId: author.id,
message: ' ',
attachmentIds: [],
}),
).rejects.toMatchObject({ status: 400 })
// Toggling parent Internal -> Public keeps reply's own isInternal flag intact
const toggledParent = await assetService.updateComment({
commentId: parent.id,
userId: author.id,
isInternal: false,
})
expect(toggledParent.isInternal).toBe(false)
expect(toggledParent.replies[0].isInternal).toBe(true)
// Agent comments cannot be edited
const agentUser = await prisma.user.create({
data: {
name: 'Bot',
email: `bot-${Date.now()}-${Math.random()}@test.com`,
type: 'agent',
},
})
const agent = await prisma.agent.create({
data: {
id: agentUser.id,
teamId: (await prisma.project.findUniqueOrThrow({ where: { id: file.projectId! } }))
.teamId,
type: 'chat',
config: { provider: 'openai', model: 'gpt-4' },
},
})
const session = await prisma.agentSession.create({
data: { agentId: agent.id, cwd: '/tmp' },
})
const agentComment = await prisma.assetComment.create({
data: {
assetId: file.id,
creatorId: author.id,
sessionId: session.id,
message: 'Agent generated reply',
},
})
await expect(
assetService.updateComment({
commentId: agentComment.id,
userId: author.id,
message: 'Try edit agent',
}),
).rejects.toMatchObject({ status: 403 })
})
})
})
+94 -345
View File
@@ -61,7 +61,6 @@ import { dedupeSymlinksToTarget } from './symlink'
import { watermarkService } from '@shumai/core/src/watermark/watermark'
import { generateKeyBetween } from 'jittered-fractional-indexing'
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
import { shareActivityService } from '@shumai/core/src/share/share-activity'
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
import { metadataService } from '@shumai/core/src/metadata/metadata'
@@ -177,17 +176,10 @@ export class AssetService {
async getDescendantFolderIds(folderId: string): Promise<string[]> {
const rows = await this.prismaClient.$queryRaw<{ id: string }[]>`
WITH RECURSIVE descendant AS (
SELECT id, parent_id
FROM assets
WHERE parent_id = ${folderId}
AND type = 'folder'::"AssetType"
AND is_deleted = false
SELECT id, parent_id FROM assets WHERE parent_id = ${folderId}
UNION ALL
SELECT a.id, a.parent_id
FROM assets a
SELECT a.id, a.parent_id FROM assets a
INNER JOIN descendant d ON a.parent_id = d.id
WHERE a.type = 'folder'::"AssetType"
AND a.is_deleted = false
)
SELECT id FROM descendant;
`
@@ -743,10 +735,7 @@ export class AssetService {
}
}
async listChildren(
req: ListChildrenRequest,
options?: { excludeInternalComments?: boolean },
): Promise<PaginatedData<AssetInfo[]>> {
async listChildren(req: ListChildrenRequest): Promise<PaginatedData<AssetInfo[]>> {
let typesToQuery: AssetType[]
if (req.assetType === 'file') {
typesToQuery = [AssetType.file, AssetType.version_stack]
@@ -834,7 +823,6 @@ export class AssetService {
const infos = await this.toAssetInfos(assets, undefined, {
includeDeletedChildren: req.showDeleted,
excludeInternalComments: options?.excludeInternalComments,
})
return { data: infos, pageInfo }
@@ -1111,10 +1099,7 @@ export class AssetService {
return this.getAsset({ assetId: asset.id })
}
async getAsset(
req: GetAssetRequest,
options?: { excludeInternalComments?: boolean },
): Promise<AssetInfo> {
async getAsset(req: GetAssetRequest): Promise<AssetInfo> {
const a = await this.prismaClient.asset.findUnique({
where: { id: req.assetId },
include: assetInclude,
@@ -1137,9 +1122,7 @@ export class AssetService {
afs.push({ id: row.id, name: row.name })
}
const infos = await this.toAssetInfos([a], undefined, {
excludeInternalComments: options?.excludeInternalComments,
})
const infos = await this.toAssetInfos([a])
const info = infos[0]
info.ancestorFolders = afs
@@ -1602,9 +1585,7 @@ export class AssetService {
private cleanupJobsRunning = false
async startCleanupJob() {
if (this.cleanupJobsRunning) return
this.cleanupJobsRunning = true
let nextGeneratedCleanupAt = 0
const runCleanup = async () => {
if (!this.cleanupJobsRunning) return
@@ -1613,12 +1594,8 @@ export class AssetService {
await this.expireTrashedAssets()
await this.purgePendingAssets()
await this.purgeUnreferencedStorageKeys()
await this.purgeExpiredGeneratedFiles()
await watermarkService.purgeOrphanWatermarkConfigs()
const now = Date.now()
if (now >= nextGeneratedCleanupAt) {
nextGeneratedCleanupAt = now + 60 * 60 * 1000
await this.purgeExpiredGeneratedFiles()
}
} catch (e: unknown) {
console.error('Error in asset cleanup job:', e)
}
@@ -1967,27 +1944,6 @@ export class AssetService {
}
}
private async lockCommentAttachments(
tx: Prisma.TransactionClient,
attachmentIds: string[],
owner?: { projectId: string | null; userId: string },
): Promise<string[]> {
if (attachmentIds.length === 0) return []
// Lock the same rows in the same order when claiming or removing attachments.
const ownerFilter = owner
? Prisma.sql`AND project_id IS NOT DISTINCT FROM ${owner.projectId} AND creator_id = ${owner.userId}`
: Prisma.empty
const attachments = await tx.$queryRaw<{ id: string }[]>`
SELECT id FROM assets
WHERE id IN (${Prisma.join(attachmentIds)}) AND type = 'attachment'
${ownerFilter}
ORDER BY id
FOR NO KEY UPDATE
`
return attachments.map(({ id }) => id)
}
/**
* Creates a comment or reply. Mentions of agents (`<@agentId>`) start a chat with them
* unless `triggerAgents` is false, which keeps an agent's own comments from starting
@@ -1995,7 +1951,7 @@ export class AssetService {
*/
async createComment(
req: CreateCommentRequest,
options: { triggerAgents?: boolean; shareLinkId?: string } = {},
options: { triggerAgents?: boolean } = {},
): Promise<CommentInfo> {
const triggerAgents = options.triggerAgents ?? true
let commentId = ''
@@ -2010,43 +1966,16 @@ export class AssetService {
let actualReplyToId = req.replyToId
let parentComment = null
let parentIsInternal = false
if (req.replyToId) {
parentComment = await tx.assetComment.findUnique({
where: { id: req.replyToId },
include: {
creator: true,
replyTo: { select: { id: true, isInternal: true } },
},
include: { creator: true },
})
if (options.shareLinkId) {
if (
!parentComment ||
parentComment.assetId !== a.id ||
parentComment.isInternal ||
parentComment.replyTo?.isInternal
) {
throw new HTTPException(404, { message: 'Comment not found' })
}
}
if (parentComment?.replyToId) {
actualReplyToId = parentComment.replyToId
parentIsInternal = Boolean(parentComment.isInternal || parentComment.replyTo?.isInternal)
} else if (parentComment) {
parentIsInternal = parentComment.isInternal
}
}
const isInternal = options.shareLinkId
? false
: parentIsInternal
? true
: Boolean(req.isInternal)
const attachmentIds = await this.lockCommentAttachments(tx, req.attachmentIds, {
projectId: a.projectId,
userId: req.userId,
})
const comment = await tx.assetComment.create({
data: {
assetId: a.id,
@@ -2055,28 +1984,27 @@ export class AssetService {
annotation: req.annotations,
second: req.second,
replyToId: actualReplyToId,
isInternal,
},
})
commentId = comment.id
if (attachmentIds.length > 0) {
// Read the links after acquiring the locks to see any claims that committed while waiting.
const unclaimed = await tx.asset.findMany({
where: { id: { in: attachmentIds }, commentAttachments: { none: {} } },
select: { id: true },
for (const attachmentId of req.attachmentIds) {
const attachmentAsset = await tx.asset.findUnique({
where: { id: attachmentId },
})
await tx.assetCommentAttachment.createMany({
data: unclaimed.map(({ id }) => ({ assetId: id, commentId: comment.id })),
})
}
if (options.shareLinkId) {
await shareActivityService.recordEvent(
options.shareLinkId,
{ kind: 'comment_created', assetId: a.id, userId: req.userId },
tx,
)
if (
attachmentAsset &&
(attachmentAsset.type === AssetType.attachment ||
attachmentAsset.type === AssetType.file) &&
attachmentAsset.projectId === a.projectId
) {
await tx.assetCommentAttachment.create({
data: {
assetId: attachmentAsset.id,
commentId: comment.id,
},
})
}
}
if (!triggerAgents) return
@@ -2254,154 +2182,22 @@ export class AssetService {
return this.getComment(commentId, userId)
}
async updateComment(params: {
commentId: string
userId: string
message?: string
isInternal?: boolean
second?: number | null
attachmentIds?: string[]
}): Promise<CommentInfo> {
await this.prismaClient.$transaction(async (tx) => {
const comment = await tx.assetComment.findUnique({
where: { id: params.commentId },
select: {
id: true,
creatorId: true,
sessionId: true,
message: true,
annotation: true,
second: true,
isInternal: true,
attachments: { select: { assetId: true } },
replyTo: { select: { isInternal: true } },
asset: { select: { projectId: true } },
},
})
if (!comment) {
throw new HTTPException(404, { message: 'Comment not found' })
}
if (comment.sessionId !== null || comment.creatorId !== params.userId) {
throw new HTTPException(403, { message: 'Only the comment author can edit this comment' })
}
if (comment.replyTo?.isInternal && params.isInternal === false) {
throw new HTTPException(400, {
message: 'Cannot make a reply public when its parent comment is internal',
})
}
const existingAttachmentIds = comment.attachments.map(({ assetId }) => assetId)
const existingSet = new Set(existingAttachmentIds)
let toAdd: string[] = []
let toRemove: string[] = []
let keptCount = existingAttachmentIds.length
if (params.attachmentIds !== undefined) {
const desiredIds = Array.from(new Set(params.attachmentIds))
const desiredSet = new Set(desiredIds)
toAdd = desiredIds.filter((id) => !existingSet.has(id))
toRemove = existingAttachmentIds.filter((id) => !desiredSet.has(id))
keptCount = existingAttachmentIds.filter((id) => desiredSet.has(id)).length
}
const idsToLock = Array.from(new Set([...toAdd, ...toRemove]))
let claimedToAdd: string[] = []
let lockedToRemove: string[] = []
if (idsToLock.length > 0) {
const lockedRows = await tx.$queryRaw<
{ id: string; projectId: string | null; creatorId: string | null }[]
>`
SELECT id, project_id AS "projectId", creator_id AS "creatorId" FROM assets
WHERE id IN (${Prisma.join(idsToLock)}) AND type = 'attachment'
ORDER BY id
FOR NO KEY UPDATE
`
const toAddSet = new Set(toAdd)
const toRemoveSet = new Set(toRemove)
const ownedToAdd = lockedRows
.filter(
(row) =>
toAddSet.has(row.id) &&
row.projectId === comment.asset.projectId &&
row.creatorId === params.userId,
)
.map((row) => row.id)
lockedToRemove = lockedRows.filter((row) => toRemoveSet.has(row.id)).map((row) => row.id)
if (ownedToAdd.length > 0) {
const unclaimed = await tx.asset.findMany({
where: { id: { in: ownedToAdd }, commentAttachments: { none: {} } },
select: { id: true },
})
claimedToAdd = unclaimed.map(({ id }) => id)
}
}
const finalMessage = params.message !== undefined ? params.message : (comment.message ?? '')
const hasAnnotations = Array.isArray(comment.annotation) && comment.annotation.length > 0
const finalAttachmentCount = keptCount + claimedToAdd.length
if (!finalMessage.trim() && finalAttachmentCount === 0 && !hasAnnotations) {
throw new HTTPException(400, { message: 'Comment cannot be empty' })
}
if (toRemove.length > 0) {
await tx.assetCommentAttachment.deleteMany({
where: {
commentId: params.commentId,
assetId: { in: toRemove },
},
})
if (lockedToRemove.length > 0) {
await tx.asset.deleteMany({
where: { id: { in: lockedToRemove }, commentAttachments: { none: {} } },
})
}
}
if (claimedToAdd.length > 0) {
await tx.assetCommentAttachment.createMany({
data: claimedToAdd.map((assetId) => ({ assetId, commentId: params.commentId })),
})
}
const updateData: Prisma.AssetCommentUpdateInput = {}
if (params.message !== undefined) {
updateData.message = params.message
}
if (params.isInternal !== undefined) {
updateData.isInternal = params.isInternal
}
if (params.second !== undefined) {
updateData.second = params.second
}
if (Object.keys(updateData).length > 0) {
await tx.assetComment.update({
where: { id: params.commentId },
data: updateData,
})
}
})
return this.getComment(params.commentId, params.userId)
}
async deleteComment({ commentId, userId }: { commentId: string; userId: string }): Promise<void> {
const comment = await this.prismaClient.assetComment.findUnique({
where: { id: commentId },
select: {
creatorId: true,
attachments: { select: { assetId: true } },
include: {
attachments: {
include: {
asset: {
include: {
storageKey: true,
},
},
},
},
asset: {
select: {
project: { select: { teamId: true } },
project: { select: { id: true, teamId: true } },
},
},
},
@@ -2439,70 +2235,75 @@ export class AssetService {
throw new HTTPException(403, { message: 'You do not have permission to delete this comment' })
}
await this.prismaClient.$transaction(async (tx) => {
const attachmentIds = await this.lockCommentAttachments(
tx,
comment.attachments.map(({ assetId }) => assetId),
)
await tx.assetComment.delete({ where: { id: commentId } })
if (attachmentIds.length > 0) {
// The storage cleanup job removes objects once every asset using their storage key is gone.
await tx.asset.deleteMany({
where: { id: { in: attachmentIds }, commentAttachments: { none: {} } },
})
// Clean up attachment files from S3/storage and delete their DB records
const bucket = process.env.S3_BUCKET || 'shumai'
for (const att of comment.attachments) {
const asset = att.asset
if (asset.storageKey) {
try {
await s3Service.deleteObject(bucket, asset.storageKey.key)
} catch (err) {
logger.error({ err, assetId: asset.id }, 'Failed to delete attachment file from S3')
}
}
})
}
private getCommentInclude(options?: { excludeInternal?: boolean }) {
return {
creator: true,
completionLastChangedBy: true,
asset: { include: { storageKey: true } },
attachments: { include: { asset: { include: { storageKey: true } } } },
reactions: {
include: {
user: { select: { id: true, name: true } },
},
orderBy: { createdAt: 'asc' as const },
},
replies: {
...(options?.excludeInternal ? { where: { isInternal: false } } : {}),
include: {
creator: true,
completionLastChangedBy: true,
attachments: { include: { asset: { include: { storageKey: true } } } },
reactions: {
include: {
user: { select: { id: true, name: true } },
},
orderBy: { createdAt: 'asc' as const },
},
},
orderBy: { id: 'asc' as const },
},
await this.prismaClient.asset.delete({
where: { id: asset.id },
})
if (asset.storageKey) {
await this.prismaClient.storageKey
.delete({
where: { id: asset.storageKey.id },
})
.catch(() => {
// Silently ignore if already deleted
})
}
}
await this.prismaClient.assetComment.delete({
where: { id: commentId },
})
}
async listComments(
assetId: string,
params: PaginationParams,
requestingUserId?: string,
options?: { excludeInternal?: boolean },
): Promise<PaginatedData<CommentInfo[]>> {
const resolvedAssetId = await this.resolveLatestVersionId(assetId)
const where: Prisma.AssetCommentWhereInput = {
assetId: resolvedAssetId,
replyToId: null,
...(options?.excludeInternal ? { isInternal: false } : {}),
}
const { data: comments, pageInfo } = await paginateQuery(
async (skip, take) => {
return this.prismaClient.assetComment.findMany({
where,
include: this.getCommentInclude(options),
where: { assetId: resolvedAssetId, replyToId: null },
include: {
creator: true,
completionLastChangedBy: true,
asset: { include: { storageKey: true } },
attachments: { include: { asset: { include: { storageKey: true } } } },
reactions: {
include: {
user: { select: { id: true, name: true } },
},
orderBy: { createdAt: 'asc' },
},
replies: {
include: {
creator: true,
completionLastChangedBy: true,
attachments: { include: { asset: { include: { storageKey: true } } } },
reactions: {
include: {
user: { select: { id: true, name: true } },
},
orderBy: { createdAt: 'asc' },
},
},
orderBy: { id: 'asc' },
},
},
skip,
take,
orderBy: { id: 'asc' },
@@ -2510,7 +2311,7 @@ export class AssetService {
},
async () =>
this.prismaClient.assetComment.count({
where,
where: { assetId: resolvedAssetId, replyToId: null },
}),
params,
)
@@ -2520,36 +2321,6 @@ export class AssetService {
return { data: infos, pageInfo }
}
async listAllComments(
assetId: string,
requestingUserId?: string,
options?: { excludeInternal?: boolean },
): Promise<CommentInfo[]> {
const resolvedAssetId = await this.resolveLatestVersionId(assetId)
const comments = await this.prismaClient.assetComment.findMany({
where: {
assetId: resolvedAssetId,
replyToId: null,
...(options?.excludeInternal ? { isInternal: false } : {}),
},
include: this.getCommentInclude(options),
orderBy: { id: 'asc' },
})
return Promise.all(comments.map((c) => this.toCommentInfo(c, requestingUserId)))
}
async getProjectNameForAsset(assetId: string): Promise<string | null> {
const asset = await this.prismaClient.asset.findUnique({
where: { id: assetId },
select: {
project: { select: { name: true } },
},
})
return asset?.project?.name ?? null
}
async exportComments(
assetId: string,
format: CommentExportFormat,
@@ -2648,10 +2419,9 @@ export class AssetService {
async toAssetInfos(
assets: AssetWithIncludes[],
previewFormat?: PreviewFormat,
options?: { includeDeletedChildren?: boolean; excludeInternalComments?: boolean },
options?: { includeDeletedChildren?: boolean },
): Promise<AssetInfo[]> {
const includeDeletedChildren = options?.includeDeletedChildren ?? false
const excludeInternalComments = options?.excludeInternalComments ?? false
const stackIds = new Set<string>()
for (const a of assets) {
@@ -2741,12 +2511,6 @@ export class AssetService {
by: ['assetId'],
where: {
assetId: { in: Array.from(commentTargetIds) },
...(excludeInternalComments
? {
isInternal: false,
OR: [{ replyToId: null }, { replyTo: { isInternal: false } }],
}
: {}),
},
_count: { _all: true },
})
@@ -2941,8 +2705,8 @@ export class AssetService {
proxyType,
latestChildren,
preview,
createdAt: latestVersion.createdAt.toISOString(),
updatedAt: latestVersion.updatedAt.toISOString(),
createdAt: a.createdAt.toISOString(),
updatedAt: a.updatedAt.toISOString(),
deletedAt: a.deletedAt ? a.deletedAt.toISOString() : null,
projectId: a.projectId,
creator,
@@ -3303,10 +3067,6 @@ export class AssetService {
* that belong to an asset they have access to.
*/
async getDownloadUrl(assetId: string, key: string): Promise<string> {
return (await this.getDownloadUrlWithAsset(assetId, key)).url
}
async getDownloadUrlWithAsset(assetId: string, key: string) {
const targetAssetId = await this.resolveLatestVersionId(assetId)
const asset = await this.prismaClient.asset.findUnique({
where: { id: targetAssetId },
@@ -3327,7 +3087,6 @@ export class AssetService {
throw new Error('Key does not belong to this asset')
}
let signedAssetId = asset.id
let storageKey = asset.storageKey.key
let assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
let targetName = asset.name
@@ -3343,14 +3102,12 @@ export class AssetService {
storageKey: { key: { startsWith: key.substring(0, key.lastIndexOf('/') + 1) } },
},
select: {
id: true,
name: true,
status: true,
storageKey: { select: { key: true, isArchived: true } },
},
})
if (sibling?.storageKey?.key) {
signedAssetId = sibling.id
storageKey = sibling.storageKey.key
assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
targetStatus = sibling.status
@@ -3406,14 +3163,7 @@ export class AssetService {
}
}
const url = await s3Service.presign(
process.env.S3_BUCKET || 'shumai',
key,
'GET',
true,
downloadFilename,
)
return { url, assetId: signedAssetId }
return s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET', true, downloadFilename)
}
async archiveAssets(
@@ -3623,7 +3373,6 @@ export class AssetService {
updatedAt: c.updatedAt.toISOString(),
sessionId: c.sessionId,
isCompleted: c.isCompleted,
isInternal: c.isInternal,
completionLastChangedBy,
reactionCounts,
}
-65
View File
@@ -595,70 +595,5 @@ describe('AuthzService', () => {
}),
).rejects.toThrow('Permission denied')
})
it('limits Kanban task reads for project-scoped members to their projects and their own tasks', async () => {
const owner = await prisma.user.create({
data: { name: 'Owner User', email: 'owner-kanban-read@example.com', password: 'pass' },
})
const client = await prisma.user.create({
data: { name: 'Client User', email: 'client-kanban-read@example.com', password: 'pass' },
})
const teamReviewer = await prisma.user.create({
data: { name: 'Team Reviewer', email: 'rev-kanban-read@example.com', password: 'pass' },
})
const team = await prisma.team.create({ data: { name: 'Kanban Read Team' } })
const ownProject = await prisma.project.create({
data: { name: 'Client Project', teamId: team.id },
})
const otherProject = await prisma.project.create({
data: { name: 'Internal Project', teamId: team.id },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: owner.id, role: 'owner', scope: 'team' },
})
const clientMember = await prisma.teamMember.create({
data: { teamId: team.id, userId: client.id, role: 'reviewer', scope: 'project' },
})
await prisma.projectMember.create({
data: { projectId: ownProject.id, teamMemberId: clientMember.id, role: 'reviewer' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: teamReviewer.id, role: 'reviewer', scope: 'team' },
})
const createTask = (title: string, projectId?: string, assigneeId?: string) =>
prisma.kanbanTask.create({
data: {
teamId: team.id,
title,
projectId,
creatorId: owner.id,
reporterId: owner.id,
assigneeId,
},
})
const ownTask = await createTask('Client task', ownProject.id)
const otherTask = await createTask('Internal task', otherProject.id)
const teamTask = await createTask('Team task')
const assignedTask = await createTask('Assigned task', otherProject.id, client.id)
const read = (user: { id: string }, id: string) =>
authzService.hasPermission({
type: ResourceType.KanbanTask,
id,
user,
permission: Permission.Read,
})
await expect(read(client, ownTask.id)).resolves.toBeUndefined()
await expect(read(client, assignedTask.id)).resolves.toBeUndefined()
await expect(read(client, otherTask.id)).rejects.toThrow('User has only project scope')
await expect(read(client, teamTask.id)).rejects.toThrow('User has only project scope')
await expect(read(teamReviewer, otherTask.id)).resolves.toBeUndefined()
await expect(read(teamReviewer, teamTask.id)).resolves.toBeUndefined()
})
})
})
+5 -4
View File
@@ -122,16 +122,17 @@ export class AuthzService {
})
if (!member) throw new HTTPException(403, { message: 'User is not a member of the team' })
// A project-scoped member can read or edit a KanbanTask outside their projects
// only when they are its assignee, reporter, or creator.
// If this is a KanbanTask and user is a team member, check if they are the assignee, reporter, or creator
if (req.type === ResourceType.KanbanTask) {
if (req.permission === Permission.Read || req.permission === Permission.Edit) {
if (req.permission === Permission.Read) {
return
}
if (req.permission === Permission.Edit) {
const isParticipant = await this.isKanbanTaskParticipant(req.id, req.user.id)
if (isParticipant) {
return
}
}
throw new HTTPException(403, { message: 'User has only project scope' })
}
// Project-scoped member on a team-level resource (no project context):
-24
View File
@@ -48,30 +48,6 @@ describe('LruTtlCache', () => {
expect(cache.size).toBe(0)
})
it('should expire items using wall-clock time even when performance.now pauses during sleep', () => {
vi.useRealTimers()
let wallNow = 1_700_000_000_000
let perfNow = 1_000
const dateNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => wallNow)
const perfNowSpy = vi.spyOn(performance, 'now').mockImplementation(() => perfNow)
try {
const cache = new LruTtlCache<string, string>(10)
cache.set('key1', 'value1', 60_000)
expect(cache.get('key1')).toBe('value1')
// Simulate host sleep: wall clock advances past TTL while monotonic clock barely moves
wallNow += 120_000
perfNow += 500
expect(cache.get('key1')).toBeUndefined()
expect(cache.size).toBe(0)
} finally {
dateNowSpy.mockRestore()
perfNowSpy.mockRestore()
}
})
it('should proactively evict expired items on get', () => {
const sampleSize = 5
const cache = new LruTtlCache<string, string>(100, sampleSize)
+2 -3
View File
@@ -101,11 +101,10 @@ export class LruTtlCache<TKey, TValue> {
}
/**
* Wall-clock time source so TTLs reflect real elapsed time across host sleep / VM suspend
* and stay aligned with wall-clock expirations such as presigned URL timestamps.
* Monotonic time source to avoid issues with system clock jumps.
*/
private now(): number {
return Date.now()
return performance.now()
}
get size(): number {
@@ -1,738 +0,0 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { prisma, AssetType, AssetStatus } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { s3Service } from '@shumai/core/src/s3/s3'
import { watermarkService } from '@shumai/core/src/watermark/watermark'
import { assetService } from '@shumai/core/src/asset/asset'
import {
CommentFrameService,
FrameExtractionQueue,
selectBestVideoProxyKey,
type ExecFileFn,
} from './comment-frame'
import { execFileSync } from 'child_process'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import sharp from 'sharp'
async function createSamplePngBuffer(): Promise<Buffer> {
return sharp({
create: {
width: 32,
height: 18,
channels: 3,
background: { r: 20, g: 120, b: 220 },
},
})
.png()
.toBuffer()
}
async function createSampleWebpBuffer(): Promise<Buffer> {
return sharp({
create: {
width: 32,
height: 18,
channels: 3,
background: { r: 220, g: 80, b: 40 },
},
})
.webp()
.toBuffer()
}
describe('FrameExtractionQueue', () => {
it('enforces maxConcurrency and processes queued tasks in FIFO order', async () => {
const queue = new FrameExtractionQueue(2)
let active = 0
let maxObserved = 0
const order: number[] = []
const resolvers: Array<() => void> = []
const makeTask = (id: number) =>
queue.enqueue(async () => {
active++
maxObserved = Math.max(maxObserved, active)
order.push(id)
await new Promise<void>((resolve) => resolvers.push(resolve))
active--
return id
})
const p1 = makeTask(1)
const p2 = makeTask(2)
const p3 = makeTask(3)
const p4 = makeTask(4)
expect(queue.activeCount).toBe(2)
expect(queue.queuedCount).toBe(2)
expect(maxObserved).toBe(2)
resolvers.shift()?.()
await p1
expect(queue.activeCount).toBe(2)
expect(queue.queuedCount).toBe(1)
resolvers.shift()?.()
await p2
expect(queue.activeCount).toBe(2)
expect(queue.queuedCount).toBe(0)
resolvers.shift()?.()
await p3
resolvers.shift()?.()
await p4
expect(order).toEqual([1, 2, 3, 4])
expect(maxObserved).toBe(2)
expect(queue.activeCount).toBe(0)
expect(queue.queuedCount).toBe(0)
})
it('cancels queued tasks when their AbortSignal fires before execution', async () => {
const queue = new FrameExtractionQueue(1)
let releaseFirst!: () => void
const first = queue.enqueue(
() =>
new Promise<string>((resolve) => {
releaseFirst = () => resolve('first')
}),
)
const controller = new AbortController()
const runSecond = vi.fn().mockResolvedValue('second')
const second = queue.enqueue(runSecond, controller.signal)
expect(queue.queuedCount).toBe(1)
controller.abort()
await expect(second).rejects.toThrow('Frame extraction aborted')
expect(queue.queuedCount).toBe(0)
expect(runSecond).not.toHaveBeenCalled()
releaseFirst()
await expect(first).resolves.toBe('first')
})
})
describe('selectBestVideoProxyKey', () => {
it('prefers SDR proxies over HDR and chooses lowest adequate resolution >= 360p', () => {
const key = selectBestVideoProxyKey([
{ key: 'hdr-720.mp4', width: 1280, height: 720, hdr: true, resolution: '720p' },
{ key: 'sdr-1080.mp4', width: 1920, height: 1080, hdr: false, resolution: '1080p' },
{ key: 'sdr-540.mp4', width: 960, height: 540, hdr: false, resolution: '540p' },
{ key: 'sdr-240.mp4', width: 426, height: 240, hdr: false, resolution: '240p' },
])
expect(key).toBe('sdr-540.mp4')
})
it('falls back to highest available SDR proxy if all are below 360p', () => {
const key = selectBestVideoProxyKey([
{ key: 'sdr-180.mp4', width: 320, height: 180, hdr: false, resolution: '180p' },
{ key: 'sdr-240.mp4', width: 426, height: 240, hdr: false, resolution: '240p' },
])
expect(key).toBe('sdr-240.mp4')
})
it('falls back to HDR proxy if no SDR proxy exists', () => {
const key = selectBestVideoProxyKey([
{ key: 'hdr-1080.mp4', width: 1920, height: 1080, hdr: true, resolution: '1080p' },
{ key: 'hdr-720.mp4', width: 1280, height: 720, hdr: true, resolution: '720p' },
])
expect(key).toBe('hdr-720.mp4')
})
it('returns null when no valid keys exist', () => {
expect(selectBestVideoProxyKey([])).toBeNull()
expect(selectBestVideoProxyKey(null)).toBeNull()
})
})
describe('CommentFrameService & AssetService print helpers', () => {
setupTestDbHooks()
let userId: string
let teamId: string
let projectId: string
let rootFolderId: string
let subFolderId: string
beforeEach(async () => {
const user = await prisma.user.create({
data: {
name: 'Alice',
email: `alice-${Date.now()}-${Math.random()}@example.com`,
},
})
userId = user.id
const team = await prisma.team.create({
data: {
name: 'Studio Team',
},
})
teamId = team.id
const rootFolder = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.root,
status: AssetStatus.processed,
creatorId: userId,
},
})
rootFolderId = rootFolder.id
const project = await prisma.project.create({
data: {
name: 'Commercial Cut',
teamId,
rootFolderId,
},
})
projectId = project.id
await prisma.asset.update({
where: { id: rootFolderId },
data: { projectId },
})
const subFolder = await prisma.asset.create({
data: {
name: 'Dailies',
type: AssetType.folder,
status: AssetStatus.processed,
projectId,
parentId: rootFolderId,
creatorId: userId,
},
})
subFolderId = subFolder.id
})
afterEach(() => {
vi.restoreAllMocks()
})
it('skips extraction when the request is aborted during asset lookup', async () => {
const storageKey = await prisma.storageKey.create({ data: { key: 'files/clip.mp4' } })
const asset = await prisma.asset.create({
data: {
name: 'clip.mp4',
type: AssetType.file,
status: AssetStatus.processed,
mediaType: 'video/mp4',
projectId,
parentId: subFolderId,
creatorId: userId,
storageKeyId: storageKey.id,
},
})
const controller = new AbortController()
const resolveLatestVersionId = assetService.resolveLatestVersionId.bind(assetService)
vi.spyOn(assetService, 'resolveLatestVersionId').mockImplementationOnce(async (assetId) => {
const resolvedId = await resolveLatestVersionId(assetId)
controller.abort()
return resolvedId
})
const resolveInput = vi.spyOn(s3Service, 'resolveInput').mockResolvedValue('/local/clip.mp4')
const execFileFn = vi.fn<ExecFileFn>().mockResolvedValue({ stdout: '', stderr: '' })
const service = new CommentFrameService({ execFileFn })
await expect(
service.extractFrame({ assetId: asset.id, second: 0, signal: controller.signal }),
).rejects.toMatchObject({ name: 'AbortError' })
expect(resolveInput).not.toHaveBeenCalled()
expect(execFileFn).not.toHaveBeenCalled()
})
it('extracts a video frame using the lowest adequate SDR proxy and deduplicates concurrent requests', async () => {
const webpBuffer = await createSampleWebpBuffer()
const storageKey = await prisma.storageKey.create({
data: { key: 'files/video-original.mp4' },
})
const videoAsset = await prisma.asset.create({
data: {
name: 'scene1.mp4',
type: AssetType.file,
status: AssetStatus.processed,
mediaType: 'video/mp4',
projectId,
parentId: subFolderId,
creatorId: userId,
storageKeyId: storageKey.id,
media: {
proxyType: 'video',
duration: 10,
filesize: 1000,
frames: 240,
imageTranscodes: [],
videoTranscodes: [
{ key: 'files/proxies/1080p.mp4', width: 1920, height: 1080, hdr: false },
{ key: 'files/proxies/540p.mp4', width: 960, height: 540, hdr: false },
{ key: 'files/proxies/720p-hdr.mp4', width: 1280, height: 720, hdr: true },
],
finishedAt: new Date().toISOString(),
metadata: null,
original: null,
},
},
})
const resolveInputSpy = vi
.spyOn(s3Service, 'resolveInput')
.mockResolvedValue('/local/files/proxies/540p.mp4')
let releaseExec!: () => void
const execFileMock = vi.fn<ExecFileFn>(async (_file, args) => {
await new Promise<void>((resolve) => {
releaseExec = resolve
})
const outPath = args[args.length - 1]
fs.writeFileSync(outPath, webpBuffer)
return { stdout: '', stderr: '' }
})
const service = new CommentFrameService({ maxConcurrency: 2, execFileFn: execFileMock })
const p1 = service.extractFrame({ assetId: videoAsset.id, second: 2.5, width: 400 })
const p2 = service.extractFrame({ assetId: videoAsset.id, second: 2.5, width: 400 })
// Let async DB lookup finish before releasing exec
await vi.waitFor(() => expect(execFileMock).toHaveBeenCalledTimes(1))
releaseExec()
const [r1, r2] = await Promise.all([p1, p2])
expect(r1.mimeType).toBe('image/webp')
expect(r1.buffer.equals(webpBuffer)).toBe(true)
expect(r2.buffer.equals(webpBuffer)).toBe(true)
expect(execFileMock).toHaveBeenCalledTimes(1)
expect(resolveInputSpy).toHaveBeenCalledWith(expect.any(String), 'files/proxies/540p.mp4')
})
it('extracts a 3D model turntable frame and enforces watermark-only proxies when watermarkConfigId is set', async () => {
const webpBuffer = await createSampleWebpBuffer()
const storageKey = await prisma.storageKey.create({
data: { key: 'files/chair.glb' },
})
const modelAsset = await prisma.asset.create({
data: {
name: 'chair.glb',
type: AssetType.file,
status: AssetStatus.processed,
mediaType: 'model/gltf-binary',
projectId,
parentId: subFolderId,
creatorId: userId,
storageKeyId: storageKey.id,
media: {
proxyType: '3d',
duration: 24,
filesize: 2000,
frames: 24,
imageTranscodes: [],
videoTranscodes: [{ key: 'files/proxies/turntable.mp4', width: 1024, height: 1024 }],
finishedAt: new Date().toISOString(),
metadata: null,
original: null,
},
},
})
const watermarkSpy = vi
.spyOn(watermarkService, 'getCompletedWatermarkMediaMap')
.mockResolvedValueOnce(
new Map([
[
modelAsset.id,
{
proxyType: '3d',
duration: 24,
filesize: 2000,
frames: 24,
imageTranscodes: [],
videoTranscodes: [{ key: 'files/wm/turntable-wm.mp4', width: 1024, height: 1024 }],
finishedAt: new Date().toISOString(),
metadata: null,
original: null,
},
],
]),
)
.mockResolvedValueOnce(new Map())
const resolveInputSpy = vi
.spyOn(s3Service, 'resolveInput')
.mockResolvedValue('/local/files/wm/turntable-wm.mp4')
const execFileMock = vi.fn<ExecFileFn>(async (_file, args) => {
const outPath = args[args.length - 1]
fs.writeFileSync(outPath, webpBuffer)
return { stdout: '', stderr: '' }
})
const service = new CommentFrameService({ execFileFn: execFileMock })
const res = await service.extractFrame({
assetId: modelAsset.id,
second: 3,
width: 400,
watermarkConfigId: 'wm-cfg-1',
})
expect(res.mimeType).toBe('image/webp')
expect(watermarkSpy).toHaveBeenCalledWith([modelAsset.id], 'wm-cfg-1')
expect(resolveInputSpy).toHaveBeenCalledWith(expect.any(String), 'files/wm/turntable-wm.mp4')
// Missing watermark proxy must reject with 422 rather than leaking unwatermarked media
await expect(
service.extractFrame({
assetId: modelAsset.id,
second: 3,
width: 400,
watermarkConfigId: 'wm-cfg-2',
}),
).rejects.toMatchObject({ status: 422 })
})
it('renders a PDF page frame via pdftoppm and sharp', async () => {
const samplePng = await createSamplePngBuffer()
const storageKey = await prisma.storageKey.create({
data: { key: 'files/deck.pdf' },
})
const pdfAsset = await prisma.asset.create({
data: {
name: 'deck.pdf',
type: AssetType.file,
status: AssetStatus.processed,
mediaType: 'application/pdf',
projectId,
parentId: subFolderId,
creatorId: userId,
storageKeyId: storageKey.id,
media: {
proxyType: 'pdf',
duration: 0,
filesize: 5000,
frames: 5,
imageTranscodes: [],
videoTranscodes: [],
pdfTranscode: { key: 'files/proxies/deck.pdf' },
finishedAt: new Date().toISOString(),
metadata: null,
original: null,
},
},
})
const downloadSpy = vi
.spyOn(s3Service, 'downloadToFile')
.mockImplementation(async (_bucket, _key, dest) => {
fs.writeFileSync(dest, '%PDF-1.4 mock')
})
const execFileMock = vi.fn<ExecFileFn>(async (file, args) => {
expect(file).toBe('pdftoppm')
expect(args[args.indexOf('-scale-to') + 1]).toBe('400')
expect(args).toContain('-f')
expect(args).toContain('3')
const prefix = args[args.length - 1]
fs.writeFileSync(`${prefix}-3.png`, samplePng)
return { stdout: '', stderr: '' }
})
const service = new CommentFrameService({ execFileFn: execFileMock })
const res = await service.extractFrame({ assetId: pdfAsset.id, second: 3, width: 400 })
expect(downloadSpy).toHaveBeenCalledWith(
expect.any(String),
'files/proxies/deck.pdf',
expect.stringContaining(path.sep),
)
expect(res.mimeType).toBe('image/webp')
expect(res.buffer.length).toBeGreaterThan(0)
})
it('rejects unsupported asset types with 400 and archived assets without proxy with 422', async () => {
const imgKey = await prisma.storageKey.create({
data: { key: 'files/photo.png' },
})
const imageAsset = await prisma.asset.create({
data: {
name: 'photo.png',
type: AssetType.file,
status: AssetStatus.processed,
mediaType: 'image/png',
projectId,
parentId: subFolderId,
creatorId: userId,
storageKeyId: imgKey.id,
media: {
proxyType: 'image',
duration: 0,
filesize: 100,
frames: 1,
imageTranscodes: [],
videoTranscodes: [],
finishedAt: new Date().toISOString(),
metadata: null,
original: null,
},
},
})
const archivedKey = await prisma.storageKey.create({
data: { key: 'files/archived.mp4', isArchived: true },
})
const archivedVideo = await prisma.asset.create({
data: {
name: 'archived.mp4',
type: AssetType.file,
status: AssetStatus.archived,
mediaType: 'video/mp4',
projectId,
parentId: subFolderId,
creatorId: userId,
storageKeyId: archivedKey.id,
},
})
const service = new CommentFrameService()
await expect(service.extractFrame({ assetId: imageAsset.id, second: 0 })).rejects.toMatchObject(
{ status: 400 },
)
await expect(
service.extractFrame({ assetId: archivedVideo.id, second: 1 }),
).rejects.toMatchObject({ status: 422 })
await expect(
service.extractFrame({ assetId: 'non-existent-id', second: 0 }),
).rejects.toMatchObject({ status: 404 })
})
it('lists all comments with replies, reactions, completion status, and fetches project name', async () => {
vi.spyOn(s3Service, 'presign').mockResolvedValue('http://mock-s3/file')
const storageKey = await prisma.storageKey.create({
data: { key: 'files/cut.mp4' },
})
const asset = await prisma.asset.create({
data: {
name: 'cut.mp4',
type: AssetType.file,
status: AssetStatus.processed,
mediaType: 'video/mp4',
projectId,
parentId: subFolderId,
creatorId: userId,
storageKeyId: storageKey.id,
},
})
const parent = await prisma.assetComment.create({
data: {
assetId: asset.id,
creatorId: userId,
message: 'Check lighting',
second: 1.5,
isCompleted: true,
completionLastChangedById: userId,
},
})
await prisma.assetCommentReaction.create({
data: { commentId: parent.id, userId, code: '👍' },
})
await prisma.assetComment.create({
data: {
assetId: asset.id,
creatorId: userId,
replyToId: parent.id,
message: 'Fixed in v2',
},
})
const allComments = await assetService.listAllComments(asset.id, userId)
expect(allComments).toHaveLength(1)
expect(allComments[0].message).toBe('Check lighting')
expect(allComments[0].isCompleted).toBe(true)
expect(allComments[0].reactionCounts).toEqual([
expect.objectContaining({ code: '👍', count: 1, requestingUserReacted: true }),
])
expect(allComments[0].replies).toHaveLength(1)
expect(allComments[0].replies[0].message).toBe('Fixed in v2')
const projectName = await assetService.getProjectNameForAsset(asset.id)
expect(projectName).toBe('Commercial Cut')
})
it('extracts exact frames with real ffmpeg for 30fps video, 23.976fps video, and 6fps 3D turntable', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shumai-frame-acc-'))
const w = 64
const h = 64
const createColorCodedVideo = (filename: string, rateArg: string, totalFrames: number) => {
const raw = Buffer.alloc(w * h * 3 * totalFrames)
for (let n = 0; n < totalFrames; n++) {
const r = (n * 9) & 255
const g = (n * 15) & 255
const off = n * w * h * 3
for (let i = 0; i < w * h; i++) {
raw[off + i * 3] = r
raw[off + i * 3 + 1] = g
raw[off + i * 3 + 2] = 120
}
}
const rawPath = path.join(tmpDir, `${filename}.rgb`)
const mp4Path = path.join(tmpDir, `${filename}.mp4`)
fs.writeFileSync(rawPath, raw)
execFileSync('ffmpeg', [
'-y',
'-loglevel',
'error',
'-f',
'rawvideo',
'-pix_fmt',
'rgb24',
'-s',
`${w}x${h}`,
'-r',
rateArg,
'-i',
rawPath,
'-c:v',
'libx264',
'-pix_fmt',
'yuv420p',
'-g',
'12',
'-bf',
'2',
'-movflags',
'+faststart',
mp4Path,
])
return mp4Path
}
const identifyExtractedFrame = async (webpBuffer: Buffer, totalFrames: number) => {
const { data, info } = await sharp(webpBuffer).raw().toBuffer({ resolveWithObject: true })
const cx = Math.floor(info.width / 2)
const cy = Math.floor(info.height / 2)
const idx = (cy * info.width + cx) * info.channels
const r = data[idx]
const g = data[idx + 1]
let best = -1
let bestDist = Infinity
for (let n = 0; n < totalFrames; n++) {
const dr = r - ((n * 9) & 255)
const dg = g - ((n * 15) & 255)
const dist = dr * dr + dg * dg
if (dist < bestDist) {
bestDist = dist
best = n
}
}
return best
}
try {
const mp4Fps30 = createColorCodedVideo('v30', '30', 24)
const mp4Fps23976 = createColorCodedVideo('v23976', '24000/1001', 24)
const mp4Turntable = createColorCodedVideo('turntable', '6', 24)
const keyMap: Record<string, string> = {
'files/proxies/v30.mp4': mp4Fps30,
'files/proxies/v23976.mp4': mp4Fps23976,
'files/proxies/turntable.mp4': mp4Turntable,
}
vi.spyOn(s3Service, 'resolveInput').mockImplementation(async (_bucket, key) => keyMap[key])
const createAsset = async (
name: string,
proxyType: 'video' | '3d',
proxyKey: string,
fps: number,
totalFrames: number,
) => {
const sk = await prisma.storageKey.create({ data: { key: `files/${name}` } })
return prisma.asset.create({
data: {
name,
type: AssetType.file,
status: AssetStatus.processed,
mediaType: proxyType === '3d' ? 'model/gltf-binary' : 'video/mp4',
projectId,
parentId: subFolderId,
creatorId: userId,
storageKeyId: sk.id,
media: {
proxyType,
duration: totalFrames / fps,
filesize: 1000,
frames: totalFrames,
imageTranscodes: [],
videoTranscodes: [{ key: proxyKey, width: 64, height: 64, hdr: false }],
finishedAt: new Date().toISOString(),
metadata: {
originalHeight: h,
originalWidth: w,
hasAudio: false,
bitRate: 100000,
frameRate: fps,
totalFrames,
duration: totalFrames / fps,
startTimecode: '00:00:00:00',
format: {},
},
original: null,
},
},
})
}
const asset30 = await createAsset('v30.mp4', 'video', 'files/proxies/v30.mp4', 30, 24)
const asset23976 = await createAsset(
'v23976.mp4',
'video',
'files/proxies/v23976.mp4',
24000 / 1001,
24,
)
const asset3d = await createAsset('chair.glb', '3d', 'files/proxies/turntable.mp4', 6, 24)
const realService = new CommentFrameService({ maxConcurrency: 2 })
// Frames where .toFixed(4) previously rounded UP and skipped to N+1:
// 30fps: frame 2 (0.06666... -> 0.0667), frame 5 (0.16666... -> 0.1667), frame 23 (last frame)
for (const frame of [0, 2, 5, 8, 17, 23]) {
const res = await realService.extractFrame({
assetId: asset30.id,
second: frame / 30,
width: 64,
})
expect(await identifyExtractedFrame(res.buffer, 24)).toBe(frame)
}
// 23.976fps: frame 7 (0.291958 -> 0.2920), frame 8, frame 19, frame 23
for (const frame of [0, 7, 8, 19, 23]) {
const res = await realService.extractFrame({
assetId: asset23976.id,
second: frame / (24000 / 1001),
width: 64,
})
expect(await identifyExtractedFrame(res.buffer, 24)).toBe(frame)
}
// 3D 6fps turntable where model-viewer stores center times ((N + 0.5) / 6, last = (23 + 0.25) / 6)
for (const frame of [0, 1, 6, 12, 23]) {
const centerSec = frame === 23 ? (frame + 0.25) / 6 : (frame + 0.5) / 6
const res = await realService.extractFrame({
assetId: asset3d.id,
second: centerSec,
width: 64,
})
expect(await identifyExtractedFrame(res.buffer, 24)).toBe(frame)
}
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true })
}
})
})
-557
View File
@@ -1,557 +0,0 @@
import { assetService } from '@shumai/core/src/asset/asset'
import { logger } from '@shumai/core/src/logger'
import { s3Service } from '@shumai/core/src/s3/s3'
import { secondToTurntableFrame, TURNTABLE_FPS } from '@shumai/core/src/utils/model3d'
import { watermarkService } from '@shumai/core/src/watermark/watermark'
import { prisma } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
import { execFile } from 'child_process'
import * as fs from 'fs'
import { HTTPException } from 'hono/http-exception'
import * as os from 'os'
import * as path from 'path'
import sharp from 'sharp'
import { ulid } from 'ulid'
import { promisify } from 'util'
const execFileAsync = promisify(execFile)
const DEFAULT_CONCURRENCY = 4
const DEFAULT_FRAME_TIMEOUT_MS = 30_000
const MIN_PREFERRED_PROXY_HEIGHT = 360
export interface ExtractCommentFrameParams {
assetId: string
second: number
width?: number
watermarkConfigId?: string | null
signal?: AbortSignal
}
export interface ExtractCommentFrameResult {
buffer: Buffer
mimeType: string
}
export type ExecFileFn = (
file: string,
args: string[],
options?: { signal?: AbortSignal; timeout?: number },
) => Promise<{ stdout: string | Buffer; stderr: string | Buffer }>
interface QueuedTask<T> {
run: () => Promise<T>
resolve: (value: T) => void
reject: (err: unknown) => void
signal?: AbortSignal
onAbort?: () => void
}
/**
* Bounded FIFO concurrency queue dedicated to on-demand comment frame extraction,
* isolated from background transcode workers so print requests stay fast without
* overloading the main API server.
*/
export class FrameExtractionQueue {
private running = 0
private readonly pending: QueuedTask<unknown>[] = []
constructor(private readonly maxConcurrency: number) {}
get activeCount(): number {
return this.running
}
get queuedCount(): number {
return this.pending.length
}
enqueue<T>(run: () => Promise<T>, signal?: AbortSignal): Promise<T> {
if (signal?.aborted) {
return Promise.reject(new DOMException('Frame extraction aborted', 'AbortError'))
}
return new Promise<T>((resolve, reject) => {
const task: QueuedTask<T> = { run, resolve, reject, signal }
if (signal) {
const onAbort = () => {
const idx = this.pending.indexOf(task as QueuedTask<unknown>)
if (idx !== -1) {
this.pending.splice(idx, 1)
signal.removeEventListener('abort', onAbort)
reject(new DOMException('Frame extraction aborted', 'AbortError'))
}
}
task.onAbort = onAbort
signal.addEventListener('abort', onAbort, { once: true })
}
this.pending.push(task as QueuedTask<unknown>)
this.drain()
})
}
private drain(): void {
while (this.running < this.maxConcurrency && this.pending.length > 0) {
const task = this.pending.shift()
if (!task) break
if (task.signal && task.onAbort) {
task.signal.removeEventListener('abort', task.onAbort)
}
if (task.signal?.aborted) {
task.reject(new DOMException('Frame extraction aborted', 'AbortError'))
continue
}
this.running++
task.run().then(
(result) => {
this.running--
this.drain()
task.resolve(result)
},
(err) => {
this.running--
this.drain()
task.reject(err)
},
)
}
}
}
/**
* Picks the fastest video proxy suitable for thumbnail extraction:
* 1. Prefer SDR proxies over HDR to avoid washed-out colors.
* 2. Among SDR proxies, pick the lowest resolution that is still >= 360p (fast seek + decode
* for a ~400px thumbnail). If none are >= 360p, pick the highest available SDR proxy.
*/
export function selectBestVideoProxyKey(
videoTranscodes?: PrismaJson.VideoTranscode[] | null,
): string | null {
if (!videoTranscodes || videoTranscodes.length === 0) return null
const valid = videoTranscodes.filter((t) => Boolean(t.key))
if (valid.length === 0) return null
const sdr = valid.filter((t) => !t.hdr)
const pool = sdr.length > 0 ? sdr : valid
const adequate = pool
.filter((t) => (t.height || 0) >= MIN_PREFERRED_PROXY_HEIGHT)
.sort((a, b) => (a.height || 0) - (b.height || 0))
if (adequate.length > 0) {
return adequate[0].key ?? null
}
const fallback = [...pool].sort((a, b) => (b.height || 0) - (a.height || 0))
return fallback[0]?.key ?? null
}
/**
* Resolves an ffmpeg `-ss` input seek timestamp that lands squarely on the exact
* target frame displayed by Shumai's video and 3D turntable players.
*
* `ffmpeg -ss T -i input -vframes 1` outputs the first frame with `PTS >= T`.
* Passing `N / fps` directly (especially after decimal rounding) or a frame center
* `(N + 0.5) / fps` causes ffmpeg to skip frame `N` and emit frame `N + 1` whenever
* `T` exceeds `PTS(N)` by even 1µs.
*
* Instead, we recover integer frame `N` with the exact player formula
* (`Math.floor(second * fps + 0.45)` for video, `secondToTurntableFrame` for 3D)
* and seek to the midpoint between frame `N - 1` and frame `N`: `(N - 0.5) / fps`,
* leaving a full ±0.5 frame tolerance margin on both sides.
*/
export function resolveFrameAccurateSeek(params: {
second: number
proxyType: 'video' | '3d'
frameRate?: number | null
totalFrames?: number | null
duration?: number | null
}): { seekTime: number; frameIndex: number | null } {
const safeSecond = Math.max(0, params.second)
if (params.proxyType === '3d') {
const frameIndex = secondToTurntableFrame(safeSecond)
const seekTime = frameIndex <= 0 ? 0 : (frameIndex - 0.5) / TURNTABLE_FPS
return { seekTime, frameIndex }
}
const fps = params.frameRate && params.frameRate > 0 ? params.frameRate : null
if (fps) {
let frameIndex = Math.max(0, Math.floor(safeSecond * fps + 0.45))
if (params.totalFrames && params.totalFrames > 0) {
frameIndex = Math.min(frameIndex, params.totalFrames - 1)
} else if (params.duration && params.duration > 0) {
const maxFrame = Math.max(0, Math.round(params.duration * fps) - 1)
frameIndex = Math.min(frameIndex, maxFrame)
}
const seekTime = frameIndex <= 0 ? 0 : (frameIndex - 0.5) / fps
return { seekTime, frameIndex }
}
const seekTime =
params.duration && params.duration > 0 && safeSecond >= params.duration
? Math.max(0, params.duration - 0.05)
: safeSecond
return { seekTime, frameIndex: null }
}
export class CommentFrameService {
private readonly queue: FrameExtractionQueue
private readonly inFlight = new Map<
string,
{
promise: Promise<ExtractCommentFrameResult>
controller: AbortController
waiters: number
}
>()
private readonly execFileFn: ExecFileFn
private readonly timeoutMs: number
constructor(options?: { maxConcurrency?: number; timeoutMs?: number; execFileFn?: ExecFileFn }) {
const envConcurrency = Number(process.env.PRINT_FRAME_CONCURRENCY)
const maxConcurrency =
options?.maxConcurrency ??
(Number.isInteger(envConcurrency) && envConcurrency > 0
? envConcurrency
: DEFAULT_CONCURRENCY)
this.queue = new FrameExtractionQueue(maxConcurrency)
this.timeoutMs = options?.timeoutMs ?? DEFAULT_FRAME_TIMEOUT_MS
this.execFileFn =
options?.execFileFn ??
((file, args, opts) =>
execFileAsync(file, args, {
signal: opts?.signal,
timeout: opts?.timeout,
maxBuffer: 10 * 1024 * 1024,
}))
}
async extractFrame(params: ExtractCommentFrameParams): Promise<ExtractCommentFrameResult> {
if (params.signal?.aborted) {
throw new DOMException('Frame extraction aborted', 'AbortError')
}
const width = Math.max(64, Math.min(1280, Math.round(params.width ?? 400)))
const second = Math.max(0, params.second)
const targetAssetId = await assetService.resolveLatestVersionId(params.assetId)
const asset = await prisma.asset.findUnique({
where: { id: targetAssetId },
include: { storageKey: true },
})
params.signal?.throwIfAborted()
if (!asset || asset.isDeleted) {
throw new HTTPException(404, { message: 'Asset not found' })
}
const media = asset.media as PrismaJson.MediaInfo | null
const proxyType = media?.proxyType ?? this.inferProxyType(asset.mediaType)
if (proxyType !== 'video' && proxyType !== '3d' && proxyType !== 'pdf') {
throw new HTTPException(400, {
message: 'Frame extraction is only supported for video, 3D model, and PDF assets',
})
}
const frameTarget =
proxyType === 'pdf'
? null
: resolveFrameAccurateSeek({
second,
proxyType,
frameRate: media?.metadata?.frameRate,
totalFrames: media?.metadata?.totalFrames ?? media?.frames,
duration: media?.duration ?? media?.metadata?.duration,
})
const normalizedKeyTime =
proxyType === 'pdf'
? `p${Math.max(1, Math.round(second))}`
: frameTarget!.frameIndex !== null
? `f${frameTarget!.frameIndex}`
: frameTarget!.seekTime.toFixed(6)
const dedupeKey = `${targetAssetId}:${params.watermarkConfigId ?? ''}:${normalizedKeyTime}:${width}`
let entry = this.inFlight.get(dedupeKey)
if (!entry) {
const controller = new AbortController()
const promise = this.queue
.enqueue(async () => {
if (proxyType === 'pdf') {
return this.extractPdfPageFrame({
asset,
media,
page: Math.max(1, Math.round(second)),
width,
signal: controller.signal,
})
}
return this.extractVideoFrame({
asset,
media,
second,
seekTime: frameTarget!.seekTime,
frameRate: proxyType === '3d' ? TURNTABLE_FPS : media?.metadata?.frameRate,
width,
watermarkConfigId: params.watermarkConfigId,
signal: controller.signal,
})
}, controller.signal)
.finally(() => {
if (this.inFlight.get(dedupeKey)?.promise === promise) {
this.inFlight.delete(dedupeKey)
}
})
entry = { promise, controller, waiters: 0 }
this.inFlight.set(dedupeKey, entry)
}
entry.waiters++
const currentEntry = entry
if (!params.signal) {
return currentEntry.promise.finally(() => {
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
})
}
return new Promise<ExtractCommentFrameResult>((resolve, reject) => {
let settled = false
const cleanup = () => {
params.signal?.removeEventListener('abort', onAbort)
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
if (currentEntry.waiters === 0) {
currentEntry.controller.abort()
}
}
const onAbort = () => {
if (settled) return
settled = true
cleanup()
reject(new DOMException('Frame extraction aborted', 'AbortError'))
}
params.signal!.addEventListener('abort', onAbort, { once: true })
currentEntry.promise.then(
(res) => {
if (settled) return
settled = true
params.signal?.removeEventListener('abort', onAbort)
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
resolve(res)
},
(err) => {
if (settled) return
settled = true
params.signal?.removeEventListener('abort', onAbort)
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
reject(err)
},
)
})
}
private inferProxyType(mediaType: string | null): PrismaJson.MediaInfo['proxyType'] | undefined {
const lower = (mediaType || '').toLowerCase()
if (lower.startsWith('video/')) return 'video'
if (lower === 'application/pdf') return 'pdf'
if (lower.startsWith('image/')) return 'image'
if (lower.startsWith('audio/')) return 'audio'
return undefined
}
private async extractVideoFrame(params: {
asset: {
id: string
status: string
storageKey: { key: string; isArchived: boolean } | null
}
media: PrismaJson.MediaInfo | null
second: number
seekTime: number
frameRate?: number | null
width: number
watermarkConfigId?: string | null
signal?: AbortSignal
}): Promise<ExtractCommentFrameResult> {
const bucket = process.env.S3_BUCKET || 'shumai'
let targetKey: string | null
if (params.watermarkConfigId) {
const wfMap = await watermarkService.getCompletedWatermarkMediaMap(
[params.asset.id],
params.watermarkConfigId,
)
const watermarkMedia = wfMap.get(params.asset.id) ?? null
targetKey = selectBestVideoProxyKey(watermarkMedia?.videoTranscodes)
if (!targetKey) {
throw new HTTPException(422, {
message: 'Watermarked proxy is not ready for this asset',
})
}
} else {
targetKey = selectBestVideoProxyKey(params.media?.videoTranscodes)
if (!targetKey) {
const originalKey = params.asset.storageKey?.key
const isArchived =
Boolean(params.asset.storageKey?.isArchived) || params.asset.status === 'archived'
if (!originalKey || isArchived) {
throw new HTTPException(422, {
message: 'Original video file is archived and no proxy is available',
})
}
targetKey = originalKey
}
}
const inputSource = await s3Service.resolveInput(bucket, targetKey)
const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://')
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shumai-print-frame-'))
try {
const outPath = path.join(tmpDir, `frame-${ulid()}.webp`)
const runFfmpeg = async (timestamp: number) => {
const args = [
'-y',
'-loglevel',
'warning',
...(isRemote
? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5']
: []),
'-ss',
timestamp.toFixed(6),
'-i',
inputSource,
'-map',
'0:V:0',
'-vframes',
'1',
'-vf',
`scale=${params.width}:-2:force_original_aspect_ratio=decrease`,
'-c:v',
'libwebp',
'-q:v',
'80',
outPath,
]
await this.execFileFn('ffmpeg', args, {
signal: params.signal,
timeout: this.timeoutMs,
})
}
await runFfmpeg(params.seekTime)
// If container metadata overestimated totalFrames at EOF, step back one frame and retry.
if ((!fs.existsSync(outPath) || fs.statSync(outPath).size === 0) && params.seekTime > 0) {
const stepBack = params.frameRate && params.frameRate > 0 ? 1 / params.frameRate : 0.1
await runFfmpeg(Math.max(0, params.seekTime - stepBack))
}
if (!fs.existsSync(outPath) || fs.statSync(outPath).size === 0) {
throw new HTTPException(404, { message: 'Could not extract frame at requested timestamp' })
}
const buffer = fs.readFileSync(outPath)
return { buffer, mimeType: 'image/webp' }
} catch (err) {
if (err instanceof HTTPException) throw err
if ((err as { name?: string })?.name === 'AbortError') throw err
logger.error(
{ assetId: params.asset.id, second: params.second, err },
'Failed to extract video comment frame',
)
throw new HTTPException(500, { message: 'Failed to extract video frame' })
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true })
}
}
private async extractPdfPageFrame(params: {
asset: {
id: string
status: string
storageKey: { key: string; isArchived: boolean } | null
}
media: PrismaJson.MediaInfo | null
page: number
width: number
signal?: AbortSignal
}): Promise<ExtractCommentFrameResult> {
const bucket = process.env.S3_BUCKET || 'shumai'
const proxyKey = params.media?.pdfTranscode?.key
const originalKey = params.asset.storageKey?.key
const isArchived =
Boolean(params.asset.storageKey?.isArchived) || params.asset.status === 'archived'
let targetKey: string | null = proxyKey || null
if (!targetKey) {
if (!originalKey || isArchived) {
throw new HTTPException(422, {
message: 'Original PDF file is archived and no proxy is available',
})
}
targetKey = originalKey
}
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shumai-print-pdf-'))
try {
const pdfPath = path.join(tmpDir, 'source.pdf')
await s3Service.downloadToFile(bucket, targetKey, pdfPath)
const pagePrefix = path.join(tmpDir, 'page')
await this.execFileFn(
'pdftoppm',
[
'-png',
'-scale-to',
String(params.width),
'-f',
String(params.page),
'-l',
String(params.page),
pdfPath,
pagePrefix,
],
{
signal: params.signal,
timeout: this.timeoutMs,
},
)
const pngFile = fs.readdirSync(tmpDir).find((f) => f.endsWith('.png'))
if (!pngFile) {
throw new HTTPException(404, { message: `PDF page ${params.page} not found` })
}
const buffer = await sharp(path.join(tmpDir, pngFile), {
limitInputPixels: (params.width + 1) ** 2,
})
.toColorspace('srgb')
.webp({ quality: 82 })
.toBuffer()
return { buffer, mimeType: 'image/webp' }
} catch (err) {
if (err instanceof HTTPException) throw err
if ((err as { name?: string })?.name === 'AbortError') throw err
logger.error(
{ assetId: params.asset.id, page: params.page, err },
'Failed to render PDF comment page frame',
)
throw new HTTPException(500, { message: 'Failed to render PDF page' })
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true })
}
}
}
export const commentFrameService = new CommentFrameService()
-3
View File
@@ -12,8 +12,6 @@ export interface PostCommentParams {
/** Timecode in seconds (or the encoded viewing angle for 3D models). */
second?: number
attachmentIds?: string[]
/** Whether the comment is internal and hidden from public share links (default false). */
isInternal?: boolean
/** Whether mentions of agents start a chat with them (default true). */
triggerAgents?: boolean
}
@@ -33,7 +31,6 @@ export class CommentService {
annotations: params.annotations,
second: params.second,
attachmentIds: params.attachmentIds ?? [],
isInternal: params.isInternal,
},
{ triggerAgents: params.triggerAgents },
)
-1
View File
@@ -5,7 +5,6 @@ export * from './asset/auto-archive-job'
export * from './auth/auth'
export * from './authz/authz'
export * from './collection/collection'
export * from './comment/comment-frame'
export * from './invite/invite'
export * from './metadata/metadata'
export * from './notification/index'
+2 -296
View File
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { KanbanTaskStatus, KanbanTaskPriority, KanbanTaskEventType } from '@shumai/db/enums'
import { KanbanTaskStatus, KanbanTaskPriority } from '@shumai/db/enums'
import { UNASSIGNED_GOAL_ID } from '@shumai/dtos'
import { kanbanService } from './kanban'
@@ -646,7 +646,7 @@ describe('KanbanService', () => {
)
// Create attachment
const att = await kanbanService.createAttachment(team.id, editor.id, {
const att = await kanbanService.createAttachment(team.id, {
fileName: 'design.png',
size: 1024,
contentType: 'image/png',
@@ -688,119 +688,6 @@ describe('KanbanService', () => {
})
})
describe('Comment attachment keys', () => {
function payload(key: string) {
return [{ id: 'att-1', name: 'file.txt', key, sizeByte: 1, contentType: 'text/plain' }]
}
it('rejects attachment keys that were not issued to the author for the task team', async () => {
const { team, editor, reviewer } = await setupTeamAndUsers()
const otherTeam = await prisma.team.create({ data: { name: 'Other Team' } })
const task = await kanbanService.createTask(team.id, { title: 'Task' }, editor.id, 'editor')
const foreignTeam = await kanbanService.createAttachment(otherTeam.id, editor.id, {
fileName: 'other.png',
size: 1,
})
const otherUser = await kanbanService.createAttachment(team.id, reviewer.id, {
fileName: 'theirs.png',
size: 1,
})
const own = await kanbanService.createAttachment(team.id, editor.id, {
fileName: 'own.png',
size: 1,
})
const ownDir = own.key.slice(0, own.key.lastIndexOf('/'))
for (const key of [
'files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov',
'avatars/someone.png',
'kanban/attachments/01JAAAAAAAAAAAAAAAAAAAAAAA/old.png',
foreignTeam.key,
otherUser.key,
`${ownDir}/../../../../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov`,
`kanban/attachments/${team.id}/${editor.id}/not-a-ulid/own.png`,
]) {
await expect(
kanbanService.addComment(task.id, editor.id, 'see attached', payload(key)),
).rejects.toThrow(/Invalid attachment/)
}
const comments = await kanbanService.listComments(task.id)
expect(comments).toHaveLength(0)
const accepted = await kanbanService.addComment(
task.id,
editor.id,
'see attached',
payload(own.key),
)
expect(accepted.attachments.map((a) => a.id)).toEqual(['att-1'])
})
it('does not sign stored attachment keys outside kanban attachments', async () => {
const { team, editor } = await setupTeamAndUsers()
const task = await kanbanService.createTask(team.id, { title: 'Task' }, editor.id, 'editor')
const legacyKey = 'kanban/attachments/01JAAAAAAAAAAAAAAAAAAAAAAA/notes.txt'
await prisma.kanbanTaskComment.create({
data: {
taskId: task.id,
authorId: editor.id,
body: 'stored before validation',
attachments: [
{
id: 'a',
name: 'secret',
key: 'files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov',
sizeByte: 1,
},
{
id: 'b',
name: 'escape',
key: 'kanban/attachments/../files/x/master.mov',
sizeByte: 1,
},
{ id: 'c', name: 'notes.txt', key: legacyKey, sizeByte: 1 },
{
id: 'd',
name: 'other-team.txt',
key: `kanban/attachments/other-team/${editor.id}/01JAAAAAAAAAAAAAAAAAAAAAAA/x.txt`,
sizeByte: 1,
},
{
id: 'e',
name: 'current.txt',
key: `kanban/attachments/${team.id}/${editor.id}/01JAAAAAAAAAAAAAAAAAAAAAAA/y.txt`,
sizeByte: 1,
},
],
},
})
const [comment] = await kanbanService.listComments(task.id)
expect(comment.attachments.map((a) => a.id)).toEqual(['c', 'e'])
const detail = await kanbanService.getTask(task.id)
expect(detail.comments[0].attachments.map((a) => a.id)).toEqual(['c', 'e'])
})
it('keeps attachment uploads inside the team attachment folder', async () => {
const { team, editor } = await setupTeamAndUsers()
const att = await kanbanService.createAttachment(team.id, editor.id, {
fileName: '../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov',
size: 1,
})
const parts = att.key.split('/')
expect(parts.slice(0, 4)).toEqual(['kanban', 'attachments', team.id, editor.id])
expect(parts).toHaveLength(6)
expect(parts).not.toContain('..')
expect(att.name).toBe('../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov')
})
})
// --------------------------------------------------------------------------
// Task Ordering & Fractional Indexing
// --------------------------------------------------------------------------
@@ -1252,185 +1139,4 @@ describe('KanbanService', () => {
expect(pdfDetail?.thumbnailUrl).toContain('posters/doc_poster.webp')
})
})
// --------------------------------------------------------------------------
// Project membership
// --------------------------------------------------------------------------
describe('Project membership', () => {
async function setupProjectScopedMember() {
const { team, owner, reviewer } = await setupTeamAndUsers()
const client = await prisma.user.create({
data: { name: 'Client Reviewer', email: 'client@example.com' },
})
const ownProject = await prisma.project.create({
data: { name: 'Client Project', teamId: team.id },
})
const otherProject = await prisma.project.create({
data: { name: 'Internal Project', teamId: team.id },
})
const clientMember = await prisma.teamMember.create({
data: { teamId: team.id, userId: client.id, role: 'reviewer', scope: 'project' },
})
await prisma.projectMember.create({
data: { projectId: ownProject.id, teamMemberId: clientMember.id, role: 'reviewer' },
})
const ownTask = await kanbanService.createTask(
team.id,
{ title: 'Client task', projectId: ownProject.id },
owner.id,
'owner',
)
const otherTask = await kanbanService.createTask(
team.id,
{ title: 'Internal task', projectId: otherProject.id },
owner.id,
'owner',
)
const teamTask = await kanbanService.createTask(
team.id,
{ title: 'Team task' },
owner.id,
'owner',
)
const assignedTask = await kanbanService.createTask(
team.id,
{ title: 'Assigned internal task', projectId: otherProject.id, assigneeId: client.id },
owner.id,
'owner',
)
return {
team,
owner,
reviewer,
client,
otherProject,
ownTask,
otherTask,
teamTask,
assignedTask,
}
}
it('lists only tasks in their projects, or that they take part in, for project-scoped members', async () => {
const { team, client, otherProject, ownTask, assignedTask } = await setupProjectScopedMember()
const list = await kanbanService.listTasks(team.id, {}, client.id)
expect(list.data.map((t) => t.id).sort()).toEqual([ownTask.id, assignedTask.id].sort())
expect(list.pageInfo.total).toBe(2)
const filtered = await kanbanService.listTasks(
team.id,
{ projectId: otherProject.id },
client.id,
)
expect(filtered.data.map((t) => t.id)).toEqual([assignedTask.id])
})
it('lists every team task for team-scoped members', async () => {
const { team, reviewer, ownTask, otherTask, teamTask, assignedTask } =
await setupProjectScopedMember()
const list = await kanbanService.listTasks(team.id, {}, reviewer.id)
expect(list.data.map((t) => t.id).sort()).toEqual(
[ownTask.id, otherTask.id, teamTask.id, assignedTask.id].sort(),
)
})
it('shows only readable dependencies, dependents, and dependency events', async () => {
const { owner, team, client, reviewer, ownTask, otherTask, teamTask, assignedTask } =
await setupProjectScopedMember()
await kanbanService.setDependencies(
ownTask.id,
[otherTask.id, assignedTask.id, teamTask.id],
owner.id,
)
await kanbanService.setDependencies(ownTask.id, [otherTask.id, assignedTask.id], owner.id)
await kanbanService.setDependencies(teamTask.id, [ownTask.id], owner.id)
await kanbanService.setDependencies(assignedTask.id, [otherTask.id], owner.id)
const detail = await kanbanService.getTask(ownTask.id, client.id)
expect(detail.dependencies.map((task) => task.id)).toEqual([assignedTask.id])
expect(detail.dependents).toEqual([])
expect(detail.dependencyCount).toBe(1)
expect(detail.dependentCount).toBe(0)
const events = await kanbanService.listEvents(ownTask.id, client.id)
for (const history of [detail.events, events]) {
expect(
history.filter((event) => event.type === KanbanTaskEventType.DEPENDENCY_ADDED),
).toEqual([expect.objectContaining({ data: { parentId: assignedTask.id } })])
expect(history).toContainEqual(
expect.objectContaining({ type: KanbanTaskEventType.CREATED }),
)
expect(history).not.toContainEqual(
expect.objectContaining({ type: KanbanTaskEventType.DEPENDENCY_REMOVED }),
)
}
const teamDetail = await kanbanService.getTask(ownTask.id, reviewer.id)
expect(teamDetail.dependencies.map((task) => task.id).sort()).toEqual(
[otherTask.id, assignedTask.id].sort(),
)
expect(teamDetail.dependents.map((task) => task.id)).toEqual([teamTask.id])
expect(teamDetail.events).toContainEqual(
expect.objectContaining({
type: KanbanTaskEventType.DEPENDENCY_REMOVED,
data: { parentId: teamTask.id },
}),
)
const summary = await kanbanService.listTasks(team.id, {}, client.id)
expect(summary.data).toContainEqual(
expect.objectContaining({ id: ownTask.id, dependencyCount: 1, dependentCount: 0 }),
)
const updated = await kanbanService.updateTask(
assignedTask.id,
{ title: 'Updated assigned task' },
client.id,
null,
)
expect(updated).toMatchObject({ dependencyCount: 0, dependentCount: 1 })
})
it('lists no tasks for users outside the team', async () => {
const { team } = await setupProjectScopedMember()
const outsider = await prisma.user.create({
data: { name: 'Outsider', email: 'outsider@example.com' },
})
const list = await kanbanService.listTasks(team.id, {}, outsider.id)
expect(list.data).toEqual([])
})
it('lists only readable tasks linked to an asset', async () => {
const { team, owner, client, reviewer, otherProject, otherTask, assignedTask } =
await setupProjectScopedMember()
const asset = await prisma.asset.create({
data: {
name: 'internal.mp4',
type: 'file',
status: 'processed',
projectId: otherProject.id,
creatorId: owner.id,
},
})
await kanbanService.linkAsset(team.id, otherTask.id, asset.id)
await kanbanService.linkAsset(team.id, assignedTask.id, asset.id)
await kanbanService.setDependencies(assignedTask.id, [otherTask.id], owner.id)
const forClient = await kanbanService.listTasksForAsset(team.id, asset.id, client.id)
expect(forClient.map((t) => t.id)).toEqual([assignedTask.id])
expect(forClient[0].dependencyCount).toBe(0)
const forReviewer = await kanbanService.listTasksForAsset(team.id, asset.id, reviewer.id)
expect(forReviewer.map((t) => t.id).sort()).toEqual([otherTask.id, assignedTask.id].sort())
expect(forReviewer).toContainEqual(
expect.objectContaining({ id: assignedTask.id, dependencyCount: 1 }),
)
})
})
})
+76 -224
View File
@@ -7,7 +7,6 @@ import { paginateQuery } from '../pagination'
import { getAvatarUrl } from '../user/avatar'
import { s3Service } from '../s3/s3'
import { getProxyType } from '../utils/mime'
import { sanitizeFilename } from '../utils/filename'
import { assetService } from '../asset/asset'
import type {
CreateKanbanGoalRequest,
@@ -29,73 +28,6 @@ import type {
} from '@shumai/dtos'
import { UNASSIGNED_GOAL_ID } from '@shumai/dtos'
type TaskEventWithActor = Prisma.KanbanTaskEventGetPayload<{ include: { actor: true } }>
function dependencyEventParentId(event: TaskEventWithActor): string | undefined {
if (
event.type === KanbanTaskEventType.DEPENDENCY_ADDED ||
event.type === KanbanTaskEventType.DEPENDENCY_REMOVED
) {
const parentId = event.data?.parentId
if (typeof parentId === 'string') return parentId
}
}
function taskRelationCountSelect(
taskFilter: Prisma.KanbanTaskWhereInput | undefined,
): Prisma.KanbanTaskCountOutputTypeSelect {
return {
comments: true,
assets: true,
dependencies: taskFilter ? { where: { parent: taskFilter } } : true,
dependents: taskFilter ? { where: { child: taskFilter } } : true,
}
}
const ULID_PATTERN = /^[0-9A-HJKMNP-TV-Z]{26}$/
function isSafeKeySegment(segment: string): boolean {
// eslint-disable-next-line no-control-regex
return segment !== '' && segment !== '.' && segment !== '..' && !/[\\\x00-\x1f\x7f]/.test(segment)
}
/**
* Parses a comment attachment key issued by `createAttachment`:
* `kanban/attachments/<teamId>/<uploaderId>/<ulid>/<file name>`.
*/
function parseAttachmentKey(key: string): { teamId: string; uploaderId: string } | null {
const parts = key.split('/')
if (
parts.length !== 6 ||
parts[0] !== 'kanban' ||
parts[1] !== 'attachments' ||
!isSafeKeySegment(parts[2]) ||
!isSafeKeySegment(parts[3]) ||
!ULID_PATTERN.test(parts[4]) ||
!isSafeKeySegment(parts[5])
) {
return null
}
return { teamId: parts[2], uploaderId: parts[3] }
}
/** Keys of comment attachments stored before keys carried the team and uploader. */
function isLegacyAttachmentKey(key: string): boolean {
const parts = key.split('/')
return (
parts.length === 4 &&
parts[0] === 'kanban' &&
parts[1] === 'attachments' &&
ULID_PATTERN.test(parts[2]) &&
isSafeKeySegment(parts[3])
)
}
/** Whether a stored attachment key may be signed for a comment on a task in `teamId`. */
function isReadableAttachmentKey(key: string, teamId: string): boolean {
return parseAttachmentKey(key)?.teamId === teamId || isLegacyAttachmentKey(key)
}
export class KanbanService {
// --------------------------------------------------------------------------
// Goal CRUD
@@ -382,7 +314,7 @@ export class KanbanService {
})
}
async getTask(taskId: string, viewerId?: string): Promise<KanbanTaskDetail> {
async getTask(taskId: string): Promise<KanbanTaskDetail> {
const task = await prisma.kanbanTask.findUnique({
where: { id: taskId },
include: {
@@ -422,38 +354,27 @@ export class KanbanService {
throw new HTTPException(404, { message: 'Task not found' })
}
const readableIds = await this.readableRelatedTaskIds(task.teamId, viewerId, [
...task.dependencies.map((link) => link.parentId),
...task.dependents.map((link) => link.childId),
...task.events.map(dependencyEventParentId).filter((id) => id !== undefined),
])
const dependencies = task.dependencies.filter(
(link) => !readableIds || readableIds.has(link.parentId),
)
const dependents = task.dependents.filter(
(link) => !readableIds || readableIds.has(link.childId),
)
const latestStatusEvent = await this.resolveLatestStatusEvent(taskId, task.status)
const resolvedAssets = await this.resolveTaskAssetInfos(task.assets)
const baseInfo = await this.toTaskInfo(task, {
latestStatusEvent,
dependencyCount: dependencies.length,
dependentCount: dependents.length,
dependencyCount: task.dependencies.length,
dependentCount: task.dependents.length,
commentCount: task.comments.length,
assetCount: task.assets.length,
})
return {
...baseInfo,
dependencies: dependencies.map((d) => ({
dependencies: task.dependencies.map((d) => ({
id: d.parent.id,
title: d.parent.title,
isAgentTask: d.parent.isAgentTask,
status: d.parent.status,
priority: d.parent.priority,
})),
dependents: dependents.map((d) => ({
dependents: task.dependents.map((d) => ({
id: d.child.id,
title: d.child.title,
isAgentTask: d.child.isAgentTask,
@@ -471,12 +392,29 @@ export class KanbanService {
image: await getAvatarUrl(c.author.image),
},
body: c.body,
attachments: await this.resolveCommentAttachments(c.attachments, task.teamId),
attachments: await this.resolveCommentAttachments(c.attachments),
createdAt: c.createdAt.toISOString(),
updatedAt: c.updatedAt.toISOString(),
})),
),
events: await this.resolveTaskEvents(task.events, readableIds),
events: await Promise.all(
task.events.map(async (e) => ({
id: e.id,
taskId: e.taskId,
actor: e.actor
? {
id: e.actor.id,
name: e.actor.name,
image: await getAvatarUrl(e.actor.image),
}
: null,
type: e.type,
fromStatus: e.fromStatus,
toStatus: e.toStatus,
data: (e.data as Record<string, unknown>) ?? null,
createdAt: e.createdAt.toISOString(),
})),
),
}
}
@@ -721,8 +659,7 @@ export class KanbanService {
}
const latestStatusEvent = await this.resolveLatestStatusEvent(taskId, updated.status)
const taskFilter = await this.readableTaskFilter(updated.teamId, actorId)
const counts = await this.getTaskCounts(taskId, taskFilter)
const counts = await this.getTaskCounts(taskId)
return await this.toTaskInfo(updated, {
latestStatusEvent,
@@ -767,54 +704,10 @@ export class KanbanService {
return taskInfo
}
/**
* Limits kanban tasks to those a user may read. Team-scoped members see every
* task in the team; project-scoped members see tasks in the projects they
* belong to and tasks they created, report, or are assigned to.
*/
private async readableTaskFilter(
teamId: string,
userId: string | undefined,
): Promise<Prisma.KanbanTaskWhereInput | undefined> {
if (!userId) return
const member = await prisma.teamMember.findUnique({
where: { teamIdUserId: { teamId, userId } },
})
if (!member) return { id: { in: [] } }
if (member.scope === 'team') return
return {
teamId,
OR: [
{ project: { members: { some: { teamMemberId: member.id } } } },
{ creatorId: userId },
{ reporterId: userId },
{ assigneeId: userId },
],
}
}
private async readableRelatedTaskIds(
teamId: string,
viewerId: string | undefined,
relatedIds: string[],
): Promise<Set<string> | undefined> {
if (relatedIds.length === 0) return
const filter = await this.readableTaskFilter(teamId, viewerId)
if (!filter) return
const tasks = await prisma.kanbanTask.findMany({
where: { id: { in: [...new Set(relatedIds)] }, AND: [filter] },
select: { id: true },
})
return new Set(tasks.map((task) => task.id))
}
async listTasks(
teamId: string,
params: ListKanbanTasksRequest,
viewerId?: string,
): Promise<{ data: KanbanTaskInfo[]; pageInfo: { total?: number; cursor?: string } }> {
const taskFilter = await this.readableTaskFilter(teamId, viewerId)
const where: Prisma.KanbanTaskWhereInput = {
teamId,
...(params.status && { status: params.status }),
@@ -828,7 +721,6 @@ export class KanbanService {
...(params.priority && { priority: params.priority }),
...(params.assigneeId && { assigneeId: params.assigneeId }),
...(params.reporterId && { reporterId: params.reporterId }),
...(taskFilter && { AND: [taskFilter] }),
}
return await paginateQuery(
@@ -840,7 +732,14 @@ export class KanbanService {
reporter: true,
assignee: true,
goal: true,
_count: { select: taskRelationCountSelect(taskFilter) },
_count: {
select: {
comments: true,
dependencies: true,
dependents: true,
assets: true,
},
},
},
orderBy: [{ sortIndex: 'asc' }, { id: 'asc' }],
skip,
@@ -970,10 +869,9 @@ export class KanbanService {
async createAttachment(
teamId: string,
uploaderId: string,
req: { fileName: string; size: number; contentType?: string },
): Promise<PostKanbanAttachmentResponse> {
const key = `kanban/attachments/${teamId}/${uploaderId}/${ulid()}/${sanitizeFilename(req.fileName)}`
const key = `kanban/attachments/${ulid()}/${req.fileName}`
const uploadUrl = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'PUT')
const proxyType = getProxyType(req.contentType, req.fileName)
@@ -997,16 +895,6 @@ export class KanbanService {
const task = await prisma.kanbanTask.findUnique({ where: { id: taskId } })
if (!task) throw new HTTPException(404, { message: 'Task not found' })
// Attachments are uploaded through createAttachment. Only keys it issued to the
// comment author for this task's team may be stored and signed later.
const isOwnUpload = (key: string) => {
const parsed = parseAttachmentKey(key)
return parsed?.teamId === task.teamId && parsed.uploaderId === authorId
}
if (attachments?.some((att) => !isOwnUpload(att.key))) {
throw new HTTPException(400, { message: 'Invalid attachment' })
}
const comment = await prisma.$transaction(async (tx) => {
const c = await tx.kanbanTaskComment.create({
data: {
@@ -1029,10 +917,7 @@ export class KanbanService {
return c
})
const resolvedAttachments = await this.resolveCommentAttachments(
comment.attachments,
task.teamId,
)
const resolvedAttachments = await this.resolveCommentAttachments(comment.attachments)
return {
id: comment.id,
@@ -1050,12 +935,6 @@ export class KanbanService {
}
async listComments(taskId: string): Promise<KanbanCommentInfo[]> {
const task = await prisma.kanbanTask.findUnique({
where: { id: taskId },
select: { teamId: true },
})
if (!task) throw new HTTPException(404, { message: 'Task not found' })
const comments = await prisma.kanbanTaskComment.findMany({
where: { taskId },
include: { author: true },
@@ -1072,7 +951,7 @@ export class KanbanService {
image: await getAvatarUrl(c.author.image),
},
body: c.body,
attachments: await this.resolveCommentAttachments(c.attachments, task.teamId),
attachments: await this.resolveCommentAttachments(c.attachments),
createdAt: c.createdAt.toISOString(),
updatedAt: c.updatedAt.toISOString(),
})),
@@ -1102,8 +981,7 @@ export class KanbanService {
}
private async resolveCommentAttachments(
attachments: PrismaJson.KanbanCommentAttachmentList | null | undefined,
teamId: string,
attachments?: PrismaJson.KanbanCommentAttachmentList | null,
): Promise<KanbanAttachmentInfo[]> {
if (!attachments || !Array.isArray(attachments) || attachments.length === 0) {
return []
@@ -1111,50 +989,29 @@ export class KanbanService {
const bucket = process.env.S3_BUCKET || 'shumai'
return await Promise.all(
attachments
.filter((att) => typeof att.key === 'string' && isReadableAttachmentKey(att.key, teamId))
.map(async (att) => {
const url = await s3Service.presign(bucket, att.key, 'GET')
return {
id: att.id,
name: att.name,
sizeByte: att.sizeByte,
contentType: att.contentType,
url,
proxyType: att.proxyType,
}
}),
attachments.map(async (att) => {
const url = await s3Service.presign(bucket, att.key, 'GET')
return {
id: att.id,
name: att.name,
sizeByte: att.sizeByte,
contentType: att.contentType,
url,
proxyType: att.proxyType,
}
}),
)
}
async listEvents(taskId: string, viewerId?: string): Promise<KanbanEventInfo[]> {
const task = await prisma.kanbanTask.findUnique({
where: { id: taskId },
select: {
teamId: true,
events: { include: { actor: true }, orderBy: { createdAt: 'desc' } },
},
})
if (!task) return []
const readableIds = await this.readableRelatedTaskIds(
task.teamId,
viewerId,
task.events.map(dependencyEventParentId).filter((id) => id !== undefined),
)
return await this.resolveTaskEvents(task.events, readableIds)
}
private async resolveTaskEvents(
events: TaskEventWithActor[],
readableIds: Set<string> | undefined,
): Promise<KanbanEventInfo[]> {
const visibleEvents = events.filter((event) => {
const parentId = dependencyEventParentId(event)
return !readableIds || parentId === undefined || readableIds.has(parentId)
async listEvents(taskId: string): Promise<KanbanEventInfo[]> {
const events = await prisma.kanbanTaskEvent.findMany({
where: { taskId },
include: { actor: true },
orderBy: { createdAt: 'desc' },
})
return await Promise.all(
visibleEvents.map(async (e) => ({
events.map(async (e) => ({
id: e.id,
taskId: e.taskId,
actor: e.actor
@@ -1167,7 +1024,7 @@ export class KanbanService {
type: e.type,
fromStatus: e.fromStatus,
toStatus: e.toStatus,
data: e.data ?? null,
data: (e.data as Record<string, unknown>) ?? null,
createdAt: e.createdAt.toISOString(),
})),
)
@@ -1258,17 +1115,9 @@ export class KanbanService {
return await this.resolveTaskAssetInfos(links)
}
async listTasksForAsset(
teamId: string,
assetId: string,
viewerId?: string,
): Promise<KanbanTaskInfo[]> {
const taskFilter = await this.readableTaskFilter(teamId, viewerId)
async listTasksForAsset(teamId: string, assetId: string): Promise<KanbanTaskInfo[]> {
const links = await prisma.kanbanTaskAsset.findMany({
where: {
assetId,
task: { teamId, ...taskFilter },
},
where: { assetId },
include: {
task: {
include: {
@@ -1276,15 +1125,24 @@ export class KanbanService {
reporter: true,
assignee: true,
goal: true,
_count: { select: taskRelationCountSelect(taskFilter) },
_count: {
select: {
comments: true,
dependencies: true,
dependents: true,
assets: true,
},
},
},
},
},
orderBy: { createdAt: 'desc' },
})
const matchingLinks = links.filter((l) => l.task && l.task.teamId === teamId)
return await Promise.all(
links.map(async (l) => {
matchingLinks.map(async (l) => {
const t = l.task
const latestStatusEvent = await this.resolveLatestStatusEvent(t.id, t.status)
return await this.toTaskInfo(t, {
@@ -1337,25 +1195,19 @@ export class KanbanService {
}
}
private async getTaskCounts(
taskId: string,
taskFilter?: Prisma.KanbanTaskWhereInput,
): Promise<{
private async getTaskCounts(taskId: string): Promise<{
commentCount: number
dependencyCount: number
dependentCount: number
assetCount: number
}> {
const task = await prisma.kanbanTask.findUnique({
where: { id: taskId },
select: { _count: { select: taskRelationCountSelect(taskFilter) } },
})
return {
commentCount: task?._count.comments ?? 0,
dependencyCount: task?._count.dependencies ?? 0,
dependentCount: task?._count.dependents ?? 0,
assetCount: task?._count.assets ?? 0,
}
const [commentCount, dependencyCount, dependentCount, assetCount] = await Promise.all([
prisma.kanbanTaskComment.count({ where: { taskId } }),
prisma.kanbanTaskLink.count({ where: { childId: taskId } }),
prisma.kanbanTaskLink.count({ where: { parentId: taskId } }),
prisma.kanbanTaskAsset.count({ where: { taskId } }),
])
return { commentCount, dependencyCount, dependentCount, assetCount }
}
private async resolveTaskAssetInfos(
@@ -240,12 +240,7 @@ describe('collaboration Operations', () => {
message: 'Too dark at the start',
second: 2.5,
})
expect(comment).toEqual({
id: expect.any(String),
assetId: file,
replyToId: null,
isInternal: false,
})
expect(comment).toEqual({ id: expect.any(String), assetId: file, replyToId: null })
const reply = await runOperation(createCommentOp, as(owner, 'agent', undefined), {
assetId: file,
@@ -253,17 +248,9 @@ describe('collaboration Operations', () => {
replyToId: comment.id,
})
expect(reply.replyToId).toBe(comment.id)
expect(reply.isInternal).toBe(false)
const internalComment = await runOperation(createCommentOp, as(reviewer), {
assetId: file,
message: 'Internal budget note',
isInternal: true,
})
expect(internalComment.isInternal).toBe(true)
const listed = await runOperation(listCommentsOp, as(reviewer), { assetId: file })
expect(listed.total).toBe(2)
expect(listed.total).toBe(1)
expect(listed.data).toEqual([
expect.objectContaining({
id: comment.id,
@@ -271,21 +258,14 @@ describe('collaboration Operations', () => {
author: { id: reviewer.id, name: 'Reviewer' },
second: 2.5,
resolved: false,
isInternal: false,
replies: [
expect.objectContaining({
id: reply.id,
message: 'Brightened in v2',
author: { id: owner.id, name: 'Owner' },
isInternal: false,
}),
],
}),
expect.objectContaining({
id: internalComment.id,
message: 'Internal budget note',
isInternal: true,
}),
])
await expect(
@@ -296,7 +276,7 @@ describe('collaboration Operations', () => {
).resolves.toEqual({ commentId: comment.id, resolved: false })
const created = await auditRows(AuditAction.comment_create)
expect(created.map((r) => r.itemId)).toEqual([comment.id, reply.id, internalComment.id])
expect(created.map((r) => r.itemId)).toEqual([comment.id, reply.id])
expect(created.every((r) => r.teamId === teamId && r.projectId === projectId)).toBe(true)
const completed = await auditRows(AuditAction.comment_complete)
expect(completed).toHaveLength(2)
@@ -20,16 +20,10 @@ export const createCommentOp = implementOperation(createComment, {
message: input.message,
replyToId: input.replyToId,
second: input.second,
isInternal: input.isInternal,
// Mentions in comments written by Shumai's own agent must not start more agent runs.
triggerAgents: ctx.via !== 'agent',
})
return {
id: comment.id,
assetId: comment.assetId,
replyToId: input.replyToId ?? null,
isInternal: comment.isInternal,
}
return { id: comment.id, assetId: comment.assetId, replyToId: input.replyToId ?? null }
},
audit: (input, output) => [
{ action: AuditAction.comment_create, itemId: output.id, contextAssetId: input.assetId },
@@ -15,7 +15,6 @@ function toCommentFields(comment: CommentInfo) {
second: comment.second,
hasMarkup: Array.isArray(comment.annotations) && comment.annotations.length > 0,
attachmentCount: comment.attachments.length,
isInternal: comment.isInternal,
createdAt: comment.createdAt,
}
}

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