Skip to content

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

fix(export): recover native preparation timeouts and show download progress

qindong5c330b1f05af
diff --git a/docs/product/architecture.md b/docs/product/architecture.md
index 13ed5786..b76d684f 100644
--- a/docs/product/architecture.md
+++ b/docs/product/architecture.md
@@ -284,7 +284,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. 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 and displays preparation progress and failure retry inside the Export panel. The header Export action opens that panel while dependencies are unavailable; readiness updates 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.
+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 and displays measured download bytes, percentage and a remaining-time estimate when transfer size and speed are available inside the Export panel. Retry stays available during preparation. Downloads use a five-minute inactivity timeout and retry transient failures up to three attempts before reporting the cause; completed components remain reusable. The header Export action opens that panel while dependencies are unavailable; readiness updates 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/DEV and stable/prod builds produce publishable artifact metadata with candidate/stage defaults; source manifests, unversioned builds and channel/environment mismatches stay private. New public test versions use DEV template routing; catalog access still depends on service network/authentication. No private catalog payloads or credentials are bundled. Existing versions retain their original defaults. 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/scripts/npm-runtime.mjs b/scripts/npm-runtime.mjs
index d1c75f41..2f59fdc3 100644
--- a/scripts/npm-runtime.mjs
+++ b/scripts/npm-runtime.mjs
@@ -83,7 +83,7 @@ async function prepareComponent(native, component) {
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;
+ if (change.stage === 'downloading' && state.stage === 'downloading' && change.receivedBytes !== undefined && state.receivedBytes > 0 && Date.now() - lastProgress < 500) return;
lastProgress = Date.now(); state = { ...state, ...change, updatedAt: Date.now() };
await writeJSON(destination + '.status.json', state);
};
@@ -119,7 +119,7 @@ async function prepareComponent(native, component) {
} 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';
+ 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' : error.name === 'TimeoutError' ? 'timeout' : state.stage === 'downloading' ? 'download' : 'checking';
await update({ stage: 'failed', errorCode, error: String(error.message).slice(0, 1000) });
throw error;
}
diff --git a/scripts/runtime-assets.mjs b/scripts/runtime-assets.mjs
index ebf48378..4569fc51 100644
--- a/scripts/runtime-assets.mjs
+++ b/scripts/runtime-assets.mjs
@@ -18,10 +18,30 @@ export async function download(asset, filename, progress = async () => {}) {
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; }
await mkdir(path.dirname(filename), { recursive: true });
- const temporary = filename + '.part';
+ const maxAttempts = 3;
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ try {
+ await downloadAttempt(asset, filename, progress, attempt, maxAttempts);
+ return;
+ } catch (error) {
+ const transient = error.name === 'TimeoutError' || error.name === 'TypeError'
+ || ['ECONNRESET', 'ETIMEDOUT', 'ENOTFOUND', 'EAI_AGAIN'].includes(error.cause?.code)
+ || error.retryable === true;
+ if (!transient || attempt === maxAttempts) throw error;
+ await progress({ stage: 'waiting', attempt: attempt + 1, maxAttempts, receivedBytes: 0, totalBytes: undefined, downloadStartedAt: undefined });
+ await new Promise(resolve => setTimeout(resolve, attempt * 1000));
+ }
+ }
+}
+
+async function downloadAttempt(asset, filename, progress, attempt, maxAttempts) {
+ const url = new URL(asset.url), temporary = filename + '.part';
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(new DOMException('Download made no progress for five minutes', 'TimeoutError')), 300_000);
try {
let current = url, response;
- const signal = AbortSignal.timeout(300_000);
+ const signal = controller.signal;
+ await progress({ stage: 'downloading', attempt, maxAttempts, receivedBytes: 0, totalBytes: undefined, downloadStartedAt: Date.now() });
for (let redirects = 0; redirects <= 5; redirects++) {
assert.equal(current.protocol, 'https:', 'Runtime redirects must use HTTPS');
response = await fetch(current, { redirect: 'manual', signal });
@@ -31,22 +51,29 @@ export async function download(asset, filename, progress = async () => {}) {
assert(location && redirects < 5, 'Invalid or excessive runtime redirects');
current = new URL(location, current);
}
- assert(response.ok && response.body, `Download ${url.hostname}${url.pathname}: HTTP ${response.status}`);
+ if (!response.ok || !response.body) {
+ await response.body?.cancel();
+ throw Object.assign(new Error(`Download ${url.hostname}${url.pathname}: HTTP ${response.status}`), { retryable: response.status === 408 || response.status === 429 || response.status >= 500 });
+ }
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) {
+ timeout.refresh();
receivedBytes += chunk.length;
await progress({ stage: 'downloading', receivedBytes, totalBytes });
yield chunk;
}
}
await pipeline(Readable.fromWeb(response.body), measured, createWriteStream(temporary));
+ clearTimeout(timeout);
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 }); }
+ } catch (error) {
+ throw controller.signal.aborted ? controller.signal.reason : error;
+ } finally { clearTimeout(timeout); await rm(temporary, { force: true }); }
}
export async function runFile(command, args, options = {}) {
diff --git a/shared/native-runtime.ts b/shared/native-runtime.ts
index 01e8e568..1697eeb3 100644
--- a/shared/native-runtime.ts
+++ b/shared/native-runtime.ts
@@ -1,5 +1,16 @@
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 NativeComponent = {
+ id: 'browser' | 'media' | 'ffmpeg' | 'ffprobe';
+ stage: NativeStage;
+ receivedBytes?: number;
+ totalBytes?: number;
+ downloadStartedAt?: number;
+ updatedAt?: number;
+ attempt?: number;
+ maxAttempts?: 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 {
@@ -8,7 +19,7 @@ export function parseNativeRuntimeStatus(value: unknown): NativeRuntimeStatus |
|| !['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.receivedBytes, component.totalBytes, component.downloadStartedAt, component.updatedAt, component.attempt, component.maxAttempts].every(bytes => bytes === undefined || Number.isFinite(bytes) && bytes >= 0)
&& (component.error === undefined || typeof component.error === 'string'))) return null;
return status;
}
diff --git a/studio/src/components/NativeRuntimeNotice.test.tsx b/studio/src/components/NativeRuntimeNotice.test.tsx
index 92ae78d4..5a68c2d6 100644
--- a/studio/src/components/NativeRuntimeNotice.test.tsx
+++ b/studio/src/components/NativeRuntimeNotice.test.tsx
@@ -2,7 +2,7 @@
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { expect, it, vi } from 'vitest';
-import { NativeRuntimeNotice, componentProgress } from './NativeRuntimeNotice';
+import { NativeRuntimeNotice, componentProgress, componentRemainingSeconds } from './NativeRuntimeNotice';
import { I18nProvider, languages, translate, useI18n } 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 () => {
@@ -12,6 +12,9 @@ it('keeps technical progress collapsed, with retry and readiness without remount
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%');
+ act(() => Array.from(host.querySelectorAll('button')).find(button => button.textContent === '重试')!.click());
+ expect(retry).toHaveBeenCalledOnce();
+ retry.mockClear();
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' }] } });
@@ -24,6 +27,10 @@ it('keeps technical progress collapsed, with retry and readiness without remount
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();
+ expect(componentRemainingSeconds({ id: 'browser', stage: 'downloading', receivedBytes: 25, totalBytes: 100, downloadStartedAt: 1000, updatedAt: 3000 }, 3000)).toBe(6);
+ expect(componentRemainingSeconds({ id: 'browser', stage: 'downloading', receivedBytes: 25, totalBytes: 100, downloadStartedAt: 1000, updatedAt: 3000 }, 15000)).toBeNull();
+ expect(componentRemainingSeconds({ id: 'browser', stage: 'checking', receivedBytes: 25, totalBytes: 100, downloadStartedAt: 1000, updatedAt: 3000 })).toBeNull();
+ expect(componentRemainingSeconds({ id: 'browser', stage: 'downloading', receivedBytes: 25 })).toBeNull();
});
it('updates an open preparation panel in all eleven languages and keeps import retry available', async () => {
diff --git a/studio/src/components/NativeRuntimeNotice.tsx b/studio/src/components/NativeRuntimeNotice.tsx
index 9524a87b..2f4d50ef 100644
--- a/studio/src/components/NativeRuntimeNotice.tsx
+++ b/studio/src/components/NativeRuntimeNotice.tsx
@@ -6,18 +6,24 @@ 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.' };
+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.', timeout: 'Download timed out after automatic retries. Check your connection and retry.', 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 }) {
+export function componentRemainingSeconds(component: NativeComponent, now = Date.now()): number | null {
+ const { receivedBytes, totalBytes, downloadStartedAt, updatedAt } = component;
+ if (component.stage !== 'downloading' || !receivedBytes || !totalBytes || !downloadStartedAt || !updatedAt
+ || totalBytes <= receivedBytes || updatedAt - downloadStartedAt < 1000 || now - updatedAt > 10_000 || updatedAt > now) return null;
+ return Math.ceil((totalBytes - receivedBytes) / receivedBytes * (updatedAt - downloadStartedAt) / 1000);
+}
+
+export function NativeRuntimeNotice({ status, 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 export is not ready' : 'Preparing video features';
return (
<div data-testid="native-runtime-notice" className="flex min-h-9 shrink-0 flex-wrap items-center justify-between gap-2 border-b border-border-strong bg-surface px-3 py-1 text-step-11 text-text-2">
@@ -28,20 +34,29 @@ export function NativeRuntimeNotice({ status, checking, onRetry, pendingImport }
</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>}
+ {!status.ok && <Button size="sm" variant="ghost" onClick={onRetry}>{t('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">
+ {runtime.components.map(component => {
+ const progress = componentProgress(component);
+ const remaining = componentRemainingSeconds(component);
+ return <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>
+ <span className="text-text-4">{progress !== null ? `${progress}%` : t(stages[component.stage])}</span>
</div>
+ {component.stage === 'downloading' && component.receivedBytes !== undefined && <p className="mt-1 text-text-4">
+ {(component.receivedBytes / 1_000_000).toFixed(1)} MB{component.totalBytes ? ` / ${(component.totalBytes / 1_000_000).toFixed(1)} MB` : ''}
+ {remaining !== null && <> · {t('About {seconds}s remaining', { seconds: remaining })}</>}
+ </p>}
+ {component.stage !== 'ready' && component.stage !== 'failed' && (component.attempt ?? 0) > 1 && (component.maxAttempts ?? 0) > 1 && <p className="mt-1 text-text-4">{t('Download attempt {attempt}/{total}', { attempt: component.attempt!, total: component.maxAttempts! })}</p>}
{component.stage === 'failed' && <p className="mt-1 text-warning-ink">{t(reasons[component.errorCode ?? 'checking'] ?? reasons.checking)}</p>}
- </li>)}
+ </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>}
diff --git a/studio/src/components/renders/useFfmpegStatus.test.tsx b/studio/src/components/renders/useFfmpegStatus.test.tsx
index 1a6f88e5..30109eb1 100644
--- a/studio/src/components/renders/useFfmpegStatus.test.tsx
+++ b/studio/src/components/renders/useFfmpegStatus.test.tsx
@@ -19,3 +19,27 @@ it('polls background readiness and restores export without reload or another dow
expect(fetch.mock.calls.every(([, init]) => !init?.method || init.method === 'GET')).toBe(true);
act(() => root.unmount());
});
+
+it('keeps a completed retry when an older status request finishes later', async () => {
+ let ready = false, reads = 0, release: (response: Response) => void;
+ let result: ReturnType<typeof useFfmpegStatus>;
+ const response = (available: boolean) => new Response(JSON.stringify({
+ managed: true, components: [{ id: 'browser', stage: available ? 'ready' : 'failed' }],
+ capabilities: { capture: available, media: true, export: available },
+ }));
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
+ if (init?.method === 'POST') { ready = true; return response(true); }
+ if (++reads === 2) return new Promise(resolve => { release = resolve; });
+ return response(ready);
+ });
+ function View() { result = useFfmpegStatus(); return null; }
+ const host = document.createElement('div'), root = createRoot(host);
+ try {
+ await act(async () => { root.render(<View />); });
+ await act(async () => { window.dispatchEvent(new Event('focus')); });
+ await act(async () => { result!.recheck(); });
+ expect(result!.status?.ok).toBe(true);
+ await act(async () => { release!(response(false)); });
+ expect(result!.status?.ok).toBe(true);
+ } finally { act(() => root.unmount()); }
+});
diff --git a/studio/src/components/renders/useFfmpegStatus.ts b/studio/src/components/renders/useFfmpegStatus.ts
index daf21950..badd0645 100644
--- a/studio/src/components/renders/useFfmpegStatus.ts
+++ b/studio/src/components/renders/useFfmpegStatus.ts
@@ -63,7 +63,7 @@ function parseStatus(body: unknown): ProbeResult {
async function probe(): Promise<ProbeResult> {
try {
- const native = await fetch('/motion-api/runtime', { cache: 'no-store' });
+ const native = await fetch('/motion-api/runtime', { cache: 'no-store', signal: AbortSignal.timeout(15_000) });
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 };
@@ -86,6 +86,7 @@ export function useFfmpegStatus(): {
const [status, setStatus] = useState<ProbeResult>(cached);
const [checking, setChecking] = useState(cached === null);
const mounted = useRef(true);
+ const latestProbe = useRef(0);
useEffect(() => {
mounted.current = true;
@@ -95,17 +96,19 @@ export function useFfmpegStatus(): {
}, []);
const run = useCallback(async (retry = false) => {
+ const request = ++latestProbe.current;
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 }) });
+ const response = await fetch('/motion-api/runtime', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ retry: true }), signal: AbortSignal.timeout(15_000) });
if (!response.ok) throw new Error('Preparation retry was refused');
} catch {
- if (mounted.current) { setStatus({ ...cached, ok: false, runtimeUnavailable: true }); setChecking(false); }
+ if (mounted.current && request === latestProbe.current) { setStatus({ ...cached, ok: false, runtimeUnavailable: true }); setChecking(false); }
return;
}
}
const next = await probe();
+ if (request !== latestProbe.current) return;
cached = next;
if (!mounted.current) return;
setStatus(next);
diff --git a/studio/src/i18n/messages.test.ts b/studio/src/i18n/messages.test.ts
index a8437923..f5775498 100644
--- a/studio/src/i18n/messages.test.ts
+++ b/studio/src/i18n/messages.test.ts
@@ -100,6 +100,8 @@ it('covers preparation and import feedback in every supported language', () => {
'Cannot write the preparation cache. Check folder permissions.',
'This platform needs compatible video components.',
'Download failed. Check your connection and retry.',
+ 'About {seconds}s remaining', 'Download attempt {attempt}/{total}',
+ 'Download timed out after automatic retries. Check your connection and retry.',
'The component could not be prepared. Retry or inspect the details.',
'Name cannot contain slashes or two consecutive dots.',
];
diff --git a/studio/src/i18n/mvp-ui.json b/studio/src/i18n/mvp-ui.json
index 18ed8f89..250a3dd9 100644
--- a/studio/src/i18n/mvp-ui.json
+++ b/studio/src/i18n/mvp-ui.json
@@ -291,7 +291,10 @@
"Duplicate": "複製",
"Volume": "音量",
"Show": "表示",
- "Hide": "非表示"
+ "Hide": "非表示",
+ "About {seconds}s remaining": "残り約 {seconds} 秒",
+ "Download attempt {attempt}/{total}": "ダウンロード試行 {attempt}/{total}",
+ "Download timed out after automatic retries. Check your connection and retry.": "自動再試行後もダウンロードがタイムアウトしました。接続を確認して再試行してください。"
},
"ko": {
"Join the OpenDesign community": "OpenDesign 커뮤니티에 참여하세요",
@@ -585,7 +588,10 @@
"Duplicate": "복제",
"Volume": "음량",
"Show": "표시",
- "Hide": "숨기기"
+ "Hide": "숨기기",
+ "About {seconds}s remaining": "약 {seconds}초 남음",
+ "Download attempt {attempt}/{total}": "다운로드 시도 {attempt}/{total}",
+ "Download timed out after automatic retries. Check your connection and retry.": "자동 재시도 후에도 다운로드 시간이 초과되었습니다. 연결을 확인하고 다시 시도하세요."
},
"de": {
"Join the OpenDesign community": "Tritt der OpenDesign-Community bei",
@@ -879,7 +885,10 @@
"Duplicate": "Duplizieren",
"Volume": "Lautstärke",
"Show": "Einblenden",
- "Hide": "Ausblenden"
+ "Hide": "Ausblenden",
+ "About {seconds}s remaining": "Noch etwa {seconds} s",
+ "Download attempt {attempt}/{total}": "Downloadversuch {attempt}/{total}",
+ "Download timed out after automatic retries. Check your connection and retry.": "Zeitüberschreitung nach automatischen Wiederholungen. Verbindung prüfen und erneut versuchen."
},
"fr": {
"Join the OpenDesign community": "Rejoignez la communauté OpenDesign",
@@ -1173,7 +1182,10 @@
"Duplicate": "Dupliquer",
"Volume": "Volume",
"Show": "Afficher",
- "Hide": "Masquer"
+ "Hide": "Masquer",
+ "About {seconds}s remaining": "Environ {seconds} s restantes",
+ "Download attempt {attempt}/{total}": "Tentative de téléchargement {attempt}/{total}",
+ "Download timed out after automatic retries. Check your connection and retry.": "Le téléchargement a expiré après les tentatives automatiques. Vérifiez votre connexion et réessayez."
},
"ru": {
"Join the OpenDesign community": "Присоединяйтесь к сообществу OpenDesign",
@@ -1467,7 +1479,10 @@
"Duplicate": "Дублировать",
"Volume": "Громкость",
"Show": "Показать",
- "Hide": "Скрыть"
+ "Hide": "Скрыть",
+ "About {seconds}s remaining": "Осталось около {seconds} с",
+ "Download attempt {attempt}/{total}": "Попытка загрузки {attempt}/{total}",
+ "Download timed out after automatic retries. Check your connection and retry.": "Время загрузки истекло после автоматических повторов. Проверьте подключение и повторите попытку."
},
"es": {
"Join the OpenDesign community": "Únete a la comunidad de OpenDesign",
@@ -1761,7 +1776,10 @@
"Duplicate": "Duplicar",
"Volume": "Volumen",
"Show": "Mostrar",
- "Hide": "Ocultar"
+ "Hide": "Ocultar",
+ "About {seconds}s remaining": "Quedan unos {seconds} s",
+ "Download attempt {attempt}/{total}": "Intento de descarga {attempt}/{total}",
+ "Download timed out after automatic retries. Check your connection and retry.": "La descarga agotó el tiempo tras los reintentos automáticos. Comprueba la conexión y vuelve a intentarlo."
},
"pt-BR": {
"Join the OpenDesign community": "Junte-se à comunidade OpenDesign",
@@ -2055,7 +2073,10 @@
"Duplicate": "Duplicar",
"Volume": "Volume",
"Show": "Mostrar",
- "Hide": "Ocultar"
+ "Hide": "Ocultar",
+ "About {seconds}s remaining": "Cerca de {seconds} s restantes",
+ "Download attempt {attempt}/{total}": "Tentativa de download {attempt}/{total}",
+ "Download timed out after automatic retries. Check your connection and retry.": "O download excedeu o tempo após as tentativas automáticas. Verifique a conexão e tente novamente."
},
"it": {
"Join the OpenDesign community": "Unisciti alla community OpenDesign",
@@ -2349,7 +2370,10 @@
"Duplicate": "Duplica",
"Volume": "Volume",
"Show": "Mostra",
- "Hide": "Nascondi"
+ "Hide": "Nascondi",
+ "About {seconds}s remaining": "Circa {seconds} s rimanenti",
+ "Download attempt {attempt}/{total}": "Tentativo di download {attempt}/{total}",
+ "Download timed out after automatic retries. Check your connection and retry.": "Il download è scaduto dopo i tentativi automatici. Controlla la connessione e riprova."
},
"tr": {
"Join the OpenDesign community": "OpenDesign topluluğuna katılın",
@@ -2643,6 +2667,9 @@
"Duplicate": "Çoğalt",
"Volume": "Ses düzeyi",
"Show": "Göster",
- "Hide": "Gizle"
+ "Hide": "Gizle",
+ "About {seconds}s remaining": "Yaklaşık {seconds} sn kaldı",
+ "Download attempt {attempt}/{total}": "İndirme denemesi {attempt}/{total}",
+ "Download timed out after automatic retries. Check your connection and retry.": "Otomatik yeniden denemelerden sonra indirme zaman aşımına uğradı. Bağlantınızı kontrol edip tekrar deneyin."
}
}
diff --git a/studio/src/i18n/mvp-zh-CN.json b/studio/src/i18n/mvp-zh-CN.json
index 1d94fc0b..3ed2e734 100644
--- a/studio/src/i18n/mvp-zh-CN.json
+++ b/studio/src/i18n/mvp-zh-CN.json
@@ -1172,5 +1172,8 @@
"The thing that slowed you down": "影响你工作效率的问题",
"What went wrong?": "遇到了什么问题?",
"The thing that made that a low score": "让你给出低分的原因",
- "How likely are you to recommend HyperFrames?": "你有多大可能推荐 HyperFrames?"
+ "How likely are you to recommend HyperFrames?": "你有多大可能推荐 HyperFrames?",
+ "About {seconds}s remaining": "预计剩余 {seconds} 秒",
+ "Download attempt {attempt}/{total}": "第 {attempt}/{total} 次下载尝试",
+ "Download timed out after automatic retries. Check your connection and retry.": "下载超时,自动重试后仍未完成。请检查网络并重试。"
}
diff --git a/tests/native-runtime.test.ts b/tests/native-runtime.test.ts
index fa4e9e6c..1e00f4a0 100644
--- a/tests/native-runtime.test.ts
+++ b/tests/native-runtime.test.ts
@@ -7,7 +7,7 @@ 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 { download, 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';
@@ -103,6 +103,101 @@ test('one failed component remains visible and retry reuses completed components
assert.equal(await readFile(path.join(native.cache, 'ffmpeg-' + assets.ffmpeg.sha256, 'ready.json'), 'utf8'), ready);
});
+test('native downloads automatically retry timeouts and report measured progress', async t => {
+ const { directory, assets } = await fixture(t);
+ const bytes = await readFile(new URL(assets.browser.url));
+ let attempts = 0;
+ t.mock.method(globalThis, 'fetch', async () => {
+ if (++attempts === 1) throw new DOMException('Fixture download timed out', 'TimeoutError');
+ return new Response(bytes, { headers: { 'content-length': String(bytes.length) } });
+ });
+ const updates: any[] = [], filename = path.join(directory, 'retried.tar.gz');
+ await download({ ...assets.browser, url: 'https://example.invalid/browser.tar.gz' }, filename, async state => { updates.push(state); });
+ assert.equal(attempts, 2);
+ assert.equal(await sha256(filename), assets.browser.sha256);
+ assert(updates.some(state => state.stage === 'waiting' && state.attempt === 2));
+ assert(updates.some(state => state.downloadStartedAt > 0 && state.receivedBytes === 0));
+ assert(updates.some(state => state.receivedBytes === bytes.length && state.totalBytes === bytes.length));
+});
+
+test('the download timeout measures inactivity instead of total transfer duration', async t => {
+ const { directory, assets } = await fixture(t);
+ const bytes = await readFile(new URL(assets.browser.url));
+ const schedule = globalThis.setTimeout;
+ t.mock.method(globalThis, 'setTimeout', (callback: any, delay: number, ...args: any[]) => schedule(callback, delay === 300_000 ? 500 : delay, ...args));
+ let attempts = 0;
+ t.mock.method(globalThis, 'fetch', async () => {
+ attempts++;
+ let offset = 0;
+ return new Response(new ReadableStream({
+ async pull(controller) {
+ await new Promise(resolve => schedule(resolve, 100));
+ const end = Math.min(bytes.length, offset + Math.ceil(bytes.length / 8));
+ controller.enqueue(bytes.subarray(offset, end));
+ offset = end;
+ if (offset === bytes.length) controller.close();
+ },
+ }));
+ });
+ const filename = path.join(directory, 'slow.tar.gz');
+ await download({ ...assets.browser, url: 'https://example.invalid/browser.tar.gz' }, filename);
+ assert.equal(attempts, 1);
+ assert.equal(await sha256(filename), assets.browser.sha256);
+});
+
+test('a stalled response body is aborted by the idle timer and retries stay bounded', async t => {
+ const { directory, assets } = await fixture(t);
+ const schedule = globalThis.setTimeout;
+ t.mock.method(globalThis, 'setTimeout', (callback: any, delay: number, ...args: any[]) =>
+ schedule(callback, delay === 300_000 ? 50 : 1, ...args));
+ let attempts = 0, aborts = 0;
+ t.mock.method(globalThis, 'fetch', async (_url: unknown, { signal }: { signal: AbortSignal }) => {
+ attempts++;
+ return new Response(new ReadableStream({
+ start(controller) {
+ controller.enqueue(new Uint8Array(50));
+ signal.addEventListener('abort', () => { aborts++; controller.error(signal.reason); }, { once: true });
+ },
+ }), { headers: { 'content-length': '100' } });
+ });
+ const filename = path.join(directory, 'stalled.tar.gz');
+ await assert.rejects(download({ ...assets.browser, url: 'https://example.invalid/browser.tar.gz' }, filename),
+ error => error.name === 'TimeoutError' && /no progress/.test(error.message));
+ assert.equal(attempts, 3);
+ assert.equal(aborts, 3);
+ await assert.rejects(readFile(filename + '.part'), { code: 'ENOENT' });
+});
+
+test('exhausted timeout retries remain actionable and successful components are reused', { skip: process.platform === 'win32' }, async t => {
+ const { root, assets, config, configFile } = await fixture(t);
+ const browserUrl = assets.browser.url;
+ await ensureNativeRuntime(root, ['ffmpeg', 'ffprobe']);
+ config.runtime.targets.fixture.browser.url = 'https://example.invalid/browser.tar.gz';
+ await writeJSON(configFile, config);
+ let attempts = 0;
+ t.mock.method(globalThis, 'fetch', async () => { attempts++; throw new DOMException('Fixture download timed out', 'TimeoutError'); });
+ await assert.rejects(ensureNativeRuntime(root), { name: 'TimeoutError' });
+ assert.equal(attempts, 3);
+ const status = await nativeRuntimeStatus(root);
+ assert.equal(status.components.find(component => component.id === 'browser')?.errorCode, 'timeout');
+ assert.equal(status.capabilities.media, true);
+ await rm(new URL(assets.ffmpeg.url)); await rm(new URL(assets.ffprobe.url));
+ config.runtime.targets.fixture.browser.url = browserUrl;
+ await writeJSON(configFile, config);
+ await ensureNativeRuntime(root);
+ assert.equal((await nativeRuntimeStatus(root)).capabilities.export, true);
+});
+
+test('permanent download failures do not retry or leave partial archives', async t => {
+ const { directory, assets } = await fixture(t);
+ let attempts = 0;
+ t.mock.method(globalThis, 'fetch', async () => { attempts++; return new Response('missing', { status: 404 }); });
+ const filename = path.join(directory, 'missing.tar.gz');
+ await assert.rejects(download({ ...assets.browser, url: 'https://example.invalid/browser.tar.gz' }, filename), /HTTP 404/);
+ assert.equal(attempts, 1);
+ await assert.rejects(readFile(filename + '.part'), { code: 'ENOENT' });
+});
+
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' });