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.

feat: export redacted local diagnostics from Studio and CLI (#302)

open-design-crew[bot]ed818e71f3c3
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a131afa2..86c32a76 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/editor-urls.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
+ run: node --experimental-strip-types --test tests/diagnostics.test.ts 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/editor-urls.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/npm-installation.md b/docs/npm-installation.md
index b48410cd..f5fad450 100644
--- a/docs/npm-installation.md
+++ b/docs/npm-installation.md
@@ -132,6 +132,34 @@ If the terminal also fails, resolve DNS/proxy/network access first and report in
References: [npmmirror](https://npmmirror.com/), [temporary npm configuration](https://docs.npmjs.com/cli/v11/using-npm/config/#environment-variables) and [npm ping](https://docs.npmjs.com/cli/v11/commands/npm-ping/).
+### Export a local diagnostic ZIP
+
+Test and stable packages share the same collector. Open **Privacy settings → Export diagnostic ZIP** in Studio; the crash screen also offers the export. It saves a local download and does not upload it. The action works while native downloads or the renderer are unavailable, provided the local backend is running.
+
+If Studio or MCP cannot connect, run the CLI from the same exact package and installation home used for setup:
+
+```sh
+openmotion diagnostics --home /absolute/installation-home --output /absolute/support.zip
+```
+
+The installed application also exposes `node /absolute/application/scripts/npm-installer.mjs diagnostics --home /absolute/installation-home --output /absolute/support.zip`. For a plugin, complete ZIP or source installation, use its actual data directory:
+
+```sh
+node /absolute/application/scripts/diagnostics.mjs --data-dir /absolute/project-data --output /absolute/support.zip
+```
+
+`--output` is optional; the default is a uniquely named ZIP in the current directory. Existing files are never overwritten. `diagnostics` collects local files without starting MCP, Studio, native downloads, a renderer or a recovery action. It can produce a partial report even when setup has not completed. The separate `diagnose` command below actively probes MCP and is not run by ZIP collection.
+
+The archive includes version/build identity, OS/CPU/Node and registered host names when available, native preparation status, a bounded sample of export-job metadata, existing service/render logs and local failure records. `files.json` identifies collected, missing, excluded and truncated files. Missing information is not a successful host-session check. Existing host application logs are not scanned; use that host's own log viewer for failures before OpenMotion starts. The collector does not inspect arbitrary files or include projects, media, conversations, full host/provider configuration or an environment dump.
+
+Local records cover installation failures after the home exists, phase-one MCP failures, export failures, displayed operation errors and browser/React crashes. They are independent of usage telemetry and work in test builds and with telemetry disabled. Studio also records page/browser identity, selected workspace and native edit/import/render HTTP requests, and diagnostic-download stages. Requests have page-local correlation IDs, fixed route categories, response status and time to response headers; no request/response bodies, headers, project IDs, file names or query values are recorded. Healthy reads under two seconds, playback/selection updates, asset traffic and cancelled reads are omitted. ZIP export records archive receipt and browser download dispatch separately; dispatch is not proof that the browser saved a file. These completion records appear in a subsequent ZIP or persisted CLI log, not in the ZIP already being downloaded.
+
+Browser records stay in memory first, with separate error (20 entries / 16 KiB) and activity (39 entries / 7 KiB) rings. Including the loss summary, UI export remains below 60 records / 24 KiB. At most 20 errors and 40 activity records are admitted per minute per page; repeated errors or failing/slow read routes are coalesced for 30 seconds. The UI archive separates `browser-errors.json` and `browser-activity.json`, including counters for omitted records and failed delivery. One timer batches local storage and backend delivery every five seconds while records are pending; there is no idle heartbeat. Page hide also attempts a flush. Delivery uses at most one request at a time, 20 records per batch and a three-second deadline, without retries. Logging is never awaited by the user operation. Backend ingestion appends a batch together and preserves event timestamps. A browser crash can lose the pending tail; offline CLI cannot recover records that never reached the backend. The backend retains the current and previous diagnostic log, each at most 128 KiB. Existing engine/service logs keep their current retention behavior; the ZIP only reads bounded tails. A crash before a record reaches disk, a failed outer npm download or a failure before the collector can run may leave no log; include reproduction steps and the host's own logs in those cases.
+
+Known secret values from the current process environment, common credential formats, authorization/cookie values, URL details, email addresses and local paths are redacted before export. New local diagnostic records are also redacted before storage. Arbitrary private text embedded in an existing error log cannot be classified perfectly: **review the ZIP before sharing**. There is no automatic cloud upload.
+
+The HTTP route accepts same-origin POST requests only, with a fixed collection scope, bounded input, one collection at a time and a 30-second cooldown. It returns the ZIP directly without saving server-side archives. Reads skip symlinks and non-regular files; log tails are limited to 128 KiB each, log/archive inputs are bounded, directory scans stop at 100 entries and at most five sampled jobs are included. Local browser-event ingestion is limited to 60 records per minute across pages; excess delivery can be dropped without affecting editing. These controls contain accidental repeated clicks and remote requests; a user with local shell access can still run the CLI repeatedly and consume their own disk space. Export does not grant access beyond the local account's existing permissions.
+
### Missing MCP tools or a failed connection
Run the installed CLI with the same application home and selected host:
diff --git a/docs/product/architecture.md b/docs/product/architecture.md
index c2d231e5..277d7cfe 100644
--- a/docs/product/architecture.md
+++ b/docs/product/architecture.md
@@ -254,6 +254,12 @@ The font picker offers detected local fonts, imported project fonts and fonts de
- **并发边界:** macOS 同目录多个 MCP 连接共用后台,各自绑定工程;工作区使用一个原生 Studio 服务进程,按需保留多个工程的原生上下文;后台仍只有一个等待/运行的导出。导出固定工程与快照,重启将中断任务持久化为失败且不重放。文件锁和 revision 保护工具写入;人工与 Agent 同时编辑同一文件仍需协调,不能当作跨工具数据库事务。
- **数据归属:** 产品文档描述数据类别与流程,不复制用户的私有工程、访问凭据或个人机器配置。
+### Local diagnostic export
+
+Test and stable distributions share `scripts/diagnostics.mjs`, its browser-safe redaction helper and the existing dependency-free ZIP writer. Studio Privacy settings and the crash screen download the same local diagnostic archive through a same-origin POST route; `openmotion diagnostics` and the standalone script can collect without a running editor/MCP or native executables. Collection does not launch probes, replay operations, change projects or upload data.
+
+The collector uses an explicit file/field allowlist, bounded log tails and job sampling, excludes links/non-files and records missing or truncated inputs. New local failure records cover installer, phase-one MCP, export and browser errors, with current/previous log rotation. Browser errors and selected workspace/native request breadcrumbs are redacted before bounded in-memory retention and batched local persistence/delivery; collection applies redaction again. Errors retain a separate budget from activity. Healthy polling, playback/selection updates and asset reads are not logged; fixed route categories, page-local request IDs, statuses and header-response timing exclude user content. A five-second pending-only timer, per-page rate limits, duplicate suppression, single-flight delivery and a three-second delivery deadline keep logging off the user-operation completion path. Archive receipt and browser download dispatch are distinct diagnostic-export stages, with dispatch not asserting file-save completion; a subsequent archive or CLI log can contain those stages. UI archives include loss counters, and process termination can lose buffered records. Logging is independent of usage analytics. Existing engine/service log retention is unchanged. Full project/media/conversation/provider/host data is excluded, while arbitrary private text in old logs still requires user review. HTTP export has a single-collection guard and cooldown, never accepts source/output paths, and streams no persistent server-side ZIP. See [diagnostic export and limits](../npm-installation.md#export-a-local-diagnostic-zip).
+
## 成功标准与验证
当前交付标准:连接可验证、模板可定位、工程可继续编辑、预览与源文件一致、导出存在真实文件、检查结果有证据。相关实现由 `tests/`、`npm run test:studio` 的原生单元/DOM 与宿主回归、类型检查、设计检查和按需浏览器验证覆盖;没有执行的检查不能记为通过。
diff --git a/docs/test-packages.md b/docs/test-packages.md
index 6ee3383f..0dbbc53d 100644
--- a/docs/test-packages.md
+++ b/docs/test-packages.md
@@ -81,3 +81,7 @@ node scripts/smoke-test-package.mjs <最终ZIP路径> .tools/codex-cli/node_modu
```
同一 Linux 构建机将 target 改为 win-x64 即可装配 Windows 包。目标机只执行 smoke,不重新打包。验证从含空格与中文的新路径展开最终 ZIP,使用系统临时目录中的独立 Codex 配置和工程目录,检查原生安装、最小 PATH 下 MCP 握手、模板、工作流、Studio HTTP,以及有声音、有运动的 1 秒 MP4 和成片技术检查;验收使用显式 `PORT` 配置,否则由系统分配临时空闲端口;不固定占用 54900,避免共享 Windows runner 的其他服务冲突。验收在首次启动时保存进程归属,避免后续预览复用覆盖登记后遗留服务;结束时按版本和工程目录校验后,只清理测试自身创建的进程。模型回合、独立播放器、旧系统及跨版本回退不由此代替。
+
+## Local diagnostic handoff
+
+Test and stable packages both include the local diagnostic ZIP collector. In Studio use Privacy settings → Export diagnostic ZIP; without a working Studio/MCP connection use `openmotion diagnostics --home /absolute/installation-home --output /absolute/support.zip` from the exact installed package. Plugin/complete-ZIP users can run the shipped `scripts/diagnostics.mjs` with `--data-dir`. Collection is local, bounded and redacted, and does not publish/upload data or run an MCP probe. Review the ZIP before sharing, include reproduction steps, and keep its exact version/build identity with the defect. See [scope, commands and limits](npm-installation.md#export-a-local-diagnostic-zip).
diff --git a/phase1.ts b/phase1.ts
index a6d8e609..0c9987dc 100644
--- a/phase1.ts
+++ b/phase1.ts
@@ -1,4 +1,5 @@
import { requireNativeRuntime } from './scripts/npm-runtime.mjs';
+import { recordDiagnostic } from './scripts/diagnostics.mjs';
import { MAX_ASSET_BYTES, isAssetFileWithinLimit } from './shared/asset-limits.ts';
import { createHash } from 'node:crypto';
import { constants } from 'node:fs';
@@ -88,6 +89,8 @@ export class Phase1Service {
this.restoreErrors.set(args.projectId, { requestId: args.requestId, message: errorText(error) });
}
trackPhase1Result(this.context.tracking, name, args, undefined, error);
+ await recordDiagnostic(this.store.directory, { kind: 'mcp_failure', tool: name, requestId: args?.requestId,
+ projectId: args?.projectId, message: errorText(error), stack: error instanceof Error ? error.stack : undefined });
throw error;
}
}
diff --git a/scripts/diagnostic-redaction.mjs b/scripts/diagnostic-redaction.mjs
new file mode 100644
index 00000000..b442003e
--- /dev/null
+++ b/scripts/diagnostic-redaction.mjs
@@ -0,0 +1,19 @@
+// Shared by local log writers and the ZIP collector; never send these logs to telemetry.
+export function redactDiagnostic(value, environment = {}, paths = []) {
+ let text = String(value);
+ for (const [key, secret] of Object.entries(environment)) {
+ if (/token|secret|password|authorization|cookie|(?:^|_)key|private.?key|api.?key/i.test(key) && typeof secret === 'string' && secret.length >= 4) text = text.replaceAll(secret, '[redacted]');
+ }
+ text = text.replace(/-----BEGIN [^-\r\n]*PRIVATE KEY-----[\s\S]*?(?:-----END [^-\r\n]*PRIVATE KEY-----|$)/g, '[redacted private key]')
+ .replace(/^(?:[A-Za-z0-9+/]{64,}={0,2})\r?$/gm, value => /^[a-f\d]+$/i.test(value) ? value : '[redacted encoded data]')
+ .replace(/((?:set-cookie|cookie|authorization)\s*:\s*)[^\r\n]+/gi, '$1[redacted]')
+ .replace(/\b(?:Bearer|Basic)\s+[^\s"',;}]+/gi, '[redacted authorization]')
+ .replace(/([\w-]*(?:token|secret|password|passwd|authorization|cookie|api.?key)[\w-]*["']?\s*[:=]\s*)("(?:\\.|[^"\\])*"|'[^']*'|[^\s,;}]+)/gi, '$1[redacted]')
+ .replace(/\b(?:sk-[\w-]{8,}|gh[pousr]_[\w]{12,}|github_pat_[\w]{12,}|AKIA[A-Z0-9]{16}|eyJ[\w-]+\.[\w-]+\.[\w-]+)\b/g, '[redacted token]')
+ .replace(/https?:\/\/[^\s<>"')]+/gi, value => {
+ try { return new URL(value).origin + '/[redacted-url]'; } catch { return '[redacted-url]'; }
+ });
+ for (const prefix of paths.filter(value => typeof value === 'string' && value.length > 1).sort((a, b) => b.length - a.length)) text = text.replaceAll(prefix, '[local]');
+ return text.replace(/(?:[A-Z]:[\\/](?:Users|Documents and Settings)[\\/][^\r\n"'<>]+|\/(?:Users|home|private|var|tmp|opt|etc|Volumes|mnt)\/[^\r\n"'<>]+)/gi, '[local path]')
+ .replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, '[redacted email]');
+}
diff --git a/scripts/diagnostics.mjs b/scripts/diagnostics.mjs
new file mode 100644
index 00000000..13ce61f5
--- /dev/null
+++ b/scripts/diagnostics.mjs
@@ -0,0 +1,210 @@
+import { constants, realpathSync } from 'node:fs';
+import { lstat, mkdir, open, opendir, realpath, rename, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import os from 'node:os';
+import { randomUUID } from 'node:crypto';
+import { fileURLToPath } from 'node:url';
+import { parseArgs } from 'node:util';
+import { zip } from './zip.mjs';
+import { redactDiagnostic } from './diagnostic-redaction.mjs';
+
+export const diagnosticLimits = { fileBytes: 128 * 1024, logBytes: 1024 * 1024, totalBytes: 2 * 1024 * 1024, jobs: 5, directoryEntries: 100, cooldownMs: 30_000 };
+const appDirectory = fileURLToPath(new URL('../', import.meta.url));
+const idPattern = /^[a-f\d-]{36}$/i;
+const writers = new Map();
+
+// Check every relative component, then open without following a final link or blocking on a FIFO.
+async function checkedPath(base, relative) {
+ let file = await realpath(base);
+ for (const part of relative.split('/')) {
+ if (!part || part === '.' || part === '..' || part.includes('\\')) throw new Error('UNSAFE_PATH');
+ file = path.join(file, part);
+ if ((await lstat(file)).isSymbolicLink()) throw new Error('SYMLINK_EXCLUDED');
+ }
+ return file;
+}
+
+async function readBounded(base, relative, limit = diagnosticLimits.fileBytes, tail = true) {
+ try {
+ const file = await checkedPath(base, relative);
+ const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
+ try {
+ const info = await handle.stat();
+ if (!info.isFile()) throw new Error('NOT_A_REGULAR_FILE');
+ const truncated = info.size > limit;
+ const data = Buffer.alloc(Math.min(info.size, limit));
+ const { bytesRead } = await handle.read(data, 0, data.length, tail ? Math.max(0, info.size - data.length) : 0);
+ let text = data.subarray(0, bytesRead).toString('utf8');
+ // A tail can begin inside a secret or a UTF-8 character; omit that partial line.
+ if (tail && truncated) text = text.includes('\n') ? text.slice(text.indexOf('\n') + 1) : '';
+ return { status: truncated ? 'truncated' : 'collected', text, modifiedAt: info.mtime.toISOString() };
+ } finally { await handle.close(); }
+ } catch (error) {
+ return { status: error.code === 'ENOENT' ? 'missing' : 'excluded', reason: error.code || error.message };
+ }
+}
+
+async function readJson(base, relative) {
+ const result = await readBounded(base, relative, 64 * 1024, false);
+ if (result.status !== 'collected') return null;
+ try { return JSON.parse(result.text); } catch { return null; }
+}
+
+export async function recordDiagnostic(directory, event) {
+ // Local diagnostics must never turn a failed user operation into another failure.
+ const previous = writers.get(directory) ?? Promise.resolve();
+ const task = previous.then(async () => {
+ const root = await realpath(directory);
+ const logs = path.join(root, 'diagnostics');
+ await mkdir(logs, { recursive: true, mode: 0o700 });
+ if ((await lstat(logs)).isSymbolicLink()) throw new Error('SYMLINK_EXCLUDED');
+ const file = path.join(logs, 'events.log'), backup = file + '.1';
+ for (const target of [file, backup]) {
+ const info = await lstat(target).catch(error => { if (error.code !== 'ENOENT') throw error; });
+ if (info && !info.isFile()) throw new Error('NOT_A_REGULAR_FILE');
+ }
+ const lines = (Array.isArray(event) ? event.slice(0, 20) : [event]).map(event => {
+ const fields = {};
+ for (const key of ['kind', 'tool', 'requestId', 'projectId', 'versionId', 'jobId', 'message', 'stack']) {
+ if (typeof event[key] === 'string') fields[key] = redactDiagnostic(event[key].slice(0, 64 * 1024), process.env, [os.homedir(), root]).slice(0, ['message', 'stack'].includes(key) ? 8192 : 256);
+ }
+ const time = typeof event.time === 'string' && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(event.time) ? event.time : new Date().toISOString();
+ return JSON.stringify({ time, ...fields }) + '\n';
+ });
+ // One append per browser batch, splitting only at the existing rotation bound.
+ let batch = '';
+ const append = async () => {
+ if (!batch) return;
+ const size = (await lstat(file).catch(() => null))?.size ?? 0;
+ if (size + Buffer.byteLength(batch) > diagnosticLimits.fileBytes) await rename(file, backup);
+ const handle = await open(file, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
+ try { await handle.writeFile(batch); } finally { await handle.close(); }
+ batch = '';
+ };
+ for (const line of lines) {
+ if (Buffer.byteLength(batch) + Buffer.byteLength(line) > diagnosticLimits.fileBytes) await append();
+ batch += line;
+ }
+ await append();
+ }).catch(() => {});
+ writers.set(directory, task);
+ try { await task; } finally { if (writers.get(directory) === task) writers.delete(directory); }
+}
+
+export async function collectDiagnostics({ appRoot = appDirectory, dataDirectory, installHome, browserErrors = [] } = {}) {
+ const entries = [], files = [];
+ let remaining = diagnosticLimits.totalBytes;
+ let logRemaining = diagnosticLimits.logBytes;
+ const paths = [os.homedir(), appRoot, dataDirectory, installHome];
+ const clean = text => redactDiagnostic(text, process.env, paths);
+ const add = (name, text, sanitize = true) => {
+ const data = Buffer.from(sanitize ? clean(text) : text);
+ const isLog = name.startsWith('logs/');
+ const bounded = data.subarray(0, Math.max(0, Math.min(diagnosticLimits.fileBytes, remaining, isLog ? logRemaining : Infinity)));
+ remaining -= bounded.length;
+ if (isLog) logRemaining -= bounded.length;
+ entries.push({ name, data: bounded });
+ return bounded.length < data.length;
+ };
+ const addJson = (name, value) => {
+ let text = JSON.stringify(value, (_key, item) => typeof item === 'string' ? clean(item) : item, 2);
+ if (Buffer.byteLength(text) > diagnosticLimits.fileBytes) {
+ files.push({ name, status: 'truncated', reason: 'structured file size limit' });
+ text = JSON.stringify({ status: 'truncated', reason: 'See files.json; structured file exceeded the size limit.' });
+ }
+ add(name, text, false);
+ };
+ const log = async (base, relative, name = relative) => {
+ if (!base) { files.push({ name, status: 'missing' }); return; }
+ const result = await readBounded(base, relative);
+ const { text, ...metadata } = result;
+ if (text !== undefined && add('logs/' + name, text)) metadata.status = 'truncated';
+ files.push({ name, ...metadata });
+ };
+ const pkg = await readJson(appRoot, 'package.json');
+ const build = await readJson(appRoot, 'shared/build-info.json');
+ const templates = await readJson(appRoot, 'shared/template-config.json');
+ const native = await readJson(appRoot, '.npm-install.json');
+ installHome ??= typeof native?.installHome === 'string' ? native.installHome : undefined;
+ const cacheDirectory = typeof native?.cacheDirectory === 'string' ? native.cacheDirectory : undefined;
+ paths.push(installHome, cacheDirectory);
+ const installation = installHome ? await readJson(installHome, 'install.json') : null;
+ dataDirectory ??= typeof installation?.dataDirectory === 'string' ? installation.dataDirectory : undefined;
+ paths.push(dataDirectory);
+ const metadata = {
+ schemaVersion: 1, createdAt: new Date().toISOString(), timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ version: typeof pkg?.version === 'string' ? pkg.version.slice(0, 128) : 'unknown',
+ commit: /^[a-f\d]{40}$/i.test(build?.commit ?? native?.commit ?? '') ? (build?.commit ?? native.commit) : null,
+ templateEnvironment: ['dev', 'prod'].includes(templates?.environment ?? installation?.templateEnvironment) ? (templates?.environment ?? installation.templateEnvironment) : 'unknown',
+ platform: process.platform, arch: process.arch, osVersion: os.release(), nodeVersion: process.version, engineVersion: pkg?.dependencies?.hyperframes,
+ applicationSHA256: /^[a-f\d]{64}$/i.test(native?.applicationSHA256 ?? '') ? native.applicationSHA256 : null,
+ hosts: Object.keys(installation?.hosts ?? {}).filter(host => ['codex', 'claude', 'deepseek', 'workbuddy'].includes(host)),
+ hostSessionVerified: false, collection: 'local files only; no MCP probe, downloads or cloud upload',
+ };
+ for (const name of ['preview.log', 'studio.log', '.editor-runtime/editor.log', 'diagnostics/events.log', 'diagnostics/events.log.1']) await log(dataDirectory, name);
+ if (installHome && path.resolve(installHome) !== path.resolve(dataDirectory || '.')) {
+ for (const name of ['diagnostics/events.log', 'diagnostics/events.log.1']) await log(installHome, name, 'installation/' + name);
+ }
+ const components = [];
+ if (cacheDirectory) {
+ const target = Object.entries(native.runtime?.targets ?? {}).find(([name, value]) => /^[a-z\d-]+$/.test(name)
+ && value?.platform === process.platform && value?.arch === process.arch)?.[0];
+ if (target) {
+ await log(cacheDirectory, target + '/preparation.log', 'native/preparation.log');
+ const config = native.runtime?.targets?.[target];
+ for (const id of ['browser', 'ffmpeg', 'ffprobe', 'media']) {
+ const hash = config?.[id]?.sha256;
+ if (!/^[a-f\d]{64}$/.test(hash ?? '')) continue;
+ const state = await readJson(cacheDirectory, `${target}/${id}-${hash}.status.json`);
+ components.push({ id, stage: typeof state?.stage === 'string' ? state.stage.slice(0, 64) : 'unknown',
+ errorCode: typeof state?.errorCode === 'string' ? state.errorCode.slice(0, 128) : undefined,
+ error: typeof state?.error === 'string' ? state.error.slice(0, 8192) : undefined });
+ }
+ } else files.push({ name: 'native/preparation.log', status: 'missing', reason: 'no matching native target' });
+ } else files.push({ name: 'native/preparation.log', status: 'missing' });
+ addJson('native.json', components);
+ const jobs = [];
+ try {
+ const directory = await opendir(await checkedPath(dataDirectory, 'jobs'));
+ let scanned = 0;
+ for await (const entry of directory) {
+ if (++scanned > diagnosticLimits.directoryEntries) { files.push({ name: 'jobs', status: 'truncated', reason: 'directory scan limit' }); break; }
+ if (entry.isDirectory() && idPattern.test(entry.name)) {
+ const job = await readJson(dataDirectory, `jobs/${entry.name}/job.json`);
+ if (job?.id === entry.name) jobs.push(job);
+ }
+ }
+ } catch { files.push({ name: 'jobs', status: 'missing' }); }
+ jobs.sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
+ const selected = jobs.slice(0, diagnosticLimits.jobs);
+ addJson('jobs.json', selected.map(job => Object.fromEntries(
+ ['id', 'projectId', 'requestId', 'versionId', 'revision', 'state', 'stage', 'createdAt', 'completedAt', 'error'].filter(key => ['string', 'number'].includes(typeof job[key])).map(key => [key, typeof job[key] === 'string' ? job[key].slice(0, key === 'error' ? 8192 : 256) : job[key]])
+ )));
+ for (const [index, job] of selected.entries()) await log(dataDirectory, `jobs/${job.id}/render.log`, `job-${index + 1}/render.log`);
+ const browser = [];
+ for (const entry of Array.isArray(browserErrors) ? browserErrors.slice(-60) : []) {
+ browser.push(Object.fromEntries(['time', 'kind', 'message', 'stack'].filter(key => typeof entry?.[key] === 'string').map(key => [key, entry[key].slice(0, 4096)])));
+ while (Buffer.byteLength(JSON.stringify(browser)) > 24 * 1024) browser.shift();
+ }
+ addJson('browser-errors.json', browser.filter(event => !event.kind?.startsWith('activity_')));
+ addJson('browser-activity.json', browser.filter(event => event.kind?.startsWith('activity_')));
+ addJson('metadata.json', metadata);
+ addJson('files.json', files);
+ add('README.txt', 'OpenMotion local diagnostics\nReview before sharing. Known credentials, URL details, email addresses and local paths are redacted; arbitrary text in existing logs can still contain private information.\nProjects, media, conversations, provider/host configuration and environment dumps are excluded.\nfiles.json lists missing, excluded and truncated logs. Only a bounded sample of jobs is included. A successful collection does not verify the active host chat. No cloud upload or automatic repair was performed.\n');
+ return { filename: `openmotion-diagnostics-${Date.now()}-${randomUUID().slice(0, 8)}.zip`, data: zip(entries) };
+}
+
+export async function exportDiagnostics(options) {
+ const result = await collectDiagnostics(options);
+ const output = path.resolve(options.output || result.filename);
+ await writeFile(output, result.data, { flag: 'wx', mode: 0o600 });
+ return { output, bytes: result.data.length };
+}
+
+if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) {
+ try {
+ const { values } = parseArgs({ options: { 'data-dir': { type: 'string' }, output: { type: 'string' } } });
+ if (!values['data-dir']) throw new Error('Usage: node scripts/diagnostics.mjs --data-dir DIR [--output FILE.zip]');
+ console.log(JSON.stringify(await exportDiagnostics({ dataDirectory: path.resolve(values['data-dir']), output: values.output })));
+ } catch { console.error('Diagnostic export failed. Check --data-dir, output permissions and that the output file does not already exist.'); process.exitCode = 1; }
+}
diff --git a/scripts/distribution.ts b/scripts/distribution.ts
index 8e5356aa..dddf3f1e 100644
--- a/scripts/distribution.ts
+++ b/scripts/distribution.ts
@@ -496,6 +496,7 @@ export async function distributionFiles(profile: string): Promise<string[]> {
'scripts/runtime-assets.mjs', 'scripts/npm-runtime.mjs', 'scripts/runtime-lock.json', 'scripts/lint-project.mjs',
'scripts/npm-installer.mjs', 'scripts/npm-hosts.mjs', 'scripts/check-installed-mcp.mjs',
'scripts/install-onboarding.mjs', 'scripts/onboarding-catalog.ts',
+ 'scripts/diagnostics.mjs', 'scripts/diagnostic-redaction.mjs', 'scripts/zip.mjs',
'scripts/verify-export.ts', 'scripts/export-adapters.ts', 'scripts/package.ts', 'scripts/distribution.ts',
'shared/workflow-entry.js', 'studio/LICENSE', 'studio/README.md', 'template-library/LICENSE', 'shared/editor-launch.pl',
'tracking/core.ts', 'tracking/node.ts', 'tracking/browser.ts', 'tracking/events.ts',
diff --git a/scripts/npm-installer.mjs b/scripts/npm-installer.mjs
index b7d1d2a7..8c3bc303 100644
--- a/scripts/npm-installer.mjs
+++ b/scripts/npm-installer.mjs
@@ -10,6 +10,7 @@ import { canonical, extractArchive, nativeComponents, obtainAsset, readJSON, rel
import { ensureNativeRuntime, startNativePreparation } from './npm-runtime.mjs';
import { hosts, hostPlan, skillTargets, obsoleteSkills, checkSkillOwner, copyHostSkills } from './npm-hosts.mjs';
import { checkTransport, redact } from './check-installed-mcp.mjs';
+import { exportDiagnostics, recordDiagnostic } from './diagnostics.mjs';
// Keep ownership stable so earlier local installations remain upgradable.
export const managedBy = '@openmotion/installer';
@@ -20,6 +21,7 @@ const usage = `Usage:
openmotion setup --host <${hosts.join('|')}> [options]
openmotion prepare [--home DIR]
openmotion diagnose --host <${hosts.join('|')}> [--home DIR] [host options]
+ openmotion diagnostics [--home DIR] [--data-dir DIR] [--output FILE.zip]
openmotion --version
Select the current Agent host explicitly; installed CLIs do not identify the current host.
@@ -39,6 +41,8 @@ Use prepare to wait explicitly for every video component or retry failed prepara
Refresh the selected host's Tools/Skills; registration alone does not prove loading.
Diagnose checks the installed host configuration and probes its MCP command without changing configuration.
It does not reconnect the host; follow its recovery guidance and verify a read in the active Agent chat.
+Diagnostics saves a redacted local ZIP without contacting hosts or uploading anything.
+Reuse the original --home; --data-dir also works when setup has not completed. Output files are never overwritten.
Use separate host configuration, home, data and Skills paths for test candidates.
-h, --help Show this help without installing or changing configuration
--version Show this package's version`;
@@ -106,7 +110,7 @@ export async function setup(options) {
const npm = process.env.npm_execpath || path.join(path.dirname(process.execPath), process.platform === 'win32' ? 'node_modules/npm/bin/npm-cli.js' : '../lib/node_modules/npm/bin/npm-cli.js');
console.error('OpenMotion: installing locked npm runtime (no native media/browser download).');
await runFile(process.execPath, [npm, 'ci', '--omit=dev', '--ignore-scripts', '--no-audit', '--no-fund'], { cwd: temporary });
- await writeJSON(path.join(temporary, '.npm-install.json'), { schemaVersion: 1, applicationSHA256: manifest.application.sha256,
+ await writeJSON(path.join(temporary, '.npm-install.json'), { schemaVersion: 1, applicationSHA256: manifest.application.sha256, installHome: home, commit: manifest.commit,
cacheDirectory: path.join(home, 'cache/native'), runtime: manifest.runtime, allowLocalAssets: true });
await rename(temporary, appRoot);
} finally { await rm(temporary, { recursive: true, force: true }); }
@@ -185,14 +189,20 @@ export async function diagnose(options) {
async function main() {
const { positionals, values } = parseArgs({ allowPositionals: true, options: {
manifest: { type: 'string' }, home: { type: 'string' }, 'data-dir': { type: 'string' }, 'skills-dir': { type: 'string' }, host: { type: 'string' }, codex: { type: 'string' }, claude: { type: 'string' }, dsh: { type: 'string' }, profile: { type: 'string' },
- help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' },
+ help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' }, output: { type: 'string' },
} });
if (values.help) { console.log(usage); return; }
if (values.version) { console.log((await readJSON(new URL('../package.json', import.meta.url))).version); return; }
const [command] = positionals;
assert(positionals.length === 1, usage);
if (command === 'setup') {
- console.log(JSON.stringify(await setup({ manifest: values.manifest, home: values.home, dataDirectory: values['data-dir'], skillsDirectory: values['skills-dir'], host: values.host, codex: values.codex, claude: values.claude, dsh: values.dsh, profile: values.profile }), null, 2));
+ try {
+ console.log(JSON.stringify(await setup({ manifest: values.manifest, home: values.home, dataDirectory: values['data-dir'], skillsDirectory: values['skills-dir'], host: values.host, codex: values.codex, claude: values.claude, dsh: values.dsh, profile: values.profile }), null, 2));
+ } catch (error) {
+ const environment = (await readJSON(bundledManifest).catch(() => null))?.templateEnvironment;
+ await recordDiagnostic(values.home || defaultHome(environment), { kind: 'installation_failed', message: error.message });
+ throw error;
+ }
} else if (command === 'prepare') {
const environment = (await readJSON(bundledManifest))?.templateEnvironment;
const state = await readJSON(path.join(values.home || defaultHome(environment), 'install.json'));
@@ -203,6 +213,12 @@ async function main() {
const result = await diagnose({ home: values.home, host: values.host, codex: values.codex, claude: values.claude, dsh: values.dsh, profile: values.profile });
console.log(JSON.stringify(result, null, 2));
if (result.status !== 'passed') process.exitCode = 1;
- } else throw new Error('Supported commands: setup, prepare, diagnose');
+ } else if (command === 'diagnostics') {
+ const environment = (await readJSON(bundledManifest))?.templateEnvironment;
+ const home = path.resolve(values.home || defaultHome(environment));
+ const state = await readJSON(path.join(home, 'install.json')).catch(() => null);
+ const dataDirectory = values['data-dir'] || state?.dataDirectory || path.join(home, 'data');
+ console.log(JSON.stringify(await exportDiagnostics({ appRoot: state?.appRoot || fileURLToPath(new URL('../', import.meta.url)), installHome: home, dataDirectory, output: values.output }), null, 2));
+ } else throw new Error('Supported commands: setup, prepare, diagnose, diagnostics');
}
if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) main().catch(error => { console.error(error.message + '\nRun openmotion --help for supported hosts and installation options.'); process.exitCode = 1; });
diff --git a/scripts/package-npm.mjs b/scripts/package-npm.mjs
index 62e85736..6c323899 100644
--- a/scripts/package-npm.mjs
+++ b/scripts/package-npm.mjs
@@ -94,8 +94,9 @@ export async function packageNpm(output = path.join(root, 'dist/npm-local'), ver
}
}
await writeJSON(path.join(application, 'shared/template-config.json'), templateConfig);
+ await writeJSON(path.join(application, 'shared/build-info.json'), { commit });
const skills = (await readdir(path.join(application, 'skills'))).sort();
- for (const name of ['runtime-assets.mjs', 'npm-runtime.mjs', 'npm-hosts.mjs', 'npm-installer.mjs', 'check-installed-mcp.mjs']) await cp(path.join(root, 'scripts', name), path.join(installer, 'scripts', name));
+ for (const name of ['runtime-assets.mjs', 'npm-runtime.mjs', 'npm-hosts.mjs', 'npm-installer.mjs', 'check-installed-mcp.mjs', 'diagnostics.mjs', 'diagnostic-redaction.mjs', 'zip.mjs']) await cp(path.join(root, 'scripts', name), path.join(installer, 'scripts', name));
await chmod(path.join(installer, 'scripts/npm-installer.mjs'), 0o755);
const installerPkg = JSON.parse(await readFile(path.join(root, 'packages/npm/package.json'), 'utf8'));
assert.equal(installerPkg.private, true, 'Keep the source package protected; publish only an explicitly versioned artifact');
diff --git a/scripts/package.ts b/scripts/package.ts
index 10d641c0..10326164 100644
--- a/scripts/package.ts
+++ b/scripts/package.ts
@@ -2,34 +2,10 @@ import { isMain } from '../shared/entry.ts';
import { readFile, mkdir } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
+import { execFileSync } from 'node:child_process';
import { distributionFiles } from './distribution.ts';
-
-// ZIP "store" format, so packaging has no runtime dependencies.
-function crc32(data: Buffer) {
- let crc = 0xffffffff;
- for (const byte of data) {
- crc ^= byte;
- for (let n = 0; n < 8; n++) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1));
- }
- return (crc ^ 0xffffffff) >>> 0;
-}
-export function zip(entries: { name: string; data: Buffer }[]): Buffer {
- const local: Buffer[] = [], central: Buffer[] = []; let offset = 0, directorySize = 0;
- for (const entry of entries) {
- const name = Buffer.from(entry.name); const crc = crc32(entry.data);
- const header = Buffer.alloc(30); header.writeUInt32LE(0x04034b50, 0); header.writeUInt16LE(20, 4);
- header.writeUInt16LE(0x800, 6); header.writeUInt16LE(33, 12); header.writeUInt32LE(crc, 14);
- header.writeUInt32LE(entry.data.length, 18); header.writeUInt32LE(entry.data.length, 22); header.writeUInt16LE(name.length, 26);
- const dir = Buffer.alloc(46); dir.writeUInt32LE(0x02014b50, 0); dir.writeUInt16LE(20, 4); dir.writeUInt16LE(20, 6);
- dir.writeUInt16LE(0x800, 8); dir.writeUInt16LE(33, 14); dir.writeUInt32LE(crc, 16);
- dir.writeUInt32LE(entry.data.length, 20); dir.writeUInt32LE(entry.data.length, 24); dir.writeUInt16LE(name.length, 28); dir.writeUInt32LE(offset, 42);
- local.push(header, name, entry.data); central.push(dir, name);
- offset += header.length + name.length + entry.data.length; directorySize += dir.length + name.length;
- }
- const end = Buffer.alloc(22); end.writeUInt32LE(0x06054b50); end.writeUInt16LE(entries.length, 8); end.writeUInt16LE(entries.length, 10);
- end.writeUInt32LE(directorySize, 12); end.writeUInt32LE(offset, 16);
- return Buffer.concat([...local, ...central, end]);
-}
+import { zip } from './zip.mjs';
+export { zip } from './zip.mjs';
const root = fileURLToPath(new URL('../', import.meta.url));
async function main() {
const { packageTemplateConfig } = await import('../shared/template-config.ts');
@@ -44,7 +20,11 @@ async function main() {
await check();
const manifest = JSON.parse(await readFile(path.join(root, '.codex-plugin/plugin.json'), 'utf8'));
const files = await distributionFiles(profile);
- const overrides: Record<string, unknown> = { 'shared/mcp-release.json': { profile }, 'shared/template-config.json': templateConfig };
+ let commit: string | null;
+ try { commit = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); }
+ catch { commit = JSON.parse(await readFile(path.join(root, 'shared/build-info.json'), 'utf8')).commit; }
+ const overrides: Record<string, unknown> = { 'shared/mcp-release.json': { profile }, 'shared/template-config.json': templateConfig,
+ 'shared/build-info.json': { commit } };
const entries = await Promise.all(files.sort().map(async file => ({ name: manifest.name + '/' + file,
data: overrides[file] ? Buffer.from(JSON.stringify(overrides[file], null, 2) + '\n') : await readFile(path.join(root, file)) })));
await mkdir(path.join(root, 'dist'), { recursive: true });
diff --git a/scripts/zip.mjs b/scripts/zip.mjs
new file mode 100644
index 00000000..3de6e431
--- /dev/null
+++ b/scripts/zip.mjs
@@ -0,0 +1,26 @@
+// ZIP "store" format, so packaging has no runtime dependencies.
+function crc32(data) {
+ let crc = 0xffffffff;
+ for (const byte of data) {
+ crc ^= byte;
+ for (let n = 0; n < 8; n++) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1));
+ }
+ return (crc ^ 0xffffffff) >>> 0;
+}
+export function zip(entries) {
+ const local = [], central = []; let offset = 0, directorySize = 0;
+ for (const entry of entries) {
+ const name = Buffer.from(entry.name); const crc = crc32(entry.data);
+ const header = Buffer.alloc(30); header.writeUInt32LE(0x04034b50, 0); header.writeUInt16LE(20, 4);
+ header.writeUInt16LE(0x800, 6); header.writeUInt16LE(33, 12); header.writeUInt32LE(crc, 14);
+ header.writeUInt32LE(entry.data.length, 18); header.writeUInt32LE(entry.data.length, 22); header.writeUInt16LE(name.length, 26);
+ const dir = Buffer.alloc(46); dir.writeUInt32LE(0x02014b50, 0); dir.writeUInt16LE(20, 4); dir.writeUInt16LE(20, 6);
+ dir.writeUInt16LE(0x800, 8); dir.writeUInt16LE(33, 14); dir.writeUInt32LE(crc, 16);
+ dir.writeUInt32LE(entry.data.length, 20); dir.writeUInt32LE(entry.data.length, 24); dir.writeUInt16LE(name.length, 28); dir.writeUInt32LE(offset, 42);
+ local.push(header, name, entry.data); central.push(dir, name);
+ offset += header.length + name.length + entry.data.length; directorySize += dir.length + name.length;
+ }
+ const end = Buffer.alloc(22); end.writeUInt32LE(0x06054b50); end.writeUInt16LE(entries.length, 8); end.writeUInt16LE(entries.length, 10);
+ end.writeUInt32LE(directorySize, 12); end.writeUInt32LE(offset, 16);
+ return Buffer.concat([...local, ...central, end]);
+}
diff --git a/server.ts b/server.ts
index 564b9e3f..1771d18d 100644
--- a/server.ts
+++ b/server.ts
@@ -30,9 +30,10 @@ import { studioEvents } from './tracking/events.ts';
import { nativeRuntimeStatus, startNativePreparation, requireNativeRuntime } from './scripts/npm-runtime.mjs';
import { nativeRouteCapability } from './shared/native-runtime.ts';
import { validPending } from './tracking/core.ts';
+import { collectDiagnostics, diagnosticLimits, recordDiagnostic } from './scripts/diagnostics.mjs';
const sharedStore = new WorkspaceStore();
-export type Service = { studio?: Studio; runtimeRoot?: string; nativeRoot?: string; ffmpeg?: boolean; switching?: boolean; studioPort?: number; browser?: WorkspaceBrowser; editorToken?: string; ensureStudio?: (projectId?: string) => Promise<Studio>; launchStudio?: (directory: string, port: number) => Promise<Studio>; phase1?: Phase1Service; phase1Mutation?: Promise<void>; tracking?: OmTracking };
+export type Service = { diagnostics?: { running: boolean; lastExport: number; events: number; window: number }; studio?: Studio; runtimeRoot?: string; nativeRoot?: string; ffmpeg?: boolean; switching?: boolean; studioPort?: number; browser?: WorkspaceBrowser; editorToken?: string; ensureStudio?: (projectId?: string) => Promise<Studio>; launchStudio?: (directory: string, port: number) => Promise<Studio>; phase1?: Phase1Service; phase1Mutation?: Promise<void>; tracking?: OmTracking };
const service: Service = {};
const working = new Set<string>();
const runningExports = new Map<string, AbortController>();
@@ -96,6 +97,8 @@ export async function renderNext(store: WorkspaceStore, runtimeRoot: string, tra
if (finished.state === 'cancelled') await rm(output, { force: true });
} catch (error) {
if (!job) throw error;
+ await recordDiagnostic(store.directory, { kind: 'export_failed', jobId: job.id, projectId: job.projectId,
+ message: error instanceof Error ? error.message : 'Render failed' });
await rm(path.join(store.directory, 'exports', job.id + '.mp4'), { force: true });
const current = await store.job(job.id);
if (current && ['running', 'cancelling'].includes(current.state)) await store.finishExport(job.id, job.token!, error instanceof Error ? error.message : '渲染失败');
@@ -254,6 +257,35 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store =
}
if (motionRequest) url.pathname = url.pathname.replace(/^\/(?:motion|design)-api\//, '/api/');
const editorUrl = `http://${host || 'localhost'}/#project/${store.projectId}`;
+ if (motionRequest && ['/api/diagnostics', '/api/diagnostics/events'].includes(url.pathname)) {
+ // Downloads are POST-only: cross-origin links must not trigger a collection.
+ if (req.method !== 'POST') return json(res, 405, { error: 'POST_REQUIRED' });
+ if (req.headers['sec-fetch-site'] === 'cross-site' || url.search) return json(res, 403, { error: 'DIAGNOSTIC_SCOPE_REJECTED' });
+ const data = await input(req, 32 * 1024);
+ if (!data || Object.keys(data).some(key => key !== 'errors') || !Array.isArray(data.errors) || data.errors.length > (url.pathname.endsWith('/events') ? 20 : 60)
+ || !data.errors.every((entry: any) => entry && typeof entry === 'object' && !Array.isArray(entry) && Object.keys(entry).every(key => ['time', 'kind', 'message', 'stack'].includes(key))
+ && Object.values(entry).every(value => typeof value === 'string' && value.length <= 4096))) return json(res, 400, { error: 'INVALID_DIAGNOSTIC_INPUT' });
+ const state = context.diagnostics ??= { running: false, lastExport: 0, events: 0, window: Date.now() };
+ const directory = (store.workspaceStore ?? store).directory;
+ if (url.pathname.endsWith('/events')) {
+ if (Date.now() - state.window > 60_000) { state.events = 0; state.window = Date.now(); }
+ if (state.events + data.errors.length > 60) return json(res, 429, { error: 'DIAGNOSTIC_RATE_LIMITED' });
+ state.events += data.errors.length;
+ await recordDiagnostic(directory, data.errors);
+ return json(res, 200, { accepted: data.errors.length });
+ }
+ if (state.running || Date.now() - state.lastExport < diagnosticLimits.cooldownMs) {
+ res.setHeader('Retry-After', '30');
+ return json(res, 429, { error: 'DIAGNOSTIC_RATE_LIMITED' });
+ }
+ state.running = true; state.lastExport = Date.now();
+ try {
+ const result = await collectDiagnostics({ appRoot: context.nativeRoot ?? pluginRoot, dataDirectory: directory, browserErrors: data.errors });
+ res.writeHead(200, { 'Content-Type': 'application/zip', 'Content-Disposition': `attachment; filename="${result.filename}"`,
+ 'Content-Length': result.data.length, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
+ res.end(result.data); return;
+ } finally { state.running = false; }
+ }
if (motionRequest && url.pathname === '/api/runtime' && ['GET', 'POST'].includes(req.method!)) {
const root = context.nativeRoot ?? pluginRoot;
if (req.method === 'POST') {
diff --git a/shared/build-info.json b/shared/build-info.json
new file mode 100644
index 00000000..3639fc0b
--- /dev/null
+++ b/shared/build-info.json
@@ -0,0 +1 @@
+{ "commit": null }
diff --git a/studio/src/components/StudioErrorBoundary.test.tsx b/studio/src/components/StudioErrorBoundary.test.tsx
index 014b6add..97a7368f 100644
--- a/studio/src/components/StudioErrorBoundary.test.tsx
+++ b/studio/src/components/StudioErrorBoundary.test.tsx
@@ -6,6 +6,8 @@ import { StudioHostContext, useStudioHost } from "../motion/StudioHost";
import { createRoot } from "react-dom/client";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
+vi.mock('../motion/diagnostics', () => ({ recordBrowserDiagnostic: vi.fn(), browserDiagnostics: () => [], nextDiagnosticRequest: () => 'fixture-request', diagnosticsActive: () => false }));
+
vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() }));
vi.mock("../telemetry/policy", () => ({ browserTelemetryAllowed: () => true }));
vi.mock("../telemetry/events", () => ({
diff --git a/studio/src/components/StudioErrorBoundary.tsx b/studio/src/components/StudioErrorBoundary.tsx
index 7656b52e..5d1919c3 100644
--- a/studio/src/components/StudioErrorBoundary.tsx
+++ b/studio/src/components/StudioErrorBoundary.tsx
@@ -3,6 +3,8 @@ import { useStudioHost } from '../motion/StudioHost';
import { Component, type ErrorInfo, type ReactNode } from "react";
import { trackStudioEvent } from "../utils/studioTelemetry";
import { CrashFeedbackPrompt } from "./feedback/CrashFeedbackPrompt";
+import { DiagnosticExport } from '../motion/DiagnosticExport';
+import { recordBrowserDiagnostic } from '../motion/diagnostics';
interface Props {
children: ReactNode;
@@ -20,6 +22,7 @@ export class StudioErrorBoundary extends Component<Props, State> {
}
componentDidCatch(error: Error, info: ErrorInfo) {
+ recordBrowserDiagnostic('react_crash', error.message, error.stack);
console.error("[Studio] Uncaught error:", error, info.componentStack);
trackStudioEvent("crash", {
error_message: error.message,
@@ -61,6 +64,7 @@ function CrashScreen({ error, retry }: { error: Error; retry: () => void }) {
{t('Reload Studio')}
</button>
</div>
+ <DiagnosticExport />
{/* The crash report tells us what broke; only the user can tell us what
they were doing when it did. This is also the one screen where they
have nothing else to get on with. */}
diff --git a/studio/src/components/ui/ErrorNotice.test.tsx b/studio/src/components/ui/ErrorNotice.test.tsx
index 400460b6..71acaaa6 100644
--- a/studio/src/components/ui/ErrorNotice.test.tsx
+++ b/studio/src/components/ui/ErrorNotice.test.tsx
@@ -8,6 +8,8 @@ import { I18nProvider } from '../../i18n/I18n';
import { languages, translate } from '../../i18n/messages';
import errorUi from '../../i18n/error-ui.json';
+vi.mock('../../motion/diagnostics', () => ({ recordBrowserDiagnostic: vi.fn(), browserDiagnostics: () => [], nextDiagnosticRequest: () => 'fixture-request', diagnosticsActive: () => false }));
+
let host: HTMLDivElement;
let root: Root;
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
diff --git a/studio/src/components/ui/ErrorNotice.tsx b/studio/src/components/ui/ErrorNotice.tsx
index 2a8eaaec..95530f0f 100644
--- a/studio/src/components/ui/ErrorNotice.tsx
+++ b/studio/src/components/ui/ErrorNotice.tsx
@@ -1,4 +1,5 @@
-import { useId, useState } from 'react';
+import { useEffect, useId, useState } from 'react';
+import { recordBrowserDiagnostic } from '../../motion/diagnostics';
import { useI18n } from '../../i18n/I18n';
import { RemixIcon } from '../../icons/RemixIcons';
import { errorNoticeMessage, type ErrorContext } from './errorNoticeMessage';
@@ -14,6 +15,7 @@ export function ErrorNotice({ message, context = 'operation', compact = false, a
const { t } = useI18n();
const id = useId();
const [expanded, setExpanded] = useState(false);
+ useEffect(() => { recordBrowserDiagnostic('operation_error', message); }, [message]);
const [copyState, setCopyState] = useState<'idle' | 'copied' | 'failed'>('idle');
const summary = errorNoticeMessage(message, context);
const copy = async () => {
diff --git a/studio/src/i18n/error-ui.json b/studio/src/i18n/error-ui.json
index 228f3460..6a8447d8 100644
--- a/studio/src/i18n/error-ui.json
+++ b/studio/src/i18n/error-ui.json
@@ -31,7 +31,13 @@
"The project changed elsewhere.": "工程已在其他地方修改",
"Changes could not be saved.": "修改未能保存",
"Action not completed. Please try again.": "操作未完成,请重试",
- "Historical files are unavailable. Version not restored.": "历史文件不可用,未恢复该版本"
+ "Historical files are unavailable. Version not restored.": "历史文件不可用,未恢复该版本",
+ "Export diagnostic ZIP": "导出诊断 ZIP",
+ "Preparing diagnostics…": "正在整理诊断信息…",
+ "Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "日志会脱敏后保存到本机,不会上传。分享前请检查 ZIP 内容。",
+ "Please wait 30 seconds before exporting diagnostics again.": "请等待 30 秒后再次导出诊断信息。",
+ "Could not export diagnostics. Use the command line if Studio cannot connect.": "无法导出诊断信息。工作室无法连接时可使用命令行。",
+ "Download started. Check your browser downloads.": "已发起下载,请查看浏览器下载列表。"
},
"ja": {
"Reconnecting…": "再接続中…",
@@ -65,7 +71,13 @@
"The project changed elsewhere.": "プロジェクトが別の場所で変更されました",
"Changes could not be saved.": "変更を保存できませんでした",
"Action not completed. Please try again.": "操作を完了できませんでした。再試行してください",
- "Historical files are unavailable. Version not restored.": "履歴ファイルを利用できないため、復元されませんでした"
+ "Historical files are unavailable. Version not restored.": "履歴ファイルを利用できないため、復元されませんでした",
+ "Export diagnostic ZIP": "診断 ZIP を書き出す",
+ "Preparing diagnostics…": "診断情報を準備中…",
+ "Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "機密情報を伏せたログを端末に保存します。アップロードは行いません。共有前に ZIP の内容をご確認ください。",
+ "Please wait 30 seconds before exporting diagnostics again.": "診断情報を再度書き出すには 30 秒お待ちください。",
+ "Could not export diagnostics. Use the command line if Studio cannot connect.": "診断情報を書き出せませんでした。Studio に接続できない場合はコマンドラインをご利用ください。",
+ "Download started. Check your browser downloads.": "ダウンロードを開始しました。ブラウザーのダウンロード一覧をご確認ください。"
},
"ko": {
"Reconnecting…": "다시 연결 중…",
@@ -99,7 +111,13 @@
"The project changed elsewhere.": "프로젝트가 다른 곳에서 변경되었습니다",
"Changes could not be saved.": "변경 사항을 저장하지 못했습니다",
"Action not completed. Please try again.": "작업을 완료하지 못했습니다. 다시 시도하세요",
- "Historical files are unavailable. Version not restored.": "이전 버전 파일을 사용할 수 없어 복원되지 않았습니다"
+ "Historical files are unavailable. Version not restored.": "이전 버전 파일을 사용할 수 없어 복원되지 않았습니다",
+ "Export diagnostic ZIP": "진단 ZIP 내보내기",
+ "Preparing diagnostics…": "진단 정보 준비 중…",
+ "Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "민감한 값을 가린 로그를 기기에 저장합니다. 업로드하지 않습니다. 공유 전에 ZIP 내용을 확인하세요.",
+ "Please wait 30 seconds before exporting diagnostics again.": "진단 정보를 다시 내보내려면 30초 기다려 주세요.",
+ "Could not export diagnostics. Use the command line if Studio cannot connect.": "진단 정보를 내보낼 수 없습니다. Studio에 연결할 수 없으면 명령줄을 사용하세요.",
+ "Download started. Check your browser downloads.": "다운로드를 시작했습니다. 브라우저의 다운로드 목록을 확인하세요."
},
"de": {
"Reconnecting…": "Verbindung wird hergestellt…",
@@ -133,7 +151,13 @@
"The project changed elsewhere.": "Projekt wurde andernorts geändert.",
"Changes could not be saved.": "Änderungen konnten nicht gespeichert werden.",
"Action not completed. Please try again.": "Vorgang nicht abgeschlossen. Bitte erneut versuchen.",
- "Historical files are unavailable. Version not restored.": "Verlaufsdateien nicht verfügbar. Version nicht wiederhergestellt."
+ "Historical files are unavailable. Version not restored.": "Verlaufsdateien nicht verfügbar. Version nicht wiederhergestellt.",
+ "Export diagnostic ZIP": "Diagnose-ZIP exportieren",
+ "Preparing diagnostics…": "Diagnosedaten werden vorbereitet…",
+ "Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "Speichert Protokolle mit unkenntlich gemachten vertraulichen Werten auf Ihrem Gerät. Kein Upload. Prüfen Sie die ZIP vor dem Teilen.",
+ "Please wait 30 seconds before exporting diagnostics again.": "Bitte warten Sie 30 Sekunden, bevor Sie erneut Diagnosedaten exportieren.",
+ "Could not export diagnostics. Use the command line if Studio cannot connect.": "Diagnosedaten konnten nicht exportiert werden. Nutzen Sie die Befehlszeile, wenn Studio keine Verbindung herstellen kann.",
+ "Download started. Check your browser downloads.": "Download gestartet. Prüfe die Downloadliste deines Browsers."
},
"fr": {
"Reconnecting…": "Reconnexion…",
@@ -167,7 +191,13 @@
"The project changed elsewhere.": "Le projet a été modifié ailleurs.",
"Changes could not be saved.": "Impossible d’enregistrer les modifications.",
"Action not completed. Please try again.": "Opération non terminée. Réessayez.",
- "Historical files are unavailable. Version not restored.": "Fichiers historiques indisponibles. Version non restaurée."
+ "Historical files are unavailable. Version not restored.": "Fichiers historiques indisponibles. Version non restaurée.",
+ "Export diagnostic ZIP": "Exporter le ZIP de diagnostic",
+ "Preparing diagnostics…": "Préparation du diagnostic…",
+ "Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "Enregistre les journaux sur votre appareil en masquant les valeurs sensibles. Aucun envoi. Vérifiez le ZIP avant de le partager.",
+ "Please wait 30 seconds before exporting diagnostics again.": "Veuillez patienter 30 secondes avant de réexporter le diagnostic.",
+ "Could not export diagnostics. Use the command line if Studio cannot connect.": "Impossible d’exporter le diagnostic. Utilisez la ligne de commande si Studio ne peut pas se connecter.",
+ "Download started. Check your browser downloads.": "Téléchargement lancé. Consultez les téléchargements de votre navigateur."
},
"es": {
"Reconnecting…": "Reconectando…",
@@ -201,7 +231,13 @@
"The project changed elsewhere.": "El proyecto se modificó en otro lugar.",
"Changes could not be saved.": "No se pudieron guardar los cambios.",
"Action not completed. Please try again.": "Operación incompleta. Inténtalo de nuevo.",
- "Historical files are unavailable. Version not restored.": "Archivos históricos no disponibles. Versión no restaurada."
+ "Historical files are unavailable. Version not restored.": "Archivos históricos no disponibles. Versión no restaurada.",
+ "Export diagnostic ZIP": "Exportar ZIP de diagnóstico",
+ "Preparing diagnostics…": "Preparando diagnóstico…",
+ "Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "Guarda los registros en tu dispositivo con los valores sensibles ocultos. No se suben. Revisa el ZIP antes de compartirlo.",
+ "Please wait 30 seconds before exporting diagnostics again.": "Espera 30 segundos antes de volver a exportar el diagnóstico.",
+ "Could not export diagnostics. Use the command line if Studio cannot connect.": "No se pudo exportar el diagnóstico. Usa la línea de comandos si Studio no puede conectarse.",
+ "Download started. Check your browser downloads.": "Descarga iniciada. Revisa las descargas de tu navegador."
},
"pt-BR": {
"Reconnecting…": "Reconectando…",
@@ -235,7 +271,13 @@
"The project changed elsewhere.": "O projeto foi alterado em outro lugar.",
"Changes could not be saved.": "Não foi possível salvar as alterações.",
"Action not completed. Please try again.": "Operação não concluída. Tente novamente.",
- "Historical files are unavailable. Version not restored.": "Arquivos históricos indisponíveis. Versão não restaurada."
+ "Historical files are unavailable. Version not restored.": "Arquivos históricos indisponíveis. Versão não restaurada.",
+ "Export diagnostic ZIP": "Exportar ZIP de diagnóstico",
+ "Preparing diagnostics…": "Preparando diagnóstico…",
+ "Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "Salva os registros no seu dispositivo com valores sensíveis ocultos. Sem envio. Revise o ZIP antes de compartilhar.",
+ "Please wait 30 seconds before exporting diagnostics again.": "Aguarde 30 segundos antes de exportar o diagnóstico novamente.",
+ "Could not export diagnostics. Use the command line if Studio cannot connect.": "Não foi possível exportar o diagnóstico. Use a linha de comando se o Studio não conseguir se conectar.",
+ "Download started. Check your browser downloads.": "Download iniciado. Confira os downloads do navegador."
},
"it": {
"Reconnecting…": "Riconnessione…",
@@ -269,7 +311,13 @@
"The project changed elsewhere.": "Il progetto è stato modificato altrove.",
"Changes could not be saved.": "Impossibile salvare le modifiche.",
"Action not completed. Please try again.": "Operazione non completata. Riprova.",
- "Historical files are unavailable. Version not restored.": "File storici non disponibili. Versione non ripristinata."
+ "Historical files are unavailable. Version not restored.": "File storici non disponibili. Versione non ripristinata.",
+ "Export diagnostic ZIP": "Esporta ZIP diagnostico",
+ "Preparing diagnostics…": "Preparazione della diagnostica…",
+ "Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "Salva i log sul dispositivo oscurando i valori sensibili. Nessun caricamento. Controlla lo ZIP prima di condividerlo.",
+ "Please wait 30 seconds before exporting diagnostics again.": "Attendi 30 secondi prima di esportare nuovamente la diagnostica.",
+ "Could not export diagnostics. Use the command line if Studio cannot connect.": "Impossibile esportare la diagnostica. Usa la riga di comando se Studio non riesce a connettersi.",
+ "Download started. Check your browser downloads.": "Download avviato. Controlla i download del browser."
},
"ru": {
"Reconnecting…": "Переподключение…",
@@ -303,7 +351,13 @@
"The project changed elsewhere.": "Проект изменён в другом месте.",
"Changes could not be saved.": "Не удалось сохранить изменения.",
"Action not completed. Please try again.": "Операция не завершена. Повторите попытку.",
- "Historical files are unavailable. Version not restored.": "Файлы истории недоступны. Версия не восстановлена."
+ "Historical files are unavailable. Version not restored.": "Файлы истории недоступны. Версия не восстановлена.",
+ "Export diagnostic ZIP": "Экспорт ZIP с диагностикой",
+ "Preparing diagnostics…": "Подготовка диагностики…",
+ "Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "Журналы сохраняются на устройстве с маскировкой конфиденциальных данных. Отправки нет. Проверьте ZIP перед передачей.",
+ "Please wait 30 seconds before exporting diagnostics again.": "Подождите 30 секунд перед повторным экспортом диагностики.",
+ "Could not export diagnostics. Use the command line if Studio cannot connect.": "Не удалось экспортировать диагностику. Если Studio не подключается, используйте командную строку.",
+ "Download started. Check your browser downloads.": "Загрузка началась. Проверьте список загрузок браузера."
},
"tr": {
"Reconnecting…": "Yeniden bağlanılıyor…",
@@ -337,6 +391,12 @@
"The project changed elsewhere.": "Proje başka bir yerde değiştirildi.",
"Changes could not be saved.": "Değişiklikler kaydedilemedi.",
"Action not completed. Please try again.": "İşlem tamamlanamadı. Tekrar deneyin.",
- "Historical files are unavailable. Version not restored.": "Geçmiş dosyaları kullanılamıyor. Sürüm geri yüklenmedi."
+ "Historical files are unavailable. Version not restored.": "Geçmiş dosyaları kullanılamıyor. Sürüm geri yüklenmedi.",
+ "Export diagnostic ZIP": "Tanılama ZIP dosyasını dışa aktar",
+ "Preparing diagnostics…": "Tanılama hazırlanıyor…",
+ "Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "Günlükleri hassas değerler gizlenmiş olarak cihazınıza kaydeder. Yükleme yapılmaz. Paylaşmadan önce ZIP içeriğini inceleyin.",
+ "Please wait 30 seconds before exporting diagnostics again.": "Tanılamayı yeniden dışa aktarmadan önce 30 saniye bekleyin.",
+ "Could not export diagnostics. Use the command line if Studio cannot connect.": "Tanılama dışa aktarılamadı. Studio bağlanamıyorsa komut satırını kullanın.",
+ "Download started. Check your browser downloads.": "İndirme başlatıldı. Tarayıcınızın indirme listesini kontrol edin."
}
}
diff --git a/studio/src/main.tsx b/studio/src/main.tsx
index 33d088da..0c12513e 100644
--- a/studio/src/main.tsx
+++ b/studio/src/main.tsx
@@ -17,6 +17,10 @@ import "./motion/theme.css";
import "./motion/workspace.css";
import "../../web/design-system/material.css";
import { MotionStudioHost } from "./motion/MotionStudioHost";
+import { initializeDiagnostics, recordBrowserDiagnostic } from './motion/diagnostics';
+
+const stopDiagnostics = initializeDiagnostics();
+import.meta.hot?.dispose(stopDiagnostics);
const unbindThumbnailPageLifecycle = bindThumbnailPageLifecycle(window, document);
import.meta.hot?.dispose(unbindThumbnailPageLifecycle);
@@ -54,6 +58,7 @@ window.addEventListener("error", (event) => {
lineno: event.lineno,
colno: event.colno,
});
+ recordBrowserDiagnostic('unhandled_error', event.message, event.error?.stack);
});
let filteredAssetErrorCount = 0;
@@ -111,6 +116,7 @@ window.addEventListener("unhandledrejection", (event) => {
}
trackStudioEvent("unhandled_promise_rejection", props);
+ recordBrowserDiagnostic('unhandled_rejection', props.error_message, props.stack_trace ?? '');
});
createRoot(document.getElementById("root")!).render(
diff --git a/studio/src/motion/DiagnosticExport.test.tsx b/studio/src/motion/DiagnosticExport.test.tsx
new file mode 100644
index 00000000..fb1142c3
--- /dev/null
+++ b/studio/src/motion/DiagnosticExport.test.tsx
@@ -0,0 +1,52 @@
+// @vitest-environment happy-dom
+import React, { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { I18nProvider } from '../i18n/I18n';
+import { DiagnosticExport } from './DiagnosticExport';
+import { recordBrowserDiagnostic } from './diagnostics';
+
+vi.mock('./diagnostics', () => ({ browserDiagnostics: () => [], nextDiagnosticRequest: () => 'fixture-request', recordBrowserDiagnostic: vi.fn() }));
+beforeEach(() => vi.clearAllMocks());
+let root: Root | undefined;
+afterEach(() => { act(() => root?.unmount()); root = undefined; document.body.innerHTML = ''; localStorage.clear(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
+async function render() {
+ const container = document.createElement('div'); document.body.append(container); root = createRoot(container);
+ await act(async () => root!.render(<I18nProvider initialLocale="zh-CN"><DiagnosticExport /></I18nProvider>));
+ return container.querySelector('button')!;
+}
+
+it('downloads one local ZIP, disables duplicate clicks and releases the browser URL', async () => {
+ let finish!: (value: Response) => void;
+ const fetcher = vi.fn(() => new Promise<Response>(resolve => { finish = resolve; }));
+ vi.stubGlobal('fetch', fetcher);
+ const create = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:diagnostic-fixture');
+ const revoke = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {
+ expect(this.download).toBe('openmotion-diagnostics-fixture.zip');
+ });
+ const button = await render(); expect(button.textContent).toBe('导出诊断 ZIP');
+ await act(async () => { button.click(); button.click(); });
+ expect(button.disabled).toBe(true); expect(fetcher).toHaveBeenCalledTimes(1);
+ expect(document.querySelector('[role=status]')).toBeNull();
+ expect(fetcher.mock.calls[0][0]).toBe('/motion-api/diagnostics');
+ await act(async () => finish(new Response('ZIP', { headers: { 'Content-Type': 'application/zip', 'Content-Disposition': 'attachment; filename="openmotion-diagnostics-fixture.zip"' } })));
+ expect(recordBrowserDiagnostic).toHaveBeenCalledWith('activity_diagnostic_export', expect.stringContaining('outcome=download_triggered'));
+ expect(button.disabled).toBe(false); expect(create).toHaveBeenCalledTimes(1); expect(click).toHaveBeenCalledTimes(1);
+ expect(document.querySelector('[role=status]')?.textContent).toBe('已发起下载,请查看浏览器下载列表。openmotion-diagnostics-fixture.zip');
+ await vi.waitFor(() => expect(revoke).toHaveBeenCalledWith('blob:diagnostic-fixture'), { timeout: 1500 });
+ await act(async () => button.click());
+ expect(document.querySelector('[role=status]')).toBeNull();
+ await act(async () => finish(new Response('', { status: 429 })));
+ expect(document.querySelector('[role=status]')).toBeNull();
+ expect(document.querySelector('[role=alert]')?.textContent).toContain('30 秒');
+});
+
+it('shows a localized rate-limit error and never starts a failed download', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => new Response('', { status: 429 })));
+ const create = vi.spyOn(URL, 'createObjectURL');
+ const button = await render(); await act(async () => button.click());
+ expect(document.querySelector('[role=alert]')?.textContent).toContain('30 秒'); expect(create).not.toHaveBeenCalled();
+ expect(recordBrowserDiagnostic).toHaveBeenCalledWith('diagnostic_export_failed', expect.stringContaining('status=429'));
+ expect(recordBrowserDiagnostic).not.toHaveBeenCalledWith('activity_diagnostic_export', expect.stringContaining('outcome=download_triggered'));
+});
diff --git a/studio/src/motion/DiagnosticExport.tsx b/studio/src/motion/DiagnosticExport.tsx
new file mode 100644
index 00000000..65d6d2d5
--- /dev/null
+++ b/studio/src/motion/DiagnosticExport.tsx
@@ -0,0 +1,43 @@
+import { useRef, useState } from 'react';
+import { useI18n } from '../i18n/I18n';
+import { browserDiagnostics, nextDiagnosticRequest, recordBrowserDiagnostic } from './diagnostics';
+
+export function DiagnosticExport() {
+ const { t } = useI18n();
+ const pending = useRef(false);
+ const [busy, setBusy] = useState(false), [error, setError] = useState('');
+ const [downloadName, setDownloadName] = useState('');
+ async function download() {
+ if (pending.current) return;
+ pending.current = true; setBusy(true); setError(''); setDownloadName('');
+ const request = nextDiagnosticRequest(), start = performance.now();
+ recordBrowserDiagnostic('activity_diagnostic_export', `request=${request} outcome=started`);
+ let status = 0;
+ try {
+ const response = await fetch('/motion-api/diagnostics', { method: 'POST', headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ errors: browserDiagnostics() }) });
+ status = response.status;
+ if (response.status === 429) throw new Error('Please wait 30 seconds before exporting diagnostics again.');
+ if (!response.ok) throw new Error('Could not export diagnostics. Use the command line if Studio cannot connect.');
+ const blob = await response.blob();
+ recordBrowserDiagnostic('activity_diagnostic_export', `request=${request} outcome=archive_received status=${status} bytes=${blob.size} durationMs=${Math.round(performance.now() - start)}`);
+ const url = URL.createObjectURL(blob), link = document.createElement('a');
+ link.href = url; link.download = response.headers.get('Content-Disposition')?.match(/filename="([\w.-]+\.zip)"/)?.[1] || 'openmotion-diagnostics.zip';
+ try {
+ document.body.append(link); link.click(); setDownloadName(link.download);
+ recordBrowserDiagnostic('activity_diagnostic_export', `request=${request} outcome=download_triggered durationMs=${Math.round(performance.now() - start)}`);
+ }
+ finally { link.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000); }
+ } catch (error) {
+ recordBrowserDiagnostic('diagnostic_export_failed', `request=${request} status=${status} durationMs=${Math.round(performance.now() - start)}`);
+ setError(t(error instanceof Error && error.message === 'Please wait 30 seconds before exporting diagnostics again.'
+ ? error.message : 'Could not export diagnostics. Use the command line if Studio cannot connect.')); }
+ finally { pending.current = false; setBusy(false); }
+ }
+ return <div className="motion-diagnostic-export">
+ <button type="button" onClick={() => void download()} disabled={busy}>{t(busy ? 'Preparing diagnostics…' : 'Export diagnostic ZIP')}</button>
+ <p className="motion-media-muted">{t('Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.')}</p>
+ {downloadName && <p role="status">{t('Download started. Check your browser downloads.')}<span className="motion-diagnostic-filename">{downloadName}</span></p>}
+ {error && <p role="alert">{error}</p>}
+ </div>;
+}
diff --git a/studio/src/motion/MotionStudioHost.test.tsx b/studio/src/motion/MotionStudioHost.test.tsx
index 032861fc..7db7fa29 100644
--- a/studio/src/motion/MotionStudioHost.test.tsx
+++ b/studio/src/motion/MotionStudioHost.test.tsx
@@ -27,6 +27,7 @@ vi.mock('../contexts/PanelLayoutContext', () => ({ usePanelLayoutContext: () =>
}) }));
vi.mock('../components/renders/RenderQueuePanel', () => ({ RenderQueuePanel: () => <div>Export settings and jobs</div> }));
vi.mock('../components/dock/Dock', () => ({ Dock: { WindowMenu: () => <button>Window</button>, Panel: () => null } }));
+vi.mock('./diagnostics', () => ({ recordBrowserDiagnostic: vi.fn(), browserDiagnostics: () => [], nextDiagnosticRequest: () => 'fixture-request', diagnosticsActive: () => false }));
vi.mock('../utils/studioTelemetry', () => ({ trackStudioEvent: vi.fn() }));
vi.mock('./MotionHistoryPanel', () => ({ MotionHistoryPanel: () => <div>History versions</div> }));
vi.mock('./useWorkspace', () => ({ useWorkspace: () => ({
diff --git a/studio/src/motion/PrivacySettings.tsx b/studio/src/motion/PrivacySettings.tsx
index bc878193..0158cc70 100644
--- a/studio/src/motion/PrivacySettings.tsx
+++ b/studio/src/motion/PrivacySettings.tsx
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from 'react';
import { useI18n } from '../i18n/I18n';
import { motionApi } from './useWorkspace';
import { setMotionTrackingEnabled } from './tracking';
+import { DiagnosticExport } from './DiagnosticExport';
type Status = { enabled: boolean; preference: boolean; locked: boolean; reason?: 'test_build' | 'environment' | null };
export function PrivacySettings({ onClose }: { onClose: () => void }) {
@@ -31,5 +32,6 @@ export function PrivacySettings({ onClose }: { onClose: () => void }) {
{status?.locked && <p role="status">{t(status.reason === 'test_build' ? 'Usage data collection is disabled in test builds.' : 'Disabled by your environment settings.')}</p>}
{error && <p role="alert">{error}</p>}
</section>
+ <section><DiagnosticExport /></section>
</dialog>;
}
diff --git a/studio/src/motion/WorkspaceFrame.tsx b/studio/src/motion/WorkspaceFrame.tsx
index a423e750..dd7aaa48 100644
--- a/studio/src/motion/WorkspaceFrame.tsx
+++ b/studio/src/motion/WorkspaceFrame.tsx
@@ -4,6 +4,7 @@ import { useI18n } from '../i18n/I18n';
import { LanguageMenu } from '../i18n/LanguageMenu';
import { ConnectionDialog } from './ConnectionDialog';
import { MotionIcon } from './icons';
+import { RemixIcon } from '../icons/RemixIcons';
import { useWorkspace } from './useWorkspace';
import { ThemeToggle } from '../components/ThemeToggle';
import { Tooltip } from '../components/ui/Tooltip';
@@ -96,7 +97,7 @@ export function WorkspaceFrame({ children, waitForSaves, projectId, sessionId, b
function PrivacySettingsButton() {
const { t } = useI18n(); const [open, setOpen] = useState(false);
- return <><button className="motion-icon-button" aria-label={t('Privacy settings')} title={t('Privacy settings')} onClick={() => setOpen(true)}><MotionIcon name="eye" /></button>
+ return <><button className="motion-icon-button" aria-label={t('Privacy settings')} title={t('Privacy settings')} onClick={() => setOpen(true)}><RemixIcon name="settings-3-line" size={16} /></button>
{open && <Suspense fallback={null}><PrivacySettings onClose={() => setOpen(false)} /></Suspense>}</>;
}
diff --git a/studio/src/motion/diagnosticRequests.ts b/studio/src/motion/diagnosticRequests.ts
new file mode 100644
index 00000000..ad4641a8
--- /dev/null
+++ b/studio/src/motion/diagnosticRequests.ts
@@ -0,0 +1,41 @@
+import { diagnosticsActive, nextDiagnosticRequest, recordBrowserDiagnostic } from './diagnostics';
+
+// Only fixed route names survive; IDs, file names, queries, bodies and headers never enter the log.
+function routeName(input: RequestInfo | URL): string | undefined {
+ if (typeof input !== 'string' || input.length > 4096) return;
+ const path = input.split(/[?#]/, 1)[0];
+ const workspace = path.match(/^\/(motion|design)-api\/(project\/status|projects|sessions|runtime|preview\/open|tracking\/preferences|template-catalog|integration)$/);
+ if (workspace) return `workspace.${workspace[2]}`;
+ const transition = path.match(/^\/(?:motion|design)-api\/(projects|templates|sessions)\/[^/]+(?:\/(open|artifacts|messages))?$/);
+ if (transition) return `workspace.${transition[1]}.${transition[2] ?? 'item'}`;
+ const native = path.match(/^\/api\/projects\/[^/]+(?:\/(files|upload|render|renders|history|file-mutations|gsap-mutations|gsap-mutations-batch|gsap-mutation-rollback|rename-file|delete-file|duplicate-file)(?:\/.*)?)?$/);
+ if (native) return `native.${native[1] ?? 'project'}`;
+ if (/^\/api\/render\/[^/]+(?:\/cancel)?$/.test(path)) return 'native.render-job';
+}
+
+export function diagnosticFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
+ const route = diagnosticsActive() ? routeName(input) : undefined;
+ if (!route) return globalThis.fetch(input, init);
+ const method = (init?.method ?? 'GET').toUpperCase();
+ const write = !['GET', 'HEAD'].includes(method);
+ const safeMethod = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(method) ? method : 'OTHER';
+ const request = nextDiagnosticRequest(), start = performance.now();
+ const context = `request=${request} method=${safeMethod} route=${route}`;
+ if (write) recordBrowserDiagnostic('activity_request', `${context} outcome=started`);
+ return (async () => {
+ try {
+ const response = await globalThis.fetch(input, init);
+ const durationMs = Math.round(performance.now() - start);
+ if (write || !response.ok || durationMs >= 2000) recordBrowserDiagnostic(response.ok ? 'activity_request' : 'request_failed',
+ `${context} outcome=${response.ok ? 'response' : 'http_error'} status=${response.status} durationMs=${durationMs}`, '',
+ !response.ok || !write ? `${safeMethod}:${route}:${response.status}` : undefined);
+ return response;
+ } catch (error) {
+ const aborted = (error as { name?: string })?.name === 'AbortError';
+ if (!aborted || write) recordBrowserDiagnostic(aborted ? 'activity_request' : 'request_failed',
+ `${context} outcome=${aborted ? 'aborted' : (error as { name?: string })?.name === 'TimeoutError' ? 'timeout' : 'network_error'} durationMs=${Math.round(performance.now() - start)}`,
+ '', `${safeMethod}:${route}:${aborted ? 'aborted' : 'network_error'}`);
+ throw error;
+ }
+ })();
+}
diff --git a/studio/src/motion/diagnostics.test.ts b/studio/src/motion/diagnostics.test.ts
new file mode 100644
index 00000000..b4834cfc
--- /dev/null
+++ b/studio/src/motion/diagnostics.test.ts
@@ -0,0 +1,122 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+let diagnostics: typeof import('./diagnostics');
+let request: typeof import('./diagnosticRequests');
+let stop: () => void;
+beforeEach(async () => {
+ vi.resetModules(); vi.useFakeTimers();
+ const values = new Map<string, string>();
+ vi.stubGlobal('localStorage', { getItem: vi.fn((key: string) => values.get(key) ?? null), setItem: vi.fn((key: string, value: string) => { values.set(key, value); }) });
+ vi.stubGlobal('fetch', vi.fn(async () => new Response('ok')));
+ diagnostics = await import('./diagnostics'); request = await import('./diagnosticRequests');
+ stop = diagnostics.initializeDiagnostics();
+ await diagnostics.flushBrowserDiagnostics(); vi.clearAllMocks();
+});
+afterEach(() => { stop(); vi.clearAllTimers(); vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
+
+it('keeps healthy polling and assets silent, and adds no storage or logging requests on the operation path', async () => {
+ const storage = vi.spyOn(localStorage, 'setItem');
+ for (let i = 0; i < 1000; i++) await request.diagnosticFetch('/motion-api/project/status?projectId=private-project');
+ expect(fetch).toHaveBeenCalledTimes(1000); expect(storage).not.toHaveBeenCalled();
+ expect(diagnostics.browserDiagnostics().filter(event => event.kind === 'activity_request')).toHaveLength(0);
+ await request.diagnosticFetch('/api/projects/private-project/selection', { method: 'POST', body: 'secret-selection' });
+ await request.diagnosticFetch('https://private.example/api/projects/x/files/private-name', { method: 'PUT' });
+ expect(diagnostics.browserDiagnostics().filter(event => event.kind === 'activity_request')).toHaveLength(0);
+ await request.diagnosticFetch('/api/projects/private-project/files/private-file.html?token=private-query', { method: 'PUT', body: 'private-content', headers: { Authorization: 'private-key' } });
+ expect(storage).not.toHaveBeenCalled(); expect(fetch).toHaveBeenCalledTimes(1003);
+ const events = diagnostics.browserDiagnostics().filter(event => event.kind === 'activity_request');
+ expect(events).toHaveLength(2); expect(events[0].message).toContain('outcome=started');
+ expect(events[1].message).toContain('status=200'); expect(events[1].message).toContain('durationMs=');
+ expect(events[0].message.match(/request=([^ ]+)/)?.[1]).toBe(events[1].message.match(/request=([^ ]+)/)?.[1]);
+ expect(JSON.stringify(events)).not.toContain('private-');
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(storage).toHaveBeenCalledTimes(1); expect(fetch).toHaveBeenCalledTimes(1004);
+ expect(vi.mocked(fetch).mock.calls.at(-1)?.[0]).toBe('/motion-api/diagnostics/events');
+});
+
+it('retains response and error identity, records HTTP/network/slow results, and ignores cancelled reads', async () => {
+ const response = new Response('private-response', { status: 503 });
+ vi.mocked(fetch).mockResolvedValue(response);
+ expect(await request.diagnosticFetch('/motion-api/project/status')).toBe(response);
+ expect(await response.text()).toBe('private-response');
+ const failure = new TypeError('private-network-detail'); vi.mocked(fetch).mockRejectedValue(failure);
+ await expect(request.diagnosticFetch('/api/projects/private/files/private')).rejects.toBe(failure);
+ vi.mocked(fetch).mockRejectedValue(new DOMException('cancelled', 'AbortError'));
+ const count = diagnostics.browserDiagnostics().length;
+ await expect(request.diagnosticFetch('/motion-api/projects')).rejects.toHaveProperty('name', 'AbortError');
+ expect(diagnostics.browserDiagnostics()).toHaveLength(count);
+ vi.mocked(fetch).mockImplementation(async () => { vi.advanceTimersByTime(2100); return new Response('ok'); });
+ await request.diagnosticFetch('/motion-api/runtime');
+ const text = JSON.stringify(diagnostics.browserDiagnostics());
+ expect(text).toContain('status=503'); expect(text).toContain('outcome=network_error'); expect(text).toContain('durationMs=2100');
+ expect(text).not.toContain('private');
+});
+
+it('coalesces repeated errors, bounds a flood, preserves errors separately and reports dropped records', async () => {
+ const storage = vi.spyOn(localStorage, 'setItem');
+ for (let i = 0; i < 100; i++) diagnostics.recordBrowserDiagnostic('failure', 'api_key=fixture-private repeated');
+ expect(diagnostics.browserDiagnostics().filter(event => event.kind === 'failure')).toHaveLength(1);
+ for (let i = 0; i < 100; i++) diagnostics.recordBrowserDiagnostic('activity_request', `request=${i} ` + 'detail '.repeat(1000));
+ const events = diagnostics.browserDiagnostics();
+ expect(events.some(event => event.kind === 'failure')).toBe(true);
+ expect(events.length).toBeLessThanOrEqual(60);
+ expect(new TextEncoder().encode(JSON.stringify(events)).length).toBeLessThanOrEqual(24 * 1024);
+ expect(events.at(-1)?.message).toContain('"repeated":99');
+ expect(events.at(-1)?.message).not.toContain('"rateLimited":0');
+ expect(storage).not.toHaveBeenCalled(); expect(fetch).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(storage).toHaveBeenCalledTimes(1); expect(fetch).toHaveBeenCalledTimes(1);
+ expect(JSON.stringify(vi.mocked(fetch).mock.calls)).not.toContain('fixture-private');
+ expect(new TextEncoder().encode(localStorage.getItem('motion.local-diagnostics.v1')!).length).toBeLessThanOrEqual(24 * 1024);
+});
+
+it('never overlaps logging requests, bounds its timeout, drops failed delivery without retrying, and survives denied storage', async () => {
+ vi.spyOn(localStorage, 'setItem').mockImplementation(() => { throw new Error('denied'); });
+ vi.mocked(fetch).mockImplementation((_url, init) => new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener('abort', () => reject(new DOMException('timeout', 'AbortError')));
+ }));
+ diagnostics.recordBrowserDiagnostic('failure', 'first');
+ const first = diagnostics.flushBrowserDiagnostics();
+ diagnostics.recordBrowserDiagnostic('failure', 'second');
+ expect(diagnostics.flushBrowserDiagnostics()).toBe(first); expect(fetch).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(3000); await first;
+ expect(diagnostics.browserDiagnostics().at(-1)?.message).toContain('"delivery":1');
+ vi.mocked(fetch).mockResolvedValue(new Response('ok'));
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(fetch).toHaveBeenCalledTimes(2);
+ const body = String(vi.mocked(fetch).mock.calls[1][1]?.body);
+ expect(body).toContain('second'); expect(body).not.toContain('first');
+ await vi.advanceTimersByTimeAsync(60_000); expect(fetch).toHaveBeenCalledTimes(2);
+});
+
+it('flushes pending records on page exit and reloads the bounded local fallback', async () => {
+ diagnostics.recordBrowserDiagnostic('failure', 'api_key=fixture-secret');
+ window.dispatchEvent(new Event('pagehide'));
+ await diagnostics.flushBrowserDiagnostics();
+ expect(fetch).toHaveBeenCalledTimes(1);
+ stop(); vi.resetModules();
+ const reloaded = await import('./diagnostics');
+ expect(reloaded.browserDiagnostics().some(event => event.kind === 'failure')).toBe(true);
+ expect(JSON.stringify(reloaded.browserDiagnostics())).not.toContain('fixture-secret');
+});
+
+it('measures polling overhead without network or storage side effects', async () => {
+ vi.useRealTimers();
+ const response = new Response('ok'); vi.mocked(fetch).mockResolvedValue(response);
+ const measure = async (operation: () => Promise<Response>) => {
+ for (let i = 0; i < 1000; i++) await operation();
+ const samples: number[] = [];
+ for (let sample = 0; sample < 5; sample++) {
+ const start = performance.now();
+ for (let i = 0; i < 2000; i++) await operation();
+ samples.push((performance.now() - start) / 2000);
+ }
+ return samples.sort((a, b) => a - b)[2];
+ };
+ const baselineMs = await measure(() => fetch('/motion-api/project/status'));
+ const instrumentedMs = await measure(() => request.diagnosticFetch('/motion-api/project/status'));
+ expect(localStorage.setItem).not.toHaveBeenCalled();
+ expect(vi.mocked(fetch).mock.calls.every(([url]) => url === '/motion-api/project/status')).toBe(true);
+ process.stdout.write('DIAGNOSTIC_OVERHEAD ' + JSON.stringify({ scope: 'mocked healthy request, median of 5 x 2000 calls; not a playback benchmark', baselineMs, instrumentedMs, addedMs: instrumentedMs - baselineMs }) + '\n');
+});
diff --git a/studio/src/motion/diagnostics.ts b/studio/src/motion/diagnostics.ts
new file mode 100644
index 00000000..d22faf8e
--- /dev/null
+++ b/studio/src/motion/diagnostics.ts
@@ -0,0 +1,98 @@
+import { redactDiagnostic } from '../../../scripts/diagnostic-redaction.mjs';
+
+const storageKey = 'motion.local-diagnostics.v1';
+type DiagnosticEvent = { time: string; kind: string; message: string; stack: string };
+type Ring = { entries: { event: DiagnosticEvent; bytes: number }[]; bytes: number };
+const errors: Ring = { entries: [], bytes: 0 }, activity: Ring = { entries: [], bytes: 0 }, pending: Ring = { entries: [], bytes: 0 };
+const encoder = new TextEncoder();
+const losses = { rateLimited: 0, repeated: 0, evicted: 0, delivery: 0 };
+const recent = new Map<string, number>();
+let loaded = false, active = false, timer: ReturnType<typeof setTimeout> | undefined, sending: Promise<void> | undefined;
+let windowStart = 0, errorCount = 0, activityCount = 0;
+let sequence = 0;
+const session = crypto.randomUUID();
+
+function push(ring: Ring, event: DiagnosticEvent, count: number, bytes: number) {
+ const size = encoder.encode(JSON.stringify(event)).length + 1;
+ ring.entries.push({ event, bytes: size }); ring.bytes += size;
+ while (ring.entries.length > count || ring.bytes > bytes) {
+ ring.bytes -= ring.entries.shift()!.bytes; losses.evicted++;
+ }
+}
+function retain(event: DiagnosticEvent) {
+ if (event.kind.startsWith('activity_')) push(activity, event, 39, 7 * 1024);
+ else push(errors, event, 20, 16 * 1024);
+}
+function load() {
+ if (loaded) return;
+ loaded = true;
+ try {
+ const text = localStorage.getItem(storageKey) || '[]';
+ if (text.length > 24 * 1024) return;
+ const entries: unknown = JSON.parse(text);
+ if (!Array.isArray(entries)) return;
+ for (const entry of entries.slice(-60)) {
+ if (entry && typeof entry === 'object' && Object.keys(entry).length === 4
+ && ['time', 'kind', 'message', 'stack'].every(key => typeof entry[key] === 'string' && entry[key].length <= 4096)) retain(entry);
+ }
+ } catch { /* Storage is optional; the in-memory ring still works. */ }
+}
+export function browserDiagnostics(): DiagnosticEvent[] {
+ load();
+ return [...errors.entries, ...activity.entries].map(item => item.event).sort((a, b) => a.time.localeCompare(b.time)).concat({
+ time: new Date().toISOString(), kind: 'activity_summary', message: JSON.stringify({ session, ...losses }), stack: '',
+ });
+}
+function schedule() {
+ if (!timer && !sending && pending.entries.length) timer = setTimeout(() => { void flushBrowserDiagnostics(); }, 5000);
+}
+export function flushBrowserDiagnostics(): Promise<void> {
+ clearTimeout(timer); timer = undefined;
+ if (sending) return sending;
+ if (!pending.entries.length) return Promise.resolve();
+ try { localStorage.setItem(storageKey, JSON.stringify(browserDiagnostics().filter(event => event.kind !== 'activity_summary'))); } catch { /* Best effort. */ }
+ const batch = pending.entries.splice(0, 20);
+ pending.bytes -= batch.reduce((sum, item) => sum + item.bytes, 0);
+ // Logging has its own deadline and never shares the caller's signal or response body.
+ const controller = new AbortController(), deadline = setTimeout(() => controller.abort(), 3000);
+ sending = (async () => {
+ try {
+ const response = await fetch('/motion-api/diagnostics/events', { method: 'POST', headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ errors: batch.map(item => item.event) }), signal: controller.signal, keepalive: true });
+ if (!response.ok) losses.delivery += batch.length;
+ } catch { losses.delivery += batch.length; }
+ finally { clearTimeout(deadline); }
+ })().finally(() => { sending = undefined; schedule(); });
+ return sending;
+}
+export function recordBrowserDiagnostic(kind: string, message: string, stack = '', deduplicationKey?: string) {
+ try {
+ load();
+ const now = Date.now(), isActivity = kind.startsWith('activity_');
+ if (now - windowStart >= 60_000) { windowStart = now; errorCount = 0; activityCount = 0; }
+ if ((isActivity ? activityCount >= 40 : errorCount >= 20)) { losses.rateLimited++; return; }
+ const clean = (text: string) => redactDiagnostic(text.slice(0, 8192)).slice(0, 4096);
+ const event = { time: new Date(now).toISOString(), kind: clean(kind).slice(0, 64), message: clean(message), stack: clean(stack) };
+ const key = deduplicationKey ?? (!isActivity ? event.kind + event.message : undefined);
+ if (key && now - (recent.get(key) ?? -Infinity) < 30_000) { losses.repeated++; return; }
+ if (key) { if (recent.size >= 32) recent.delete(recent.keys().next().value!); recent.set(key, now); }
+ if (isActivity) activityCount++; else errorCount++;
+ retain(event); push(pending, event, 60, 24 * 1024 - 2); schedule();
+ } catch { /* Diagnostic capture must not break the editor or recurse on failures. */ }
+}
+export function diagnosticsActive() { return active; }
+export function nextDiagnosticRequest() { return `${session}:${++sequence}`; }
+export function initializeDiagnostics() {
+ active = true;
+ const browser = navigator.userAgent.match(/(?:Edg|Firefox)\/[\d.]+/)?.[0]
+ ?? navigator.userAgent.match(/Chrome\/[\d.]+/)?.[0]
+ ?? navigator.userAgent.match(/Version\/[\d.]+/)?.[0]?.replace('Version/', 'Safari/') ?? 'unknown';
+ recordBrowserDiagnostic('activity_session', `session=${session} browser=${browser} inFrame=${window.self !== window.top} viewport=${innerWidth}x${innerHeight}`);
+ const hide = () => { void flushBrowserDiagnostics(); };
+ const visibility = () => { if (document.visibilityState === 'hidden') hide(); };
+ window.addEventListener('pagehide', hide); document.addEventListener('visibilitychange', visibility);
+ return () => {
+ active = false; window.removeEventListener('pagehide', hide); document.removeEventListener('visibilitychange', visibility);
+ clearTimeout(timer); timer = undefined;
+ };
+}
diff --git a/studio/src/motion/media-gateway.css b/studio/src/motion/media-gateway.css
index 1789e5c9..8d0bb11f 100644
--- a/studio/src/motion/media-gateway.css
+++ b/studio/src/motion/media-gateway.css
@@ -5,9 +5,9 @@
.motion-media-surface h3 { color: var(--motion-strong); font-size: 14px; font-weight: 600; margin: 0 0 12px; }
.motion-media-surface small { display: block; font-size: 11px; }
.motion-media-surface header small { letter-spacing: .12em; color: var(--motion-accent); }
-.motion-media-surface button, .motion-empty-media-actions button, .motion-timeline-media-actions button, .motion-asset-generate { min-height: 32px; padding: 6px 12px; border: 1px solid var(--motion-border); border-radius: 8px; background: var(--motion-panel); color: var(--motion-text); font-size: 12px; font-weight: 500; cursor: pointer; white-space: nowrap; }
-.motion-media-surface button:hover, .motion-empty-media-actions button:hover, .motion-timeline-media-actions button:hover, .motion-asset-generate:hover { background: var(--motion-hover); }
-.motion-media-surface button:disabled, .motion-timeline-media-actions button:disabled { cursor: default; opacity: .5; }
+.motion-media-surface button, .motion-diagnostic-export button, .motion-empty-media-actions button, .motion-timeline-media-actions button, .motion-asset-generate { min-height: 32px; padding: 6px 12px; border: 1px solid var(--motion-border); border-radius: 8px; background: var(--motion-panel); color: var(--motion-text); font-size: 12px; font-weight: 500; cursor: pointer; white-space: nowrap; }
+.motion-media-surface button:hover, .motion-diagnostic-export button:hover, .motion-empty-media-actions button:hover, .motion-timeline-media-actions button:hover, .motion-asset-generate:hover { background: var(--motion-hover); }
+.motion-media-surface button:disabled, .motion-diagnostic-export button:disabled, .motion-timeline-media-actions button:disabled { cursor: default; opacity: .5; }
.motion-media-surface .motion-media-primary, .motion-empty-media-actions .motion-media-primary { color: var(--motion-on-action); background: var(--motion-action); border-color: var(--motion-action); }
.motion-media-surface .motion-media-primary:hover, .motion-empty-media-actions .motion-media-primary:hover { background: var(--motion-action-hover); }
.motion-media-surface .motion-media-close { border: 0; background: transparent; font-size: 22px; line-height: 1; padding: 4px; width: 32px; }
@@ -24,6 +24,15 @@
.motion-media-surface details[open] summary { margin-bottom: 8px; }
.motion-model-dialog { position: fixed; inset: 0; margin: auto; width: min(960px, calc(100vw - 40px)); max-height: calc(100dvh - 48px); padding: 24px; overflow: auto; }
.motion-privacy-dialog { width: min(520px, calc(100vw - 40px)); }
+.motion-privacy-dialog header { margin-bottom: 24px; }
+.motion-privacy-dialog section, .motion-privacy-dialog .motion-diagnostic-export { display: grid; gap: 12px; min-width: 0; }
+.motion-privacy-dialog p { margin: 0; line-height: 1.65; }
+.motion-privacy-dialog section > .motion-media-toggle { gap: 8px; font-size: 13px; font-weight: 600; color: var(--motion-strong); }
+.motion-privacy-dialog .motion-diagnostic-export > button { justify-self: start; }
+.motion-privacy-dialog .motion-diagnostic-export [role=status] { padding: 12px; border-radius: 8px; background: var(--motion-inset); font-size: 12px; }
+.motion-diagnostic-filename { display: block; overflow-wrap: anywhere; }
+.motion-privacy-dialog .motion-diagnostic-filename { margin-top: 6px; color: var(--motion-muted); }
+.motion-privacy-dialog [role=alert] { color: var(--motion-danger); overflow-wrap: anywhere; }
.motion-model-dialog::backdrop { background: var(--motion-overlay); backdrop-filter: blur(3px); }
.motion-model-dialog section + section { border-top: 1px solid var(--motion-border); margin-top: 24px; padding-top: 20px; }
.motion-model-routes select { min-height: 36px; }
diff --git a/studio/src/motion/useWorkspace.ts b/studio/src/motion/useWorkspace.ts
index b75de709..83d5b218 100644
--- a/studio/src/motion/useWorkspace.ts
+++ b/studio/src/motion/useWorkspace.ts
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { projectHref, sessionHref } from './workspaceRouting';
import type { CreativeSession, CreationMode } from '../../../shared/session';
import { preservePresentation } from '../../../shared/workspace-url';
+import { diagnosticFetch } from './diagnosticRequests';
export type SavedProject = { id: string; title: string; templateId?: string; createdAt?: number; openedAt?: number };
type Job = { id: string; state: 'pending' | 'running' | 'completed' | 'failed'; error?: string };
@@ -9,7 +10,7 @@ export type WorkspaceStatus = { revision: string; projectId: string; projectTitl
historyRestoreError?: { requestId: string; message: string } | null };
export type ProjectCatalog = { activeId: string; projects: SavedProject[]; sessions?: CreativeSession[]; activeSessionId?: string };
export async function motionApi<T>(path: string, init?: RequestInit, projectId?: string): Promise<T> {
- const response = await fetch((path.startsWith('/sessions') || path.startsWith('/modes') ? '/design-api' : '/motion-api') + path
+ const response = await diagnosticFetch((path.startsWith('/sessions') || path.startsWith('/modes') ? '/design-api' : '/motion-api') + path
+ (projectId ? (path.includes('?') ? '&' : '?') + 'projectId=' + encodeURIComponent(projectId) : ''), init);
const data = await response.json();
if (!response.ok) throw new Error(data.error || '本地工作室连接失败');
diff --git a/studio/src/utils/studioApiFetch.ts b/studio/src/utils/studioApiFetch.ts
index d4961ab8..8f1159cf 100644
--- a/studio/src/utils/studioApiFetch.ts
+++ b/studio/src/utils/studioApiFetch.ts
@@ -1,5 +1,6 @@
import { STUDIO_API_SAME_ORIGIN_CREDENTIALS } from "../components/editor/manualEditingAvailability";
import { parseProjectIdFromHash } from './projectRouting';
+import { diagnosticFetch } from '../motion/diagnosticRequests';
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
@@ -10,7 +11,7 @@ function studioApiCredentials(): RequestCredentials {
}
export function studioApiFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
- return globalThis.fetch(typeof input === 'string' ? studioProjectUrl(input) : input, { ...init, credentials: studioApiCredentials() });
+ return diagnosticFetch(typeof input === 'string' ? studioProjectUrl(input) : input, { ...init, credentials: studioApiCredentials() });
}
export function studioProjectUrl(input: string, projectId?: string | null): string {
diff --git a/tests/adapters.test.ts b/tests/adapters.test.ts
index e08ef599..606f55f7 100644
--- a/tests/adapters.test.ts
+++ b/tests/adapters.test.ts
@@ -103,7 +103,7 @@ test('bundled runtime adapters preserve the Node preload and launch with a minim
await cp(process.execPath, node);
await mkdir(path.join(runtime, 'docs'));
for (const name of ['AGENTS.md', 'CLAUDE.md']) await writeFile(path.join(runtime, name), '# Fixture');
- for (const filename of ['scripts/export-adapters.ts', 'scripts/package.ts', 'scripts/distribution.ts', 'shared/entry.ts', 'shared/integration.ts', 'shared/template-locale.ts', 'shared/template-prompts.ts', 'shared/workflow.ts', 'shared/workflow-entry.js', 'web/design-system/icons.svg', 'web/design-system/remix-icon-LICENSE.txt', 'web/design-system/remix-icon-NOTICE.txt']) {
+ for (const filename of ['scripts/export-adapters.ts', 'scripts/package.ts', 'scripts/zip.mjs', 'scripts/distribution.ts', 'shared/entry.ts', 'shared/integration.ts', 'shared/template-locale.ts', 'shared/template-prompts.ts', 'shared/workflow.ts', 'shared/workflow-entry.js', 'web/design-system/icons.svg', 'web/design-system/remix-icon-LICENSE.txt', 'web/design-system/remix-icon-NOTICE.txt']) {
await mkdir(path.dirname(path.join(runtime, filename)), { recursive: true });
await cp(path.join(source, filename), path.join(runtime, filename));
}
diff --git a/tests/diagnostics-browser.mjs b/tests/diagnostics-browser.mjs
new file mode 100644
index 00000000..ac6da323
--- /dev/null
+++ b/tests/diagnostics-browser.mjs
@@ -0,0 +1,82 @@
+import assert from 'node:assert/strict';
+import { createServer } from 'node:http';
+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import puppeteer from 'puppeteer-core';
+import { WorkspaceStore } from '../workspace.ts';
+import { handler } from '../server.ts';
+import { pluginRoot } from '../hyperframes.ts';
+import { runFile } from '../scripts/runtime-assets.mjs';
+
+const output = process.argv[2];
+assert(output && path.isAbsolute(output), 'Pass an absolute evidence directory');
+assert(process.env.D4_LANE && process.env.PLAYWRIGHT_WEB_PORT, 'Run with the shared browser-lock.sh wrapper');
+await mkdir(output, { recursive: true });
+const downloads = path.join(output, 'downloads'); await mkdir(downloads);
+const data = await mkdtemp(path.join(tmpdir(), 'motion-diagnostic-browser-'));
+const store = new WorkspaceStore(data), context = { nativeRoot: pluginRoot };
+const server = createServer((req, res) => { void handler(req, res, store, context); });
+let browser;
+try {
+ await store.initialize(pluginRoot);
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(Number(process.env.PLAYWRIGHT_WEB_PORT), '127.0.0.1', resolve); });
+ const origin = `http://127.0.0.1:${server.address().port}`;
+ browser = await puppeteer.launch({ executablePath: process.env.HYPERFRAMES_BROWSER_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', headless: true,
+ userDataDir: path.join(data, 'browser'), args: ['--no-first-run'] });
+ const page = await browser.newPage(); await page.setViewport({ width: 1280, height: 850 });
+ await page.evaluateOnNewDocument(() => { localStorage.setItem('motion.studio.locale', 'en'); });
+ const client = await page.createCDPSession();
+ await client.send('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: downloads });
+ await page.goto(origin, { waitUntil: 'networkidle0' });
+ const menu = await page.waitForSelector('[aria-label="Open project list"]'); await menu.click();
+ await (await page.waitForSelector('[aria-label="Privacy settings"]')).click();
+ await page.waitForSelector('dialog[open] .motion-diagnostic-export button');
+ await page.evaluate(() => window.dispatchEvent(new ErrorEvent('error', { message: 'api_key=fixture-browser-secret', error: new Error('api_key=fixture-browser-secret') })));
+ await page.waitForFunction(() => localStorage.getItem('motion.local-diagnostics.v1')?.includes('redacted'));
+ await page.screenshot({ path: path.join(output, 'privacy-diagnostic-export.png') });
+ const persistedDownload = page.waitForResponse(response => response.url() === origin + '/motion-api/diagnostics/events'
+ && response.request().postData()?.includes('download_triggered'), { timeout: 15000 });
+ const response = page.waitForResponse(response => response.url() === origin + '/motion-api/diagnostics' && response.request().method() === 'POST');
+ await page.click('dialog[open] .motion-diagnostic-export button');
+ assert.equal((await response).status(), 200);
+ await page.waitForFunction(() => document.querySelector('.motion-diagnostic-export [role=status]')?.textContent.includes('Download started. Check your browser downloads.'));
+ let archive;
+ for (let attempt = 0; attempt < 40; attempt++) {
+ archive = (await readdir(downloads)).find(file => file.endsWith('.zip'));
+ if (archive) break;
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ assert(archive, 'Chrome must actually save the ZIP');
+ const zipFile = path.join(downloads, archive);
+ assert.match(await runFile('unzip', ['-t', zipFile]), /No errors detected/);
+ assert(!(await readFile(zipFile)).includes(Buffer.from('fixture-browser-secret')));
+ const metadata = JSON.parse(await runFile('unzip', ['-p', zipFile, 'metadata.json']));
+ assert.equal(metadata.platform, process.platform);
+ const activity = JSON.parse(await runFile('unzip', ['-p', zipFile, 'browser-activity.json']));
+ assert(activity.some(event => event.kind === 'activity_session' && event.message.includes('browser=Chrome/')));
+ assert(activity.some(event => event.kind === 'activity_diagnostic_export' && event.message.includes('outcome=started')));
+ assert(activity.some(event => event.kind === 'activity_summary'));
+ await page.setViewport({ width: 360, height: 800 });
+ assert(await page.evaluate(() => { const dialog = document.querySelector('dialog[open]'); const bounds = dialog.getBoundingClientRect(); return bounds.left >= 0 && bounds.right <= innerWidth && dialog.scrollWidth <= dialog.clientWidth; }), 'Download feedback and filename must fit a narrow dialog');
+ await page.screenshot({ path: path.join(output, 'diagnostic-success-narrow.png') });
+ await page.click('dialog[open] .motion-diagnostic-export button');
+ await page.waitForFunction(() => document.querySelector('.motion-diagnostic-export [role=alert]')?.textContent.includes('30 seconds'));
+ await page.emulateMediaFeatures([{ name: 'prefers-color-scheme', value: 'dark' }]);
+ await page.setViewport({ width: 540, height: 800 });
+ assert(await page.evaluate(() => { const bounds = document.querySelector('dialog[open]').getBoundingClientRect(); return bounds.left >= 0 && bounds.right <= innerWidth; }));
+ await page.screenshot({ path: path.join(output, 'diagnostic-rate-limit-narrow.png') });
+ assert.equal((await persistedDownload).status(), 200);
+ await browser.close(); browser = undefined;
+ server.closeAllConnections(); await new Promise(resolve => server.close(resolve));
+ const offline = path.join(output, 'offline-cli.zip');
+ await runFile(process.execPath, ['scripts/diagnostics.mjs', '--data-dir', data, '--output', offline]);
+ const log = await runFile('unzip', ['-p', offline, 'logs/diagnostics/events.log']);
+ assert(log.includes('unhandled_error') && !log.includes('fixture-browser-secret'));
+ assert(log.includes('archive_received') && log.includes('download_triggered') && log.includes('diagnostic_export_failed'));
+ await writeFile(path.join(output, 'result.json'), JSON.stringify({ status: 'passed', scope: 'real Chrome + workspace HTTP handler + offline CLI; no native renderer or real host installation',
+ checks: ['privacy download', 'actual ZIP integrity', 'default redaction', 'repeat-click limit', 'narrow dialog', 'offline CLI retains browser error'], archive, metadata }, null, 2));
+ console.log('PASS real Chrome download, redaction, throttling, narrow layout and offline CLI');
+} finally {
+ await browser?.close(); server.closeAllConnections(); server.close(); await rm(data, { recursive: true, force: true });
+}
diff --git a/tests/diagnostics.test.ts b/tests/diagnostics.test.ts
new file mode 100644
index 00000000..d1e0cc91
--- /dev/null
+++ b/tests/diagnostics.test.ts
@@ -0,0 +1,196 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { collectDiagnostics, diagnosticLimits, exportDiagnostics, recordDiagnostic } from '../scripts/diagnostics.mjs';
+import { redactDiagnostic } from '../scripts/diagnostic-redaction.mjs';
+import { runFile } from '../scripts/runtime-assets.mjs';
+import { WorkspaceStore } from '../workspace.ts';
+import { handler } from '../server.ts';
+import { transport } from './http.ts';
+
+function contents(buffer: Buffer): Record<string, string> {
+ const entries: Record<string, string> = {};
+ let offset = 0;
+ while (buffer.readUInt32LE(offset) === 0x04034b50) {
+ const size = buffer.readUInt32LE(offset + 18), length = buffer.readUInt16LE(offset + 26);
+ const name = buffer.subarray(offset + 30, offset + 30 + length).toString();
+ const start = offset + 30 + length + buffer.readUInt16LE(offset + 28);
+ entries[name] = buffer.subarray(start, start + size).toString();
+ offset = start + size;
+ }
+ return entries;
+}
+async function fixture(t: any) {
+ const root = await mkdtemp(path.join(tmpdir(), 'motion-diagnostics-'));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const appRoot = path.join(root, 'app'), dataDirectory = path.join(root, 'data'), installHome = path.join(root, 'install');
+ for (const directory of [appRoot, dataDirectory, installHome]) await mkdir(directory);
+ await mkdir(path.join(appRoot, 'shared'));
+ await writeFile(path.join(appRoot, 'package.json'), JSON.stringify({ version: '0.7.0' }));
+ return { root, appRoot, dataDirectory, installHome };
+}
+
+test('diagnostic ZIPs are readable, redacted, bounded and contain only allowlisted data in test and stable builds', async t => {
+ const options = await fixture(t);
+ const secret = 'fixture-' + randomUUID(), jobId = randomUUID();
+ const personalPath = path.posix.join('/', 'Users', 'person', 'private', 'file.txt');
+ const previous = process.env.DIAGNOSTIC_TEST_TOKEN;
+ process.env.DIAGNOSTIC_TEST_TOKEN = secret;
+ t.after(() => { if (previous === undefined) delete process.env.DIAGNOSTIC_TEST_TOKEN; else process.env.DIAGNOSTIC_TEST_TOKEN = previous; });
+ await writeFile(path.join(options.appRoot, 'shared/build-info.json'), JSON.stringify({ commit: 'a'.repeat(40) }));
+ await writeFile(path.join(options.dataDirectory, 'preview.log'), `startup ${secret}\napi_key="${secret}"\nCookie: session=${secret}; other=${secret}\nhttps://user:${secret}@example.com/private/${secret}?token=${secret}\n${personalPath}\n`);
+ const privateContent = 'private-project-' + randomUUID();
+ for (const name of ['.env', 'project.html', 'providers.json', 'conversation.json']) await writeFile(path.join(options.dataDirectory, name), privateContent);
+ await mkdir(path.join(options.dataDirectory, 'jobs', jobId), { recursive: true });
+ await writeFile(path.join(options.dataDirectory, 'jobs', jobId, 'job.json'), JSON.stringify({ id: jobId, state: 'failed', error: `api_key=${secret}`, createdAt: 123, token: secret, prompt: privateContent }));
+ await writeFile(path.join(options.dataDirectory, 'jobs', jobId, 'render.log'), 'render failed\n');
+ for (const version of ['0.7.0', '0.7.1-test.4']) {
+ await writeFile(path.join(options.appRoot, 'package.json'), JSON.stringify({ version }));
+ const result = await collectDiagnostics(options), files = contents(result.data);
+ assert.equal(JSON.parse(files['metadata.json']).version, version);
+ assert.equal(JSON.parse(files['metadata.json']).commit, 'a'.repeat(40));
+ assert.equal(JSON.parse(files['jobs.json'])[0].error, 'api_key=[redacted]');
+ assert.equal(JSON.parse(files['jobs.json'])[0].token, undefined);
+ assert(!result.data.includes(Buffer.from(secret)) && !result.data.includes(Buffer.from(privateContent)));
+ assert(!result.data.includes(Buffer.from(path.posix.dirname(personalPath))));
+ assert(files['logs/job-1/render.log'].includes('render failed'));
+ assert(JSON.parse(files['files.json']).some((file: any) => file.name === 'studio.log' && file.status === 'missing'));
+ assert(result.data.length < diagnosticLimits.totalBytes + 64 * 1024);
+ const filename = path.join(options.root, version + '.zip'); await writeFile(filename, result.data);
+ assert.match(await runFile('unzip', ['-t', filename]), /No errors detected/);
+ }
+});
+
+test('collection excludes symlinks and non-files, truncates large logs and never overwrites CLI output', async t => {
+ const options = await fixture(t);
+ const outside = path.join(options.root, 'outside'); await mkdir(outside);
+ const secret = 'outside-' + randomUUID();
+ await writeFile(path.join(outside, 'editor.log'), secret);
+ await symlink(path.join(outside, 'editor.log'), path.join(options.dataDirectory, 'preview.log'));
+ await symlink(outside, path.join(options.dataDirectory, '.editor-runtime'), process.platform === 'win32' ? 'junction' : 'dir');
+ await mkdir(path.join(options.dataDirectory, 'studio.log'));
+ await mkdir(path.join(options.dataDirectory, 'diagnostics'));
+ await writeFile(path.join(options.dataDirectory, 'diagnostics/events.log'), 'large log line\n'.repeat(20_000));
+ const result = await collectDiagnostics(options), files = contents(result.data);
+ assert(!result.data.includes(Buffer.from(secret)));
+ const list = JSON.parse(files['files.json']);
+ for (const name of ['preview.log', 'studio.log', '.editor-runtime/editor.log']) assert.equal(list.find((file: any) => file.name === name).status, 'excluded');
+ assert.equal(list.find((file: any) => file.name === 'diagnostics/events.log').status, 'truncated');
+ assert(Buffer.byteLength(files['logs/diagnostics/events.log']) <= diagnosticLimits.fileBytes);
+ const output = path.join(options.root, 'saved.zip');
+ await exportDiagnostics({ ...options, output });
+ const before = await readFile(output);
+ await assert.rejects(exportDiagnostics({ ...options, output }), { code: 'EEXIST' });
+ assert.deepEqual(await readFile(output), before);
+ if (process.platform !== 'win32') assert.equal((await stat(output)).mode & 0o777, 0o600);
+});
+
+test('local failure logging rotates, redacts and refuses linked log destinations', async t => {
+ const options = await fixture(t), secret = 'fixture-secret-' + randomUUID();
+ await Promise.all(Array.from({ length: 40 }, () => recordDiagnostic(options.dataDirectory, { kind: 'failure', message: 'api_key=' + secret + ' ' + 'detail '.repeat(1200) })));
+ for (const name of ['events.log', 'events.log.1']) {
+ const file = path.join(options.dataDirectory, 'diagnostics', name);
+ assert((await stat(file)).size <= diagnosticLimits.fileBytes);
+ assert(!(await readFile(file, 'utf8')).includes(secret));
+ }
+ const target = path.join(options.root, 'untouched'); await writeFile(target, 'original');
+ await rm(path.join(options.dataDirectory, 'diagnostics/events.log'));
+ await symlink(target, path.join(options.dataDirectory, 'diagnostics/events.log'));
+ await recordDiagnostic(options.dataDirectory, { message: 'do not write' });
+ assert.equal(await readFile(target, 'utf8'), 'original');
+});
+
+test('CLI works without a running app or completed setup, and with a saved custom data directory', async t => {
+ const options = await fixture(t), output = path.join(options.root, 'cli.zip');
+ await writeFile(path.join(options.installHome, 'install.json'), JSON.stringify({ appRoot: options.appRoot, dataDirectory: options.dataDirectory }));
+ const result = await runFile(process.execPath, ['scripts/npm-installer.mjs', 'diagnostics', '--home', options.installHome, '--output', output]);
+ assert.equal(JSON.parse(result).output, output);
+ assert.equal(JSON.parse(contents(await readFile(output))['metadata.json']).version, '0.7.0');
+ const source = path.join(options.root, 'source.zip');
+ await runFile(process.execPath, ['scripts/diagnostics.mjs', '--data-dir', options.dataDirectory, '--output', source]);
+ assert(contents(await readFile(source))['metadata.json']);
+ await runFile(process.execPath, ['scripts/npm-installer.mjs', 'diagnostics', '--home', path.join(options.root, 'not-installed'), '--output', path.join(options.root, 'not-installed.zip')]);
+});
+
+test('redaction removes credential formats, private keys, URLs, home paths and email', () => {
+ const secret = 'test-secret-' + randomUUID();
+ const result = redactDiagnostic(`Bearer ${secret}\nAuthorization: Basic ${secret}\npassword='${secret}'\nhttps://user:${secret}@example.com/path?q=${secret}\n-----BEGIN PRIVATE KEY-----\n${secret}\n-----END PRIVATE KEY-----\nC:\\Users\\person\\project file\[email protected]`);
+ for (const privateValue of [secret, 'person', 'project file']) assert(!result.includes(privateValue));
+});
+
+test('HTTP export is local POST-only, rejects path selection and throttles repeated or concurrent collection', async t => {
+ const options = await fixture(t), store = new WorkspaceStore(options.dataDirectory), context = { nativeRoot: options.appRoot };
+ const request = transport(store, context), init = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ errors: [] }) };
+ assert.equal((await request('/motion-api/diagnostics')).status, 405);
+ assert.equal((await request('/motion-api/diagnostics?output=/tmp/forbidden', init)).status, 403);
+ assert.equal((await request('/motion-api/diagnostics', { ...init, body: JSON.stringify({ errors: [], dataDirectory: options.root }) })).status, 400);
+ const concurrent = await Promise.all([request('/motion-api/diagnostics', init), request('/motion-api/diagnostics', init)]);
+ assert.deepEqual(concurrent.map(response => response.status).sort(), [200, 429]);
+ const ok = concurrent.find(response => response.status === 200)!;
+ assert.equal(ok.headers.get('content-type'), 'application/zip'); assert.equal(ok.headers.get('cache-control'), 'no-store');
+ assert(contents(Buffer.from(await ok.arrayBuffer()))['metadata.json']);
+ assert.equal((await request('/design-api/diagnostics', init)).status, 429);
+ const hostile = transport(store, {}, async (req, res, source, service) => {
+ req.headers.origin = 'https://evil.example'; await handler(req, res, source, service);
+ });
+ assert.equal((await hostile('/motion-api/diagnostics', init)).status, 403);
+});
+
+test('browser error persistence is bounded and available to subsequent offline CLI collection', async t => {
+ const options = await fixture(t), store = new WorkspaceStore(options.dataDirectory), request = transport(store, { nativeRoot: options.appRoot });
+ const init = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ errors: [{ kind: 'react_crash', message: 'api_key=fixture-private', stack: 'stack' }] }) };
+ assert.equal((await request('/motion-api/diagnostics/events', init)).status, 200);
+ const files = contents((await collectDiagnostics(options)).data);
+ assert.match(files['logs/diagnostics/events.log'], /react_crash/); assert(!files['logs/diagnostics/events.log'].includes('fixture-private'));
+ const tooMany = { ...init, body: JSON.stringify({ errors: Array(21).fill({ message: 'spam' }) }) };
+ assert.equal((await request('/motion-api/diagnostics/events', tooMany)).status, 400);
+ const batch = { ...init, body: JSON.stringify({ errors: Array(20).fill({ message: 'spam' }) }) };
+ assert.equal((await request('/motion-api/diagnostics/events', batch)).status, 200);
+ assert.equal((await request('/motion-api/diagnostics/events', batch)).status, 200);
+ assert.equal((await request('/motion-api/diagnostics/events', batch)).status, 429);
+});
+
+test('exhausted log budgets still produce valid metadata and native status uses the configured platform target', async t => {
+ const options = await fixture(t), cache = path.join(options.root, 'cache'), target = 'custom-target';
+ await mkdir(path.join(cache, target), { recursive: true });
+ const hash = 'a'.repeat(64);
+ await writeFile(path.join(options.appRoot, '.npm-install.json'), JSON.stringify({ cacheDirectory: cache, runtime: { targets: {
+ [target]: { platform: process.platform, arch: process.arch, browser: { sha256: hash } },
+ } } }));
+ await writeFile(path.join(cache, target, `browser-${hash}.status.json`), JSON.stringify({ stage: 'failed', errorCode: 'download', error: 'token=fixture-private' }));
+ await writeFile(path.join(cache, target, 'preparation.log'), 'native preparation failed\n');
+ const content = ('[email protected] token=test\n').repeat(20_000);
+ for (const name of ['preview.log', 'studio.log', '.editor-runtime/editor.log', 'diagnostics/events.log', 'diagnostics/events.log.1']) {
+ await mkdir(path.dirname(path.join(options.dataDirectory, name)), { recursive: true });
+ await writeFile(path.join(options.dataDirectory, name), content);
+ }
+ const files = contents((await collectDiagnostics(options)).data);
+ for (const [name, data] of Object.entries(files)) if (name.endsWith('.json')) assert.doesNotThrow(() => JSON.parse(data), name);
+ const native = JSON.parse(files['native.json']);
+ assert.equal(native[0].stage, 'failed'); assert.equal(native[0].errorCode, 'download'); assert(!native[0].error.includes('fixture-private'));
+ assert(Object.entries(files).filter(([name]) => name.startsWith('logs/')).reduce((size, [, data]) => size + Buffer.byteLength(data), 0) <= diagnosticLimits.logBytes);
+ assert.equal(JSON.parse(files['metadata.json']).version, '0.7.0');
+});
+
+test('browser batches preserve event time, redact values and separate bounded activity from errors in ZIPs', async t => {
+ const options = await fixture(t), store = new WorkspaceStore(options.dataDirectory), request = transport(store, { nativeRoot: options.appRoot });
+ const time = '2026-11-12T01:02:03.000Z';
+ const events = Array.from({ length: 20 }, (_, i) => ({ time, kind: i ? 'activity_request' : 'request_failed', message: `request=page:${i} api_key=fixture-secret`, stack: '' }));
+ const init = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ errors: events }) };
+ assert.equal((await request('/motion-api/diagnostics/events', init)).status, 200);
+ const saved = (await readFile(path.join(options.dataDirectory, 'diagnostics/events.log'), 'utf8')).trim().split('\n').map(line => JSON.parse(line));
+ assert.equal(saved.length, 20); assert(saved.every(event => event.time === time));
+ assert(!JSON.stringify(saved).includes('fixture-secret'));
+ const archiveEvents = [...events, ...events, ...events];
+ const response = await request('/motion-api/diagnostics', { ...init, body: JSON.stringify({ errors: archiveEvents }) });
+ assert.equal(response.status, 200);
+ const files = contents(Buffer.from(await response.arrayBuffer()));
+ assert.equal(JSON.parse(files['browser-errors.json']).length, 3);
+ assert.equal(JSON.parse(files['browser-activity.json']).length, 57);
+ assert(!JSON.stringify(files).includes('fixture-secret'));
+ assert.equal((await request('/motion-api/diagnostics/events', { ...init, body: JSON.stringify({ errors: [{} , []] }) })).status, 400);
+ assert.equal((await request('/motion-api/diagnostics', { ...init, body: JSON.stringify({ errors: [...archiveEvents, {}] }) })).status, 400);
+});
diff --git a/tests/npm-installer.test.ts b/tests/npm-installer.test.ts
index d1a5bd5a..457ca053 100644
--- a/tests/npm-installer.test.ts
+++ b/tests/npm-installer.test.ts
@@ -62,7 +62,7 @@ test('successful setup hands the current Agent an invitation before any MCP use,
test('bundled CLI installs without a sidecar manifest, isolates DEV defaults and rejects a mixed-environment home', async t => {
const options = await setupFixture(t), bundle = path.join(options.directory, 'bundle');
await mkdir(path.join(bundle, 'scripts'), { recursive: true }); await mkdir(path.join(bundle, 'payload'));
- for (const file of ['npm-installer.mjs', 'npm-hosts.mjs', 'npm-runtime.mjs', 'runtime-assets.mjs', 'check-installed-mcp.mjs']) {
+ for (const file of ['npm-installer.mjs', 'npm-hosts.mjs', 'npm-runtime.mjs', 'runtime-assets.mjs', 'check-installed-mcp.mjs', 'diagnostics.mjs', 'diagnostic-redaction.mjs', 'zip.mjs']) {
await cp(new URL('../scripts/' + file, import.meta.url), path.join(bundle, 'scripts', file));
}
await writeJSON(path.join(bundle, 'package.json'), { version: '1.2.3', type: 'module' });
diff --git a/tests/npm-package.test.ts b/tests/npm-package.test.ts
index 61b813db..4ff2001f 100644
--- a/tests/npm-package.test.ts
+++ b/tests/npm-package.test.ts
@@ -118,8 +118,12 @@ test('test npm artifacts contain their application, locked manifest and no bundl
assert(entries.includes('skills/motion-recreate/references/verify.md'));
assert(entries.includes('studio/build/index.html'));
assert(entries.includes('shared/editor-launch.pl'), 'macOS shared editor launcher must ship');
- for (const script of ['lint-project.mjs', 'npm-installer.mjs', 'npm-hosts.mjs', 'check-installed-mcp.mjs', 'install-onboarding.mjs', 'onboarding-catalog.ts']) assert(entries.includes('scripts/' + script), 'Runtime diagnostic and lint entry must ship: ' + script);
+ for (const script of ['lint-project.mjs', 'npm-installer.mjs', 'npm-hosts.mjs', 'check-installed-mcp.mjs', 'diagnostics.mjs', 'zip.mjs', 'diagnostic-redaction.mjs', 'install-onboarding.mjs', 'onboarding-catalog.ts']) assert(entries.includes('scripts/' + script), 'Runtime diagnostic and lint entry must ship: ' + script);
await readFile(path.join(installer, 'package/scripts/check-installed-mcp.mjs'));
+ const diagnosticFile = path.join(directory, 'packaged-diagnostics.zip');
+ await runFile(process.execPath, [cli, 'diagnostics', '--home', path.join(directory, 'not-installed'), '--output', diagnosticFile]);
+ assert.match(await runFile('unzip', ['-p', diagnosticFile, 'metadata.json']), new RegExp(version.replaceAll('.', '\\.')));
+ assert.equal((await json(path.join(application, 'shared/build-info.json'))).commit, release.commit);
assert(entries.includes('shared/workflow-entry.js'), 'Workflow discovery must ship with the five Skills');
assert(!entries.split('\n').some(file => file.split('/').some(part => part.startsWith('._'))), 'Do not distribute macOS file metadata');
assert(entries.includes('template-library/NOTICE.md'));
@@ -158,6 +162,9 @@ test('stable artifacts stage publication instead of replacing latest and retain
const metadata = await json(path.join(directory, 'npm/package/package.json'));
assert.equal((await json(built.manifest)).templateEnvironment, 'prod');
const application = path.join(directory, 'app'); await extractArchive(built.application, application);
+ const diagnosticFile = path.join(directory, 'stable-diagnostics.zip');
+ await runFile(process.execPath, [path.join(application, 'scripts/diagnostics.mjs'), '--data-dir', path.join(directory, 'missing-data'), '--output', diagnosticFile]);
+ assert.match(await runFile('unzip', ['-p', diagnosticFile, 'metadata.json']), /"version": "0\.6\.4"/);
await verifyTrackingPolicy(application, 'stable');
assert.equal(metadata.version, '0.6.4'); assert.equal(metadata.private, false); assert.equal(metadata.publishConfig.tag, 'stage');
assert.equal((await json('package.json')).private, true);
diff --git a/tests/package.test.ts b/tests/package.test.ts
index f76c5761..81344f8b 100644
--- a/tests/package.test.ts
+++ b/tests/package.test.ts
@@ -9,7 +9,7 @@ test('every distribution preserves public workflow dependencies and licenses whi
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);
+ 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', 'scripts/diagnostics.mjs', 'scripts/zip.mjs', 'scripts/diagnostic-redaction.mjs', 'shared/build-info.json', '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)) {
for (const section of Object.keys(definition.sections)) {
diff --git a/tests/phase1.test.ts b/tests/phase1.test.ts
index d475031b..21541108 100644
--- a/tests/phase1.test.ts
+++ b/tests/phase1.test.ts
@@ -23,6 +23,14 @@ const edit = (service: Phase1Service, p: any, content: string) => service.call('
expectedVersionId: p.version.versionId, files: [{ path: 'note.txt', content }],
});
+test('MCP validation failures remain unchanged while local diagnostics record the failure', () => fixture(async store => {
+ const service = api(store);
+ await assert.rejects(service.call('motion_get_project', null), /INVALID_ARGUMENT: arguments must be an object/);
+ const event = JSON.parse((await readFile(path.join(store.directory, 'diagnostics/events.log'), 'utf8')).trim());
+ assert.equal(event.kind, 'mcp_failure'); assert.equal(event.tool, 'motion_get_project');
+ assert.match(event.message, /INVALID_ARGUMENT/);
+}, false));
+
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');