Skip to content

The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.

fix: enforce a strict 500 MB asset import limit (#286)

open-design-crew[bot]6af39d822f91
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1b53f13a..d03bbbd3 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -138,7 +138,7 @@ jobs:
npm run build:tracking
node --experimental-strip-types --test tests/tracking.test.ts
- name: Validate standalone installation and packaging
- run: node --experimental-strip-types --test tests/install.test.ts tests/npm-installer.test.ts tests/native-runtime.test.ts tests/npm-package.test.ts tests/test-package.test.ts tests/source-install.test.ts tests/bootstrap.test.ts tests/mcp-registry.test.ts tests/mcp-runtime.test.ts tests/mcp-upgrade.test.ts tests/preview.test.ts tests/phase1.test.ts tests/preview-handoff.test.ts tests/adapters.test.ts tests/package.test.ts tests/recreate-measure.test.ts tests/workflow.test.ts tests/catalog.test.ts tests/prism-templates.test.ts tests/extension-boundary.test.ts tests/connections.test.ts tests/install-guide.test.ts tests/readme-resources.test.ts tests/motion-design-remix.test.ts
+ run: node --experimental-strip-types --test tests/install.test.ts tests/npm-installer.test.ts tests/native-runtime.test.ts tests/npm-package.test.ts tests/test-package.test.ts tests/source-install.test.ts tests/bootstrap.test.ts tests/mcp-registry.test.ts tests/mcp-runtime.test.ts tests/mcp-upgrade.test.ts tests/preview.test.ts tests/workspace-studio.test.ts tests/sync.test.ts tests/phase1.test.ts tests/preview-handoff.test.ts tests/adapters.test.ts tests/package.test.ts tests/recreate-measure.test.ts tests/workflow.test.ts tests/catalog.test.ts tests/prism-templates.test.ts tests/extension-boundary.test.ts tests/connections.test.ts tests/install-guide.test.ts tests/readme-resources.test.ts tests/motion-design-remix.test.ts
- name: Studio regression
run: npm run test:studio -- --maxWorkers=2
- name: Build phase-one ZIP and exercise all public tools
diff --git a/docs/mcp-phase1-tools.md b/docs/mcp-phase1-tools.md
index 4d4eed83..ae47f037 100644
--- a/docs/mcp-phase1-tools.md
+++ b/docs/mcp-phase1-tools.md
@@ -29,7 +29,7 @@ Skill 是指导文档,与公开 Tool 数量分开。本次后续命名与分
- versionId 是历史身份;versionNumber 显示 vN;revision 是内容哈希。恢复后哈希可与旧版相同,版本身份仍是新的。GUI 的已保存改动也进入原生历史。
- 有副作用的保存使用稳定 requestId。同 ID 同输入找回原结果(导出/取消同时刷新同一任务状态);异输入报 REQUEST_ID_CONFLICT。修正失败输入时使用新 ID。对进程中断但无法确认结果的请求返回 REQUEST_STATE_UNKNOWN,不自动重复写入。
- 编辑/恢复以 Studio 原生独占窗口协调 GUI 写入,暂存文件和恢复日志保护整批写入。进程重启先恢复未完成写入;发现外部第三种内容报 RECOVERY_CONFLICT 并保留副本。普通文件系统的多文件提交不等于断电级数据库事务;macOS共享后台持有系统所有权锁后才回收旧私有锁;独立旧服务的workspace.lock仍明确阻塞,不能自动强删。
-- 素材成功项与索引作为一次项目保存;无效素材逐项失败并保留有效项。不覆盖已导入资源。小于2 GiB/项、最多100项;当前为本机绝对路径传输,不是云附件上传协议。
+- 素材成功项与索引作为一次项目保存;无效素材逐项失败并保留有效项。不覆盖已导入资源。At most 500 MB (500000000 bytes) per file and 100 items per call; local absolute paths only, not a cloud attachment upload protocol. Studio enforces the same decimal byte threshold for the entire multipart request, including form overhead, so a batch may need separate uploads. 500.5 MB (500500000 bytes) is rejected; sizes are never rounded down.
- 源码最多100个文本文件、总计8 MiB;可仅更新 requirements;分段读取上限2 MiB/次,offset 是 UTF-8 字节边界。HTTP JSON 请求另受9 MiB传输体积限制。只允许项目内白名单路径,拒绝符号链接、越界及保留元数据路径。
- 错误通过 MCP isError 和 error.code/message/applied 返回原因;来源读取/版本/路径/媒体/任务错误不返回空成功。无法确认写入或丢失回复时,先读取项目/历史/原任务,不盲目重试。服务错误的 applied=unknown 表示无法替调用方推断是否生效。
- 技术验证、视觉/声音/播放审阅和用户采用分开。record_review 只保存所声明的真实依据,verifiedUserAdoption 固定为 false,不证明用户实际采用。
diff --git a/docs/product/architecture.md b/docs/product/architecture.md
index 986e4d53..fba9eef4 100644
--- a/docs/product/architecture.md
+++ b/docs/product/architecture.md
@@ -228,6 +228,8 @@ flowchart LR
## 数据与边界
+Local asset import through phase-one MCP and internal legacy tools allows at most 500 MB (500000000 bytes) per file, using a shared byte check before and after copying. The OpenMotion workspace host enforces the same decimal threshold before forwarding Studio uploads to the pinned engine, counting each complete multipart request including all files and form overhead; it rejects oversized requests before saving files, including streamed uploads without Content-Length. Existing project media and historical restoration are not re-imports.
+
| 数据范围 | 当前内容 | 可移交 / 恢复语义 |
| --- | --- | --- |
| 原生工程 | HTML/CSS/JS、媒体、字体、Studio manifest | 是继续编辑与渲染的输入;按工程打包,不依赖生成供应商的临时输出 URL |
diff --git a/docs/usage.md b/docs/usage.md
index a9bcb1fd..bfc41ccf 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -146,7 +146,7 @@ npm run dev
模板从 Studio 画廊或已有指引选择,当前3个 builtin 可由创建工具复制;没有单独公开目录查询 Tool。其他外部源码/视频由宿主实际检查并重建。
-编辑须同时传 expectedRevision 与 expectedVersionId;文本批量/需求保存和版本恢复使用原生独占历史窗口、暂存与恢复日志。旧 `motion_write_files` 的逐文件行为仅留内部兼容。8 MiB/100文件与2 MiB分段读取是传输限制;媒体小于2 GiB/项并实际探测。恢复旧版本创建新 vN,保留后续历史。
+编辑须同时传 expectedRevision 与 expectedVersionId;文本批量/需求保存和版本恢复使用原生独占历史窗口、暂存与恢复日志。旧 `motion_write_files` 的逐文件行为仅留内部兼容。8 MiB/100文件与2 MiB分段读取是传输限制;Media imports allow at most 500 MB (500000000 bytes) per file and probe actual media. Studio limits each complete multipart request to the same decimal 500 MB, including form overhead; split larger batches into separate uploads. 500.5 MB is rejected without rounding. 恢复旧版本创建新 vN,保留后续历史。
## 本地文件与升级
diff --git a/mcp-tools.ts b/mcp-tools.ts
index 58468b68..aeca30ac 100644
--- a/mcp-tools.ts
+++ b/mcp-tools.ts
@@ -58,7 +58,7 @@ export const tools = [
inputSchema: { type: 'object', properties: { expectedRevision: revision, files: { type: 'array', minItems: 1, maxItems: 100, items: {
type: 'object', properties: { path: { type: 'string' }, content: { type: 'string' } }, required: ['path', 'content'], additionalProperties: false,
} } }, required: ['expectedRevision', 'files'], additionalProperties: false }, annotations: writes },
- { name: 'motion_import_asset', description: 'Copy a local media, font or reference file into the native project assets directory. Use its relative path in Hyperframes HTML. Supports video, audio and images; no base64 media in tool responses.',
+ { name: 'motion_import_asset', description: 'Copy a local media, font or reference file, at most 500 MB (500000000 bytes), into the native project assets directory. Use its relative path in Hyperframes HTML. Supports video, audio and images; no base64 media in tool responses.',
inputSchema: { type: 'object', properties: { expectedRevision: revision, sourcePath: { type: 'string', description: 'Absolute local source path' }, targetPath: { type: 'string', description: 'Project-relative destination under assets/' } }, required: ['expectedRevision', 'sourcePath', 'targetPath'], additionalProperties: false }, annotations: writes },
{ name: 'motion_inspect_project', description: 'Delegate project inspection to the pinned Hyperframes CLI. info returns composition metadata, timeline returns native clips and timing, lint returns official syntax/runtime-contract diagnostics. Fix lint errors before rendering.',
inputSchema: { type: 'object', properties: { view: { enum: ['info', 'timeline', 'lint'] } }, required: ['view'], additionalProperties: false }, annotations: reads },
diff --git a/phase1.ts b/phase1.ts
index 9b119b12..a6d8e609 100644
--- a/phase1.ts
+++ b/phase1.ts
@@ -1,4 +1,5 @@
import { requireNativeRuntime } from './scripts/npm-runtime.mjs';
+import { MAX_ASSET_BYTES, isAssetFileWithinLimit } from './shared/asset-limits.ts';
import { createHash } from 'node:crypto';
import { constants } from 'node:fs';
import { copyFile, lstat, mkdir, open, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';
@@ -200,7 +201,7 @@ export class Phase1Service {
projectType: meta.projectType ?? 'legacy', source: meta.source ?? null, assets, file, exportJob,
previewDisplay: await this.previewDisplay(projectId, version),
exports: jobs.map(({ token, workerPid, ...job }) => job), reviews: await jsonFile(path.join(this.store.directory, 'phase1', 'reviews', projectId + '.json'), []),
- limits: { textBatchFiles: 100, textBatchBytes: 8388608, textReadBytes: 2097152, assetBytes: 2147483648, attachmentTransport: 'local_path' } };
+ limits: { textBatchFiles: 100, textBatchBytes: 8388608, textReadBytes: 2097152, assetBytes: MAX_ASSET_BYTES, attachmentTransport: 'local_path' } };
});
}
async previewDisplay(projectId: string, version: ContentVersion) {
@@ -404,9 +405,9 @@ export class Phase1Service {
}
if (!path.isAbsolute(item.sourcePath)) throw new Error('ATTACHMENT_NOT_READABLE: 需要本机实际绝对路径');
const info = await stat(item.sourcePath);
- if (!info.isFile() || info.size >= 2147483648) throw new Error('ASSET_TOO_LARGE_OR_NOT_FILE');
+ if (!isAssetFileWithinLimit(info)) throw new Error('ASSET_TOO_LARGE_OR_NOT_FILE: max 500 MB (500000000 bytes)');
const staged = path.join(staging, crypto.randomUUID()); await cloneFile(item.sourcePath, staged);
- if ((await stat(staged)).size >= 2147483648) throw new Error('ASSET_TOO_LARGE_OR_NOT_FILE');
+ if (!isAssetFileWithinLimit(await stat(staged))) throw new Error('ASSET_TOO_LARGE_OR_NOT_FILE: max 500 MB (500000000 bytes)');
const probe = await execute(verificationBinaries().ffprobe, ['-v', 'error', '-show_streams', '-show_format', '-of', 'json', staged], staging, 60_000);
if (probe.code) throw new Error('INVALID_MEDIA: 无法读取真实媒体');
const media = JSON.parse(probe.stdout), stream = media.streams?.find((s: any) => s.codec_type === 'video' && !s.disposition?.attached_pic) ?? media.streams?.find((s: any) => s.codec_type === 'audio');
diff --git a/shared/asset-limits.ts b/shared/asset-limits.ts
new file mode 100644
index 00000000..9ef5b2fc
--- /dev/null
+++ b/shared/asset-limits.ts
@@ -0,0 +1,5 @@
+export const MAX_ASSET_BYTES = 500_000_000;
+
+export function isAssetFileWithinLimit(file: { isFile(): boolean; size: number }) {
+ return file.isFile() && file.size <= MAX_ASSET_BYTES;
+}
diff --git a/shared/phase1-tools.ts b/shared/phase1-tools.ts
index 8a0f9de9..5da56d6f 100644
--- a/shared/phase1-tools.ts
+++ b/shared/phase1-tools.ts
@@ -19,7 +19,7 @@ export const phase1Tools = [
sessionId: projectId, templateId: id, referenceVideoId: id, referenceUrl: { type: 'string', maxLength: 2000 } }, ['requestId', 'projectType', 'title', 'requirements']), annotations: write },
{ name: 'motion_open_preview', description: 'Open the named project in the shared editable Studio. Without projectId use only an explicitly bound OpenMotion session, never the global most-recent project. Returns a version-bound previewHandoff; default foreground queues for the calling chat without switching chats. Only an explicit show-now request uses presentation=now to permit switching for this turn. Inspect the latest content after the user returns. action=record_display records the host observation against the current revision/version; queued or unverified content stays pending. action=record_review records evidence about a previously viewed frozen version without changing source.',
inputSchema: object({ action: { enum: ['open', 'record_review', 'record_display'] }, projectId, sessionId: projectId, embedded: { type: 'boolean' }, presentation, expectedRevision: revision, expectedVersionId: id, requestId: id, review, display }, []), annotations: write },
- { name: 'motion_import_assets', description: 'Persist a batch of real local attachments into this project, probe actual media, and return per-item asset IDs, types, sizes, paths and errors. Successful items survive other failures. Existing history is not overwritten. Import does not place media on the timeline. Reuse the same requestId/itemId to retry without duplicate assets.',
+ { name: 'motion_import_assets', description: 'Persist a batch of real local attachments into this project, at most 500 MB (500000000 bytes) per file. Probe actual media and return per-item asset IDs, types, sizes, paths and errors. Successful items survive other failures. Existing history is not overwritten. Import does not place media on the timeline. Reuse the same requestId/itemId to retry without duplicate assets.',
inputSchema: object({ projectId, requestId: id, items: { type: 'array', minItems: 1, maxItems: 100, items: object({ itemId: id, sourcePath: { type: 'string', minLength: 1, maxLength: 4096 }, name: { type: 'string', maxLength: 200 } }, ['itemId', 'sourcePath']) } }, ['projectId', 'requestId', 'items']), annotations: write },
{ name: 'motion_get_project', description: 'Without projectId list projects in the current workspace, newest creation first, exactly five per page (except the last); use nextCursor. With projectId read that project, current revision/version, requirements, native file inventory, asset references and associated export state. file supports bounded UTF-8 reads; exportJobId reads a historical task. This does not switch Studio or create projects.',
inputSchema: object({ projectId, sessionId: projectId, cursor: { type: 'string', maxLength: 2000 }, file: object({ path: { type: 'string', minLength: 1, maxLength: 240 }, offset: { type: 'integer', minimum: 0 }, length: { type: 'integer', minimum: 1, maximum: 2097152 } }, ['path']), expectedRevision: revision, exportJobId: id }, []), annotations: read },
diff --git a/shared/workspace-studio.ts b/shared/workspace-studio.ts
index 335c1328..7dbe64c7 100644
--- a/shared/workspace-studio.ts
+++ b/shared/workspace-studio.ts
@@ -7,6 +7,7 @@ import { WorkspaceStore } from '../workspace.ts';
import { HYPERFRAMES_VERSION, repairGeneratedRegistry } from '../hyperframes.ts';
import { isMain } from './entry.ts';
import { withAvailableHistorySteps } from './studio-history-availability.ts';
+import { MAX_ASSET_BYTES } from './asset-limits.ts';
export async function startWorkspaceStudio(runtimeRoot: string, dataDirectory: string, initialDirectory: string, port: number) {
const require = createRequire(path.join(runtimeRoot, 'package.json'));
@@ -19,6 +20,8 @@ export async function startWorkspaceStudio(runtimeRoot: string, dataDirectory: s
const { createStudioServer } = await import(pathToFileURL(path.join(cli, 'dist', bundles[0])).href);
if (typeof createStudioServer !== 'function') throw new Error('Hyperframes workspace host factory is unavailable');
const { getRequestListener } = await import(pathToFileURL(require.resolve('@hono/node-server')).href);
+ const { Hono } = await import(pathToFileURL(require.resolve('hono')).href);
+ const { bodyLimit } = await import(pathToFileURL(require.resolve('hono/body-limit')).href);
const historyModule = path.join(path.dirname(require.resolve('@hyperframes/studio-server/package.json')), 'dist/history/index.js');
const { DEFAULT_HISTORY_ROOT } = await import(pathToFileURL(historyModule).href);
const historyRoot = process.env.HYPERFRAMES_HISTORY_ROOT ?? DEFAULT_HISTORY_ROOT;
@@ -36,6 +39,11 @@ export async function startWorkspaceStudio(runtimeRoot: string, dataDirectory: s
if (closing) throw new Error('Studio is stopping');
const host = createStudioServer({ projectDir: scoped.projectDirectory, projectName: id,
origin: () => origin, historyRoot });
+ const nativeApp = host.app;
+ host.app = new Hono().post('/api/projects/:id/upload', bodyLimit({
+ maxSize: MAX_ASSET_BYTES,
+ onError: c => c.json({ error: 'Upload exceeds 500 MB (500000000 bytes)', maxBytes: MAX_ASSET_BYTES }, 413),
+ }), c => nativeApp.fetch(c.req.raw)).all('*', c => nativeApp.fetch(c.req.raw));
const openHistory = host.adapter.history;
const histories = new WeakMap();
host.adapter.history = async () => {
diff --git a/skills/motion-production/references/native.md b/skills/motion-production/references/native.md
index 4bf08035..bf921f71 100644
--- a/skills/motion-production/references/native.md
+++ b/skills/motion-production/references/native.md
@@ -7,7 +7,7 @@ Read the pinned engine guide returned as `authoringGuide` by project details, or
1. New work uses `motion_create_project` with a stable requestId, projectType, title and requirements. A prompt/reference creates a carrier, not a finished film. Template creation requires a real copyable builtin ID; select it through the Studio gallery or a provided guide. Existing work reuses its projectId.
2. `motion_get_project({projectId})` reads the explicit project, entry HTML, directory, file inventory, requirements, revision and current version. Without projectId it lists five projects per page; follow nextCursor. Never infer another chat's active project.
3. Read text through `motion_get_project({projectId,file:{path,offset,length},expectedRevision})`. Offsets are UTF-8 byte boundaries; follow nextOffset. Media bytes stay out of MCP text responses.
-4. `motion_import_assets({projectId,requestId,items:[{itemId,sourcePath}]})` imports real local image/video/audio attachments in a batch. Source paths must exist on the server machine. Check every result and use the returned asset path. Import does not place media on the timeline. Keep stable itemIds for retries; never overwrite historical resources. Successful imports can create a new content version: reread project details before saving with expectedRevision/expectedVersionId. This Tool does not accept fonts, SVG/PDF, arbitrary binary files or remote URLs. Keep such files in an independent portable project using host capabilities; do not bypass managed-project guards by writing binary files directly. Inline SVG markup can be authored in native HTML.
+4. `motion_import_assets({projectId,requestId,items:[{itemId,sourcePath}]})` imports real local image/video/audio attachments in a batch. Each file must be at most 500 MB (500000000 bytes); compare exact bytes, not rounded MB. Source paths must exist on the server machine. Check every result and use the returned asset path. Import does not place media on the timeline. Keep stable itemIds for retries; never overwrite historical resources. Successful imports can create a new content version: reread project details before saving with expectedRevision/expectedVersionId. This Tool does not accept fonts, SVG/PDF, arbitrary binary files or remote URLs. Keep such files in an independent portable project using host capabilities; do not bypass managed-project guards by writing binary files directly. Inline SVG markup can be authored in native HTML.
5. `motion_edit_project({projectId,requestId,expectedRevision,expectedVersionId,files:[{path,content}]})` saves one batch of text files and optional requirements. Maximum 100 files / 8 MiB; metadata paths are reserved. All-or-none failure protection uses Studio's exclusive native history window and a recovery journal. Reread after a conflict; do not replay an old patch against unknown GUI changes.
6. For original creation, reference-video recreation and editable-template production, complete the editable preview handoff below once this turn's HTML output is ready. Existing-project content edits follow its continuing-edit rules before writing and after saving, regardless of the selected Skill. Other scopes open Studio on request.
7. Inspect actual motion, timing, sound and affected joins. Local/Studio changes become native content snapshots; querying flushes saved history metadata without editing source. Return to step 2 after GUI edits.
diff --git a/tests/package.test.ts b/tests/package.test.ts
index a2bf430c..f76c5761 100644
--- a/tests/package.test.ts
+++ b/tests/package.test.ts
@@ -8,6 +8,7 @@ test('every distribution preserves public workflow dependencies and licenses whi
for (const profile of ['phase1', 'legacy']) {
const files = new Set(await distributionFiles(profile));
assert(files.has('docs/release-guide.md'), 'The public test/stable manual must ship');
+ assert(files.has('shared/asset-limits.ts'), 'The shared asset import limit must ship');
for (const file of ['studio/build/index.html', 'studio/LICENSE', 'template-library/LICENSE', 'template-library/NOTICE.md', 'web/design-system/fonts/Albert-Sans-OFL.txt', 'scripts/distribution.ts', 'shared/editor-launch.pl', 'shared/workspace-studio.ts', 'shared/owned-studio.mjs', 'shared/workflow-entry.js', 'skills/motion-recreate/scripts/measure_frame.mjs']) assert(files.has(file), 'Missing runtime or license: ' + file);
assert(![...files].some(file => /^(?:tests\/|studio\/(?:src|tests)\/)|\.map$|publish-test-package|acceptance\.md$/.test(file)));
for (const [workflow, definition] of Object.entries(workflowRegistry)) {
diff --git a/tests/phase1.test.ts b/tests/phase1.test.ts
index 353cb0d1..d475031b 100644
--- a/tests/phase1.test.ts
+++ b/tests/phase1.test.ts
@@ -1,6 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
-import { readFile, writeFile, rm, mkdir } from 'node:fs/promises';
+import { readFile, writeFile, rm, mkdir, stat, truncate } from 'node:fs/promises';
import path from 'node:path';
import { fixture } from './fixtures.ts';
import { Phase1Service } from '../phase1.ts';
@@ -9,6 +9,7 @@ import { cancelExport } from '../server.ts';
import { atomicJson, fileHash, recoverProjectTransactions } from '../phase1-versions.ts';
import { validateInput, phase1Tools } from '../shared/phase1-tools.ts';
import { transport } from './http.ts';
+import { MAX_ASSET_BYTES, isAssetFileWithinLimit } from '../shared/asset-limits.ts';
function api(store: any) { return new Phase1Service(store, pluginRoot, {
origin: () => 'http://127.0.0.1:4173', nativeUrl: () => undefined, openProject: async () => {},
@@ -22,9 +23,21 @@ const edit = (service: Phase1Service, p: any, content: string) => service.call('
expectedVersionId: p.version.versionId, files: [{ path: 'note.txt', content }],
});
+test('asset limits enforce decimal 500 MB without rounding', () => fixture(async store => {
+ assert.equal(MAX_ASSET_BYTES, 500_000_000);
+ const file = path.join(store.directory, 'sparse-media');
+ await writeFile(file, '');
+ for (const [size, accepted] of [[499_999_999, true], [500_000_000, true], [500_000_001, false], [500_500_000, false], [524_288_000, false]] as const) {
+ await truncate(file, size);
+ assert.equal(isAssetFileWithinLimit(await stat(file)), accepted, String(size));
+ }
+ assert.equal(isAssetFileWithinLimit(await stat(store.directory)), false);
+}, false));
+
test('phase1 validates real inputs before effects, creates idempotently and pages without switching', () => fixture(async store => {
const service = api(store), p = await create(service, 'first');
assert.equal(p.version.versionNumber, 1); assert.equal(p.filmComplete, false);
+ assert.equal(p.limits.assetBytes, MAX_ASSET_BYTES);
await assert.rejects(service.call('motion_create_project', { requestId: 'mixed-sources', projectType: 'natural_language', title: 'x', requirements: 'x', templateId: 'nyt-graph' }), /INVALID_ARGUMENT/);
await assert.rejects(service.call('motion_get_project', { projectId: p.projectId, sessionId: crypto.randomUUID() }), /PROJECT_SESSION_MISMATCH/);
assert.equal((await create(service, 'first')).projectId, p.projectId);
@@ -80,9 +93,13 @@ test('imports retain historical media and reject missing or corrupt blobs withou
const wav = path.join(store.directory, 'source.wav'), fake = path.join(store.directory, 'fake.png');
const made = await execute('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'sine=duration=0.2', wav], store.directory);
assert.equal(made.code, 0, made.stderr); await writeFile(fake, 'not an image');
- const args = { projectId: p.projectId, requestId: 'import', items: [{ itemId: 'audio', sourcePath: wav }, { itemId: 'fake', sourcePath: fake }, { itemId: 'image', sourcePath: png }, { itemId: 'video', sourcePath: video }] };
+ const oversized = path.join(store.directory, 'oversized.mp4');
+ await writeFile(oversized, ''); await truncate(oversized, MAX_ASSET_BYTES + 1);
+ const args = { projectId: p.projectId, requestId: 'import', items: [{ itemId: 'audio', sourcePath: wav }, { itemId: 'fake', sourcePath: fake }, { itemId: 'image', sourcePath: png }, { itemId: 'video', sourcePath: video }, { itemId: 'oversized', sourcePath: oversized }] };
const imported = await service.call('motion_import_assets', args);
assert.equal(imported.status, 'partial'); assert.equal(imported.items[0].mimeType, 'audio/wav'); assert.equal(imported.items[1].status, 'failed'); assert.equal(imported.items[2].mimeType, 'image/png'); assert.equal(imported.items[3].mimeType, 'video/mp4');
+ assert.equal(imported.items[4].status, 'failed');
+ assert.match(imported.items[4].error, /^ASSET_TOO_LARGE_OR_NOT_FILE: max 500 MB/);
assert.equal((await service.call('motion_import_assets', args)).items[0].assetId, imported.items[0].assetId);
const deduped = await service.call('motion_import_assets', { ...args, requestId: 'new-import', items: [args.items[0]] });
assert.equal(deduped.items[0].reused, true);
diff --git a/tests/sync.test.ts b/tests/sync.test.ts
index efdf3d5d..baaf7691 100644
--- a/tests/sync.test.ts
+++ b/tests/sync.test.ts
@@ -1,6 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
-import { mkdir, readFile, rm, symlink, writeFile } from 'node:fs/promises';
+import { mkdir, readFile, rm, symlink, truncate, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { WorkspaceStore, Conflict } from '../workspace.ts';
import { callTool } from '../mcp.ts';
@@ -49,6 +49,10 @@ test('asset imports are local files and their content participates in revisions'
assert.notEqual(next.revision, first.revision);
assert.deepEqual(await readFile(path.join(store.projectDirectory, 'assets/audio.wav')), Buffer.from([1, 2, 3, 4]));
await assert.rejects(store.importAsset(next.revision, source, '../outside.wav'));
+ await truncate(source, 500_000_001);
+ await assert.rejects(store.importAsset(next.revision, source, 'assets/audio.wav'), /500 MB/);
+ assert.equal((await store.get()).revision, next.revision);
+ assert.deepEqual(await readFile(path.join(store.projectDirectory, 'assets/audio.wav')), Buffer.from([1, 2, 3, 4]));
await writeFile(path.join(store.projectDirectory, 'assets/audio.wav'), Buffer.from([4, 3, 2, 1]));
assert.notEqual((await store.get()).revision, next.revision);
}));
diff --git a/tests/workspace-studio.test.ts b/tests/workspace-studio.test.ts
index 4527c490..c5f190db 100644
--- a/tests/workspace-studio.test.ts
+++ b/tests/workspace-studio.test.ts
@@ -1,10 +1,43 @@
import test from 'node:test';
import assert from 'node:assert/strict';
-import { mkdtemp, mkdir, writeFile, copyFile, rm } from 'node:fs/promises';
+import { mkdtemp, mkdir, writeFile, copyFile, readdir, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { startWorkspaceStudio } from '../shared/workspace-studio.ts';
+import { request } from 'node:http';
+import { fixture } from './fixtures.ts';
+import { pluginRoot } from '../hyperframes.ts';
+
+test('Studio rejects decimal uploads above 500 MB before saving and still accepts normal uploads', () => fixture(async store => {
+ const studio = await startWorkspaceStudio(pluginRoot, store.directory, store.projectDirectory, 0);
+ const url = `${studio.origin}/api/projects/${store.projectId}/upload?dir=assets`;
+ const assets = path.join(store.projectDirectory, 'assets');
+ const before = await readdir(assets);
+ try {
+ for (const size of [500_000_001, 500_500_000, 524_288_000]) {
+ const response = await new Promise<{ status: number; body: string }>((resolve, reject) => {
+ const req = request(url, { method: 'POST', headers: { Origin: studio.origin, 'Content-Length': size, Connection: 'close' } }, res => {
+ let body = '';
+ res.setEncoding('utf8'); res.on('data', chunk => { body += chunk; });
+ res.on('error', reject);
+ res.on('end', () => { resolve({ status: res.statusCode!, body }); req.destroy(); });
+ });
+ req.on('error', reject); req.setTimeout(5000, () => req.destroy(new Error('Upload limit response timed out')));
+ req.end();
+ });
+ assert.equal(response.status, 413);
+ assert.equal(JSON.parse(response.body).maxBytes, 500_000_000);
+ assert.deepEqual(await readdir(assets), before);
+ }
+ const form = new FormData();
+ form.append('file', new Blob([Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==', 'base64')], { type: 'image/png' }), 'clip.png');
+ const response = await fetch(url, { method: 'POST', headers: { Origin: studio.origin }, body: form });
+ assert.equal(response.status, 201, await response.clone().text());
+ assert.deepEqual((await response.json()).files, ['assets/clip.png']);
+ assert.equal((await fetch(studio.origin + '/api/projects')).status, 200);
+ } finally { await studio.close(); }
+}));
test('the shipped history availability module loads without plugin-local node_modules', async () => {
const root = await mkdtemp(path.join(tmpdir(), 'motion-history-module-'));
diff --git a/workspace.ts b/workspace.ts
index de05a4d1..dba652b7 100644
--- a/workspace.ts
+++ b/workspace.ts
@@ -1,4 +1,5 @@
import { createHash } from 'node:crypto';
+import { isAssetFileWithinLimit } from './shared/asset-limits.ts';
import { createReadStream, existsSync, readFileSync } from 'node:fs';
import os from 'node:os';
import { copyFile, cp, lstat, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
@@ -315,7 +316,7 @@ export class WorkspaceStore {
projectPath(targetPath);
if (!targetPath.startsWith('assets/')) throw new Error('素材目标必须位于 assets/');
const source = await stat(sourcePath);
- if (!source.isFile() || source.size > 2 * 1024 ** 3) throw new Error('素材必须是小于 2 GB 的文件');
+ if (!isAssetFileWithinLimit(source)) throw new Error('素材必须是不超过 500 MB(500000000 字节)的文件');
return this.lock(async () => {
if ((await this.get()).revision !== expectedRevision) throw new Conflict();
const target = await this.safePath(targetPath);
@@ -323,6 +324,7 @@ export class WorkspaceStore {
const temporary = path.join(path.dirname(target), '.motion-import-' + crypto.randomUUID());
try {
await copyFile(sourcePath, temporary);
+ if (!isAssetFileWithinLimit(await stat(temporary))) throw new Error('素材必须是不超过 500 MB(500000000 字节)的文件');
if ((await this.get()).revision !== expectedRevision) throw new Conflict();
await rename(temporary, target);
} finally { await rm(temporary, { force: true }); }