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.
TypeScript agent-skillsagentic-aiai-agentsai-videobyokclaude-codecodexdeepseek-harnessdsh-plugingenerative-ailocal-firstmcpmotionmotion-graphicsmultimodalopenmotionreverse-engineeringvideo-editingvideo-generationworkbuddy
Prepare native video dependencies in the background
罗高3493ae9253f3
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a1428106..df5477f9 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -78,7 +78,7 @@ jobs:npm run build:trackingnode --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/npm-package.test.ts tests/test-package.test.ts tests/source-install.test.ts tests/bootstrap.test.ts tests/mcp-registry.test.ts tests/mcp-runtime.test.ts tests/mcp-upgrade.test.ts tests/preview.test.ts tests/phase1.test.ts tests/preview-handoff.test.ts tests/adapters.test.ts tests/package.test.ts tests/recreate-measure.test.ts tests/workflow.test.ts tests/catalog.test.ts tests/prism-templates.test.ts tests/extension-boundary.test.ts tests/connections.test.ts tests/install-guide.test.ts+ run: node --experimental-strip-types --test tests/install.test.ts tests/npm-installer.test.ts tests/native-runtime.test.ts tests/npm-package.test.ts tests/test-package.test.ts tests/source-install.test.ts tests/bootstrap.test.ts tests/mcp-registry.test.ts tests/mcp-runtime.test.ts tests/mcp-upgrade.test.ts tests/preview.test.ts tests/phase1.test.ts tests/preview-handoff.test.ts tests/adapters.test.ts tests/package.test.ts tests/recreate-measure.test.ts tests/workflow.test.ts tests/catalog.test.ts tests/prism-templates.test.ts tests/extension-boundary.test.ts tests/connections.test.ts tests/install-guide.test.ts- name: Studio regressionrun: npm run test:studio -- --maxWorkers=2- name: Build phase-one ZIP and exercise all public toolsdiff --git a/docs/install.md b/docs/install.mdindex 8e24a319..e7f999bb 100644--- a/docs/install.md+++ b/docs/install.md@@ -9,7 +9,7 @@ If you are reading this file in the source repository and see `{{...}}`, it is a1. Collect OS/CPU, Node.js/npm versions and the current Agent identity together, using the host's supplied context where available. Node.js 22.18+ with npm and the Agent must already be installed. Supported native targets: {{TARGETS}}. Do not claim support for another target from package-download success.2. Select the current host explicitly: `codex` (Codex), `claude` (Claude Code), `deepseek` (DeepSeek Harness) or `workbuddy` (WorkBuddy). An explicit user selection takes precedence. Do not infer the current host from which CLIs happen to be installed. Ask only when the current host or required profile cannot be established. Configure only that host; preserve projects, credentials and unrelated MCP/Skills settings.3. For a test candidate, use a separate host profile, application home, project data and Skills directory. Keep those paths and reuse them for prepare and future reconnects. The [platform installation recipes]({{DETAILS_URL}}) describe the actual supported options. Do not run a test candidate into the user's daily profile by default.-4. Choose exactly one setup command below, applying the test isolation paths first when required. Run prepare only after successful setup, with the same application home, and wait for completion before native operations. Follow the selected host's discovery/reload mechanism. Compatible phase-one updates can keep existing connections; reconnect closed or incompatible transports. Confirm the application version, template environment, eleven public Tools and five Skills through that host, including an actual `motion_get_project` call. Registration alone does not prove loading.+4. Choose exactly one setup command below, applying the test isolation paths first when required. Setup starts checked video-component downloads in the background. Do not wait for prepare to connect MCP, create/edit projects or open ordinary preview. Studio shows preparation status and retry; media import, automated capture and export require their respective components. Follow the selected host's discovery/reload mechanism. Compatible phase-one updates can keep existing connections; reconnect closed or incompatible transports. Confirm the application version, template environment, eleven public Tools and five Skills through that host, including an actual `motion_get_project` call. Registration alone does not prove loading.5. Report the result and any failed step. Introduce the available capabilities and wait for the user's next request. Installation does not authorize generating a video or calling a paid model.## Choose the selected host's setup command@@ -23,7 +23,7 @@ The commands below show normal installations. For test candidates, apply the sep| DeepSeek Harness | `npx --yes --package "{{PACKAGE_SPEC}}" openmotion setup --host deepseek --profile PROFILE` | Replace `PROFILE` with the actual selected profile from the host context; do not guess `web` or `desktop`. The standard macOS Desktop CLI is detected even when `dsh` is absent from PATH; use `--dsh` for another executable location. || WorkBuddy | `npx --yes --package "{{PACKAGE_SPEC}}" openmotion setup --host workbuddy` | Preserve the selected `WORKBUDDY_CONFIG_DIR` and Skills root. |-Then prepare the same installation:+Optional: explicitly wait for all video components or retry preparation for the same installation:```shnpx --yes --package "{{PACKAGE_SPEC}}" openmotion prepare@@ -33,7 +33,7 @@ Repeat an explicit `--home` from setup on prepare. Setup installs the selected h## Runtime and environment-Setup copies the checked application into a managed writable directory and installs its locked production npm dependencies. The application and user projects do not run from the temporary npx cache. Prepare or first native use prepares the platform's independent native archives concurrently: browser/FFmpeg/ffprobe separately on macOS, browser/combined media on Windows. It waits for all components and reports a failure if any component fails; successful checked components remain reusable. This is not an offline package.+Setup copies the checked application into a managed writable directory and installs its locked production npm dependencies. The application and user projects do not run from the temporary npx cache. Setup starts a detached preparation worker for the platform's independent native archives concurrently: browser/FFmpeg/ffprobe separately on macOS, browser/combined media on Windows. The local backend and Studio start without waiting. Studio displays per-component download/verification/extraction/checking status and retries failed components. Installers, MCP and Studio join shared cache locks rather than downloading again. An explicit prepare waits for all components and reports failure; successful checked components remain reusable. No export starts automatically after preparation. This is not an offline package.There is no persisted switch-environment command in this version. Internal DEV testing uses its separately configured installation; merely setting an environment variable while running setup does not configure a later desktop Agent. Do not silently fall back from one environment to another.diff --git a/docs/npm-installation.md b/docs/npm-installation.mdindex 6c874752..c0be5e38 100644--- a/docs/npm-installation.md+++ b/docs/npm-installation.md@@ -6,7 +6,7 @@ The npm tgz contains the installer, a prebuilt Motion application archive and it## Requirements and package contents-Users provide Node.js 22.18+ with npm and their Agent host. Builds use the Node version pinned in CI. npm installs locked production dependencies with `npm ci --omit=dev --ignore-scripts`; FFmpeg, ffprobe and the browser are downloaded and checked separately by `prepare` or the first native operation. Node, native binaries, node_modules, user projects and credentials are not bundled in this npm format. It is not an offline package. Complete platform ZIPs remain a backup.+Users provide Node.js 22.18+ with npm and their Agent host. Builds use the Node version pinned in CI. npm installs locked production dependencies with `npm ci --omit=dev --ignore-scripts`. Setup starts FFmpeg, ffprobe and browser preparation in a detached background worker. MCP connection, source editing and ordinary preview do not wait; Studio displays readiness and retry. `prepare` remains an explicit wait/retry command. Node, native binaries, node_modules, user projects and credentials are not bundled in this npm format. It is not an offline package. Complete platform ZIPs remain a backup.The embedded application uses `scripts/distribution.ts`'s positive file list: MCP/backend, prebuilt Studio, five Skills and references, bundled examples, npm/native locks, licenses and approved documentation. Remote Prism templates are fetched separately. The embedded manifest omits the containing tgz's hash; the external delivery manifest records that hash without a circular self-reference.@@ -38,7 +38,7 @@ cd "$motion_test/workspace" &&codex```-Run `prepare` only after successful setup. Wait for it to finish before starting a native project operation: slow first downloads can exceed the backend startup timeout. The isolated Codex profile may require its own login; do not copy credentials into the package.+The acceptance recipe explicitly waits with `prepare` after setup. Ordinary installation can continue immediately: the backend starts without native-download waits, and Studio reports preparation. Media import, automated screenshots and export check the required components before starting. The isolated Codex profile may require its own login; do not copy credentials into the package.Equivalent Windows PowerShell commands:@@ -84,7 +84,7 @@ There is no automatic fallback from prod to DEV and no `switch-env` CLI. This seSelect `--host codex|claude|deepseek|workbuddy`. `--skills-dir` selects the Codex/Claude/WorkBuddy root; Harness uses its own provider. Executable overrides are `--codex`, `--claude`, `--dsh`; Harness also accepts `--profile`. Isolate host configuration with `CODEX_HOME`, `CLAUDE_CONFIG_DIR`, `DSH_HOME` or `WORKBUDDY_CONFIG_DIR`; `--home` controls the application installation, not the host profile.-Use the same installation flow for every host: collect the platform and Node/npm facts once, select the current Agent, run its setup adapter, prepare the same home, then verify actual host loading. An explicit `--host` takes precedence over host context; do not choose a host merely because its CLI is installed. The CLI retains its Codex default for compatibility, so Agent-driven installs should always pass `--host`. Only ask for the missing host/profile when reliable context is unavailable. `openmotion --help`, `setup --help`, `prepare --help` and `--version` work without installing or modifying configuration.+Use the same installation flow for every host: collect the platform and Node/npm facts once, select the current Agent, run its setup adapter, then verify actual host loading while video components prepare in the background. An explicit `--host` takes precedence over host context; do not choose a host merely because its CLI is installed. The CLI retains its Codex default for compatibility, so Agent-driven installs should always pass `--host`. Only ask for the missing host/profile when reliable context is unavailable. `openmotion --help`, `setup --help`, `prepare --help` and `--version` work without installing or modifying configuration.For a non-Codex test, keep the isolated application/data paths from the examples above and change only the host-specific configuration:@@ -97,7 +97,7 @@ For a non-Codex test, keep the isolated application/data paths from the examplesHarness callers should pass the actual current profile from their host context, such as `DSH_PROFILE`, rather than assuming `web` or `desktop`. On macOS, setup already detects the standard Desktop CLI at `/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh`; it need not be on PATH. Keep that host-specific lookup in the Harness adapter. Other executable locations use `--dsh`; do not unpack the host or invent a wrapper for ordinary installation.-After prepare, use each host's supported discovery/reload action to load the Tools and Skills. Confirm all eleven public Tools and five Skills, and call `motion_get_project` to verify the expected data directory. Do not impose another host's restart or refresh procedure, or substitute an on-disk registration for host loading evidence.+After setup, use each host's supported discovery/reload action to load the Tools and Skills. Confirm all eleven public Tools and five Skills, and call `motion_get_project` to verify the expected data directory. Do not impose another host's restart or refresh procedure, or substitute an on-disk registration for host loading evidence.The internal ownership marker remains stable across the npm package rename so earlier local installations can be upgraded in place. An installation can serve multiple hosts using the same home/data. `install.json.hosts` retains each host. Skill documentation links are rewritten for flat layouts; Codex/Harness retain bundle-relative links. Re-run setup for each installed host when upgrading Skills. Unowned same-name MCP/Skills are refused. Unrelated settings/Skills and existing projects are retained. Registration failure restores the prior install state and Skills; checked application caches remain available for retry.@@ -109,13 +109,13 @@ Explicit builds accept `MAJOR.MINOR.PATCH-test.N[.N]` or `MAJOR.MINOR.PATCH`. CISource package manifests remain `private:true`. Only an explicitly versioned **prod** build produces publishable tgz metadata. test artifacts default to the `test` npm tag; stable artifacts default to `stage` so a later authorized registry smoke can precede moving `latest`. Local/default and DEV artifacts remain private. No command here publishes or changes npm tags. See [test and stable acceptance](release-guide.md) for separate maintainer authorization and gates.-After publication, the intended user entry is `npx --yes --package @openmotion/app@<exact-version> -- openmotion setup --host codex`, followed by `prepare` and host discovery/reload for a new installation. `@test` and `@latest` select channels; acceptance always records the exact resolved version. Installing/running npx alone, publishing a new package or moving a tag does not update an existing managed app.+After publication, the intended user entry is `npx --yes --package @openmotion/app@<exact-version> -- openmotion setup --host codex`, followed by host discovery/reload; `prepare` is optional when an explicit wait or retry is needed. `@test` and `@latest` select channels; acceptance always records the exact resolved version. Installing/running npx alone, publishing a new package or moving a tag does not update an existing managed app.-Before upgrading, back up projects/configuration, run setup with the new exact tgz and the **same** home/data/Skills paths, then prepare. Compatible phase-one connections and active exports can continue. Refresh host discovery for new Tools or Skills; reconnect a closed transport. For an incompatible protocol, finish active exports before updating only the owned connection and idle backend together. Do not terminate unrelated services. Older app directories may remain, but rollback requires a compatible old package and data; back up before an irreversible format change. There is no automatic update or arbitrary-version rollback promise.+Before upgrading, back up projects/configuration, run setup with the new exact tgz and the **same** home/data/Skills paths, then reconnect while preparation runs (or explicitly wait with prepare). Compatible phase-one connections and active exports can continue. Refresh host discovery for new Tools or Skills; reconnect a closed transport. For an incompatible protocol, finish active exports before updating only the owned connection and idle backend together. Do not terminate unrelated services. Older app directories may remain, but rollback requires a compatible old package and data; back up before an irreversible format change. There is no automatic update or arbitrary-version rollback promise.## Native tools and diagnostics-The runtime lock pins HTTPS URLs, versions, target OS/CPU and SHA256 for FFmpeg, ffprobe and Chrome for Testing. Downloads require no repository credentials, never attach repository tokens, and do not run brew/winget. Independent archives are prepared concurrently from the existing platform manifest: three separate components on macOS, browser and combined media on Windows. Preparation settles every component before returning; any failure rejects the operation while completed components remain reusable. Separate component locks, temporary extraction and completion markers retain retry/cache protection. A failed download is not ready. Explicit native path overrides remain supported. See [runtime details](test-packages.md).+The runtime lock pins HTTPS URLs, versions, target OS/CPU and SHA256 for FFmpeg, ffprobe and Chrome for Testing. Downloads require no repository credentials, never attach repository tokens, and do not run brew/winget. Independent archives are prepared concurrently from the existing platform manifest: three separate components on macOS, browser and combined media on Windows. Explicit `prepare` settles every component before returning; any failure rejects the operation while completed components remain reusable. Component and archive cache locks coalesce requests across processes and app versions sharing the same platform/hash cache. Contenders wait; dead-owner locks can be recovered without deleting live locks. Atomic per-component state supports Studio reloads and failure retry. Completed components are reused, including after another component fails. Temporary extraction and completion markers retain retry/cache protection. Downloads interrupted mid-transfer restart that asset; HTTP range resume is not implemented. A failed download is not ready. Explicit native path overrides remain supported. See [runtime details](test-packages.md).A local `--manifest /absolute/release-npm.json` remains available for legacy delivery and controlled fixtures. HTTP, URL credentials, unsafe extraction paths and invalid hashes are rejected. Do not remove a leftover install lock until its owning process is confirmed stopped.diff --git a/docs/product/architecture.md b/docs/product/architecture.mdindex 82d30ea4..b5ac227d 100644--- a/docs/product/architecture.md+++ b/docs/product/architecture.md@@ -188,7 +188,7 @@ The following product measures still require agreed observation windows and vali## Application npm distribution-The `@openmotion/app` npm tgz contains installer scripts, the prebuilt application archive and its pinned default manifest. Setup needs only that tgz, stages the checked application into a managed writable directory, installs production npm dependencies from its lock and registers the selected host's eleven MCP Tools and five Skills. It never runs the app or writes projects in the npx cache. Node/Agent remain user-provided; FFmpeg, ffprobe and the browser are checked downloads, deferred until prepare or native use. Existing plugin and complete platform ZIP channels remain available.+The `@openmotion/app` npm tgz contains installer scripts, the prebuilt application archive and its pinned default manifest. Setup needs only that tgz, stages the checked application into a managed writable directory, installs production npm dependencies from its lock and registers the selected host's eleven MCP Tools and five Skills. The application server and projects never run in the npx cache. Node/Agent remain user-provided. After successful setup, a detached worker prepares pinned FFmpeg, ffprobe and browser assets concurrently. MCP and the local editor backend start without waiting for native downloads. Installers and running apps share platform/hash cache locks and atomic component status; Studio polls readiness, shows progress and failure retry, and updates export availability without reloading. Media import checks the media components before applying work; automated capture and export require the full local runtime because captured compositions may contain media. Selected Studio imports are retained in memory for explicit retry in the same project; preparation does not create or replay exports. Explicit prepare remains a blocking wait/retry, completed assets are reused across app versions sharing the cache, and interrupted transfers restart only the incomplete asset. Existing plugin and complete platform ZIP channels remain available.Explicit test/stable prod builds produce publishable artifact metadata with test/stage defaults; the source manifests and local/DEV artifacts stay private. Packaging does not publish, update users, move main or rename the repository. DEV packages embed their template source, default to a separate installation home and refuse cross-environment reuse. Application, project data, host configuration and dependency cache retain distinct ownership. See [installation](../npm-installation.md) and [test/stable acceptance](../release-guide.md).diff --git a/mcp-tools.ts b/mcp-tools.tsindex 4b770d23..58468b68 100644--- a/mcp-tools.ts+++ b/mcp-tools.ts@@ -165,7 +165,7 @@ export async function callTool(name: string, args: Record<string, unknown> = {},if (name === 'motion_inspect_project') {if (!(await store.get()).project) throw new Error('请先调用 motion_open_preview 创建工程');if (typeof args.view !== 'string' || !['info', 'timeline', 'lint'].includes(args.view)) throw new Error('view 必须为 info、timeline 或 lint');- return inspectProject(await ensureRuntime(store.directory), store.projectDirectory, args.view);+ return inspectProject(await ensureRuntime(store.directory, false), store.projectDirectory, args.view);}if (name === 'motion_get_export') {if (args.jobId !== undefined && typeof args.jobId !== 'string') throw new Error('导出任务编号无效');diff --git a/mcp.ts b/mcp.tsindex fc25f93c..4c7e0c47 100644--- a/mcp.ts+++ b/mcp.ts@@ -82,7 +82,7 @@ async function invokeRpc(message: any, store: WorkspaceStore, registry: ReturnTyconst response = await fetch(origin + '/motion-api/phase1/call', { method: 'POST', headers: await editorHeaders(store, origin),body: JSON.stringify({ name, arguments: args }), signal: AbortSignal.timeout(600_000) });const value = await response.json();- if (!response.ok) throw new Error(value.error || 'Tool failed');+ if (!response.ok) throw Object.assign(new Error(value.error || 'Tool failed'), { code: value.code, details: value.runtime });if (value.projectId && value.sessionId) selections.set(store, { projectId: value.projectId, sessionId: value.sessionId });return result({ content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value });}@@ -96,10 +96,10 @@ async function invokeRpc(message: any, store: WorkspaceStore, registry: ReturnTy} catch (error) {const message = error instanceof Error ? error.message : 'Tool failed';const code = (error as any).code || /^([A-Z][A-Z_]+):?/.exec(message)?.[1] || 'TOOL_FAILED';- const runtimeFailure = ['MCP_RUNTIME_RELOAD_REQUIRED', 'EDITOR_RUNTIME_INCOMPATIBLE'].includes(code);+ const runtimeFailure = ['MCP_RUNTIME_RELOAD_REQUIRED', 'EDITOR_RUNTIME_INCOMPATIBLE', 'NATIVE_RUNTIME_NOT_READY'].includes(code);return result({ isError: true, content: [{ type: 'text', text: message }], structuredContent: { error: { code, message,...(runtimeFailure && (error as any).details ? { details: (error as any).details } : {}),- applied: runtimeFailure || /^(INVALID_|VERSION_CONFLICT|PROJECT_NOT_|PROJECT_SESSION_|REQUEST_ID_CONFLICT|MCP_TOOL_NOT_EXPOSED|EXPORT_NOT_|TEMPLATE_NOT_)/.test(code) ? false : 'unknown' } } });+ applied: runtimeFailure || /^(NATIVE_RUNTIME_NOT_READY|INVALID_|VERSION_CONFLICT|PROJECT_NOT_|PROJECT_SESSION_|REQUEST_ID_CONFLICT|MCP_TOOL_NOT_EXPOSED|EXPORT_NOT_|TEMPLATE_NOT_)/.test(code) ? false : 'unknown' } } });}}return { jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } };diff --git a/phase1.ts b/phase1.tsindex 26e5f297..c54c8ba5 100644--- a/phase1.ts+++ b/phase1.ts@@ -1,3 +1,4 @@+import { requireNativeRuntime } from './scripts/npm-runtime.mjs';import { createHash } from 'node:crypto';import { constants } from 'node:fs';import { copyFile, lstat, mkdir, open, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';@@ -6,7 +7,7 @@ import { WorkspaceStore, createBlankProject, projectPath, validateProjectTitle }import { templateCatalogFor } from './prism-templates.ts';import { isEditableTemplate } from './shared/catalog.ts';import { getTemplate } from './template-catalog.ts';-import { execute, inspectProject } from './hyperframes.ts';+import { execute, inspectProject, pluginRoot } from './hyperframes.ts';import { verificationBinaries } from './scripts/verify-export.ts';import { validateInstruction } from './shared/conversation.ts';import { sessionPath } from './shared/workspace-url.ts';@@ -134,6 +135,8 @@ export class Phase1Service {}throw new Error('REQUEST_STATE_UNKNOWN: 原请求未确认终态,未重复执行;请查询项目或任务状态');}+ if (name === 'motion_import_assets') await requireNativeRuntime(pluginRoot, 'media');+ if (name === 'motion_export_request' && args.action !== 'record_review') await requireNativeRuntime(pluginRoot, 'export');const record = { inputHash, name, state: 'pending', projectId: name === 'motion_create_project' ? crypto.randomUUID() : args.projectId,sessionId: args.sessionId ?? crypto.randomUUID(), createdAt: Date.now() };await atomicJson(file, record);diff --git a/scripts/npm-installer.mjs b/scripts/npm-installer.mjsindex 20949941..02841d2a 100644--- a/scripts/npm-installer.mjs+++ b/scripts/npm-installer.mjs@@ -7,7 +7,7 @@ import { realpathSync } from 'node:fs';import { fileURLToPath, pathToFileURL } from 'node:url';import { parseArgs } from 'node:util';import { canonical, extractArchive, nativeComponents, obtainAsset, readJSON, relativePath, runFile, withLock, writeAtomic, writeJSON } from './runtime-assets.mjs';-import { ensureNativeRuntime } from './npm-runtime.mjs';+import { ensureNativeRuntime, startNativePreparation } from './npm-runtime.mjs';import { hosts, hostPlan, skillTargets, obsoleteSkills, checkSkillOwner, copyHostSkills } from './npm-hosts.mjs';// Keep ownership stable so earlier local installations remain upgradable.@@ -32,7 +32,8 @@ Setup options:--profile NAME Harness profile (default: web); use the selected host profile--manifest FILE Explicit release manifest for controlled local installations-Run prepare after successful setup and wait before native project operations.+Setup starts native preparation in the background; editing does not wait for it.+Use prepare to wait explicitly for every video component or retry failed preparation.Refresh the selected host's Tools/Skills; registration alone does not prove loading.Use separate host configuration, home, data and Skills paths for test candidates.-h, --help Show this help without installing or changing configuration@@ -133,7 +134,8 @@ export async function setup(options) {await writeJSON(stateFile, state); wroteState = true;await plan.register();for (const item of directories) await rm(item.backup, { recursive: true, force: true }).catch(error => console.error('Old instruction backup retained: ' + error.message));- return { ...state, host: plan.host, hostInstallation: plan.metadata, nativeDependencies: 'deferred-until-native-operation-or-prepare' };+ await startNativePreparation(appRoot).catch(error => console.error('OpenMotion: background preparation could not start; retry in Studio or run prepare. ' + error.message));+ return { ...state, host: plan.host, hostInstallation: plan.metadata, nativeDependencies: 'background-preparation; status and retry available in Studio' };} catch (error) {if (wroteLauncher && !previous) await rm(launcher, { force: true });if (wroteState) { if (previous) await writeJSON(stateFile, previous); else await rm(stateFile, { force: true }); }diff --git a/scripts/npm-runtime.mjs b/scripts/npm-runtime.mjsindex 69fb832a..ec6673c3 100644--- a/scripts/npm-runtime.mjs+++ b/scripts/npm-runtime.mjs@@ -1,8 +1,10 @@import assert from 'node:assert/strict';-import { mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises';+import { mkdir, mkdtemp, open, rename, rm, writeFile } from 'node:fs/promises';import path from 'node:path';import os from 'node:os';-import { executable, extractArchive, nativeComponents, obtainAsset, readJSON, relativePath, runFile, withLock } from './runtime-assets.mjs';+import { spawn } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { executable, extractArchive, nativeComponents, obtainAsset, readJSON, relativePath, runFile, withCacheLock, writeJSON, processAlive } from './runtime-assets.mjs';export async function nativeConfiguration(root) {const config = await readJSON(path.join(root, '.npm-install.json'));@@ -35,35 +37,77 @@ export async function configureNativeEnvironment(root) {return native;}-export async function ensureNativeRuntime(root) {+const componentKeys = { browser: ['HYPERFRAMES_BROWSER_PATH'], media: ['HYPERFRAMES_FFMPEG_PATH', 'HYPERFRAMES_FFPROBE_PATH'], ffmpeg: ['HYPERFRAMES_FFMPEG_PATH'], ffprobe: ['HYPERFRAMES_FFPROBE_PATH'] };+const preparing = new Map();+const launching = new Map();+const location = (native, component) => path.join(native.cache, component + '-' + native.info[component].sha256);+const overridden = (native, key) => process.env[key] && process.env[key] !== native.paths[key];+async function ready(native, component) {+ const keys = componentKeys[component];+ if (!keys.every(key => overridden(native, key)) && (await readJSON(path.join(location(native, component), 'ready.json')))?.sha256 !== native.info[component].sha256) return false;+ try {+ for (const key of keys) {+ await executable(overridden(native, key) ? process.env[key] : native.paths[key]);+ if (overridden(native, key)) await runFile(process.env[key], [key.includes('BROWSER') ? '--version' : '-version'], { timeout: 5000 });+ }+ return true;+ } catch { return false; }+}++export async function nativeRuntimeStatus(root) {const native = await configureNativeEnvironment(root);- if (!native) return;- const { config, info, cache, components, paths } = native;- const overrides = Object.fromEntries(Object.entries(paths).filter(([key, value]) => process.env[key] !== value));- for (const key of Object.keys(overrides)) await executable(process.env[key]);- const componentKeys = { browser: ['HYPERFRAMES_BROWSER_PATH'], media: ['HYPERFRAMES_FFMPEG_PATH', 'HYPERFRAMES_FFPROBE_PATH'], ffmpeg: ['HYPERFRAMES_FFMPEG_PATH'], ffprobe: ['HYPERFRAMES_FFPROBE_PATH'] };- const prepared = await Promise.allSettled(components.map(async component => {- const keys = componentKeys[component];- if (keys.every(key => Object.hasOwn(overrides, key))) return;- const asset = info[component];- assert(/^[a-f0-9]{64}$/.test(asset.sha256), 'Require a pinned native SHA256');- if (process.platform === 'darwin') assert(Number(os.release().split('.')[0]) >= 25, 'Pinned native downloads require macOS 26 or later; supply compatible media and browser paths on older systems.');- if (process.platform === 'win32') assert(Number(os.release().split('.')[2]) >= 22000, 'Pinned native runtime requires Windows 11 or later');- const destination = path.join(cache, component + '-' + asset.sha256);- const ready = async () => {- if ((await readJSON(path.join(destination, 'ready.json')))?.sha256 !== asset.sha256) return false;- try { for (const key of keys) await executable(paths[key]); return true; } catch { return false; }+ if (!native) return { managed: false, components: [], capabilities: { capture: true, media: true, export: true } };+ const components = await Promise.all(native.components.map(async id => {+ try {+ if (await ready(native, id)) return { id, stage: 'ready' };+ const destination = location(native, id), state = await readJSON(destination + '.status.json');+ const owner = await readJSON(destination + '.lock');+ const pid = typeof owner === 'number' ? owner : owner?.pid;+ if (processAlive(pid)) return { id, ...(state?.pid === pid && !['ready', 'failed'].includes(state.stage) ? state : { stage: 'waiting' }) };+ if (state?.stage === 'failed') return { id, stage: 'failed', error: state.error, errorCode: state.errorCode };+ return { id, stage: 'idle' };+ } catch (error) {+ return { id, stage: 'failed', errorCode: ['EACCES', 'EPERM'].includes(error.code) ? 'permission' : 'checking', error: String(error.message).slice(0, 1000) };+ }+ }));+ const available = ids => components.filter(component => ids.includes(component.id)).every(component => component.stage === 'ready');+ return { managed: true, components, capabilities: { capture: available(native.components), media: available(['media', 'ffmpeg', 'ffprobe']), export: available(native.components) } };+}++async function prepareComponent(native, component) {+ const destination = location(native, component);+ if (preparing.has(destination)) return preparing.get(destination);+ if (await ready(native, component)) return;+ if (preparing.has(destination)) return preparing.get(destination);+ const task = withCacheLock(destination + '.lock', async () => {+ if (await ready(native, component)) return;+ let state = { pid: process.pid, stage: 'waiting' }, lastProgress = 0;+ const update = async change => {+ if (change.stage === 'downloading' && state.stage === 'downloading' && change.receivedBytes !== undefined && state.receivedBytes !== undefined && Date.now() - lastProgress < 500) return;+ lastProgress = Date.now(); state = { ...state, ...change, updatedAt: Date.now() };+ await writeJSON(destination + '.status.json', state);};- if (await ready()) return;- await withLock(destination + '.lock', async () => {- if (await ready()) return;- console.error(`OpenMotion: downloading pinned ${component}; this first use needs network access.`);+ try {+ await update({ stage: 'waiting' });+ const { config, info, paths, cache } = native, keys = componentKeys[component];+ for (const key of keys.filter(key => overridden(native, key))) {+ await executable(process.env[key]);+ await runFile(process.env[key], [key.includes('BROWSER') ? '--version' : '-version']);+ }+ if (await ready(native, component)) return;+ const asset = info[component];+ if (process.platform === 'darwin') assert(Number(os.release().split('.')[0]) >= 25, 'Pinned native downloads require macOS 26 or later; supply compatible media and browser paths on older systems.');+ if (process.platform === 'win32') assert(Number(os.release().split('.')[2]) >= 22000, 'Pinned native runtime requires Windows 11 or later');+ console.error(`OpenMotion: preparing pinned ${component} in the background.`);const archive = path.join(config.cacheDirectory, 'downloads', asset.sha256 + (new URL(asset.url).pathname.endsWith('.zip') ? '.zip' : '.tar.gz'));- await obtainAsset(asset, archive, config.allowLocalAssets === true);+ await update({ stage: 'downloading' });+ await obtainAsset(asset, archive, config.allowLocalAssets === true, update);+ await update({ stage: 'extracting' });await mkdir(cache, { recursive: true });const temporary = await mkdtemp(path.join(cache, component + '-'));try {await extractArchive(archive, temporary);+ await update({ stage: 'checking' });for (const key of keys) {const filename = path.join(temporary, path.relative(destination, paths[key]));if (process.platform === 'win32') assert(filename.length < 260, 'Native tool path is too long; choose a shorter --home directory');@@ -74,9 +118,58 @@ export async function ensureNativeRuntime(root) {await rm(destination, { recursive: true, force: true });await rename(temporary, destination);} finally { await rm(temporary, { recursive: true, force: true }); }- });- }));+ await update({ stage: 'ready' });+ } catch (error) {+ const errorCode = /SHA256/.test(error.message) ? 'integrity' : error.code === 'ENOSPC' ? 'disk_space' : ['EACCES', 'EPERM'].includes(error.code) ? 'permission' : /requires? (?:macOS|Windows)/i.test(error.message) ? 'platform' : state.stage === 'downloading' ? 'download' : 'checking';+ await update({ stage: 'failed', errorCode, error: String(error.message).slice(0, 1000) });+ throw error;+ }+ });+ preparing.set(destination, task);+ try { return await task; } finally { preparing.delete(destination); }+}++export async function ensureNativeRuntime(root, components) {+ const native = await configureNativeEnvironment(root);+ if (!native) return;+ const selected = components ?? native.components;+ assert(selected.every(component => native.components.includes(component)), 'Unknown native component');+ const prepared = await Promise.allSettled(selected.map(component => prepareComponent(native, component)));const failed = prepared.find(result => result.status === 'rejected');if (failed) throw failed.reason;- for (const [key] of Object.entries(overrides)) await runFile(process.env[key], [key.includes('BROWSER') ? '--version' : '-version']);+}++export async function startNativePreparation(root, retry = false) {+ if (launching.has(root)) return launching.get(root);+ const task = (async () => {+ const status = await nativeRuntimeStatus(root);+ const components = status.components.filter(component => component.stage === 'idle' || retry && component.stage === 'failed').map(component => component.id);+ if (!components.length) return status;+ const native = await nativeConfiguration(root);+ await mkdir(native.cache, { recursive: true });+ const log = await open(path.join(native.cache, 'preparation.log'), 'a', 0o600);+ try {+ const child = spawn(process.execPath, [path.join(root, 'scripts/npm-runtime.mjs'), root, ...components], {+ detached: true, stdio: ['ignore', log.fd, log.fd], env: process.env, windowsHide: true,+ });+ await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); });+ child.unref();+ } finally { await log.close(); }+ return status;+ })();+ launching.set(root, task);+ try { return await task; } finally { launching.delete(root); }+}++export async function requireNativeRuntime(root, capability) {+ assert(['capture', 'media', 'export'].includes(capability), 'Unknown native capability');+ const status = await nativeRuntimeStatus(root);+ if (!status.managed || status.capabilities[capability]) return;+ await startNativePreparation(root);+ throw Object.assign(new Error('NATIVE_RUNTIME_NOT_READY: Video components are preparing or need retry. Continue editing; check Studio preparation status or run openmotion prepare for this installation, then retry this operation.'),+ { code: 'NATIVE_RUNTIME_NOT_READY', details: status });+}++if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ ensureNativeRuntime(process.argv[2], process.argv.length > 3 ? process.argv.slice(3) : undefined).catch(error => { console.error(error.message); process.exitCode = 1; });}diff --git a/scripts/runtime-assets.mjs b/scripts/runtime-assets.mjsindex 35462e57..ebf48378 100644--- a/scripts/runtime-assets.mjs+++ b/scripts/runtime-assets.mjs@@ -1,7 +1,7 @@import assert from 'node:assert/strict';import { createHash, randomUUID } from 'node:crypto';import { createReadStream, createWriteStream, constants } from 'node:fs';-import { access, copyFile, mkdir, open, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';+import { access, copyFile, link, mkdir, open, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';import { spawn } from 'node:child_process';import { fileURLToPath } from 'node:url';import path from 'node:path';@@ -13,7 +13,7 @@ export async function sha256(filename) {for await (const chunk of createReadStream(filename)) hash.update(chunk);return hash.digest('hex');}-export async function download(asset, filename) {+export async function download(asset, filename, progress = async () => {}) {const url = new URL(asset.url);assert(url.protocol === 'https:' && /^[a-f0-9]{64}$/.test(asset.sha256), 'Require HTTPS and a pinned SHA256');try { if (await sha256(filename) === asset.sha256) return; } catch (error) { if (error.code !== 'ENOENT') throw error; }@@ -32,7 +32,18 @@ export async function download(asset, filename) {current = new URL(location, current);}assert(response.ok && response.body, `Download ${url.hostname}${url.pathname}: HTTP ${response.status}`);- await pipeline(Readable.fromWeb(response.body), createWriteStream(temporary));+ let receivedBytes = 0;+ const encoding = response.headers.get('content-encoding');+ const totalBytes = !encoding || encoding === 'identity' ? Number(response.headers.get('content-length')) || undefined : undefined;+ async function* measured(source) {+ for await (const chunk of source) {+ receivedBytes += chunk.length;+ await progress({ stage: 'downloading', receivedBytes, totalBytes });+ yield chunk;+ }+ }+ await pipeline(Readable.fromWeb(response.body), measured, createWriteStream(temporary));+ await progress({ stage: 'verifying' });assert.equal(await sha256(temporary), asset.sha256, `SHA256 mismatch: ${url.pathname}`);await rename(temporary, filename);} finally { await rm(temporary, { force: true }); }@@ -77,10 +88,43 @@ export async function withLock(filename, work) {finally { await handle.close(); await rm(filename, { force: true }); }}-export async function obtainAsset(asset, filename, allowLocal = false) {+export function processAlive(pid) {+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;+ try { process.kill(pid, 0); return true; } catch (error) { return error.code !== 'ESRCH'; }+}++// Native caches are shared by installers and running apps; contenders join the owner.+export async function withCacheLock(filename, work) {+ await mkdir(path.dirname(filename), { recursive: true });+ const token = randomUUID(), candidate = filename + '.' + token;+ await writeFile(candidate, JSON.stringify({ pid: process.pid, token }), { mode: 0o600 });+ const deadline = Date.now() + 15 * 60_000;+ try {+ for (;;) {+ try { await link(candidate, filename); break; }+ catch (error) { if (error.code !== 'EEXIST') throw error; }+ const owner = await readJSON(filename);+ const pid = typeof owner === 'number' ? owner : owner?.pid;+ if (pid && !processAlive(pid)) {+ await withCacheLock(filename + '.reclaim', async () => {+ if (JSON.stringify(await readJSON(filename)) === JSON.stringify(owner)) await rm(filename, { force: true });+ });+ }+ if (Date.now() > deadline) throw new Error('Timed out waiting for native preparation; no live download lock was removed.');+ await new Promise(resolve => setTimeout(resolve, 100));+ }+ try { return await work(); }+ finally { if ((await readJSON(filename))?.token === token) await rm(filename, { force: true }); }+ } finally { await rm(candidate, { force: true }); }+}++export async function obtainAsset(asset, filename, allowLocal = false, progress) {+ return withCacheLock(filename + '.lock', () => obtainLockedAsset(asset, filename, allowLocal, progress));+}+async function obtainLockedAsset(asset, filename, allowLocal, progress) {assert(/^[a-f0-9]{64}$/.test(asset.sha256), 'Require a pinned SHA256');const url = new URL(asset.url);- if (url.protocol !== 'file:') return download(asset, filename);+ if (url.protocol !== 'file:') return download(asset, filename, progress);assert(allowLocal, 'Local assets require an explicitly supplied local manifest');if (await sha256(filename).catch(error => { if (error.code !== 'ENOENT') throw error; }) === asset.sha256) return;await mkdir(path.dirname(filename), { recursive: true });diff --git a/server.ts b/server.tsindex 0be62bd0..1dc9b833 100644--- a/server.ts+++ b/server.ts@@ -27,10 +27,12 @@ import { recoverProjectTransactions } from './phase1-versions.ts';import { verifyExport } from './scripts/verify-export.ts';import { createAppTracking, closeTracking, saveTrackingPreference, trackingPreference, trackingLocked, type OmTracking } from './shared/tracking.ts';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';const sharedStore = new WorkspaceStore();-export type Service = { studio?: Studio; runtimeRoot?: 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 = { 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>();@@ -252,6 +254,15 @@ 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 && url.pathname === '/api/runtime' && ['GET', 'POST'].includes(req.method!)) {+ const root = context.nativeRoot ?? pluginRoot;+ if (req.method === 'POST') {+ const data = await input(req, 1024);+ if (!data || Object.keys(data).length !== 1 || data.retry !== true) return json(res, 400, { error: 'INVALID_RUNTIME_RETRY' });+ await startNativePreparation(root, true);+ }+ return json(res, 200, await nativeRuntimeStatus(root));+ }if (motionRequest && url.pathname === '/api/tracking/preferences' && ['GET', 'PUT'].includes(req.method!)) {const directory = (store.workspaceStore ?? store).directory;if (req.method === 'PUT') {@@ -312,12 +323,15 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store =if (req.method === 'GET' && /^\/connect\/?$/.test(url.pathname)) {res.writeHead(302, { Location: '/?panel=connections&host=' + integrationHost(url.searchParams.get('host')) }); return res.end();}- if (url.pathname === '/api/health' && req.method === 'GET') return json(res, 200, {- service: 'motion-preview', protocol: 2, version: VERSION, dataDirectory: store.directory, mcp: phase1McpCapabilities,- engine: 'hyperframes', engineVersion: HYPERFRAMES_VERSION, editor: 'opendesign-motion', ffmpeg: Boolean(context.ffmpeg),- ready: Boolean(context.runtimeRoot && (!context.studio || context.studio.alive())), editorReady: Boolean(context.studio?.alive()), studioUrl: context.studio?.alive() ? editorUrl : undefined, nativeStudioUrl: context.studio?.url,- ...(context.runtimeRoot ? { hyperframesCli: cliPath(context.runtimeRoot), authoringGuide: path.join(context.runtimeRoot, 'node_modules/hyperframes/dist/skills/hyperframes/SKILL.md') } : {}),- });+ if (url.pathname === '/api/health' && req.method === 'GET') {+ const nativeRuntime = await nativeRuntimeStatus(context.nativeRoot ?? pluginRoot);+ return json(res, 200, {+ service: 'motion-preview', protocol: 2, version: VERSION, dataDirectory: store.directory, mcp: phase1McpCapabilities,+ engine: 'hyperframes', engineVersion: HYPERFRAMES_VERSION, editor: 'opendesign-motion', nativeRuntime, ffmpeg: nativeRuntime.managed ? nativeRuntime.capabilities.media : Boolean(context.ffmpeg),+ ready: Boolean(context.runtimeRoot && (!context.studio || context.studio.alive())), editorReady: Boolean(context.studio?.alive()), studioUrl: context.studio?.alive() ? editorUrl : undefined, nativeStudioUrl: context.studio?.url,+ ...(context.runtimeRoot ? { hyperframesCli: cliPath(context.runtimeRoot), authoringGuide: path.join(context.runtimeRoot, 'node_modules/hyperframes/dist/skills/hyperframes/SKILL.md') } : {}),+ });+ }if (motionRequest && url.pathname === '/api/preview/open' && req.method === 'POST') {await openEditor(store, context);return json(res, 200, { studioUrl: editorUrl, ...(await store.status()) });@@ -439,6 +453,7 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store =}if (url.pathname === '/api/export' && req.method === 'POST') {if (!context.runtimeRoot) return json(res, 503, { error: 'Hyperframes 服务尚未就绪' });+ await requireNativeRuntime(context.nativeRoot ?? pluginRoot, 'export');const data = await input(req); revision(data.expectedRevision);return json(res, 202, { job: await store.requestExport(data.expectedRevision) });}@@ -459,6 +474,8 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store =const scopedProject = url.pathname.match(/^\/api\/projects\/([^/]+)/);if (scopedProject) store.forProject(decodeURIComponent(scopedProject[1]));if (!context.studio?.alive()) return json(res, 503, { error: '编辑服务尚未就绪' });+ const capability = nativeRouteCapability(req.method!, url.pathname);+ if (capability) await requireNativeRuntime(context.nativeRoot ?? pluginRoot, capability);return await proxyStudio(req, res, url, context.studio.url);}if (req.method !== 'GET') return json(res, 405, { error: '不支持此操作' });@@ -466,16 +483,17 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store =return json(res, 404, { error: 'Not found' });} catch (error) {if (res.headersSent) res.destroy();- else json(res, error instanceof Conflict ? 409 : 400, { error: error instanceof Error ? error.message : '操作失败' });+ else json(res, error instanceof Conflict || (error as any).code === 'NATIVE_RUNTIME_NOT_READY' ? 409 : 400, { error: error instanceof Error ? error.message : '操作失败', ...((error as any).code === 'NATIVE_RUNTIME_NOT_READY' ? { code: (error as any).code, applied: false, runtime: (error as any).details } : {}) });}}export async function startServer(store = sharedStore, port = Number(process.env.PORT || 4173), options: { editor?: boolean; editorToken?: string; privateHandler?: (req: IncomingMessage, res: ServerResponse) => Promise<boolean> } = { editor: process.env.MOTION_HEADLESS !== '1' }) {await access(path.join(pluginRoot, 'studio/build/index.html')).catch(() => { throw new Error('编辑器尚未构建,请先运行 npm run build:studio。'); });- const runtimeRoot = await ensureRuntime(store.directory);+ const runtimeRoot = await ensureRuntime(store.directory, false);+ void startNativePreparation(pluginRoot).catch(error => console.error('Native preparation could not start: ' + error.message));await recoverProjectTransactions(store, runtimeRoot);const ffmpeg = await execute(process.env.HYPERFRAMES_FFMPEG_PATH || process.env.FFMPEG_PATH || 'ffmpeg', ['-version'], pluginRoot, 5000).then(r => r.code === 0, () => false);- const context: Service = { runtimeRoot, ffmpeg, studioPort: !port || port === 65535 ? 4174 : port + 1, editorToken: options.editorToken,+ const context: Service = { runtimeRoot, nativeRoot: pluginRoot, ffmpeg, studioPort: !port || port === 65535 ? 4174 : port + 1, editorToken: options.editorToken,tracking: await createAppTracking(store.directory, 'mcp') };context.launchStudio = async (directory, chosenPort) => {if (!process.env.OPENMOTION_EDITOR_LOCK_FD) return startStudio(runtimeRoot, directory, path.join(store.directory, 'studio.log'), chosenPort, store.directory);@@ -513,7 +531,7 @@ export async function startServer(store = sharedStore, port = Number(process.env};const timer = setInterval(tick, 500); tick();return { server, get activeToolCalls() { return context.phase1?.pending ?? 0; }, openProject: async (projectId: string) => openProject(store, context, (await store.get()).revision, { projectId }, store.projectId), get studio() { return context.studio!; }, ensureStudio: context.ensureStudio,- info: async () => ({ previewUrl: `http://127.0.0.1:${(server.address() as any).port}`, studioUrl: context.studio?.url, engine: 'hyperframes', ready: true, editorReady: Boolean(context.studio?.alive()), ffmpeg, revision: (await store.get()).revision, dataDirectory: store.directory, browserOpened: false, authoringGuide: path.join(runtimeRoot, 'node_modules/hyperframes/dist/skills/hyperframes/SKILL.md'), hyperframesCli: cliPath(runtimeRoot) }),+ info: async () => ({ previewUrl: `http://127.0.0.1:${(server.address() as any).port}`, studioUrl: context.studio?.url, engine: 'hyperframes', ready: true, editorReady: Boolean(context.studio?.alive()), ffmpeg, revision: (await store.get()).revision, dataDirectory: store.directory, browserOpened: false, nativeRuntime: await nativeRuntimeStatus(pluginRoot), authoringGuide: path.join(runtimeRoot, 'node_modules/hyperframes/dist/skills/hyperframes/SKILL.md'), hyperframesCli: cliPath(runtimeRoot) }),close: async () => { clearInterval(timer); await context.browser?.close(); await gateway.close(); server.closeAllConnections(); server.close(); await context.studio?.close(); await closeTracking(context.tracking); } };}if (isMain(import.meta.url)) {diff --git a/shared/export-expectation.ts b/shared/export-expectation.tsindex 5a40ce61..defdb3f5 100644--- a/shared/export-expectation.ts+++ b/shared/export-expectation.ts@@ -4,5 +4,5 @@ import type { ExportExpectation } from './export-spec.ts';// Resolve the runtime only when an export is requested. Packaged MCP discovery// must still work before dependencies have been installed in the data directory.export async function exportExpectation(dataDirectory: string, snapshot: string): Promise<ExportExpectation> {- return snapshotExportExpectation(await ensureRuntime(dataDirectory), snapshot);+ return snapshotExportExpectation(await ensureRuntime(dataDirectory, false), snapshot);}diff --git a/shared/native-runtime.ts b/shared/native-runtime.tsnew file mode 100644index 00000000..01e8e568--- /dev/null+++ b/shared/native-runtime.ts@@ -0,0 +1,20 @@+export type NativeStage = 'idle' | 'waiting' | 'downloading' | 'verifying' | 'extracting' | 'checking' | 'ready' | 'failed';+export type NativeComponent = { id: 'browser' | 'media' | 'ffmpeg' | 'ffprobe'; stage: NativeStage; receivedBytes?: number; totalBytes?: number; errorCode?: string; error?: string };+export type NativeRuntimeStatus = { managed: boolean; components: NativeComponent[]; capabilities: { capture: boolean; media: boolean; export: boolean } };++export function parseNativeRuntimeStatus(value: unknown): NativeRuntimeStatus | null {+ const status = value as NativeRuntimeStatus | null;+ if (!status || typeof status.managed !== 'boolean' || !Array.isArray(status.components) || !status.capabilities+ || !['capture', 'media', 'export'].every(key => typeof (status.capabilities as any)[key] === 'boolean')+ || !status.components.every(component => component && ['browser', 'media', 'ffmpeg', 'ffprobe'].includes(component.id)+ && ['idle', 'waiting', 'downloading', 'verifying', 'extracting', 'checking', 'ready', 'failed'].includes(component.stage)+ && [component.receivedBytes, component.totalBytes].every(bytes => bytes === undefined || Number.isFinite(bytes) && bytes >= 0)+ && (component.error === undefined || typeof component.error === 'string'))) return null;+ return status;+}++export function nativeRouteCapability(method: string, pathname: string): 'capture' | 'media' | 'export' | undefined {+ if (method === 'POST' && /^\/api\/projects\/[^/]+\/render$/.test(pathname)) return 'export';+ if (method === 'GET' && /^\/api\/projects\/[^/]+\/thumbnail\//.test(pathname)) return 'capture';+ if (/^\/api\/projects\/[^/]+\/(?:upload|waveform\/|peaks\/|media\/|loudness\/normalize|file-mutations\/freeze-frame)/.test(pathname)) return 'media';+}diff --git a/studio/src/App.tsx b/studio/src/App.tsxindex 5d487740..8d7358fe 100644--- a/studio/src/App.tsx+++ b/studio/src/App.tsx@@ -7,6 +7,7 @@ import { useDismissingTabSetter, useRightPanelIntent } from "./hooks/useRightPanimport { useRenderQueue } from "./components/renders/useRenderQueue";import { usePlayerStore } from "./player";import { StudioOverlays } from "./components/StudioOverlays";+import { NativeRuntimeNotice } from "./components/NativeRuntimeNotice";import { SaveQueuePausedBanner } from "./components/SaveQueuePausedBanner";import { ExternalFileConflictBanner } from "./components/ExternalFileConflictBanner";import { ProjectUnreachableBanner } from "./components/ProjectUnreachableBanner";@@ -522,6 +523,7 @@ export function StudioApp({ readOnlyPreview = false, readOnlyPreviewReason }: StinspectorPanelActive={inspectorPanelActive}onExport={handleExport}/>+ <NativeRuntimeNotice status={renderQueue.ffmpeg} checking={renderQueue.ffmpegChecking} onRetry={renderQueue.recheckFfmpeg} pendingImport={fileManager.pendingImport ? { count: fileManager.pendingImport.files.length, retry: () => { void fileManager.retryPendingImport(); } } : undefined} />{previewPersistence.domEditSaveQueuePaused && !externalFileChanges.blocked && (<SaveQueuePausedBannermessage={previewPersistence.domEditSaveQueuePaused}diff --git a/studio/src/components/NativeRuntimeNotice.test.tsx b/studio/src/components/NativeRuntimeNotice.test.tsxnew file mode 100644index 00000000..35b79b60--- /dev/null+++ b/studio/src/components/NativeRuntimeNotice.test.tsx@@ -0,0 +1,27 @@+// @vitest-environment happy-dom+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { expect, it, vi } from 'vitest';+import { NativeRuntimeNotice, componentProgress } from './NativeRuntimeNotice';+import { I18nProvider } from '../i18n/I18n';+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+it('keeps technical progress collapsed, with retry and readiness without remounting the editor', async () => {+ const host = document.createElement('div'); document.body.append(host);+ const root = createRoot(host), retry = vi.fn();+ const runtime = { managed: true, components: [{ id: 'browser' as const, stage: 'downloading' as const, receivedBytes: 25, totalBytes: 100 }], capabilities: { capture: false, media: true, export: false } };+ const render = (status: any) => act(() => root.render(<I18nProvider initialLocale="zh-CN"><NativeRuntimeNotice status={status} checking={false} onRetry={retry} /></I18nProvider>));+ render({ ok: false, runtime });+ expect(host.textContent).toContain('可继续编辑'); expect(host.textContent).not.toContain('25%');+ await act(async () => { Array.from(host.querySelectorAll('button')).find(button => button.textContent === '查看进度')!.click(); });+ expect(document.body.textContent).toContain('25%');+ render({ ok: false, runtime: { ...runtime, components: [{ id: 'browser', stage: 'failed', error: 'Offline' }] } });+ act(() => Array.from(host.querySelectorAll('button')).find(button => button.textContent === '重试')!.click()); expect(retry).toHaveBeenCalledOnce();+ expect(document.body.textContent).toContain('Offline');+ render({ ok: true, runtime: { ...runtime, capabilities: { capture: true, media: true, export: true } } });+ expect(host.textContent).toBe('');+ act(() => root.unmount()); host.remove();+});+it('does not invent progress or confuse completed transfer with readiness', () => {+ expect(componentProgress({ id: 'browser', stage: 'downloading', receivedBytes: 25 })).toBeNull();+ expect(componentProgress({ id: 'browser', stage: 'checking', receivedBytes: 100, totalBytes: 100 })).toBeNull();+});diff --git a/studio/src/components/NativeRuntimeNotice.tsx b/studio/src/components/NativeRuntimeNotice.tsxnew file mode 100644index 00000000..5aeaaa08--- /dev/null+++ b/studio/src/components/NativeRuntimeNotice.tsx@@ -0,0 +1,52 @@+import type { NativeComponent } from '../../../shared/native-runtime';+import type { FfmpegStatus } from './renders/useFfmpegStatus';+import { useI18n } from '../i18n/I18n';+import { Button, Popover } from './ui';+import { RemixIcon } from '../icons/RemixIcons';++const names = { browser: 'Rendering component', media: 'Media components', ffmpeg: 'Media processing', ffprobe: 'Media inspection' };+const stages = { idle: 'Waiting to prepare', waiting: 'Waiting for shared download', downloading: 'Downloading', verifying: 'Verifying download', extracting: 'Extracting', checking: 'Checking component', ready: 'Ready', failed: 'Preparation failed' };+const reasons: Record<string, string> = { integrity: 'Download verification failed. Retry the download.', disk_space: 'Not enough disk space. Free some space and retry.', permission: 'Cannot write the preparation cache. Check folder permissions.', platform: 'This platform needs compatible video components.', download: 'Download failed. Check your connection and retry.', checking: 'The component could not be prepared. Retry or inspect the details.' };+export function componentProgress(component: NativeComponent): number | null {+ return component.stage === 'downloading' && component.totalBytes && component.receivedBytes !== undefined+ ? Math.min(100, Math.floor(component.receivedBytes / component.totalBytes * 100)) : null;+}++export function NativeRuntimeNotice({ status, checking, onRetry, pendingImport }: { pendingImport?: { count: number; retry: () => void }; status: FfmpegStatus | null; checking: boolean; onRetry: () => void }) {+ const { t } = useI18n();+ const runtime = status?.runtime;+ if (!runtime || status.ok && !status.runtimeUnavailable && !pendingImport) return null;+ const failed = runtime.components.some(component => component.stage === 'failed');+ const retryable = failed || runtime.components.some(component => component.stage === 'idle') || status.runtimeUnavailable;+ const headline = status.runtimeUnavailable ? 'Preparation progress unavailable' : status.ok ? 'Your files are ready to import' : failed ? 'Video features are not ready' : 'Preparing video features';+ return (+ <div data-testid="native-runtime-notice" className="flex min-h-9 shrink-0 items-center justify-between gap-2 border-b border-border-strong bg-surface px-3 py-1 text-step-11 text-text-2">+ <div className="flex min-w-0 items-center gap-2" role="status" aria-live="polite">+ {failed || status.runtimeUnavailable ? <span aria-hidden="true" className="size-1.5 shrink-0 rounded-full bg-warning" /> : status.ok ? null : <RemixIcon name="loader-4-line" size={12} className="shrink-0 animate-spin motion-reduce:animate-none" />}+ <span className="truncate">{t(headline)}</span>+ {!status.ok && <span className="hidden shrink-0 text-text-4 sm:inline">{t('You can keep editing')}</span>}+ </div>+ <div className="flex shrink-0 items-center gap-1">+ {pendingImport && runtime.capabilities.media && !status.runtimeUnavailable && <Button size="sm" variant="secondary" onClick={pendingImport.retry}>{t('Continue import')}</Button>}+ {retryable && <Button size="sm" variant="ghost" disabled={checking} onClick={onRetry}>{t(checking ? 'Checking…' : 'Retry')}</Button>}+ <Popover align="end" aria-label={t('Video preparation')} className="w-72 max-w-[calc(100vw-16px)]" trigger={<Button size="sm" variant="ghost">{t('View progress')}</Button>}>+ <div className="mb-2 flex items-center justify-between gap-3 font-medium">+ <span>{t('Video preparation')}</span>+ <span className="text-text-4">{runtime.components.filter(component => component.stage === 'ready').length}/{runtime.components.length}</span>+ </div>+ <ul>+ {runtime.components.map(component => <li key={component.id} className="border-b border-border-strong py-2 last:border-0">+ <div className="flex items-center justify-between gap-4">+ <span>{t(names[component.id])}</span>+ <span className="text-text-4">{componentProgress(component) !== null ? `${componentProgress(component)}%` : t(stages[component.stage])}</span>+ </div>+ {component.stage === 'failed' && <p className="mt-1 text-warning-ink">{t(reasons[component.errorCode ?? 'checking'] ?? reasons.checking)}</p>}+ </li>)}+ </ul>+ {pendingImport && <p className="mt-2 text-text-4">{t('Files waiting for import: {count}', { count: pendingImport.count })}</p>}+ {runtime.components.some(component => component.error) && <details className="mt-2 text-text-4"><summary className="cursor-pointer">{t('Technical details')}</summary><p className="mt-1 break-all">{runtime.components.filter(component => component.error).map(component => component.error).join('\n')}</p></details>}+ </Popover>+ </div>+ </div>+ );+}diff --git a/studio/src/components/StudioHeader.tsx b/studio/src/components/StudioHeader.tsxindex 7d82ef41..425afe4c 100644--- a/studio/src/components/StudioHeader.tsx+++ b/studio/src/components/StudioHeader.tsx@@ -149,7 +149,7 @@ export const StudioHeader = memo(function StudioHeader({<Tooltiplabel={ffmpegMissing- ? t("FFmpeg is not installed. Opens the Renders panel with the install command.")+ ? renderQueue.ffmpeg?.runtime ? t("Video components are not ready. Check preparation status.") : t("FFmpeg is not installed. Opens the Renders panel with the install command."): isRendering? t("A render is already in progress"): t("Render and export this composition")diff --git a/studio/src/components/renders/RenderQueue.tsx b/studio/src/components/renders/RenderQueue.tsxindex a2ed47d6..2d7c4283 100644--- a/studio/src/components/renders/RenderQueue.tsx+++ b/studio/src/components/renders/RenderQueue.tsx@@ -299,7 +299,7 @@ function FormatExportButton({return (<div className="flex flex-col gap-3">- {missingFfmpeg && (+ {missingFfmpeg && !missingFfmpeg.runtime && (<FfmpegRequiredNoticestatus={missingFfmpeg}checking={ffmpegChecking}@@ -476,7 +476,7 @@ export const RenderQueue = memo(function RenderQueue({role="alert"className="flex items-start justify-between gap-2 px-3 py-2 border-b border-border bg-danger/10">- <span className="text-step-10 text-danger-ink">{actionError}</span>+ <span className="text-step-10 text-danger-ink">{t(actionError)}</span>{onDismissActionError && (<IconButtonsize="sm"diff --git a/studio/src/components/renders/useFfmpegStatus.test.tsx b/studio/src/components/renders/useFfmpegStatus.test.tsxnew file mode 100644index 00000000..1a6f88e5--- /dev/null+++ b/studio/src/components/renders/useFfmpegStatus.test.tsx@@ -0,0 +1,21 @@+// @vitest-environment happy-dom+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, expect, it, vi } from 'vitest';+import { useFfmpegStatus } from './useFfmpegStatus';+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers(); });+it('polls background readiness and restores export without reload or another download request', async () => {+ vi.useFakeTimers();+ let ready = false, result: ReturnType<typeof useFfmpegStatus>;+ const fetch = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => new Response(JSON.stringify({ managed: true, components: [{ id: 'browser', stage: ready ? 'ready' : 'downloading' }], capabilities: { capture: ready, media: true, export: ready } })));+ function View() { result = useFfmpegStatus(); return <span>{String(result.status?.ok)}</span>; }+ const host = document.createElement('div'), root = createRoot(host);+ await act(async () => { root.render(<View />); });+ expect(result!.status?.ok).toBe(false);+ ready = true;+ await act(async () => { await vi.advanceTimersByTimeAsync(1500); });+ expect(result!.status?.ok).toBe(true);+ expect(fetch.mock.calls.every(([, init]) => !init?.method || init.method === 'GET')).toBe(true);+ act(() => root.unmount());+});diff --git a/studio/src/components/renders/useFfmpegStatus.ts b/studio/src/components/renders/useFfmpegStatus.tsindex b25f4976..daf21950 100644--- a/studio/src/components/renders/useFfmpegStatus.ts+++ b/studio/src/components/renders/useFfmpegStatus.ts@@ -1,3 +1,4 @@+import { parseNativeRuntimeStatus, type NativeRuntimeStatus } from '../../../../shared/native-runtime';import { useCallback, useEffect, useRef, useState } from "react";import { studioApiFetch } from "../../utils/studioApiFetch";@@ -9,6 +10,8 @@ import { studioApiFetch } from "../../utils/studioApiFetch";*/export interface FfmpegStatus {ok: boolean;+ runtime?: NativeRuntimeStatus;+ runtimeUnavailable?: boolean;/** Short headline, e.g. "FFmpeg not found". Absent when ok. */title?: string;/** Why it cannot run, in the server's words. Absent when ok. */@@ -59,6 +62,14 @@ function parseStatus(body: unknown): ProbeResult {}async function probe(): Promise<ProbeResult> {+ try {+ const native = await fetch('/motion-api/runtime', { cache: 'no-store' });+ const runtime = native.ok ? parseNativeRuntimeStatus(await native.json()) : null;+ if (runtime?.managed) return { ok: runtime.capabilities.export, runtime };+ if (cached?.runtime) return { ...cached, ok: false, runtimeUnavailable: true };+ } catch {+ if (cached?.runtime) return { ...cached, ok: false, runtimeUnavailable: true };+ }try {const res = await studioApiFetch("/api/environment/ffmpeg");return res.ok ? parseStatus(await res.json()) : null;@@ -70,7 +81,7 @@ async function probe(): Promise<ProbeResult> {export function useFfmpegStatus(): {status: ProbeResult;checking: boolean;- recheck: () => void;+ recheck: (retry?: boolean) => void;} {const [status, setStatus] = useState<ProbeResult>(cached);const [checking, setChecking] = useState(cached === null);@@ -83,8 +94,17 @@ export function useFfmpegStatus(): {};}, []);- const run = useCallback(async () => {+ const run = useCallback(async (retry = false) => {setChecking(true);+ if (retry && cached?.runtime) {+ try {+ const response = await fetch('/motion-api/runtime', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ retry: true }) });+ if (!response.ok) throw new Error('Preparation retry was refused');+ } catch {+ if (mounted.current) { setStatus({ ...cached, ok: false, runtimeUnavailable: true }); setChecking(false); }+ return;+ }+ }const next = await probe();cached = next;if (!mounted.current) return;@@ -93,16 +113,20 @@ export function useFfmpegStatus(): {}, []);useEffect(() => {- if (cached !== null) return;- void run();+ let stopped = false, timer: ReturnType<typeof setTimeout>;+ const tick = async () => {+ await run();+ if (!stopped && cached?.runtime && (!cached.ok || cached.runtimeUnavailable)) timer = setTimeout(tick, 1500);+ };+ void tick();+ const refresh = () => { clearTimeout(timer); void tick(); };+ window.addEventListener('focus', refresh);+ return () => { stopped = true; clearTimeout(timer); window.removeEventListener('focus', refresh); };}, [run]);- // Someone who just installed FFmpeg should not have to restart Studio to- // prove it. Drops the cache so the server re-probes rather than replaying- // the stale "not found" it already cached against.- const recheck = useCallback(() => {- cached = null;- void run();+ // Retry only failed managed components; legacy installations keep their probe.+ const recheck = useCallback((retry = true) => {+ void run(retry);}, [run]);return { status, checking, recheck };diff --git a/studio/src/components/renders/useRenderQueue.ts b/studio/src/components/renders/useRenderQueue.tsindex e17ccdc9..7d500938 100644--- a/studio/src/components/renders/useRenderQueue.ts+++ b/studio/src/components/renders/useRenderQueue.ts@@ -181,6 +181,7 @@ export function useRenderQueue(// the reason and the fix in the message, and keeps a control that// forgot to disable itself from producing a mystery failure.if (ffmpegMissing) {+ if (ffmpeg?.runtime) return;addSessionJob({id: generateId(),@@ -294,6 +295,11 @@ export function useRenderQueue(return;}if (!res.ok) {+ if (res.status === 409 && (await res.clone().json().catch(() => null))?.code === 'NATIVE_RUNTIME_NOT_READY') {+ setActionError('Video components are not ready. Check preparation status.');+ recheckFfmpeg(false);+ return;+ }const failedJob: RenderJob = {id: generateId(),status: "failed",@@ -373,7 +379,7 @@ export function useRenderQueue(return jobId;},- [projectId, activeCompPathRef, closeActiveEventSource, addSessionJob, ffmpeg, ffmpegMissing],+ [projectId, activeCompPathRef, closeActiveEventSource, addSessionJob, ffmpeg, ffmpegMissing, recheckFfmpeg],);// Cancel an in-flight render. The job row stays (as "cancelled") so thediff --git a/studio/src/components/renders/useRenderQueueFfmpegGate.test.tsx b/studio/src/components/renders/useRenderQueueFfmpegGate.test.tsxindex 3bca83c1..8c878e67 100644--- a/studio/src/components/renders/useRenderQueueFfmpegGate.test.tsx+++ b/studio/src/components/renders/useRenderQueueFfmpegGate.test.tsx@@ -77,3 +77,11 @@ describe("useRenderQueue FFmpeg gate", () => {expect(mounted.api().ffmpegMissing).toBe(false);});});++it('does not create a failed render row while managed components are preparing', async () => {+ ffmpegStatus = { ok: false, runtime: { managed: true, components: [{ id: 'browser', stage: 'downloading' }], capabilities: { capture: false, media: true, export: false } } };+ queue = mountRenderQueue(useRenderQueue);+ await queue.api().startRender();+ expect(renderPosts(fetchMock)).toHaveLength(0);+ expect(queue.api().jobs).toHaveLength(0);+});diff --git a/studio/src/contexts/FileManagerContext.tsx b/studio/src/contexts/FileManagerContext.tsxindex b23e4e5d..0626a254 100644--- a/studio/src/contexts/FileManagerContext.tsx+++ b/studio/src/contexts/FileManagerContext.tsx@@ -43,6 +43,8 @@ export function FileManagerProvider({handleContentChange,refreshFileTree,uploadProjectFiles,+ pendingImport,+ retryPendingImport,handleCreateFile,handleCreateFolder,handleDeleteFile,@@ -86,6 +88,8 @@ export function FileManagerProvider({handleContentChange,refreshFileTree,uploadProjectFiles,+ pendingImport,+ retryPendingImport,handleCreateFile,handleCreateFolder,handleDeleteFile,@@ -123,6 +127,8 @@ export function FileManagerProvider({handleContentChange,refreshFileTree,uploadProjectFiles,+ pendingImport,+ retryPendingImport,handleCreateFile,handleCreateFolder,handleDeleteFile,diff --git a/studio/src/hooks/useFileManager.projectOwnership.test.tsx b/studio/src/hooks/useFileManager.projectOwnership.test.tsxindex d3bb75ba..620704a8 100644--- a/studio/src/hooks/useFileManager.projectOwnership.test.tsx+++ b/studio/src/hooks/useFileManager.projectOwnership.test.tsx@@ -50,7 +50,7 @@ async function mountTestFileManager(projectId = "project-a", showToast = vi.fn()await act(async () => root.render(<Probe />));const manager = captured.manager;if (!manager) throw new Error("file manager did not render");- return { manager, root };+ return { get manager() { return captured.manager!; }, root };}async function mountOverwriteRequest(response: Response) {@@ -289,3 +289,20 @@ describe("useFileManager uploads", () => {);});});+++it("retains selected files on native preparation refusal and imports them only on explicit retry", async () => {+ let ready = false;+ const fetch = vi.fn(async () => Response.json(ready ? { ok: true, files: ['clip.mp4'] } : { code: 'NATIVE_RUNTIME_NOT_READY' }, { status: ready ? 201 : 409 }));+ vi.stubGlobal('fetch', fetch);+ const mounted = await mountTestFileManager('project-a'), file = new File(['x'], 'clip.mp4');+ await act(async () => { await mounted.manager.uploadProjectFiles([file]); });+ expect(mounted.manager.pendingImport?.files[0]).toBe(file);+ expect(fetch).toHaveBeenCalledTimes(1);+ ready = true;+ await act(async () => { await mounted.manager.retryPendingImport(); });+ expect(fetch).toHaveBeenCalledTimes(2);+ expect(mounted.manager.pendingImport).toBeNull();+ await act(async () => mounted.root.unmount());+ vi.unstubAllGlobals();+});diff --git a/studio/src/hooks/useFileManager.ts b/studio/src/hooks/useFileManager.tsindex 30a16c00..45435d64 100644--- a/studio/src/hooks/useFileManager.ts+++ b/studio/src/hooks/useFileManager.ts@@ -39,6 +39,7 @@ export function useFileManager({const { t } = useI18n();// ── Shared refs ──+ const [pendingImport, setPendingImport] = useState<{ projectId: string; files: File[]; dir?: string } | null>(null);const [editingFile, setEditingFile] = useState<EditingFile | null>(null);const [revealSourceOffset, setRevealSourceOffset] = useState<number | null>(null);@@ -227,9 +228,13 @@ export function useFileManager({const names = data.unchecked.map((entry: { name: string }) => entry.name).join(", ");showToast(t("Added {name}, {message}", { name: names, message: importValidationMessage(data.unchecked[0].reason, t) }), "info");}+ setPendingImport(previous => previous?.projectId === pid && previous.dir === dir && previous.files.length === fileList.length && previous.files.every((file, index) => file === fileList[index]) ? null : previous);await refreshFileTree();setRefreshKey((k) => k + 1);return Array.isArray(data.files) ? data.files : [];+ } else if (res.status === 409 && (await res.clone().json().catch(() => null))?.code === 'NATIVE_RUNTIME_NOT_READY') {+ if (projectIdRef.current === pid) setPendingImport({ projectId: pid, files: fileList, dir });+ showToast(t('Media components are preparing. Selected files are kept for retry.'), 'info');} else if (res.status === 413) {showToast("Upload rejected: payload too large");} else {@@ -370,6 +375,9 @@ export function useFileManager({const handleMoveFile = handleRenameFile;+ const retryPendingImport = useCallback(() => pendingImport?.projectId === projectIdRef.current+ ? uploadProjectFiles(pendingImport.files, pendingImport.dir) : Promise.resolve([]), [pendingImport, uploadProjectFiles]);+const handleImportFiles = useCallback(async (files: FileList | File[], dir?: string) => {return uploadProjectFiles(Array.from(files), dir);@@ -440,6 +448,8 @@ export function useFileManager({handleContentChange,refreshFileTree,uploadProjectFiles,+ pendingImport: pendingImport?.projectId === projectId ? pendingImport : null,+ retryPendingImport,handleCreateFile,handleCreateFolder,handleDeleteFile,diff --git a/studio/src/i18n/mvp-zh-CN.json b/studio/src/i18n/mvp-zh-CN.jsonindex f2236227..f50b9061 100644--- a/studio/src/i18n/mvp-zh-CN.json+++ b/studio/src/i18n/mvp-zh-CN.json@@ -935,5 +935,35 @@"The project changed during splitting. Refresh the editor and retry.": "分割时工程发生了变化,请刷新编辑器后重试。","Cannot read the latest clip source. Refresh the editor and retry.": "无法读取片段的最新内容,请刷新编辑器后重试。","This clip cannot be split. Select a different clip.": "此片段暂不支持分割,请选择其他片段。",- "Could not split the clip. Check the current clip and retry.": "未能分割片段,请检查当前片段后重试。"+ "Could not split the clip. Check the current clip and retry.": "未能分割片段,请检查当前片段后重试。",+ "Rendering component": "画面渲染",+ "Media components": "素材处理",+ "Media processing": "素材处理",+ "Media inspection": "媒体读取",+ "Waiting to prepare": "待准备",+ "Waiting for shared download": "等待中",+ "Downloading": "下载中",+ "Verifying download": "校验中",+ "Extracting": "解压中",+ "Checking component": "检查中",+ "Ready": "已就绪",+ "Preparation failed": "需重试",+ "Video components are not ready. Check preparation status.": "视频组件尚未就绪,请查看准备状态。",+ "Media components are preparing. Selected files are kept for retry.": "媒体组件正在准备,已保留所选文件,可稍后重试。",+ "Files waiting for import: {count}": "等待导入的文件:{count} 个",+ "Download verification failed. Retry the download.": "下载文件校验失败,请重试下载。",+ "Not enough disk space. Free some space and retry.": "磁盘空间不足,请释放空间后重试。",+ "Cannot write the preparation cache. Check folder permissions.": "无法写入准备目录,请检查目录权限。",+ "This platform needs compatible video components.": "当前系统需要兼容的视频组件。",+ "Download failed. Check your connection and retry.": "下载失败,请检查网络后重试。",+ "The component could not be prepared. Retry or inspect the details.": "组件准备失败,请重试或展开查看详情。",+ "Preparing video features": "正在准备视频功能",+ "Video features are not ready": "视频功能尚未就绪",+ "You can keep editing": "可继续编辑",+ "View progress": "查看进度",+ "Video preparation": "视频功能准备",+ "Technical details": "技术详情",+ "Preparation progress unavailable": "暂时无法获取准备进度",+ "Your files are ready to import": "所选文件可继续导入",+ "Continue import": "继续导入"}diff --git a/tests/native-runtime.test.ts b/tests/native-runtime.test.tsnew file mode 100644index 00000000..09742034--- /dev/null+++ b/tests/native-runtime.test.ts@@ -0,0 +1,157 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { spawn } from 'node:child_process';+import { once } from 'node:events';+import { pathToFileURL, fileURLToPath } from 'node:url';+import { ensureNativeRuntime, nativeConfiguration, nativeRuntimeStatus, requireNativeRuntime, startNativePreparation } from '../scripts/npm-runtime.mjs';+import { runFile, sha256, writeJSON, withCacheLock } from '../scripts/runtime-assets.mjs';+import { nativeRouteCapability } from '../shared/native-runtime.ts';+import { transport } from './http.ts';+import { WorkspaceStore } from '../workspace.ts';++async function fixture(t: any) {+ const directory = await mkdtemp(path.join(tmpdir(), 'motion-native-'));+ t.after(() => rm(directory, { recursive: true, force: true }));+ const keys = ['HYPERFRAMES_BROWSER_PATH', 'HYPERFRAMES_FFMPEG_PATH', 'HYPERFRAMES_FFPROBE_PATH', 'MOTION_BROWSER_PATH', 'FFMPEG_PATH', 'FFPROBE_PATH'];+ const previous = keys.map(key => process.env[key]); keys.forEach(key => delete process.env[key]);+ t.after(() => keys.forEach((key, i) => previous[i] === undefined ? delete process.env[key] : process.env[key] = previous[i]));+ const root = path.join(directory, 'app'); await mkdir(path.join(root, 'scripts'), { recursive: true });+ for (const file of ['npm-runtime.mjs', 'runtime-assets.mjs']) await cp(new URL('../scripts/' + file, import.meta.url), path.join(root, 'scripts', file));+ const assets: Record<string, any> = {};+ for (const id of ['browser', 'ffmpeg', 'ffprobe']) {+ const source = path.join(directory, id); await mkdir(source);+ await writeFile(path.join(source, id), '#!/bin/sh\necho fixture-version\n', { mode: 0o755 });+ const archive = path.join(directory, id + '.tar.gz');+ await runFile('tar', ['-czf', archive, '-C', source, '.']);+ assets[id] = { url: pathToFileURL(archive).href, sha256: await sha256(archive), executable: id };+ }+ const configFile = path.join(root, '.npm-install.json');+ const config = { schemaVersion: 1, cacheDirectory: path.join(directory, 'cache'), allowLocalAssets: true,+ runtime: { targets: { fixture: { platform: process.platform, arch: process.arch, ...assets } } } };+ await writeJSON(configFile, config);+ return { directory, root, assets, config, configFile };+}++test('cold status is readable without downloading, and runtime guards do not create export jobs', { skip: process.platform === 'win32' }, async t => {+ const { directory, root } = await fixture(t);+ const initial = await nativeRuntimeStatus(root);+ assert(initial.components.every(item => item.stage === 'idle')); assert.equal(initial.capabilities.export, false);+ await assert.rejects(readFile(path.join(directory, 'cache/preparation.log')), { code: 'ENOENT' });+ const store = new WorkspaceStore(path.join(directory, 'data'));+ const request = transport(store, { nativeRoot: root, runtimeRoot: root, studio: { alive: () => true } as any });+ const status = await request('/motion-api/runtime'); assert.equal(status.status, 200);+ assert.equal((await status.json()).managed, true);+ assert.equal((await request('/motion-api/runtime', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' })).status, 400);+ const response = await request(`/api/projects/${store.projectId}/render`, { method: 'POST' });+ assert.equal(response.status, 409); assert.equal((await response.json()).applied, false);+ assert.equal(await store.job(), null);+ // Join the detached preparation before fixture cleanup.+ await ensureNativeRuntime(root);+ assert.equal((await nativeRuntimeStatus(root)).capabilities.export, true);+});++test('concurrent processes and app versions share one download per native asset', { skip: process.platform === 'win32', timeout: 20_000 }, async t => {+ const { directory, root, assets, config, configFile } = await fixture(t);+ const bytes: Record<string, string> = {};+ for (const [id, asset] of Object.entries(assets)) {+ bytes[`https://example.invalid/${id}.tar.gz`] = new URL(asset.url).pathname;+ config.runtime.targets.fixture[id].url = `https://example.invalid/${id}.tar.gz`;+ }+ await writeJSON(configFile, config);+ const secondRoot = path.join(directory, 'app-v2'); await mkdir(secondRoot); await cp(configFile, path.join(secondRoot, '.npm-install.json'));+ const counts = path.join(directory, 'fetches');+ const module = pathToFileURL(fileURLToPath(new URL('../scripts/npm-runtime.mjs', import.meta.url))).href;+ const script = `import { appendFile, readFile } from 'node:fs/promises';+ const bytes = ${JSON.stringify(bytes)};+ globalThis.fetch = async url => { await appendFile(${JSON.stringify(counts)}, url.href+'\\n'); await new Promise(r => setTimeout(r, 200)); return new Response(await readFile(bytes[url.href])); };+ const { ensureNativeRuntime } = await import(${JSON.stringify(module)});+ await Promise.all([ensureNativeRuntime(process.argv[1]), ensureNativeRuntime(process.argv[1])]);`;+ await Promise.all([root, secondRoot].map(app => runFile(process.execPath, ['--input-type=module', '-e', script, app])));+ assert.equal((await readFile(counts, 'utf8')).trim().split('\n').length, 3);+ await rm(counts); for (const id of Object.keys(assets)) await rm(path.join(directory, id + '.tar.gz'));+ await Promise.all([ensureNativeRuntime(root), ensureNativeRuntime(secondRoot)]);+ await assert.rejects(readFile(counts), { code: 'ENOENT' });+});++test('one failed component remains visible and retry reuses completed components', { skip: process.platform === 'win32' }, async t => {+ const { root, assets } = await fixture(t);+ const original = await readFile(new URL(assets.browser.url)); await writeFile(new URL(assets.browser.url), 'bad browser');+ await assert.rejects(ensureNativeRuntime(root), /SHA256 mismatch/);+ const failed = await nativeRuntimeStatus(root);+ assert.equal(failed.components.find(item => item.id === 'browser')?.stage, 'failed');+ assert.equal(failed.capabilities.media, true); assert.equal(failed.capabilities.capture, false);+ await requireNativeRuntime(root, 'media');+ const native = await nativeConfiguration(root);+ const ready = await readFile(path.join(native.cache, 'ffmpeg-' + assets.ffmpeg.sha256, 'ready.json'), 'utf8');+ await rm(new URL(assets.ffmpeg.url)); await rm(new URL(assets.ffprobe.url));+ await writeFile(new URL(assets.browser.url), original);+ await startNativePreparation(root, true); await ensureNativeRuntime(root);+ assert.equal((await nativeRuntimeStatus(root)).capabilities.export, true);+ assert.equal(await readFile(path.join(native.cache, 'ffmpeg-' + assets.ffmpeg.sha256, 'ready.json'), 'utf8'), ready);+});++test('dead download ownership is recoverable while a live lock is never stolen', async t => {+ const { directory } = await fixture(t), lock = path.join(directory, 'test.lock');+ await writeJSON(lock, { pid: 2147483647, token: 'dead' });+ let firstDone = false, secondRan = false;+ let second: Promise<unknown>;+ await withCacheLock(lock, async () => {+ second = withCacheLock(lock, async () => { secondRan = true; assert(firstDone); });+ await new Promise(resolve => setTimeout(resolve, 180)); assert.equal(secondRan, false);+ firstDone = true;+ });+ await second!;+});++test('capability routing leaves editing, history and ordinary preview available', () => {+ assert.equal(nativeRouteCapability('POST', '/api/projects/a/render'), 'export');+ assert.equal(nativeRouteCapability('GET', '/api/projects/a/thumbnail/index.html'), 'capture');+ assert.equal(nativeRouteCapability('POST', '/api/projects/a/upload'), 'media');+ assert.equal(nativeRouteCapability('GET', '/api/projects/a/media/metadata'), 'media');+ for (const route of ['/api/projects/a/preview', '/api/projects/a/files/index.html', '/api/projects/a/renders', '/api/projects/a/history']) assert.equal(nativeRouteCapability('GET', route), undefined);+});+++test('interrupted downloads retain truthful progress and recover only the incomplete component', { skip: process.platform === 'win32', timeout: 20_000 }, async t => {+ const { directory, root, assets, config, configFile } = await fixture(t);+ await ensureNativeRuntime(root, ['ffmpeg', 'ffprobe']);+ config.runtime.targets.fixture.browser.url = 'https://example.invalid/interrupted.tar.gz';+ await writeJSON(configFile, config);+ const module = pathToFileURL(fileURLToPath(new URL('../scripts/npm-runtime.mjs', import.meta.url))).href;+ const script = `const hold = setInterval(() => {}, 1000);+ globalThis.fetch = async () => new Response(new ReadableStream({ start(controller) { controller.enqueue(new Uint8Array(50)); } }), { headers: { 'content-length': '100' } });+ const { ensureNativeRuntime } = await import(${JSON.stringify(module)});+ await ensureNativeRuntime(process.argv[1], ['browser']); clearInterval(hold);`;+ const child = spawn(process.execPath, ['--input-type=module', '-e', script, root], { stdio: 'ignore' });+ t.after(() => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); });+ let component;+ for (let i = 0; i < 100; i++) {+ component = (await nativeRuntimeStatus(root)).components.find(item => item.id === 'browser');+ if (component?.receivedBytes === 50) break;+ await new Promise(resolve => setTimeout(resolve, 30));+ }+ assert.equal(component?.stage, 'downloading'); assert.equal(component.receivedBytes, 50); assert.equal(component.totalBytes, 100);+ const exited = once(child, 'exit'); child.kill('SIGKILL'); await exited;+ assert.equal((await nativeRuntimeStatus(root)).components.find(item => item.id === 'browser')?.stage, 'idle');+ config.runtime.targets.fixture.browser.url = pathToFileURL(path.join(directory, 'browser.tar.gz')).href;+ await writeJSON(configFile, config);+ await rm(path.join(directory, 'ffmpeg.tar.gz')); await rm(path.join(directory, 'ffprobe.tar.gz'));+ await ensureNativeRuntime(root);+ assert.equal((await nativeRuntimeStatus(root)).capabilities.export, true);+});+++test('an unreadable component state is reported without blocking basic service health', { skip: process.platform === 'win32' }, async t => {+ const { root, directory, assets } = await fixture(t);+ const native = await nativeConfiguration(root); await mkdir(native.cache, { recursive: true });+ await writeFile(path.join(native.cache, 'browser-' + assets.browser.sha256 + '.status.json'), '{broken');+ const store = new WorkspaceStore(path.join(directory, 'data'));+ const response = await transport(store, { runtimeRoot: root, nativeRoot: root })('/api/health');+ assert.equal(response.status, 200);+ const health = await response.json(); assert.equal(health.ready, true);+ assert.equal(health.nativeRuntime.components.find(item => item.id === 'browser').stage, 'failed');+ assert.equal(health.nativeRuntime.capabilities.export, false);+});diff --git a/tests/npm-installer.test.ts b/tests/npm-installer.test.tsindex e403b2c3..ed034a51 100644--- a/tests/npm-installer.test.ts+++ b/tests/npm-installer.test.ts@@ -144,7 +144,7 @@ test('native preparation runs independent components together for separate and cawait ensureNativeRuntime(root);assert.deepEqual(started.sort(), [...downloads.keys()].sort());const native = await nativeConfiguration(root);- assert.deepEqual((await readdir(native.cache)).sort(), Object.entries(assets).map(([name, asset]: any) => name + '-' + asset.sha256).sort());+ assert.deepEqual((await readdir(native.cache)).filter(name => !name.endsWith('.status.json')).sort(), Object.entries(assets).map(([name, asset]: any) => name + '-' + asset.sha256).sort());});});@@ -196,16 +196,16 @@ test('npm bin symlink executes the CLI instead of silently exiting', { skip: proawait assert.rejects(runFile(process.execPath, [link, 'prepare', '--home', directory]), /Run setup first/);});-test('setup installs complete Skills and MCP without native downloads and preserves repeated-install data', { skip: process.platform === 'win32' }, async t => {+test('setup installs complete Skills and MCP without waiting for native downloads and preserves repeated-install data', { skip: process.platform === 'win32' }, async t => {const options = await setupFixture(t);await mkdir(path.join(options.skillsDirectory, 'unrelated'), { recursive: true });await writeFile(path.join(options.skillsDirectory, 'unrelated/keep.txt'), 'keep');const first = await setup(options);- assert.equal(first.nativeDependencies, 'deferred-until-native-operation-or-prepare');+ assert.equal(first.nativeDependencies, 'background-preparation; status and retry available in Studio');const scope = JSON.parse(await readFile(path.join(options.skillsDirectory, 'openmotion/scope.json'), 'utf8'));assert.equal(scope.runtimeRoot, first.appRoot);assert.match(await readFile(path.join(options.skillsDirectory, 'openmotion/skills/motion-production/SKILL.md'), 'utf8'), /motion-production/);- await assert.rejects(readdir(path.join(options.home, 'cache/native')), { code: 'ENOENT' });+ assert((await readdir(path.join(options.home, 'cache/native/fixture'))).includes('preparation.log'));await mkdir(first.dataDirectory, { recursive: true });await writeFile(path.join(first.dataDirectory, 'keep.txt'), 'user work');assert.equal((await setup(options)).appRoot, first.appRoot);