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
[OPEND-5096] fix(history): reject unavailable restores and show editor feedback
open-design-crew[bot]210859eca1ac
diff --git a/README.md b/README.mdindex 8967a345..d474ec05 100644--- a/README.md+++ b/README.md@@ -344,6 +344,8 @@ The rotating field becomes a vinyl record; the title lands on its sleeve.<br>**Write it. Watch it. Change it. Render it.** Ask your agent to replace the product, tighten the hook, add a presenter, change the captions or try another ending. It edits the project source; you review the result in the visual editor. Local MCP clients use the project tools, while agents with shell access can follow the Skills and pinned CLI workflow. [Agent setup](#agent-setup) · [Native composition guide](skills/motion-production/references/native.md) · [Example HTML project](template-library/product-promo/index.html)+If historical media are unavailable, an Agent restore is refused before changing the project. The editor shows a dismissible error with the affected file paths and confirms that the current project is unchanged.+#### What you can change in Studio| In the Studio | What you can do today |diff --git a/docs/mcp-phase1-tools.md b/docs/mcp-phase1-tools.mdindex a295d5d4..4d4eed83 100644--- a/docs/mcp-phase1-tools.md+++ b/docs/mcp-phase1-tools.md@@ -90,12 +90,18 @@ action=record_review 要求 projectId/requestId/jobId/review;只能对本项必填 projectId,可选 cursor。返回 currentVersionId/currentVersionNumber、versions、pageSize=5、hasMore、nextCursor。每条有 versionId、versionNumber、createdAt、source、summary、revision、restorable/unavailableFiles;filePaths 是完整文件路径清单,不等同精确逐行 diff。首次读取建立现有工程基线;仅实际内容变化产生后续 vN。+Availability is checked against the current native and retained blob contents, including SHA-256 verification. Missing, unreadable or corrupt files set `restorable=false` and appear in `unavailableFiles` by project-relative path. Restoring the original blob bytes makes the version available again; capture-time flags are not authoritative.+### motion_restore_version必填 projectId、requestId、versionId(目标)、expectedRevision、expectedVersionId(当前)。校验目标属于该项目及历史资源完整,再恢复原生源文件、样式、时间/效果数据及媒体为新内容版本。v5→v3 得到 v6;v4/v5 仍可查/恢复。目标本就等同当前内容时 changed=false。返回 version/revision、restoredFromVersionId、changed、previewSync。完整媒体恢复保证适用于本Tool,Studio自身GUI历史恢复仍沿用原生行为。不自动混合两个版本,不替换/删除已有导出成片;缺资源、并发改变或恢复冲突时明确报错。+Restore repeats the availability check and verifies staged files before changing the project. Unavailable resources return `VERSION_NOT_RESTORABLE` with the affected paths and `applied=false`; current source files, revision/version identity and asset index remain unchanged. A successful list response cannot guarantee that files will remain available until a later restore.++The open editor also shows these restore refusals through its shared dismissible error toast, including the affected paths and unchanged-project message. Existing project-status polling delivers the latest failure only to that project; each request is shown once per editor mount. This transient notice is cleared from server status after a successful restore or backend restart. Native history panel action errors use the same toast component; native restoration semantics are unchanged.+### motion_export_cancel必填 projectId、requestId、jobId。只能操作项目自己的任务;返回 job 最新状态。pending 直接 cancelled;running 先 cancelling,发出停止信号并在执行进程退出后 cancelled。执行器被异常杀死/超时返回 failed,不谎报取消成功。completed 保持 completed,历史视频保留。宿主停止对话不自动调用本 Tool。diff --git a/docs/product/architecture.md b/docs/product/architecture.mdindex b3e82237..1506d25f 100644--- a/docs/product/architecture.md+++ b/docs/product/architecture.md@@ -162,6 +162,10 @@ README 参考 OpenDesign 的产品导览和 HTML Anything 的贡献、来源表一期公开 MCP 已按[11 Tool 契约](../mcp-phase1-tools.md) 实现本地适配与构建过滤,默认 phase1。发布清单同时控制发现/调用、HTTP 接入元数据及各分发包,原28项内部兼容实现和 Studio 服务保留。phase1.ts 负责明确项目、请求去重、批量素材/保存、具名任务与审阅;phase1-versions.ts 复用原生 history、补稳定 vN 和原生未留存媒体及保存恢复日志。恢复历史创建新版本并保留后续历史,区别于内容哈希和单文件保存。导出继续委托原渲染器并自动完整技术验证;取消区分受理和进程退出。5个随包 Skill 与 MCP resources 指引同步新契约。此为本地实现,未据此宣布部署/平台/宿主业务验收。+MCP version availability is derived from readable, hash-verified native or retained blobs at query time. Restore repeats this check and stages verified contents before entering the existing write transaction. Missing or corrupt historical resources report project-relative paths with `VERSION_NOT_RESTORABLE` and `applied=false`, preserving current project contents and version identity. Availability can change between calls; Studio's native GUI history retains its own restoration semantics.++MCP restore refusals also reach the owning editor through its existing project-status polling and shared error toast. Notices retain file paths, localize the explanation and remain dismissible; repeated polls do not repeat a request's notice. The latest refusal is transient backend state, cleared on successful restoration or restart, and is separate from project source and history. Native history panel action failures reuse the same toast.+Preview/export preflight and the bundled OpenMotion lint command use the pinned native linter's Studio policy in an isolated, cancellable process. A structurally invalid project is rejected before editor opening or rendering; non-blocking warnings remain warnings. The npm CLI's `diagnose` command reads the installed host configuration and probes initialization, tool discovery and the expected workspace through an independent MCP process. It does not mutate configuration, create projects or prove active-chat connectivity. Host reconnection and a subsequent real host read remain separate completion conditions; see [connection diagnosis](../npm-installation.md#missing-mcp-tools-or-a-failed-connection).| 能力 | 负责模块 | 当前边界 |diff --git a/docs/product/changes.md b/docs/product/changes.mdindex e56b3613..1d4e0f17 100644--- a/docs/product/changes.md+++ b/docs/product/changes.md@@ -1,5 +1,13 @@# 公开变更记录+## 2026-11-11: Check historical media before offering MCP restoration++- **Problem and audience:** Agents and creators could be told that a historical version was restorable after its media blobs had disappeared; restoration then exposed a low-level file-copy error.+- **Implementation:** Public version metadata checks native and retained blob contents and hashes. Restoration repeats the check and verifies staged files before the existing transaction. Unavailable files are reported by project-relative path as `VERSION_NOT_RESTORABLE`, with `applied=false`.+- **Editor feedback:** The owning editor displays refused Agent restores using the existing persistent, dismissible error toast, with localized text and original file paths. Existing status polling carries the latest failure; repeated polls do not repeat the notice and other projects do not receive it. Native history panel action failures also use the shared toast.+- **Validation:** `tests/phase1.test.ts` covers missing and corrupt audio, image and video blobs, unchanged current source hashes/version/asset index after rejection, successful complete-media restoration and identical-content restoration without a new version. It also covers native blob read failures and recovery from stale capture-time missing flags. Actual check results are recorded with the delivery.+- **Scope:** This repairs the existing MCP history contract. It does not change personas, pricing, the Studio GUI history contract or distribution formats. Native host and other operating-system acceptance remain separate checks.+## REQ-20261109-004:README 资源闭环与 Agent 创作标语diff --git a/mcp.ts b/mcp.tsindex 4c7e0c47..9cb3aad6 100644--- a/mcp.ts+++ b/mcp.ts@@ -99,7 +99,7 @@ async function invokeRpc(message: any, store: WorkspaceStore, registry: ReturnTyconst 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 || /^(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' } } });+ applied: runtimeFailure || /^(NATIVE_RUNTIME_NOT_READY|INVALID_|VERSION_CONFLICT|VERSION_NOT_RESTORABLE|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-versions.ts b/phase1-versions.tsindex 4bfff132..aad384fd 100644--- a/phase1-versions.ts+++ b/phase1-versions.ts@@ -126,9 +126,16 @@ export class ProjectVersions {await atomicJson(this.indexFile, index);return index;}- publicVersion(version: ContentVersion) {+ async publicVersion(version: ContentVersion, history: NativeHistory) {const { files, nativePoint, ...value } = version;- return { ...value, restorable: files.every(file => !file.missing), unavailableFiles: files.filter(file => file.missing).map(file => file.path), filePaths: files.map(file => file.path) };+ const unavailableFiles: string[] = [];+ for (const file of files) {+ try {+ const hash = file.retained ? await fileHash(this.blob(file.hash)) : createHash('sha256').update(await history.readBlob(file.hash)).digest('hex');+ if (hash !== file.hash) unavailableFiles.push(file.path);+ } catch { unavailableFiles.push(file.path); }+ }+ return { ...value, restorable: unavailableFiles.length === 0, unavailableFiles, filePaths: files.map(file => file.path) };}async current(history: NativeHistory) {const index = await this.sync(history); const version = index.versions.at(-1)!;@@ -179,7 +186,7 @@ export class ProjectVersions {await atomicJson(this.indexFile, index);journal.state = 'committed'; journal.versionId = version.versionId;await atomicJson(path.join(transaction, 'journal.json'), journal); committed = true;- return { version: this.publicVersion(version), revision: version.revision, changed: version.versionId !== current.versionId };+ return { version: await this.publicVersion(version, history), revision: version.revision, changed: version.versionId !== current.versionId };} catch (error) {if (await exists(path.join(transaction, 'journal.json'))) await this.rollback(transaction, journal);throw error;@@ -206,15 +213,19 @@ export class ProjectVersions {await rm(directory, { recursive: true, force: true });}async restore(history: NativeHistory, target: ContentVersion, expectedRevision: string, expectedVersionId: string, requestId: string) {+ const { unavailableFiles } = await this.publicVersion(target, history);+ if (unavailableFiles.length) throw new Error('VERSION_NOT_RESTORABLE: Historical files are missing, unreadable or corrupt: ' + unavailableFiles.join(', '));const directory = path.join(this.root, 'restore-' + crypto.randomUUID());try {const changes: { path: string; source?: string; remove?: boolean }[] = [];for (const file of target.files) {const staged = path.join(directory, file.path);await mkdir(path.dirname(staged), { recursive: true });- if (file.retained) await cloneFile(this.blob(file.hash), staged);- else await writeFile(staged, await history.readBlob(file.hash), { mode: 0o600 });- if (await fileHash(staged) !== file.hash) throw new Error('VERSION_NOT_RESTORABLE: 历史文件缺失或损坏');+ try {+ if (file.retained) await cloneFile(this.blob(file.hash), staged);+ else await writeFile(staged, await history.readBlob(file.hash), { mode: 0o600 });+ if (await fileHash(staged) !== file.hash) throw new Error('Historical file checksum mismatch');+ } catch { throw new Error('VERSION_NOT_RESTORABLE: Cannot stage historical file: ' + file.path); }changes.push({ path: file.path, source: staged });}const wanted = new Set(target.files.map(file => file.path));diff --git a/phase1.ts b/phase1.tsindex c54c8ba5..9b119b12 100644--- a/phase1.ts+++ b/phase1.ts@@ -70,6 +70,7 @@ export class Phase1Service {private tail: Promise<unknown> = Promise.resolve();private recovered = false;pending = 0;+ readonly restoreErrors = new Map<string, { requestId: string; message: string }>();readonly store: WorkspaceStore;readonly runtimeRoot: string;readonly context: Phase1Context;@@ -78,9 +79,13 @@ export class Phase1Service {async call(name: string, args: any) {try {const result = await this.invoke(name, args);+ if (name === 'motion_restore_version') this.restoreErrors.delete(args.projectId);trackPhase1Result(this.context.tracking, name, args, result);return result;} catch (error) {+ if (name === 'motion_restore_version' && errorText(error).startsWith('VERSION_NOT_RESTORABLE:')) {+ this.restoreErrors.set(args.projectId, { requestId: args.requestId, message: errorText(error) });+ }trackPhase1Result(this.context.tracking, name, args, undefined, error);throw error;}@@ -118,7 +123,8 @@ export class Phase1Service {const index = await this.versions(args.projectId).index();const version = index.versions.find(item => item.requestId === args.requestId);if (version) {- const result = { projectId: args.projectId, version: this.versions(args.projectId).publicVersion(version), revision: version.revision, recovered: true };+ const versions = this.versions(args.projectId);+ const result = { projectId: args.projectId, version: await versions.withHistory(history => versions.publicVersion(version, history)), revision: version.revision, recovered: true };await atomicJson(file, { ...previous, state: 'completed', result }); return result;}for (const id of await readdir(path.join(this.store.directory, 'jobs')).catch(e => { if (e.code === 'ENOENT') return []; throw e; })) {@@ -187,7 +193,7 @@ export class Phase1Service {if (args.exportJobId && !jobs.some(job => job.id === args.exportJobId)) throw new Error('EXPORT_NOT_FOUND: 任务不属于该项目');const exportJob = args.exportJobId ? await this.publicJob(args.exportJobId) : jobs[0] ? await this.publicJob(jobs[0].id) : null;if ((await scoped.get()).revision !== state.revision) throw new Error('VERSION_CONFLICT: 读取期间工程已变化');- return { projectId, sessionId: owner.id, project: state.project, revision: state.revision, version: versions.publicVersion(version),+ return { projectId, sessionId: owner.id, project: state.project, revision: state.revision, version: await versions.publicVersion(version, history),currentVersionId: version.versionId, currentVersionNumber: version.versionNumber, dataDirectory: this.store.directory,hyperframesCli: path.join(this.runtimeRoot, 'node_modules/hyperframes/bin/hyperframes.mjs'), authoringGuide: path.join(this.runtimeRoot, 'node_modules/hyperframes/dist/skills/hyperframes/SKILL.md'),requirements: meta.requirements ?? (await scoped.conversation(projectId)).messages.map(message => message.content).join('\n'),@@ -260,7 +266,7 @@ export class Phase1Service {const all = [...index.versions].reverse().filter(item => !page || item.versionNumber < page.after[0]);const shown = all.slice(0, 5), current = index.versions.at(-1)!;return { projectId: args.projectId, currentVersionId: current.versionId, currentVersionNumber: current.versionNumber,- versions: shown.map(item => ({ ...versions.publicVersion(item), isCurrent: item.versionId === current.versionId })), pageSize: 5,+ versions: await Promise.all(shown.map(async item => ({ ...await versions.publicVersion(item, history), isCurrent: item.versionId === current.versionId }))), pageSize: 5,hasMore: all.length > 5, nextCursor: all.length > 5 ? cursor({ kind: 'versions', scope: args.projectId, after: [shown.at(-1)!.versionNumber, shown.at(-1)!.versionId] }) : null };});}diff --git a/server.ts b/server.tsindex 2cec9c14..44e6a736 100644--- a/server.ts+++ b/server.ts@@ -301,7 +301,10 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store =});const data = await input(req);try { return json(res, 200, await context.phase1.call(data.name, data.arguments ?? {})); }- catch (error) { return json(res, 400, { error: error instanceof Error ? error.message : 'Tool failed', applied: 'unknown' }); }+ catch (error) {+ const message = error instanceof Error ? error.message : 'Tool failed';+ return json(res, 400, { error: message, applied: message.startsWith('VERSION_NOT_RESTORABLE:') ? false : 'unknown' });+ }}if (req.method === 'GET' && ['/api/integration', '/connect/guide', '/connect/config'].includes(url.pathname)) {const address = new URL(editorUrl);@@ -449,7 +452,9 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store =const data = await input(req); revision(data.expectedRevision);return json(res, 200, openTemplate ? await legacyCreation(store, context, { ...data, templateId: openTemplate[1] }) : await openProject(store, context, data.expectedRevision, { projectId: openSaved![1] }, data.expectedProjectId));}- if (url.pathname === '/api/project/status' && req.method === 'GET') return json(res, 200, await store.status());+ if (url.pathname === '/api/project/status' && req.method === 'GET') return json(res, 200, {+ ...await store.status(), historyRestoreError: context.phase1?.restoreErrors.get(store.projectId) ?? null,+ });if (url.pathname === '/api/project' && req.method === 'GET') return json(res, 200, await store.get());if (url.pathname === '/api/project' && req.method === 'PUT') {const data = await input(req); revision(data.expectedRevision);diff --git a/studio/src/i18n/I18n.test.tsx b/studio/src/i18n/I18n.test.tsxindex 77979705..f27beae1 100644--- a/studio/src/i18n/I18n.test.tsx+++ b/studio/src/i18n/I18n.test.tsx@@ -172,6 +172,18 @@ it('updates an already visible toast when the interface language changes', () =>expect(host.querySelector('[role="status"]')?.textContent).toContain('Undid: Edit layer style');});+it('renders a dismissible restore error with localized text and unchanged file paths', () => {+ const dismiss = vi.fn();+ const message = 'VERSION_NOT_RESTORABLE: Historical files are missing, unreadable or corrupt: assets/原始配乐.wav';+ act(() => root.render(<I18nProvider initialLocale="zh-CN"><StudioToast message={message} tone="error" onDismiss={dismiss} /></I18nProvider>));+ const alert = host.querySelector('[role="alert"]')!;+ expect(alert.textContent).toContain('历史文件缺失、无法读取或已损坏:assets/原始配乐.wav');+ expect(alert.textContent).toContain('未恢复此版本,当前工程保持不变');+ expect(alert.textContent).not.toContain('VERSION_NOT_RESTORABLE');+ act(() => alert.querySelector<HTMLButtonElement>('button')!.click());+ expect(dismiss).toHaveBeenCalledOnce();+});+it('localizes the complete lint success dialog and updates it when the language changes', () => {function Results() {const { setLocale } = useI18n();diff --git a/studio/src/i18n/de.json b/studio/src/i18n/de.jsonindex c950fceb..0b293d84 100644--- a/studio/src/i18n/de.json+++ b/studio/src/i18n/de.json@@ -1803,5 +1803,7 @@"green": "Grün","blue": "Blau","purple": "Violett",- "multicolor": "Mehrfarbig"+ "multicolor": "Mehrfarbig",+ "Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Verlaufsdateien fehlen, sind nicht lesbar oder beschädigt: {files}. Diese Version wurde nicht wiederhergestellt. Das aktuelle Projekt bleibt unverändert.",+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Verlaufsdateien konnten nicht für die Wiederherstellung vorbereitet werden: {files}. Das aktuelle Projekt bleibt unverändert."}diff --git a/studio/src/i18n/es.json b/studio/src/i18n/es.jsonindex 14f8a896..08c2cc6f 100644--- a/studio/src/i18n/es.json+++ b/studio/src/i18n/es.json@@ -1803,5 +1803,7 @@"green": "Verde","blue": "Azul","purple": "Morado",- "multicolor": "Multicolor"+ "multicolor": "Multicolor",+ "Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Faltan archivos del historial, no se pueden leer o están dañados: {files}. Esta versión no se ha restaurado. El proyecto actual no ha cambiado.",+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "No se pudieron preparar los archivos del historial para la restauración: {files}. El proyecto actual no ha cambiado."}diff --git a/studio/src/i18n/fr.json b/studio/src/i18n/fr.jsonindex f8572247..98720af5 100644--- a/studio/src/i18n/fr.json+++ b/studio/src/i18n/fr.json@@ -1803,5 +1803,7 @@"green": "Vert","blue": "Bleu","purple": "Violet",- "multicolor": "Multicolore"+ "multicolor": "Multicolore",+ "Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Des fichiers de l’historique sont manquants, illisibles ou endommagés : {files}. Cette version n’a pas été restaurée. Le projet actuel reste inchangé.",+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Impossible de préparer les fichiers de l’historique pour la restauration : {files}. Le projet actuel reste inchangé."}diff --git a/studio/src/i18n/it.json b/studio/src/i18n/it.jsonindex fdefbc7e..68233cbf 100644--- a/studio/src/i18n/it.json+++ b/studio/src/i18n/it.json@@ -1803,5 +1803,7 @@"green": "Verde","blue": "Blu","purple": "Viola",- "multicolor": "Multicolore"+ "multicolor": "Multicolore",+ "Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Alcuni file della cronologia sono mancanti, illeggibili o danneggiati: {files}. Questa versione non è stata ripristinata. Il progetto attuale rimane invariato.",+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Impossibile preparare i file della cronologia per il ripristino: {files}. Il progetto attuale rimane invariato."}diff --git a/studio/src/i18n/ja.json b/studio/src/i18n/ja.jsonindex 5b2c8ec6..03f41ba3 100644--- a/studio/src/i18n/ja.json+++ b/studio/src/i18n/ja.json@@ -1767,5 +1767,7 @@"purple": "紫","red": "赤","blue": "青",- "monochrome": "モノクロ"+ "monochrome": "モノクロ",+ "Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "履歴ファイルが見つからないか、読み取れないか、破損しています:{files}。このバージョンは復元されませんでした。現在のプロジェクトは変更されていません。",+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "復元に必要な履歴ファイルを準備できませんでした:{files}。現在のプロジェクトは変更されていません。"}diff --git a/studio/src/i18n/ko.json b/studio/src/i18n/ko.jsonindex cbab692e..94c55046 100644--- a/studio/src/i18n/ko.json+++ b/studio/src/i18n/ko.json@@ -1767,5 +1767,7 @@"purple": "보라","red": "빨강","blue": "파랑",- "monochrome": "흑백"+ "monochrome": "흑백",+ "Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "이전 버전의 파일이 없거나 읽을 수 없거나 손상되었습니다: {files}. 이 버전은 복원되지 않았습니다. 현재 프로젝트는 변경되지 않았습니다.",+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "복원에 필요한 이전 버전의 파일을 준비하지 못했습니다: {files}. 현재 프로젝트는 변경되지 않았습니다."}diff --git a/studio/src/i18n/operationFeedback.test.ts b/studio/src/i18n/operationFeedback.test.tsindex 0510e78e..a4ee1191 100644--- a/studio/src/i18n/operationFeedback.test.ts+++ b/studio/src/i18n/operationFeedback.test.ts@@ -2,6 +2,24 @@ import { expect, it } from 'vitest';import { translate } from './I18n';import { importValidationMessage } from './importMessages';import { splitFailureMessage } from './editorErrors';+import { systemMessage } from './systemMessages';+import { languages } from './messages';++it('localizes rejected history restores while preserving project-relative paths', () => {+ const files = 'assets/原始配乐.wav, assets/photo.png';+ const messages = [+ 'VERSION_NOT_RESTORABLE: Historical files are missing, unreadable or corrupt: ' + files,+ 'VERSION_NOT_RESTORABLE: Cannot stage historical file: ' + files,+ ];+ for (const { locale } of languages) for (const message of messages) {+ const localized = systemMessage(message, (key, values) => translate(locale, key, values));+ expect(localized).toContain(files);+ expect(localized).not.toContain('VERSION_NOT_RESTORABLE');+ expect(localized).not.toMatch(/\{files\}/);+ if (locale === 'zh-CN') expect(localized).toContain('当前工程保持不变');+ if (locale === 'en') expect(localized).toContain('Your current project is unchanged');+ }+});it('distinguishes invalid media, missing tracks and unavailable validation in both languages', () => {const reasons = [diff --git a/studio/src/i18n/pt-BR.json b/studio/src/i18n/pt-BR.jsonindex bf73d62e..6a0a6ca9 100644--- a/studio/src/i18n/pt-BR.json+++ b/studio/src/i18n/pt-BR.json@@ -1803,5 +1803,7 @@"purple": "Roxo","red": "Vermelho","blue": "Azul",- "monochrome": "Monocromático"+ "monochrome": "Monocromático",+ "Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Arquivos do histórico estão ausentes, ilegíveis ou danificados: {files}. Esta versão não foi restaurada. O projeto atual permanece inalterado.",+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Não foi possível preparar os arquivos do histórico para restauração: {files}. O projeto atual permanece inalterado."}diff --git a/studio/src/i18n/ru.json b/studio/src/i18n/ru.jsonindex c8842b22..0934ecf6 100644--- a/studio/src/i18n/ru.json+++ b/studio/src/i18n/ru.json@@ -1827,5 +1827,7 @@"purple": "Фиолетовый","red": "Красный","blue": "Синий",- "monochrome": "Монохромный"+ "monochrome": "Монохромный",+ "Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Файлы истории отсутствуют, недоступны для чтения или повреждены: {files}. Эта версия не восстановлена. Текущий проект не изменён.",+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Не удалось подготовить файлы истории для восстановления: {files}. Текущий проект не изменён."}diff --git a/studio/src/i18n/systemMessages.ts b/studio/src/i18n/systemMessages.tsindex 3ac9c4cc..5f126211 100644--- a/studio/src/i18n/systemMessages.ts+++ b/studio/src/i18n/systemMessages.ts@@ -72,6 +72,10 @@ const patterns = TEMPLATES.map(template => {});export function systemMessage(message: string, t: Translate): string {+ const restore = /^VERSION_NOT_RESTORABLE: (Historical files are missing, unreadable or corrupt|Cannot stage historical file): (.+)$/s.exec(message);+ if (restore) return t(restore[1] === 'Cannot stage historical file'+ ? 'Could not prepare historical files for restoration: {files}. Your current project is unchanged.'+ : 'Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.', { files: restore[2] });const plainHistory = /^(Undid|Redid) (.+)$/s.exec(message);if (plainHistory) return t(plainHistory[1] === 'Undid' ? 'Undid {label}' : 'Redid {label}', { label: historyEntryLabel(plainHistory[2], t) });const history = /^(Undid|Redid): (.+)$/s.exec(message);diff --git a/studio/src/i18n/tr.json b/studio/src/i18n/tr.jsonindex 33e97909..5ef5de22 100644--- a/studio/src/i18n/tr.json+++ b/studio/src/i18n/tr.json@@ -1767,5 +1767,7 @@"purple": "Mor","red": "Kırmızı","blue": "Mavi",- "monochrome": "Tek renkli"+ "monochrome": "Tek renkli",+ "Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Geçmiş dosyaları eksik, okunamıyor veya hasarlı: {files}. Bu sürüm geri yüklenmedi. Mevcut proje değişmedi.",+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Geçmiş dosyaları geri yükleme için hazırlanamadı: {files}. Mevcut proje değişmedi."}diff --git a/studio/src/i18n/zh-CN.json b/studio/src/i18n/zh-CN.jsonindex 45a5dad4..4ea27c80 100644--- a/studio/src/i18n/zh-CN.json+++ b/studio/src/i18n/zh-CN.json@@ -1767,5 +1767,7 @@"purple": "紫色","red": "红色","yellow": "黄色",- "{count} templates": "{count} 个模板"+ "{count} templates": "{count} 个模板",+ "Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "历史文件缺失、无法读取或已损坏:{files}。未恢复此版本,当前工程保持不变。",+ "Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "无法准备恢复所需的历史文件:{files}。当前工程保持不变。"}diff --git a/studio/src/motion/MotionHistoryPanel.test.tsx b/studio/src/motion/MotionHistoryPanel.test.tsxindex cbfce752..b94ed806 100644--- a/studio/src/motion/MotionHistoryPanel.test.tsx+++ b/studio/src/motion/MotionHistoryPanel.test.tsx@@ -7,6 +7,7 @@ import { MotionHistoryPanel } from './MotionHistoryPanel';const shell = vi.hoisted(() => ({projectId: 'project', waitForPendingDomEditSaves: vi.fn<() => Promise<void>>(),+ showToast: vi.fn(),writeBlockedReason: null as string | null, renderQueue: { isRendering: false },}));vi.mock('../contexts/StudioContext', () => ({ useStudioShellContext: () => shell }));@@ -63,14 +64,14 @@ it('does not replace the project when pending edits fail to save', async () => {await render(); await click('first edit'); await click('恢复此版本');expect(calls.filter(call => call.body)).toEqual([]);expect(onRestored).not.toHaveBeenCalled();- expect(container.querySelector('[role="alert"]')?.textContent).toContain('Save conflict');+ expect(shell.showToast).toHaveBeenCalledWith('Save conflict', 'error');});it('shows native restore refusals and keeps the current editor open', async () => {restoreError = true;await render(); await click('first edit'); await click('恢复此版本');expect(onRestored).not.toHaveBeenCalled();- expect(container.querySelector('[role="alert"]')?.textContent).toContain('Version is no longer kept');+ expect(shell.showToast).toHaveBeenCalledWith('Version is no longer kept', 'error');});it('blocks restoring and pinning during a render', async () => {diff --git a/studio/src/motion/MotionHistoryPanel.tsx b/studio/src/motion/MotionHistoryPanel.tsxindex 21b363e4..718b95ff 100644--- a/studio/src/motion/MotionHistoryPanel.tsx+++ b/studio/src/motion/MotionHistoryPanel.tsx@@ -26,7 +26,7 @@ const reloadProject = () => window.location.reload();/** Reads and restores Studio's own history; no parallel snapshot store or undo stack. */export function MotionHistoryPanel({ onRestored = reloadProject }: { onRestored?: () => void }) {const { t, formatDate } = useI18n();- const { projectId, waitForPendingDomEditSaves, writeBlockedReason, renderQueue } = useStudioShellContext();+ const { projectId, waitForPendingDomEditSaves, writeBlockedReason, renderQueue, showToast } = useStudioShellContext();const historyOperation = useMotionHistoryOperation();const [entries, setEntries] = useState<HistoryListItem[]>([]);const [selectedId, setSelectedId] = useState<string | null>(null);@@ -75,7 +75,7 @@ export function MotionHistoryPanel({ onRestored = reloadProject }: { onRestored?activeRead.current?.abort();setBusy(true); setError(''); setNotice('');try { await operation(); }- catch (cause) { if (mounted.current) setError(cause instanceof Error ? cause.message : 'Version operation failed'); }+ catch (cause) { if (mounted.current) showToast(cause instanceof Error ? cause.message : 'Version operation failed', 'error'); }finally { running.current = false; historyOperation.setBusy(false); if (mounted.current) setBusy(false); }};const keepCurrent = () => run(async () => {diff --git a/studio/src/motion/MotionStudioHost.test.tsx b/studio/src/motion/MotionStudioHost.test.tsxindex b86b7e82..d15ee708 100644--- a/studio/src/motion/MotionStudioHost.test.tsx+++ b/studio/src/motion/MotionStudioHost.test.tsx@@ -10,9 +10,11 @@ const state = vi.hoisted(() => ({renderQueue: { isRendering: false, ffmpegMissing: false },open: vi.fn(), export: vi.fn(), setTab: vi.fn(), setCollapsed: vi.fn(),undo: vi.fn(), redo: vi.fn(), create: vi.fn(), home: vi.fn(), rename: vi.fn(),+ showToast: vi.fn(), status: { projectId: 'demo', historyRestoreError: null as { requestId: string; message: string } | null },}));vi.mock('../contexts/StudioContext', () => ({ useStudioShellContext: () => ({projectId: 'demo', renderQueue: state.renderQueue, waitForPendingDomEditSaves: async () => {},+ showToast: state.showToast,}), useStudioShellContextOptional: () => ({editHistory: { canUndo: true, canRedo: true }, handleUndo: state.undo, handleRedo: state.redo,}) }));@@ -22,7 +24,7 @@ vi.mock('../contexts/PanelLayoutContext', () => ({ usePanelLayoutContext: () =>vi.mock('../components/dock/Dock', () => ({ Dock: { WindowMenu: () => <button>Window</button>, Panel: () => null } }));vi.mock('../utils/studioTelemetry', () => ({ trackStudioEvent: vi.fn() }));vi.mock('./useWorkspace', () => ({ useWorkspace: () => ({- status: { projectId: 'demo' }, projects: [{ id: 'demo', title: 'Demo' }, { id: 'second', title: 'Second' }],+ status: state.status, projects: [{ id: 'demo', title: 'Demo' }, { id: 'second', title: 'Second' }],busy: false, error: '', clearError: vi.fn(), open: state.open, openSession: state.open, startSession: state.create, create: state.create, home: state.home, rename: state.rename,}) }));vi.mock('./ConnectionDialog', () => ({ ConnectionDialog: ({ open, section, busy, onOpen }: { open: boolean; section: string; busy: boolean; onOpen: (id: string) => void }) =>@@ -37,6 +39,7 @@ beforeEach(() => {vi.clearAllMocks();localStorage.clear();state.renderQueue.isRendering = false;+ state.status = { projectId: 'demo', historyRestoreError: null };container = document.createElement('div');document.body.append(container);root = createRoot(container);@@ -57,6 +60,22 @@ function openSidebar() {}const button = (text: string) => [...container.querySelectorAll('button')].find(el => el.textContent === text)!;+it('shows a restore failure once in its own project through the shared toast', () => {+ const message = 'VERSION_NOT_RESTORABLE: Historical files are missing, unreadable or corrupt: assets/music.wav';+ state.status = { projectId: 'second', historyRestoreError: { requestId: 'failed-restore', message } };+ render();+ expect(state.showToast).not.toHaveBeenCalled();+ state.status = { ...state.status, projectId: 'demo' };+ render(); render();+ expect(state.showToast).toHaveBeenCalledExactlyOnceWith(message, 'error');+ state.status = { projectId: 'demo', historyRestoreError: { requestId: 'new-attempt', message } };+ render();+ expect(state.showToast).toHaveBeenCalledTimes(2);+ state.status = { projectId: 'demo', historyRestoreError: { requestId: 'failed-restore', message } };+ render();+ expect(state.showToast).toHaveBeenCalledTimes(2);+});+it('keeps project switching, templates, history actions and native export in the MVP', () => {render();const header = container.querySelector('.motion-studio-header')!;diff --git a/studio/src/motion/MotionStudioHost.tsx b/studio/src/motion/MotionStudioHost.tsxindex 005838c6..0670cf05 100644--- a/studio/src/motion/MotionStudioHost.tsx+++ b/studio/src/motion/MotionStudioHost.tsx@@ -47,11 +47,24 @@ export function MotionEditorFrame({ children }: { children: ReactNode }) {register?.({ waitForSaves: waitForPendingDomEditSaves, blocked, saveState, message: writeBlockedReason || '' });return () => register?.(null);}, [register, waitForPendingDomEditSaves, blocked, saveState, writeBlockedReason]);- const editor = <MediaGatewayProvider>{children}</MediaGatewayProvider>;+ const editor = <MediaGatewayProvider><HistoryRestoreFeedback />{children}</MediaGatewayProvider>;if (chrome) return editor;return <WorkspaceFrame projectId={projectId} waitForSaves={waitForPendingDomEditSaves} blocked={blocked} message={writeBlockedReason || ''} saveState={saveState}>{editor}</WorkspaceFrame>;}+function HistoryRestoreFeedback() {+ const { projectId, showToast } = useStudioShellContext();+ const status = useOptionalWorkspaceChrome()?.workspace.status;+ const shown = useRef(new Set<string>());+ useEffect(() => {+ const error = status?.historyRestoreError;+ if (status?.projectId !== projectId || !error || shown.current.has(error.requestId)) return;+ shown.current.add(error.requestId);+ showToast(error.message, 'error');+ }, [projectId, status, showToast]);+ return null;+}+function WorkspaceProject() {const { t } = useI18n();const { workspace, switchingDisabled, saveState } = useWorkspaceChrome();diff --git a/studio/src/motion/useWorkspace.ts b/studio/src/motion/useWorkspace.tsindex 4ee65cc4..df242407 100644--- a/studio/src/motion/useWorkspace.ts+++ b/studio/src/motion/useWorkspace.ts@@ -5,7 +5,8 @@ import { preservePresentation } from '../../../shared/workspace-url';export type SavedProject = { id: string; title: string; templateId?: string; createdAt?: number; openedAt?: number };type Job = { id: string; state: 'pending' | 'running' | 'completed' | 'failed'; error?: string };-export type WorkspaceStatus = { revision: string; projectId: string; projectTitle: string; exportJob: Job | null; sessionId?: string };+export type WorkspaceStatus = { revision: string; projectId: string; projectTitle: string; exportJob: Job | null; sessionId?: string;+ historyRestoreError?: { requestId: string; message: string } | null };export type ProjectCatalog = { activeId: string; projects: SavedProject[]; sessions?: CreativeSession[]; activeSessionId?: string };export async function motionApi<T>(path: string, init?: RequestInit, projectId?: string): Promise<T> {const response = await fetch((path.startsWith('/sessions') || path.startsWith('/modes') ? '/design-api' : '/motion-api') + pathdiff --git a/tests/mcp-runtime.test.ts b/tests/mcp-runtime.test.tsindex f8e9a53b..b5755f73 100644--- a/tests/mcp-runtime.test.ts+++ b/tests/mcp-runtime.test.ts@@ -11,7 +11,7 @@ import { rpc } from '../mcp.ts';import { copyRuntimeFixture } from './fixtures.ts';import { WorkspaceStore } from '../workspace.ts';-async function incompatibleEditor(directory: string, changed: Record<string, unknown>) {+async function incompatibleEditor(directory: string, changed: Record<string, unknown>, toolError?: string) {const { data, runtime } = await editorDirectory(directory);const requests: string[] = [];const registry = { service: 'opendesign-editor', protocol: 1, version: JSON.parse(await readFile(path.join(pluginRoot, 'package.json'), 'utf8')).version,@@ -25,6 +25,7 @@ async function incompatibleEditor(directory: string, changed: Record<string, unkif (req.url === '/motion-api/phase1/call') {let body = ''; for await (const chunk of req) body += chunk;calls.push(JSON.parse(body));+ if (toolError) { res.statusCode = 400; return res.end(JSON.stringify({ error: toolError, applied: false })); }return res.end(JSON.stringify({ projectId: 'project', sessionId: 'project', authority: 'compatible-backend', job: { id: 'existing-export' } }));}res.end(JSON.stringify(health));@@ -41,6 +42,19 @@ const exportCall = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { nameprojectId: 'project', requestId: 'must-not-export', expectedRevision: '0'.repeat(64), versionId: 'unavailable', audio: 'silent',} } };+test('MCP reports unavailable historical files as not applied', { skip: !sharedEditorEnabled }, async () => {+ const directory = await mkdtemp(path.join(tmpdir(), 'motion-unavailable-version-'));+ const message = 'VERSION_NOT_RESTORABLE: Historical files are missing, unreadable or corrupt: assets/audio.wav';+ const editor = await incompatibleEditor(directory, { mcp: { protocol: 1, tools: ['motion_restore_version'] } }, message);+ try {+ const response: any = await rpc({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'motion_restore_version', arguments: {+ projectId: 'project', requestId: 'missing-media', versionId: 'unavailable', expectedVersionId: 'current', expectedRevision: '0'.repeat(64),+ } } }, new WorkspaceStore(directory));+ assert.equal(response.result.isError, true);+ assert.deepEqual(response.result.structuredContent.error, { code: 'VERSION_NOT_RESTORABLE', message, applied: false });+ } finally { await editor.close(); await rm(directory, { recursive: true, force: true }); }+});+test('MCP reports incompatible editor identity fields without starting an export or exposing credentials', { skip: !sharedEditorEnabled }, async t => {for (const changed of [{ protocol: 999 }, { version: '0.0.0' }, { build: '0'.repeat(64) }]) await t.test(Object.keys(changed)[0], async () => {const directory = await mkdtemp(path.join(tmpdir(), 'motion-runtime-mismatch-'));diff --git a/tests/phase1.test.ts b/tests/phase1.test.tsindex 45cdc13c..353cb0d1 100644--- a/tests/phase1.test.ts+++ b/tests/phase1.test.ts@@ -8,6 +8,7 @@ import { pluginRoot, execute } from '../hyperframes.ts';import { cancelExport } from '../server.ts';import { atomicJson, fileHash, recoverProjectTransactions } from '../phase1-versions.ts';import { validateInput, phase1Tools } from '../shared/phase1-tools.ts';+import { transport } from './http.ts';function api(store: any) { return new Phase1Service(store, pluginRoot, {origin: () => 'http://127.0.0.1:4173', nativeUrl: () => undefined, openProject: async () => {},@@ -65,7 +66,10 @@ test('v5 to v3 creates v6, retains v4/v5, rejects stale writes and recovers afteawait assert.rejects(service.call('motion_get_project', { projectId: p.projectId, file: { path: 'note.txt', offset: 1 } }), /INVALID_UTF8_OFFSET/);}, false));-test('imports probe media, return partial results, deduplicate and retain historical audio', () => fixture(async store => {+test('imports retain historical media and reject missing or corrupt blobs without changing the project', t => fixture(async store => {+ const previous = process.env.HYPERFRAMES_HISTORY_ROOT, historyRoot = path.join(store.directory, 'native-history');+ process.env.HYPERFRAMES_HISTORY_ROOT = historyRoot;+ t.after(() => { if (previous === undefined) delete process.env.HYPERFRAMES_HISTORY_ROOT; else process.env.HYPERFRAMES_HISTORY_ROOT = previous; });const service = api(store), p = await create(service);const png = path.join(store.directory, 'source.png');const pngResult = await execute('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'color=c=red:size=16x16', '-frames:v', '1', png], store.directory);@@ -85,8 +89,82 @@ test('imports probe media, return partial results, deduplicate and retain historawait rm(wav);const after = await service.call('motion_get_project', { projectId: p.projectId });const restored = await service.call('motion_restore_version', { projectId: p.projectId, requestId: 'before-media', versionId: p.version.versionId, expectedVersionId: after.version.versionId, expectedRevision: after.revision });- await service.call('motion_restore_version', { projectId: p.projectId, requestId: 'after-media', versionId: imported.version.versionId, expectedVersionId: restored.version.versionId, expectedRevision: restored.revision });- assert.equal(await fileHash(path.join(store.projectDirectoryFor(p.projectId), imported.items[0].path)), imported.items[0].sha256);+ const complete = await service.call('motion_restore_version', { projectId: p.projectId, requestId: 'after-media', versionId: imported.version.versionId, expectedVersionId: restored.version.versionId, expectedRevision: restored.revision });+ const media = imported.items.filter((item: any) => item.status !== 'failed');+ for (const item of media) assert.equal(await fileHash(path.join(store.projectDirectoryFor(p.projectId), item.path)), item.sha256);+ const noop = await service.call('motion_restore_version', { projectId: p.projectId, requestId: 'same-media', versionId: imported.version.versionId, expectedVersionId: complete.version.versionId, expectedRevision: complete.revision });+ assert.equal(noop.changed, false); assert.equal(noop.version.versionId, complete.version.versionId);+ await service.call('motion_restore_version', { projectId: p.projectId, requestId: 'remove-media', versionId: p.version.versionId, expectedVersionId: complete.version.versionId, expectedRevision: complete.revision });+ const before = await service.call('motion_get_project', { projectId: p.projectId });+ const scoped = store.forProject(p.projectId), beforeFiles = await scoped.files();+ const beforeAssets = await readFile(path.join(scoped.projectDirectory, 'motion-assets.json'));+ const versions = service.versions(p.projectId);+ const target = (await versions.index()).versions.find(version => version.versionId === imported.version.versionId)!;+ const historyId = (await readFile(path.join(scoped.projectDirectory, '.hyperframes/history-id'), 'utf8')).trim();+ const request = transport(store, { runtimeRoot: pluginRoot, phase1: service });+ for (const item of media) {+ const file = target.files.find(file => file.path === item.path)!;+ const blob = file.retained ? versions.blob(file.hash) : path.join(historyRoot, historyId, 'blobs', file.hash.slice(0, 2), file.hash);+ const bytes = await readFile(blob);+ for (const damage of ['missing', 'corrupt']) {+ if (damage === 'missing') await rm(blob); else await writeFile(blob, Buffer.alloc(bytes.length));+ const list = await service.call('motion_list_versions', { projectId: p.projectId });+ const listed = list.versions.find((version: any) => version.versionId === target.versionId);+ assert.equal(listed.restorable, false, item.mimeType + ': ' + damage);+ assert.deepEqual(listed.unavailableFiles, [item.path]);+ const requestId = crypto.randomUUID();+ const response = await request('/motion-api/phase1/call', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'motion_restore_version', arguments: {+ projectId: p.projectId, requestId, versionId: target.versionId,+ expectedVersionId: before.currentVersionId, expectedRevision: before.revision,+ } }) });+ assert.equal(response.status, 400);+ const error = await response.json();+ assert.match(error.error, /^VERSION_NOT_RESTORABLE:/); assert.ok(error.error.includes(item.path));+ assert.equal(error.applied, false);+ const status = await request('/motion-api/project/status?projectId=' + p.projectId);+ assert.deepEqual((await status.json()).historyRestoreError, { requestId, message: error.error });+ const after = await service.call('motion_get_project', { projectId: p.projectId });+ assert.equal(after.revision, before.revision); assert.equal(after.currentVersionId, before.currentVersionId);+ assert.deepEqual(after.assets, before.assets); assert.deepEqual(await scoped.files(), beforeFiles);+ assert.deepEqual(await readFile(path.join(scoped.projectDirectory, 'motion-assets.json')), beforeAssets);+ await writeFile(blob, bytes);+ }+ }+ const available = (await service.call('motion_list_versions', { projectId: p.projectId })).versions.find((version: any) => version.versionId === target.versionId);+ assert.equal(available.restorable, true); assert.deepEqual(available.unavailableFiles, []);+ const other = await create(service);+ assert.equal((await (await request('/motion-api/project/status?projectId=' + other.projectId)).json()).historyRestoreError, null);+ await service.call('motion_restore_version', { projectId: p.projectId, requestId: 'recovered-media', versionId: target.versionId,+ expectedVersionId: before.currentVersionId, expectedRevision: before.revision });+ assert.equal((await (await request('/motion-api/project/status?projectId=' + p.projectId)).json()).historyRestoreError, null);+}, false));++test('version availability rechecks native blobs and does not persist missing-file flags', () => fixture(async store => {+ const service = api(store), p = await create(service), versions = service.versions(p.projectId);+ const target = (await versions.index()).versions[0], file = target.files.find(file => file.path === 'index.html')!;+ await versions.withHistory(async history => {+ const bytes = await history.readBlob(file.hash);+ for (const blob of [null, Buffer.alloc(bytes.length)]) {+ const unavailable = { ...history, readBlob: async (hash: string) => {+ if (hash !== file.hash) return history.readBlob(hash);+ if (blob === null) throw new Error('ENOENT');+ return blob;+ } };+ const listed = await versions.publicVersion(target, unavailable);+ assert.equal(listed.restorable, false); assert.deepEqual(listed.unavailableFiles, [file.path]);+ await assert.rejects(versions.restore(unavailable, target, p.revision, p.version.versionId, 'native-missing'), /VERSION_NOT_RESTORABLE:.*index\.html/);+ }+ const listed = await versions.publicVersion({ ...target, files: target.files.map(file => ({ ...file, missing: true })) }, history);+ assert.equal(listed.restorable, true); assert.deepEqual(listed.unavailableFiles, []);+ let reads = 0;+ const disappears = { ...history, readBlob: async (hash: string) => {+ if (hash === file.hash && ++reads > 1) throw new Error('ENOENT');+ return history.readBlob(hash);+ } };+ await assert.rejects(versions.restore(disappears, target, p.revision, p.version.versionId, 'native-disappears'), /VERSION_NOT_RESTORABLE:.*index\.html/);+ });+ const after = await service.call('motion_get_project', { projectId: p.projectId });+ assert.equal(after.currentVersionId, p.version.versionId); assert.equal(after.revision, p.revision);}, false));test('an interrupted partial save rolls back, but recovery never overwrites foreign writes', () => fixture(async store => {