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
fix(motion): preserve chat focus when showing latest edit previews
bone3deep1962-collab5191422ccc1c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex dc486f07..6daf35da 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -73,7 +73,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/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+ 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- name: Studio regressionrun: npm run test:studio -- --maxWorkers=2- name: Build phase-one ZIP and exercise all public toolsdiff --git a/README.md b/README.mdindex 0ee8a3e3..1dd72d46 100644--- a/README.md+++ b/README.md@@ -58,6 +58,8 @@ The gallery's **one-click recreate** action copies the selected reference and in+After each editing turn, the Agent requests the latest preview in the same chat without switching chats. If you are elsewhere, it stays queued until you return; only an explicit show-now request permits switching back. Actual visibility and the latest content are checked separately; explicit background requests skip presentation. See [multi-turn editing](skills/motion-production/references/native.md#continuing-edits) for host capability limits.+## Start in CodexClone this public repository at `feature/motion` and open the checkout in Codex. You'll need Git, Node.js **22.18+** with npm, and a Codex CLI that supports plugins. MP4 export also requires Chrome/Chromium and FFmpeg/FFprobe. See [Windows test packages](docs/test-packages.md) for that installation path.diff --git a/docs/mcp-phase1-tools.md b/docs/mcp-phase1-tools.mdindex ff66edfd..db9ad970 100644--- a/docs/mcp-phase1-tools.md+++ b/docs/mcp-phase1-tools.md@@ -48,7 +48,13 @@ list 无参数,返回 indexPath、total、catalogVersion 和可选 warning,### motion_open_preview-默认 action=open;传 projectId 或已绑定 sessionId,可选 embedded。执行原生 lint,再选择同一实际工程,返回工程详情、previewUrl、preflight、selectionSource、openedByHost=false。无项目不自动创建;真正打开网页由宿主浏览器执行。+Default action=open accepts an explicit projectId or bound sessionId, optional embedded, presentation, expectedRevision and expectedVersionId. When supplied, both identities are checked before and after lint/open. The result includes previewHandoff, previewUrl, preflight, selectionSource and openedByHost=false; the host must present the existing project. No project is created implicitly.++The handoff preserves the current chat by default (presentation=foreground): reuse its native Tab and queue while inactive. On return, resolve the latest project version without replaying the queued version. Codex actions include a calling-chat-only visibilitySync and bounded observation instructions; queued alone is not confirmation. Only an explicit presentation=now request allows switching back for this turn; background skips presentation. See the shared [continuing-edit workflow](../skills/motion-production/references/native.md#continuing-edits).++action=record_display requires projectId, requestId and display={revision,versionId,previewUrl,visibility,contentVerified,evidence}; optional hostStatus and hostTabId retain the acknowledgment and actual native providerTabId independently. Only visible plus inspected latest content returns confirmed. Hidden/queued/unavailable or unverified content remains pending. Reject foreign project/session/origin URLs and stale revision/version identities, including same-hash restores and retries. Records are host_reported; motion_get_project.previewDisplay exposes isCurrentVersion and liveVisibilityVerified=false, never a live visibility claim.++motion_edit_project and motion_restore_version accept the same optional presentation and return a fresh version-bound previewHandoff after each save or replay. The host owns persistent background preferences; show-now permission does not persist. Stored native Tab IDs are reuse hints that must be validated against the current host inventory. A host queue can open on return without another model turn; absent a new observation the service receipt stays pending.可选 action=record_review,须 projectId、requestId、review,记录已观察对象/versionId/结论/依据/来源与可选时间范围,不修改源码。diff --git a/docs/product/architecture.md b/docs/product/architecture.mdindex baacedc2..b58d3f88 100644--- a/docs/product/architecture.md+++ b/docs/product/architecture.md@@ -44,7 +44,7 @@ Model Gateway 是共用的素材生成服务,可由 Motion Viewer 或 MCP 调1. 用户在首页切到 Motion 模式,选择 Motion 模板并提交需求创建会话;也可直接新建空白创作,或打开左侧已有会话。内置模板复制为该会话的工程,外部参考由 Agent 制作。2. 需要 Agent 时选择 Codex、Claude Code、DeepSeek Harness 或通用 stdio 客户端。接入配置绑定当前工作区;Agent 验证工具和数据目录,读取当前工程与制作规范。 安装后先介绍能力、邀请并等待选择;接受首次体验即确认 `product-promo` 示例内容、独立 20 秒工程、MP4 导出及右侧可编辑页面。Agent 不再问素材/模板/导出确认,实际打开宿主面板,等待并验证成片。Successful first-run delivery uses one completion sentence, the playable MP4 and an LLM-generated contextual invitation to the user's next video, following the [first-run defaults](../../skills/motion-production/references/templates.md#first-run-experience-defaults); the editable project stays open on the right. 宿主没有面板能力时明确提供链接作为降级,不能冒称已打开;实际行为按客户端验证。-3. 用户在会话补充需求并复制给外部 Agent。一期 Agent 用 `motion_get_project` 读取明确工程及其 sessionId、需求、来源与版本,按本轮意图选择入口或直接继续已选范围;编辑前校验工程归属。For original creation, reference-video recreation and editable-template production, the Agent automatically calls `motion_open_preview({projectId})` after the requested HTML is saved and visibly opens its exact `previewUrl` in the host browser, before export or delivery; no extra user request is required. The shared [editable preview handoff](../../skills/motion-production/references/native.md#editable-preview-handoff) defines readiness, host checks and capability limitations. Continued content edits, including motion-production work, confirm the same project is visible before writing, reopen a closed tab as needed, reuse an existing tab and inspect the latest visible content after saving; explicit background requests suppress opening/focusing the editor. 旧 design_* handler 仅留内部兼容。+3. 用户在会话补充需求并复制给外部 Agent。一期 Agent 用 `motion_get_project` 读取明确工程及其 sessionId、需求、来源与版本,按本轮意图选择入口或直接继续已选范围;编辑前校验工程归属。For original creation, reference-video recreation and editable-template production, the Agent automatically calls `motion_open_preview({projectId})` after the requested HTML is saved and visibly opens its exact `previewUrl` in the host browser, before export or delivery; no extra user request is required. The shared [editable preview handoff](../../skills/motion-production/references/native.md#editable-preview-handoff) defines readiness, host checks and capability limitations. Continued content edits, including motion-production work, return a project/revision/version-bound previewHandoff after saving or restoring. Reuse the native project tab: present it when the calling chat is active, otherwise queue it without switching chats and resolve the latest version when the user returns. Only this turn's explicit presentation=now request permits switching back; explicit background requests suppress presentation. Codex IAB synchronizes visibility within the calling chat. A queued acknowledgment is separate from observed visibility and live-content freshness; record_display rejects stale content identities, and stored previewDisplay remains historical host-reported evidence rather than a live server measurement. 旧 design_* handler 仅留内部兼容。4. Agent 根据本轮目标直接选择 Skill:motion-director 负责原创、局部/整体叙事动作声音重新设计和创作审片;motion-template-to-video 负责已有模板出片;motion-recreate 负责参考作品重建(已接入实际流程、独立参考与测量脚本);motion-video-to-template 负责可复用模板生产;motion-production 承接既定决定下的工程操作、预览、技术检查、排错和导出。共享规则同源引用,已有 production/start 保留导航,无需前置总路由。项目来源与画面锁定不固定入口;保持项和已完成操作继续有效。5. Agent 导入素材或通过 Model Gateway 生成图片/视频/音频,完成后写入原生工程。用户在右侧浏览器 Tab 的 Motion Artifact Viewer 预览与编辑,可从空时间轴、素材面板或时间轴选区生成并放入指定时段;选中图片可交给 Codex 参考修改,确认后只替换素材引用并保留原生撤销。也可新增同会话的另一个工程,关闭浏览器继续会话、收起会话沉浸浏览。发生 revision 冲突时重新读取并合并。 按共享 context 补齐缺少的正文并先返回模型再执行;修改按共享 edit 核对保持项、相邻关系与后续延续。6. 完成画面、文案、声音检查后,按用户要求导出固定 revision 的快照,等待真实产物并验证。diff --git a/docs/usage.md b/docs/usage.mdindex 17cfa729..04ab3639 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -239,3 +239,7 @@ The phase-one plugin and all four local host adapters ship the five canonical moThe plugin name, install script, data directory and Studio ports are the team base, unchanged by this extension. See [scope](motion-extension-scope.md).内部兼容诊断 `motion_compare_video`(一期不公开)接受视频绝对路径,候选还可用 `latest-export`。工程先导出再比较;执行错误与画面差异分别返回,指标不代替人工视觉验收。++## Preview after continued edits++Each saved content edit or restore requests the latest preview in the calling chat. The default preserves your current chat: show the right panel here, or queue it while you are elsewhere and open it when you return. Only an explicit show-now request permits switching back for that turn. Background requests skip presentation. A queued acknowledgment, saved source or hidden screenshot does not prove you saw the latest result; the Agent checks live content and visibility separately. See the [shared handoff](../skills/motion-production/references/native.md#continuing-edits) for host capabilities and receipt limits.diff --git a/phase1.ts b/phase1.tsindex 79a75b7b..26e5f297 100644--- a/phase1.ts+++ b/phase1.ts@@ -20,6 +20,35 @@ const textExtensions = new Set(['.html', '.css', '.js', '.mjs', '.json', '.svg',const digest = (value: unknown) => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(canonical(value))).digest('hex');function canonical(value: any): any { return Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value; }function errorText(error: unknown) { return error instanceof Error ? error.message : String(error); }+/** A saved file and a live host panel are separate completion conditions. */+function previewHandoff(origin: string, target: { projectId: string; sessionId: string; revision: string; versionId: string }, presentation = 'foreground', display?: any, prepared = false, url?: string, hostTabId?: string) {+ const previewUrl = url ?? origin + sessionPath(target.sessionId, target.projectId, { embedded: true });+ const confirmed = display?.visibility === 'visible' && display.contentVerified === true;+ const background = presentation === 'background';+ const now = presentation === 'now';+ const onReturn = { tool: 'motion_open_preview', arguments: { projectId: target.projectId } };+ const deferred = !now && display?.visibility !== 'visible' && (display?.hostStatus === 'queued' || display?.visibility === 'queued');+ const recovery = now ? { when: 'hidden_after_queued_ack', tool: 'navigate_to_codex_page', scope: 'calling_chat_only',+ threadIdFrom: 'open_in_codex.response.threadId', then: 'present_same_tab_and_recheck_visibility' } :+ { when: 'calling_chat_not_visible', operation: 'wait_for_calling_chat', onReturn };+ return { ...target, previewUrl, placement: 'right', reuseExistingTab: true, presentation,+ focusPolicy: background ? 'background' : now ? 'switch_to_calling_chat' : 'preserve_current_chat',+ state: background ? 'background' : confirmed ? 'confirmed' : 'pending', openedByHost: confirmed,+ hostActionRequired: !background && !confirmed, confirmationSource: display ? 'host_reported' : null,+ nextAction: background || confirmed ? null : deferred ? { kind: 'host', operation: 'wait_for_calling_chat', onReturn } : prepared ? { kind: 'host', operation: 'present_preview',+ previewUrl, placement: 'right', reuseExistingTab: true, codex: { tool: 'open_in_codex', arguments: {+ placement: 'right', target: { type: 'browser', url: previewUrl, ...(hostTabId ? { tabId: hostTabId } : {}) } },+ tabIdentity: 'Validate any stored Tab ID against the current host inventory; reuse the actual native host Tab ID (providerTabId), never a CUA wrapper id. After presenting, rebind the matching native panel tab before observing visibility; a hidden browser-use tab is separate.',+ visibilitySync: { capability: 'visibility', method: 'set', value: true,+ when: 'after_binding_native_tab', scope: 'calling_chat_only', navigation: false },+ observation: { visibility: 'get', settleTimeoutMs: 6000, content: 'latest_live_preview', recheckVisibilityAfterContent: true },+ recovery } } : { kind: 'motion', tool: 'motion_open_preview', arguments: {+ projectId: target.projectId, expectedRevision: target.revision, expectedVersionId: target.versionId, presentation } },+ instructions: background ? 'Keep this edit in the background as explicitly requested by the user.' :+ (now ? 'The user explicitly requested immediate display for this turn; current-chat recovery may navigate to the calling chat. ' :+ 'Preserve the current chat. Queue the preview for its calling chat without navigating; if queued or hidden, wait for the user to return. On return, prepare the latest project version rather than replaying an old version-bound action. ') ++ 'Bind the native project tab and request Codex IAB visibility for the calling chat without navigation; inactive chats queue this request. Observe settled visibility and changed live content/time, recheck visibility, then record_display for the currently observed revision/version. A queued acknowledgment alone is not display confirmation. Follow motion://workflow/production/native#continuing-edits.' };+}function cursor(value: any) { return Buffer.from(JSON.stringify(value)).toString('base64url'); }function parseCursor(value: string | undefined, kind: string, scope: string) {if (!value) return null;@@ -63,7 +92,13 @@ export class Phase1Service {if (name === 'motion_get_template') return templateCatalogFor(this.store.directory).detail(args.templateId);const run = async () => {if (!this.recovered) { await recoverProjectTransactions(this.store, this.runtimeRoot); this.recovered = true; }- return this.dispatch(name, args);+ const result = await this.dispatch(name, args);+ if (name === 'motion_edit_project' || name === 'motion_restore_version') {+ const owner = this.store.projectCatalog().sessions!.find(session => session.artifacts.some(artifact => artifact.projectId === args.projectId))!;+ result.previewHandoff = previewHandoff(this.context.origin(), { projectId: args.projectId, sessionId: owner.id,+ revision: result.revision, versionId: result.version.versionId }, args.presentation);+ }+ return result;};this.pending++;const result = this.tail.then(run, run).finally(() => { this.pending--; }); this.tail = result.catch(() => {}); return result;@@ -154,10 +189,31 @@ export class Phase1Service {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'),projectType: meta.projectType ?? 'legacy', source: meta.source ?? null, assets, file, exportJob,+ previewDisplay: await this.previewDisplay(projectId, version),exports: jobs.map(({ token, workerPid, ...job }) => job), reviews: await jsonFile(path.join(this.store.directory, 'phase1', 'reviews', projectId + '.json'), []),limits: { textBatchFiles: 100, textBatchBytes: 8388608, textReadBytes: 2097152, assetBytes: 2147483648, attachmentTransport: 'local_path' } };});}+ async previewDisplay(projectId: string, version: ContentVersion) {+ const display = await jsonFile<any>(path.join(this.store.directory, 'phase1', 'preview-displays', projectId + '.json'), null);+ return display ? { ...display, isCurrentVersion: display.revision === version.revision && display.versionId === version.versionId,+ liveVisibilityVerified: false } : null;+ }+ async recordDisplay(args: any, detail: any) {+ const display = args.display;+ const target = new URL(this.context.origin() + sessionPath(detail.sessionId, detail.projectId, { embedded: true }));+ let observed: URL;+ try { observed = new URL(display.previewUrl); } catch { throw new Error('PREVIEW_TARGET_MISMATCH'); }+ if (observed.origin !== target.origin || observed.pathname !== target.pathname || observed.searchParams.get('project') !== detail.projectId ||+ observed.searchParams.get('session') !== detail.sessionId || observed.username || observed.password ||+ observed.hash.split('?')[0] !== target.hash) throw new Error('PREVIEW_TARGET_MISMATCH');+ const record = { ...display, projectId: detail.projectId, source: 'host_reported', requestId: args.requestId, recordedAt: Date.now() };+ await atomicJson(path.join(this.store.directory, 'phase1', 'preview-displays', detail.projectId + '.json'), record);+ const current = await this.detail(detail.projectId);+ if (current.revision !== detail.revision || current.currentVersionId !== detail.currentVersionId) throw new Error('VERSION_CONFLICT: content changed during display confirmation');+ return { projectId: detail.projectId, changed: false, previewHandoff: previewHandoff(this.context.origin(), {+ projectId: detail.projectId, sessionId: detail.sessionId, revision: detail.revision, versionId: detail.currentVersionId }, args.presentation, record, true, display.previewUrl), display: record };+ }async review(args: any, objectId?: string) {if (!args.review) throw new Error('INVALID_ARGUMENT: review is required');const review = args.review, index = await this.versions(args.projectId).index();@@ -242,6 +298,12 @@ export class Phase1Service {} catch (error) { if (!registered) await rm(directory, { recursive: true, force: true }); throw error; }});if (name === 'motion_open_preview') {+ if (args.action === 'record_display') {+ if (!args.projectId || !args.display) throw new Error('INVALID_ARGUMENT: projectId and display are required');+ const detail = await this.detail(args.projectId);+ if (args.display.revision !== detail.revision || args.display.versionId !== detail.currentVersionId) throw new Error('VERSION_CONFLICT: preview display refers to a different content version');+ return this.writeRequest(name, args, () => this.recordDisplay(args, detail));+ }if (args.action === 'record_review') {if (!args.projectId) throw new Error('INVALID_ARGUMENT: projectId is required for review');return this.writeRequest(name, args, () => this.review(args));@@ -253,12 +315,17 @@ export class Phase1Service {if (!projectId) throw new Error('PROJECT_NOT_BOUND: 请传入 projectId 或已绑定的 OpenMotion sessionId');this.store.forProject(projectId);if (session && !session.artifacts.some(artifact => artifact.projectId === projectId)) throw new Error('PROJECT_SESSION_MISMATCH');+ const before = await this.detail(projectId);+ if (args.expectedRevision && args.expectedRevision !== before.revision || args.expectedVersionId && args.expectedVersionId !== before.currentVersionId) throw new Error('VERSION_CONFLICT');const checked = await inspectProject(this.runtimeRoot, this.store.projectDirectoryFor(projectId), 'lint');if (checked.exitCode) throw new Error('PROJECT_VALIDATION_FAILED: ' + JSON.stringify(checked.result));await this.context.openProject(projectId);const detail = await this.detail(projectId);+ if (args.expectedRevision && args.expectedRevision !== detail.revision || args.expectedVersionId && args.expectedVersionId !== detail.currentVersionId) throw new Error('VERSION_CONFLICT');return { ...detail, previewUrl: this.context.origin() + sessionPath(detail.sessionId, projectId, { embedded: args.embedded !== false }),sessionUrl: this.context.origin() + sessionPath(detail.sessionId, projectId), embeddedPreviewUrl: this.context.origin() + sessionPath(detail.sessionId, projectId, { embedded: true }),+ previewHandoff: previewHandoff(this.context.origin(), { projectId, sessionId: detail.sessionId, revision: detail.revision, versionId: detail.currentVersionId }, args.presentation, undefined, true,+ this.context.origin() + sessionPath(detail.sessionId, projectId, { embedded: args.embedded !== false }), detail.previewDisplay?.hostTabId),preflight: checked.result, openedByHost: false, selectionSource: args.projectId ? 'explicit_project' : 'bound_session' };}if (name === 'motion_edit_project') return this.writeRequest(name, args, () => this.context.mutation(() => this.store.lock(async () => {diff --git a/shared/integration.ts b/shared/integration.tsindex 64333dd7..5a1706b2 100644--- a/shared/integration.ts+++ b/shared/integration.ts@@ -129,7 +129,7 @@ ${workflowEntryGuide}素材通过 motion_import_assets 批量持久导入实际本机附件,检查逐项结果;再用 motion_edit_project 保存原生 HTML/CSS/JS 和可选需求,传 expectedRevision、expectedVersionId 及稳定 requestId。冲突时重新读,不盲目覆盖 GUI 修改。媒体生成使用宿主或 Studio 已有能力,本期 MCP 不公开生成/供应商配置入口。-motion_open_preview 打开指定已有项目,宿主浏览器打开完整 previewUrl 后才能说已打开;保留查询参数和路由。未绑定的宿主不能用全局最近项目猜测当前会话。+After each content edit or restore, follow previewHandoff and production/native#continuing-edits. Request the same project on the calling chat's right panel, preserving embed/query/hash and reusing the actual native Tab ID. Default foreground preserves the current chat: queue while inactive, resolve the latest version on return, and verify actual visibility and changed live content before action=record_display. Codex IAB visibility synchronization is scoped to the calling chat and does not navigate. queued is only an acknowledgment. Only this turn's explicit show-now request permits presentation=now and switching back; background skips presentation. Never guess a project from another chat or workspace.## 版本与导出diff --git a/shared/mcp-profiles.json b/shared/mcp-profiles.jsonindex 42375efa..f73123ba 100644--- a/shared/mcp-profiles.json+++ b/shared/mcp-profiles.json@@ -17,6 +17,6 @@"motion_restore_version","motion_export_cancel"],- "instructions": "Use only the tools returned by tools/list. Follow the installed phase-one production skills. Read the selected project and current content version before editing. Save native source through motion_edit_project; preview and export perform their required checks internally. Use motion_list_versions to find project snapshots and motion_restore_version to restore one as a new version while retaining later history. A transport cancellation does not prove a background export stopped. Report actual export state and accessible results; technical validation does not replace visual, audio and player review. Never guess a project from another conversation. Read skills locally or with resources/list and resources/read (motion://workflow/production/start, or the selected specialist); engine authoring guidance is motion://engine/SKILL.md and relative Markdown references under motion://engine/. For new work create explicitly; motion_open_preview never silently creates a project. Persisted create/import/edit/restore/export/cancel and review requests require a stable requestId; preview action=open does not. Edits require projectId, expectedRevision and expectedVersionId. Query export progress through motion_get_project with projectId and exportJobId. Project list and version list are five per page; follow nextCursor. For template discovery, call motion_list_templates to obtain a local JSONL index path, then search that file with local tools. It does not return search results. Read the selected ID with motion_get_template; create its independent editable copy with motion_create_project projectType=template. Use the connected Motion MCP tools for project operations and exports; a shell HTTP call is not an MCP tool invocation. Before opening a project, verify the connection dataDirectory and project/version with motion_get_project. Browser URLs and project IDs do not select another workspace. Compatible phase-one plugin/backend updates continue automatically on the existing connection through API protocol and Tool negotiation; keep the workspace, project binding and running exports. If the API is incompatible, update the incompatible components together when idle. Only an already-closed host transport or an internal legacy runtime replacement requires reconnection. Do not silently bypass MCP or change workspaces."+ "instructions": "Use only the tools returned by tools/list. Follow the installed phase-one production skills. Read the selected project and current content version before editing. Save native source through motion_edit_project; preview and export perform their required checks internally. Use motion_list_versions to find project snapshots and motion_restore_version to restore one as a new version while retaining later history. A transport cancellation does not prove a background export stopped. Report actual export state and accessible results; technical validation does not replace visual, audio and player review. Never guess a project from another conversation. Read skills locally or with resources/list and resources/read (motion://workflow/production/start, or the selected specialist); engine authoring guidance is motion://engine/SKILL.md and relative Markdown references under motion://engine/. For new work create explicitly; motion_open_preview never silently creates a project. Persisted create/import/edit/restore/export/cancel and review requests require a stable requestId; preview action=open does not. Edits require projectId, expectedRevision and expectedVersionId. Query export progress through motion_get_project with projectId and exportJobId. Project list and version list are five per page; follow nextCursor. For template discovery, call motion_list_templates to obtain a local JSONL index path, then search that file with local tools. It does not return search results. Read the selected ID with motion_get_template; create its independent editable copy with motion_create_project projectType=template. Use the connected Motion MCP tools for project operations and exports; a shell HTTP call is not an MCP tool invocation. Before opening a project, verify the connection dataDirectory and project/version with motion_get_project. Browser URLs and project IDs do not select another workspace. Compatible phase-one plugin/backend updates continue automatically on the existing connection through API protocol and Tool negotiation; keep the workspace, project binding and running exports. If the API is incompatible, update the incompatible components together when idle. Only an already-closed host transport or an internal legacy runtime replacement requires reconnection. Do not silently bypass MCP or change workspaces. After each content edit or restore, follow previewHandoff and production/native#continuing-edits to request the latest preview in the calling chat. Default foreground preserves the current chat: queue while inactive, then resolve the latest project version on return. Bind the actual native providerTabId, synchronize Codex IAB visibility without navigation, and independently verify settled visibility and changed live content. Record action=record_display only for the observed revision/version; queued alone is not confirmation. Use presentation=now only for this turn's explicit show-now request; background skips presentation."}}diff --git a/shared/phase1-tools.ts b/shared/phase1-tools.tsindex 0ccb6a4c..8a0f9de9 100644--- a/shared/phase1-tools.ts+++ b/shared/phase1-tools.ts@@ -2,9 +2,13 @@ const id = { type: 'string', minLength: 1, maxLength: 100 };const projectId = { type: 'string', pattern: '^(project|[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12})$' };const revision = { type: 'string', pattern: '^[a-f0-9]{64}$' };const text = { type: 'string', minLength: 1, maxLength: 8000 };+const presentation = { enum: ['foreground', 'background', 'now'], description: 'Default foreground queues for the calling chat without switching chats. Use now only for an explicit request to display immediately in this turn; background skips presentation.' };const object = (properties: Record<string, unknown>, required: string[] = []) => ({ type: 'object', properties, required, additionalProperties: false });const review = object({ objectId: id, versionId: id, range: object({ start: { type: 'number', minimum: 0 }, end: { type: 'number', minimum: 0 } }, ['start', 'end']),conclusion: { enum: ['passed', 'failed', 'pending', 'unable_to_view'] }, evidence: text, source: { enum: ['agent', 'user'] } }, ['objectId', 'versionId', 'conclusion', 'evidence', 'source']);+const display = object({ revision, versionId: id, previewUrl: { type: 'string', minLength: 1, maxLength: 4000 },+ visibility: { enum: ['visible', 'queued', 'hidden', 'unavailable'] }, hostStatus: { type: 'string', minLength: 1, maxLength: 80, description: 'Host action acknowledgment, such as queued; independent of observed panel visibility.' }, hostTabId: { ...id, description: 'Actual native host Tab ID, such as providerTabId; never the CUA wrapper id. A reuse hint, not proof of current visibility.' }, contentVerified: { type: 'boolean' }, evidence: text },+ ['revision', 'versionId', 'previewUrl', 'visibility', 'contentVerified', 'evidence']);const read = { readOnlyHint: true, openWorldHint: false };const write = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false };export const phase1Tools = [@@ -13,22 +17,22 @@ export const phase1Tools = [{ name: 'motion_create_project', description: 'Create an independent editable native Motion project from a prompt, an editable template ID or reference-video ID. The host Agent authors the film; creation does not generate a finished video. Persist requirements and source, return project/session IDs and the initial content version. A requestId is required for safe retries.',inputSchema: object({ requestId: id, projectType: { enum: ['natural_language', 'template', 'reference_video'] }, title: { type: 'string', minLength: 1, maxLength: 100 }, requirements: text,sessionId: projectId, templateId: id, referenceVideoId: id, referenceUrl: { type: 'string', maxLength: 2000 } }, ['requestId', 'projectType', 'title', 'requirements']), annotations: write },- { name: 'motion_open_preview', description: 'Open the named project in the shared editable Studio. Without projectId use only an explicitly bound OpenMotion session, never the global most-recent project. Returns the actual URL and checks; the host must open it. action=record_review records evidence about a previously viewed frozen version without changing source.',- inputSchema: object({ action: { enum: ['open', 'record_review'] }, projectId, sessionId: projectId, embedded: { type: 'boolean' }, requestId: id, review }, []), annotations: write },+ { name: 'motion_open_preview', description: 'Open the named project in the shared editable Studio. Without projectId use only an explicitly bound OpenMotion session, never the global most-recent project. Returns a version-bound previewHandoff; default foreground queues for the calling chat without switching chats. Only an explicit show-now request uses presentation=now to permit switching for this turn. Inspect the latest content after the user returns. action=record_display records the host observation against the current revision/version; queued or unverified content stays pending. action=record_review records evidence about a previously viewed frozen version without changing source.',+ inputSchema: object({ action: { enum: ['open', 'record_review', 'record_display'] }, projectId, sessionId: projectId, embedded: { type: 'boolean' }, presentation, expectedRevision: revision, expectedVersionId: id, requestId: id, review, display }, []), annotations: write },{ name: 'motion_import_assets', description: 'Persist a batch of real local attachments into this project, probe actual media, and return per-item asset IDs, types, sizes, paths and errors. Successful items survive other failures. Existing history is not overwritten. Import does not place media on the timeline. Reuse the same requestId/itemId to retry without duplicate assets.',inputSchema: object({ projectId, requestId: id, items: { type: 'array', minItems: 1, maxItems: 100, items: object({ itemId: id, sourcePath: { type: 'string', minLength: 1, maxLength: 4096 }, name: { type: 'string', maxLength: 200 } }, ['itemId', 'sourcePath']) } }, ['projectId', 'requestId', 'items']), annotations: write },{ name: 'motion_get_project', description: 'Without projectId list projects in the current workspace, newest creation first, exactly five per page (except the last); use nextCursor. With projectId read that project, current revision/version, requirements, native file inventory, asset references and associated export state. file supports bounded UTF-8 reads; exportJobId reads a historical task. This does not switch Studio or create projects.',inputSchema: object({ projectId, sessionId: projectId, cursor: { type: 'string', maxLength: 2000 }, file: object({ path: { type: 'string', minLength: 1, maxLength: 240 }, offset: { type: 'integer', minimum: 0 }, length: { type: 'integer', minimum: 1, maximum: 2097152 } }, ['path']), expectedRevision: revision, exportJobId: id }, []), annotations: read },- { name: 'motion_edit_project', description: 'Save the host Agent\'s native text-file batch and associated requirements into the explicitly named project. Check both expectedRevision and expectedVersionId, commit all files or none, protect GUI writes, record one complete content version and let Studio refresh. The service does not generate code. Read project/version again after conflicts.',- inputSchema: object({ projectId, requestId: id, expectedRevision: revision, expectedVersionId: id, requirements: text, summary: { type: 'string', maxLength: 300 },+ { name: 'motion_edit_project', description: 'Save the host Agent\'s native text-file batch and associated requirements into the explicitly named project. Check both expectedRevision and expectedVersionId, commit all files or none, protect GUI writes, record one complete content version and let Studio refresh. Every save returns a version-bound previewHandoff: preserve the current chat by default, queue when inactive and confirm the latest content on return. An accepted queued preview may be reported as saved and waiting for return. Only an explicit show-now request permits presentation=now for this turn; background skips presentation. The service does not generate code. Read project/version again after conflicts.',+ inputSchema: object({ projectId, requestId: id, expectedRevision: revision, expectedVersionId: id, presentation, requirements: text, summary: { type: 'string', maxLength: 300 },files: { type: 'array', maxItems: 100, items: object({ path: { type: 'string', minLength: 1, maxLength: 240 }, content: { type: 'string' } }, ['path', 'content']) } }, ['projectId', 'requestId', 'expectedRevision', 'expectedVersionId', 'files']), annotations: write },{ name: 'motion_export_request', description: 'Queue a background MP4 of the explicit project version and immutable source/media snapshot. Automatically lint and fully technically verify the result. Return jobId; read progress/results with motion_get_project exportJobId. Repeated requestId returns the original task. action=record_review only records actual playback/visual/audio evidence for an existing job; it never starts another render.',inputSchema: object({ action: { enum: ['request', 'record_review'] }, projectId, requestId: id, expectedRevision: revision, versionId: id, jobId: id,audio: { enum: ['required', 'silent', 'optional'] }, review }, ['projectId', 'requestId']), annotations: write },{ name: 'motion_list_versions', description: 'List consistent project content snapshots, not individual file save counts. Return current-version identity and five snapshots per page with a cursor for older pages, including stable IDs, vN labels, source, summary and restorability. Five is a page size, not a retention limit.',inputSchema: object({ projectId, cursor: { type: 'string', maxLength: 2000 } }, ['projectId']), annotations: read },- { name: 'motion_restore_version', description: 'Restore the explicitly selected project snapshot as a NEW version. Restoring v3 while current is v5 produces v6 with v3 content; v4 and v5 remain. Check current version/revision, restore native source, styles, timing and retained media together, and reject missing historical resources without changing the current project.',- inputSchema: object({ projectId, requestId: id, versionId: id, expectedRevision: revision, expectedVersionId: id }, ['projectId', 'requestId', 'versionId', 'expectedRevision', 'expectedVersionId']), annotations: write },+ { name: 'motion_restore_version', description: 'Restore the explicitly selected project snapshot as a NEW version. Restoring v3 while current is v5 produces v6 with v3 content; v4 and v5 remain. Check current version/revision, restore native source, styles, timing and retained media together, and reject missing historical resources without changing the current project. Returns the same previewHandoff as a source edit; explicit background requests use presentation=background.',+ inputSchema: object({ projectId, requestId: id, versionId: id, expectedRevision: revision, expectedVersionId: id, presentation }, ['projectId', 'requestId', 'versionId', 'expectedRevision', 'expectedVersionId']), annotations: write },{ name: 'motion_export_cancel', description: 'Cancel the specified export owned by this project. Distinguish cancellation accepted/cancelling from a confirmed cancelled terminal state. A completed task stays completed. Cancellation does not restore source, delete older results or promise a refund. Stopping a host conversation does not automatically call this tool.',inputSchema: object({ projectId, requestId: id, jobId: id }, ['projectId', 'requestId', 'jobId']), annotations: write },];diff --git a/skills/motion-production/SKILL.md b/skills/motion-production/SKILL.mdindex 23a6a684..d37ba81b 100644--- a/skills/motion-production/SKILL.md+++ b/skills/motion-production/SKILL.md@@ -20,7 +20,7 @@ Agent 根据本轮意图选择入口,专业任务可直接进入对应 Skill## 2. 工程操作与交付1. 修改已有内容时读取 [共享修改流程](references/edit.md),确定变化、保持项及连带影响;仅查询、预览、审查或导出按本轮范围执行。-2. Existing-project content edits apply the [continuing-edit preview rules](references/native.md#continuing-edits) before writing and after saving, including scoped engineering work. 操作工程前读取 [运行规范](references/production.md);编写原生内容前另读 [Native authoring](references/native.md) 及工具返回的固定版本引擎指南。确认 projectId、最新 revision 与 currentVersionId,复用已完成操作。+2. Existing-project content edits apply the [continuing-edit preview rules](references/native.md#continuing-edits) before writing and after saving, including scoped engineering work. Preserve the current chat by default; queue its latest preview while inactive and inspect it on return. Only an explicit show-now request permits switching back for this turn. 操作工程前读取 [运行规范](references/production.md);编写原生内容前另读 [Native authoring](references/native.md) 及工具返回的固定版本引擎指南。确认 projectId、最新 revision 与 currentVersionId,复用已完成操作。3. 按共享上下文的依赖清单补齐受影响的质量规范。换现成音乐、调音量也需核对声画锚点与原有 SFX;画面锁定时保持视觉内容。补读结果先返回模型,后续调用再执行依赖操作。4. 检查受影响区间、接点和保持项。需要新渲染的导出或成片交付读取 [验证](references/verification.md),针对已审查 revision/versionId 导出,已有适用任务先查询并复用;原样模板预览按专业入口核验,检查实际 MP4。技术通过与创作品质、正常播放及试听分别记录。5. 停在用户要求的方案、预览、工程或成片阶段。交付实际结果、检查与必要限制。diff --git a/skills/motion-production/references/edit.md b/skills/motion-production/references/edit.mdindex d2f31790..d216838b 100644--- a/skills/motion-production/references/edit.md+++ b/skills/motion-production/references/edit.md@@ -12,9 +12,9 @@例子用于说明范围判断,不限定对象形式、镜头结构或实现手法。文字变长可能需要排版调整,时长变化可能影响相邻转场和声音;在已授权范围内处理必要依赖并说明实际影响,不能为形式上的“少改几行”留下坏结果。只有影响目标的重要歧义或需要扩大授权范围时才追问。-## Keep the preview visible during continued edits+## Present the latest preview without switching chats-Before the first content write and after the saved batch, apply the [continuing-edit preview rules](native.md#continuing-edits). This applies across specialist and motion-production entries: reuse the same project/tab, restore a closed preview before editing, and inspect the latest content after saving. Explicit background requests take precedence.+Before the first content write and after the saved batch, apply the [continuing-edit preview rules](native.md#continuing-edits). Reuse the same project/native tab; show it when the calling chat is active, otherwise queue it until the user returns. Confirm the latest version and live content before recording display evidence. Only an explicit show-now request permits switching back for this turn. Explicit background requests take precedence.## 基于当前工程修改diff --git a/skills/motion-production/references/native.md b/skills/motion-production/references/native.mdindex 0bd1e609..66269c0a 100644--- a/skills/motion-production/references/native.md+++ b/skills/motion-production/references/native.md@@ -20,9 +20,21 @@ The Tool runs lint and selects an existing project in Studio; it does not create### Continuing edits-For follow-up turns that change an existing editable project's content, confirm the intended project is visible in the host browser before the first write, including scoped edits handled by motion-production. Reuse its existing tab. If the tab is closed, unavailable or showing a different project, call `motion_open_preview({projectId})` for the same project and open the returned exact `previewUrl` in the host browser, then check the project identity. Closing a tab alone does not request background work or cancel an edit. An explicit request to keep working in the background skips opening/focusing the editor and remains in force until the user changes it. Discussion, queries, review-only and export-only turns do not trigger this editing rule.+Every content-editing turn saves the result and requests its preview in the same host chat. Reuse the project and native tab. Default `presentation:"foreground"` preserves the user's current chat: show the right panel when this chat is active; otherwise queue it until the user returns. Before writing, confirm project ownership and the current source/version; show the target when this chat is active. Apply this shared rule across production, director, template and recreation edits.-After the turn's content batch is saved, confirm that the same visible preview shows the requested latest change, using the affected time/frame and sound when relevant. Existing pages normally update from file-change events; reuse that page rather than reopening on every save. `previewSync=file_watcher_notified` and a successful save are not proof of visible freshness. If the page was closed during the edit, reopen the same project before this check unless background work was requested. If it stays stale, reload that existing tab once and check again; report any remaining refresh, loading or browser limitation instead of claiming the latest result is visible. With explicit background work, verify persisted source/version and report visual freshness as unverified.+After the final source batch, complete the applicable delivery branch:++1. Take `projectId`, `revision` and `versionId` from the save's `previewHandoff`. Call its `nextAction` (`motion_open_preview` with both expected identities) when the HTML is ready. A conflict means reread the current project and source, preserve intervening GUI changes, and prepare the preview with the newly read identities. Studio can add source handles on first open; do not overwrite that normalization with the old batch. Verify and acknowledge the current version returned by the successful open.+2. Request the same project's native preview on the right. In Codex, call `open_in_codex` with `placement:"right"` in the calling chat; omit `threadId` unless the user asked for another chat. The host queues the action when its target chat is inactive. Reuse the actual native Tab ID when available; CUA wrapper `id` is not the host's `providerTabId`. A hidden `browser-use:` tab may be separate from the native right-panel tab. Without an established native Tab ID use the exact returned `previewUrl`, preserving embed/query/hash. Reuse an already queued same-project live preview while subsequent edits update that project; avoid duplicate tabs or a queue of frozen versions.+3. Read the host acknowledgment **and separately observe visibility**. `queued` is neither success nor failure evidence. Rebind the actual native panel tab; a previous hidden automation tab can report false while a native tab is visible. In Codex IAB, after binding that tab, call the browser's supported `visibility.set(true)` capability once: it requests the calling chat's panel, queues while that chat is inactive, and does not navigate to it. Do not substitute another host's unverified focus-changing API. Observe `visibility.get()` as the host settles (bounded by the handoff's `settleTimeoutMs`); an immediate false can precede queued panel activation. If inactive, leave it queued and finish with “saved; latest preview will appear when you return.” Navigation remains forbidden by default. A still-hidden active-chat panel is a display failure to report. A closed/collapsed panel is not a request to skip preview entirely.+4. When the user returns, the host consumes its queued action. If executing a follow-up observation, use the handoff's `onReturn` action to resolve the **latest** project version, rather than replaying an old version-bound open or acknowledging the queued version. Locate the newest changed content at the affected time in the live preview, then recheck host visibility after inspecting it. A hidden WebContents screenshot, DOM `visibilityState`, metadata, a source read, file-watcher notification and a successful open alone do not prove visible freshness. Reload that native tab once if stale; preserve saved content and report any remaining failure. The host queue, not a continuing model turn, owns opening when the user returns; without a new observation leave the receipt pending. In disposable tests, consume queued actions before closing their tabs/server so an old queued tab cannot reappear later.+5. Record `motion_open_preview({action:"record_display",projectId,requestId,presentation,display:{revision,versionId,previewUrl,visibility,hostStatus,hostTabId,contentVerified,evidence}})` with the observed current version and a stable requestId per observation. Optional `hostStatus` preserves the acknowledgment (`queued` can coexist with actual `visibility:"visible"`); optional `hostTabId` preserves the established native ID as a reuse hint, validated against the current inventory. A closed tab's stale ID is omitted in favor of the fresh URL. A queued/hidden observation stays pending; only a visible preview with the latest content actually inspected can be `confirmed`. Deferred delivery is reported as queued, without claiming the user has seen it or polling indefinitely.++Only an explicit request such as “show it now / 现在展示” permits `presentation:"now"` for this turn, carried through save/open/display calls. Its recovery may take the verified calling-chat `threadId` from `open_in_codex`, call `navigate_to_codex_page({threadId})` once, and present/recheck the native tab. Use the host chat identity, not the OpenMotion sessionId. This permission does not persist into later ordinary edits. An ordinary “finish editing” or hidden/queued state is not immediate-display authorization.++This receipt is **host-reported evidence**, not an independent server measurement of the outer panel or user acceptance. The server rejects stale content versions, including a restored version with the same revision hash. `motion_get_project.previewDisplay` is a historical observation; `isCurrentVersion` says whether its content identity still matches, while `liveVisibilityVerified` remains false. Reobserve visibility each turn.++An explicit user instruction to keep work in the background skips opening/focusing the editor. Carry that preference across turns until the user changes it; pass `presentation:"background"` on those saves. Default foreground saves return a pending handoff. Capability failures keep presentation pending; they do not undo the source save. A local implementation or source edit does not install/reload the host plugin.## Native composition contractdiff --git a/tests/preview-handoff.test.ts b/tests/preview-handoff.test.tsnew file mode 100644index 00000000..46aef5ab--- /dev/null+++ b/tests/preview-handoff.test.ts@@ -0,0 +1,218 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { fixture } from './fixtures.ts';+import { Phase1Service } from '../phase1.ts';+import { pluginRoot } from '../hyperframes.ts';++const origin = 'http://127.0.0.1:4173';+function api(store: any, openProject = async () => { throw new Error('The host must explicitly open the preview'); }) { return new Phase1Service(store, pluginRoot, {+ origin: () => origin, nativeUrl: () => undefined,+ openProject,+ mutation: async task => task(), cancel: async () => {},+}); }+async function create(service: Phase1Service) {+ return service.call('motion_create_project', { requestId: crypto.randomUUID(), projectType: 'natural_language', title: 'Preview handoff', requirements: 'An editable film' });+}+async function edit(service: Phase1Service, p: any, text: string, presentation?: string) {+ return service.call('motion_edit_project', { projectId: p.projectId, expectedRevision: p.revision, expectedVersionId: p.version.versionId,+ requestId: crypto.randomUUID(), files: [{ path: 'note.txt', content: text }], ...(presentation ? { presentation } : {}) });+}+function display(saved: any, visibility = 'visible', contentVerified = true) {+ return { projectId: saved.projectId, requestId: crypto.randomUUID(), action: 'record_display', display: {+ revision: saved.revision, versionId: saved.version.versionId, previewUrl: saved.previewHandoff.previewUrl,+ visibility, contentVerified, evidence: 'Host panel visibility read back; inspected the edited text in the live preview at 1s.' } };+}++test('default deferred preview preserves the current chat and resolves the latest version on return', () => fixture(async store => {+ const service = api(store, async () => {}), p = await create(service), first = await edit(service, p, 'first');+ const opened = await service.call('motion_open_preview', first.previewHandoff.nextAction.arguments);+ assert.equal(opened.previewHandoff.focusPolicy, 'preserve_current_chat');+ assert.equal(opened.previewHandoff.nextAction.codex.recovery.tool, undefined);+ const queued = display(first, 'hidden', false);+ queued.display = { ...queued.display, hostStatus: 'queued' } as any;+ const pending = await service.call('motion_open_preview', queued);+ assert.equal(pending.previewHandoff.state, 'pending');+ assert.equal(pending.previewHandoff.nextAction.operation, 'wait_for_calling_chat');+ const second = await edit(service, first, 'second');+ const resume = pending.previewHandoff.nextAction.onReturn;+ const latest = await service.call(resume.tool, resume.arguments);+ assert.equal(latest.currentVersionId, second.version.versionId);+ assert.equal(latest.previewHandoff.focusPolicy, 'preserve_current_chat');+ await assert.rejects(service.call('motion_open_preview', display(first)), /VERSION_CONFLICT/);+ assert.equal((await service.call('motion_open_preview', display({ ...second, previewHandoff: latest.previewHandoff }))).previewHandoff.state, 'confirmed');+}, false));++test('every edit returns a version-bound foreground handoff without claiming the host opened', () => fixture(async store => {+ const service = api(store), p = await create(service);+ const first = await edit(service, p, 'first');+ assert.equal(first.previewHandoff.state, 'pending');+ assert.equal(first.previewHandoff.revision, first.revision);+ assert.equal(first.previewHandoff.versionId, first.version.versionId);+ assert.equal(first.previewHandoff.placement, 'right');+ assert.equal(first.previewHandoff.reuseExistingTab, true);+ assert.equal(first.previewHandoff.openedByHost, false);+ assert.equal(new URL(first.previewHandoff.previewUrl).searchParams.get('project'), p.projectId);+ const args = display(first);+ const confirmed = await service.call('motion_open_preview', args);+ assert.equal(confirmed.previewHandoff.state, 'confirmed');+ assert.equal(confirmed.previewHandoff.confirmationSource, 'host_reported');+ assert.equal((await service.call('motion_open_preview', args)).replayed, true);+ const second = await edit(service, first, 'second');+ assert.equal(second.previewHandoff.state, 'pending');+ assert.notEqual(second.previewHandoff.versionId, first.previewHandoff.versionId);+ await assert.rejects(service.call('motion_open_preview', display(first)), /VERSION_CONFLICT/);+ await assert.rejects(service.call('motion_open_preview', args), /VERSION_CONFLICT/, 'replaying an old confirmation must not confirm the new version');+ await assert.rejects(service.call('motion_open_preview', { projectId: p.projectId, expectedRevision: first.revision, expectedVersionId: first.version.versionId }), /VERSION_CONFLICT/);+ const detail = await service.call('motion_get_project', { projectId: p.projectId });+ assert.equal(detail.previewDisplay.isCurrentVersion, false);+ assert.equal(detail.previewDisplay.liveVisibilityVerified, false);+}, false));++test('queued, hidden, unavailable and unverified content remain pending; background is explicit', () => fixture(async store => {+ const service = api(store), p = await create(service), saved = await edit(service, p, 'first');+ for (const visibility of ['queued', 'hidden', 'unavailable']) {+ const result = await service.call('motion_open_preview', display(saved, visibility));+ assert.equal(result.previewHandoff.state, 'pending');+ assert.equal(result.previewHandoff.openedByHost, false);+ assert.equal(result.previewHandoff.nextAction.kind, 'host');+ }+ assert.equal((await service.call('motion_open_preview', display(saved, 'visible', false))).previewHandoff.state, 'pending');+ const bad = display(saved); bad.display.previewUrl = origin + '/?project=' + crypto.randomUUID();+ await assert.rejects(service.call('motion_open_preview', bad), /PREVIEW_TARGET_MISMATCH/);+ const background = await edit(service, saved, 'background', 'background');+ assert.equal(background.previewHandoff.state, 'background');+ assert.equal(background.previewHandoff.hostActionRequired, false);+ assert.equal(background.previewHandoff.openedByHost, false);+ // The API defaults to foreground; the host must keep passing an active background preference.+ const foreground = await edit(service, background, 'foreground');+ assert.equal(foreground.previewHandoff.hostActionRequired, true);+}, false));++test('restoring identical content still requires a new display confirmation', () => fixture(async store => {+ const service = api(store), p = await create(service), first = await edit(service, p, 'first');+ await service.call('motion_open_preview', display(first));+ const second = await edit(service, first, 'second');+ const restored = await service.call('motion_restore_version', { projectId: p.projectId, requestId: crypto.randomUUID(),+ versionId: first.version.versionId, expectedRevision: second.revision, expectedVersionId: second.version.versionId });+ assert.equal(restored.previewHandoff.state, 'pending');+ assert.equal(restored.previewHandoff.versionId, restored.version.versionId);+ assert.equal(restored.revision, first.revision);+ assert.notEqual(restored.version.versionId, first.version.versionId);+ await assert.rejects(service.call('motion_open_preview', display(first)), /VERSION_CONFLICT/);+ assert.equal((await service.call('motion_get_project', { projectId: p.projectId })).previewDisplay.isCurrentVersion, false);+}, false));++test('opening prepares the host action without recursively reopening and preserves full-workspace links', () => fixture(async store => {+ let opened = 0;+ const service = api(store, async () => { opened++; }), p = await create(service);+ const saved = await edit(service, p, 'first');+ const result = await service.call('motion_open_preview', { ...saved.previewHandoff.nextAction.arguments, embedded: false });+ assert.equal(opened, 1);+ assert.equal(result.previewHandoff.nextAction.kind, 'host');+ assert.equal(result.previewHandoff.nextAction.codex.arguments.placement, 'right');+ assert.equal(result.previewHandoff.nextAction.codex.recovery.tool, undefined);+ assert.equal(result.previewHandoff.nextAction.codex.recovery.operation, 'wait_for_calling_chat');+ assert.equal(result.previewHandoff.nextAction.codex.arguments.threadId, undefined);+ assert.match(result.previewHandoff.nextAction.codex.tabIdentity, /providerTabId/);+ assert.deepEqual(result.previewHandoff.nextAction.codex.visibilitySync, {+ capability: 'visibility', method: 'set', value: true,+ when: 'after_binding_native_tab', scope: 'calling_chat_only', navigation: false,+ });+ assert.deepEqual(result.previewHandoff.nextAction.codex.observation, {+ visibility: 'get', settleTimeoutMs: 6000, content: 'latest_live_preview',+ recheckVisibilityAfterContent: true,+ });+ assert.equal(result.previewHandoff.previewUrl, result.previewUrl);+ assert.equal(new URL(result.previewUrl).searchParams.has('embed'), false);+ assert.equal(result.openedByHost, false);+ const receipt = display({ ...saved, previewHandoff: result.previewHandoff });+ assert.equal((await service.call('motion_open_preview', receipt)).previewHandoff.state, 'confirmed');+}, false));++test('only an explicit now request permits switching and it does not persist into the next turn', () => fixture(async store => {+ const service = api(store, async () => {}), p = await create(service), saved = await edit(service, p, 'show now', 'now');+ assert.equal(saved.previewHandoff.focusPolicy, 'switch_to_calling_chat');+ assert.equal(saved.previewHandoff.nextAction.arguments.presentation, 'now');+ const opened = await service.call('motion_open_preview', saved.previewHandoff.nextAction.arguments);+ assert.equal(opened.previewHandoff.nextAction.codex.recovery.tool, 'navigate_to_codex_page');+ assert.equal(opened.previewHandoff.nextAction.codex.recovery.scope, 'calling_chat_only');+ const pending = await service.call('motion_open_preview', { ...display(saved, 'hidden', false), presentation: 'now' });+ assert.equal(pending.previewHandoff.focusPolicy, 'switch_to_calling_chat');+ assert.equal(pending.previewHandoff.nextAction.codex.recovery.tool, 'navigate_to_codex_page');+ const next = await edit(service, saved, 'next ordinary edit');+ assert.equal(next.previewHandoff.focusPolicy, 'preserve_current_chat');+ const restored = await service.call('motion_restore_version', { projectId: p.projectId, requestId: crypto.randomUUID(),+ versionId: saved.version.versionId, expectedRevision: next.revision, expectedVersionId: next.version.versionId, presentation: 'now' });+ assert.equal(restored.previewHandoff.nextAction.arguments.presentation, 'now');+ assert.equal((await service.call('motion_open_preview', { projectId: p.projectId })).previewHandoff.focusPolicy, 'preserve_current_chat');+}, false));++test('a queued host acknowledgment can confirm an actually visible current preview', () => fixture(async store => {+ const service = api(store, async () => {}), p = await create(service), saved = await edit(service, p, 'latest');+ const nativeTabId = crypto.randomUUID();+ const visible = { ...display(saved), display: { ...display(saved).display, hostStatus: 'queued', hostTabId: nativeTabId } };+ const confirmed = await service.call('motion_open_preview', visible);+ assert.equal(confirmed.previewHandoff.state, 'confirmed');+ assert.equal(confirmed.display.hostStatus, 'queued');+ const second = await edit(service, saved, 'second');+ assert.equal(second.previewHandoff.state, 'pending');+ const reopened = await service.call('motion_open_preview', second.previewHandoff.nextAction.arguments);+ assert.equal(reopened.previewHandoff.nextAction.codex.arguments.target.tabId, nativeTabId);+ assert.equal(reopened.previewHandoff.nextAction.codex.arguments.target.url, reopened.previewUrl);+ assert.equal(reopened.previewHandoff.state, 'pending', 'reusing a native tab must not reuse its old content confirmation');+ const hidden = { ...display(second, 'hidden'), display: { ...display(second, 'hidden').display, hostStatus: 'queued' } };+ const pending = await service.call('motion_open_preview', hidden);+ assert.equal(pending.previewHandoff.state, 'pending');+ assert.equal(pending.previewHandoff.openedByHost, false);+}, false));++test('public MCP round trips expose the handoff and reject a stale host receipt', { timeout: 60_000 }, () => fixture(async store => {+ const { startServer } = await import('../server.ts');+ const { rpc } = await import('../mcp.ts');+ const { writeFile } = await import('node:fs/promises');+ const { join } = await import('node:path');+ const running = await startServer(store, 0, { editor: false });+ const address = running.server.address(); assert.ok(address && typeof address !== 'string');+ await writeFile(join(store.directory, 'preview.json'), JSON.stringify({ port: address.port }));+ const call = async (name: string, args: any) => {+ const response: any = await rpc({ jsonrpc: '2.0', id: crypto.randomUUID(), method: 'tools/call', params: { name, arguments: args } }, store);+ return response.result;+ };+ try {+ const created = await call('motion_create_project', { requestId: crypto.randomUUID(), projectType: 'natural_language', title: 'RPC preview', requirements: 'Check a two-turn editing handoff' });+ assert.equal(created.isError, undefined);+ const p = created.structuredContent;+ const save = async (current: any, content: string) => call('motion_edit_project', { projectId: p.projectId, requestId: crypto.randomUUID(),+ expectedRevision: current.revision, expectedVersionId: current.version.versionId, files: [{ path: 'note.txt', content }] });+ const first = await save(p, 'first'); assert.equal(first.isError, undefined);+ assert.equal(first.structuredContent.previewHandoff.state, 'pending');+ const receipt = await call('motion_open_preview', display(first.structuredContent, 'queued', false));+ assert.equal(receipt.isError, undefined); assert.equal(receipt.structuredContent.previewHandoff.state, 'pending');+ const second = await save(first.structuredContent, 'second'); assert.equal(second.isError, undefined);+ assert.equal(second.structuredContent.previewHandoff.state, 'pending');+ const stale = await call('motion_open_preview', display(first.structuredContent));+ assert.equal(stale.isError, true); assert.match(JSON.stringify(stale), /VERSION_CONFLICT/);+ const unchanged = await call('motion_get_project', { projectId: p.projectId });+ assert.equal(unchanged.structuredContent.currentVersionId, second.structuredContent.version.versionId);+ } finally { await running.close(); }+}, false));++test('content changes during opening require rereading before a new preview handoff', () => fixture(async store => {+ const { writeFile } = await import('node:fs/promises');+ const { join } = await import('node:path');+ let changed = false;+ let projectId: string;+ const service = api(store, async () => {+ if (!changed) { changed = true; await writeFile(join(store.projectDirectoryFor(projectId), 'note.txt'), 'Changed while opening'); }+ });+ const p = await create(service); projectId = p.projectId;+ const saved = await edit(service, p, 'first');+ await assert.rejects(service.call('motion_open_preview', saved.previewHandoff.nextAction.arguments), /VERSION_CONFLICT/);+ const current = await service.call('motion_get_project', { projectId });+ assert.notEqual(current.currentVersionId, saved.version.versionId);+ const opened = await service.call('motion_open_preview', { projectId, expectedRevision: current.revision, expectedVersionId: current.currentVersionId });+ assert.equal(opened.previewHandoff.versionId, current.currentVersionId);+ await assert.rejects(service.call('motion_open_preview', display(saved)), /VERSION_CONFLICT/);+ const receipt = await service.call('motion_open_preview', display({ ...current, previewHandoff: opened.previewHandoff }));+ assert.equal(receipt.previewHandoff.state, 'confirmed');+}, false));