Skip to content

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

feat: port installation template library onboarding to main (#325)

MasonJJ0972235e1bb4
diff --git a/README.md b/README.md
index eec0b7e8..e925458c 100644
--- a/README.md
+++ b/README.md
@@ -405,6 +405,8 @@ When choosing or replacing media, creation workflows share a [material sourcing
For agent-led installation, use the [installation instruction above](#quick-start). To run from source, follow the steps below.
+After a successful Agent-led installation, open the editor's template library in the current conversation, without creating a project. Browse and preview first; choose **Open and edit** to create an independent editable copy. Setup provides a direct library link even before the chat reloads MCP. See the [installation reply rules](docs/install.md#installation-success-reply).
+
If MCP tools are missing or fail to connect, use the installed [connection diagnosis and recovery guide](docs/npm-installation.md#missing-mcp-tools-or-a-failed-connection) to inspect the actual host configuration and verify the original workspace before continuing.
Use Git, npm and **Node.js 26.11.1**. Source-based preview and export also need Chrome/Chromium and FFmpeg/FFprobe. [Runtime setup](docs/usage.md)
diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.md
index ac7294f6..5b3ecc3f 100644
--- a/docs/README.zh-CN.md
+++ b/docs/README.zh-CN.md
@@ -401,6 +401,8 @@ Brand Kit 章节记录自己的 Logo、配色、字体、语气和已确认的
通过 Agent 安装,请使用[上方的安装指令](#quick-start)。如需从源码运行,使用下面的步骤。
+Agent 安装成功后会直接打开编辑器的模板库,暂不创建项目。先浏览和预览,选好后点击“打开并编辑”,再创建独立工程。当前聊天尚未加载 MCP 时,可使用安装结果中的模板库直达链接;宿主不支持自动展示时会提供链接。
+
#### 运行 OpenMotion
**从免费本地创作全栈开始。** 连接自己的 Agent、打开内置模板或导入实拍,用本地应用渲染。需要生成新素材时,在 Model Settings 加入受支持的媒体 Key。
diff --git a/docs/install.md b/docs/install.md
index 1ceadf22..0d1c5bb6 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -9,62 +9,40 @@ If you are reading this file in the source repository and see `{{...}}`, it is a
1. Collect OS/CPU, Node.js/npm versions and the current Agent identity together, using the host's supplied context where available. Node.js 22.18+ with npm and the Agent must already be installed. Supported native targets: {{TARGETS}}. If a macOS target has no declared minimum version, proceed with setup and native executable checks; do not infer a minimum from the build/test machine's OS version. Do not claim support for another target from package-download success.
2. Select the current host explicitly: `codex` (Codex), `claude` (Claude Code), `deepseek` (DeepSeek Harness) or `workbuddy` (WorkBuddy). An explicit user selection takes precedence. Do not infer the current host from which CLIs happen to be installed. Ask only when the current host or required profile cannot be established. Configure only that host; preserve projects, credentials and unrelated MCP/Skills settings.
3. For a test candidate, use a separate host profile, application home, project data and Skills directory. Keep those paths and reuse them for prepare and future reconnects. The [platform installation recipes]({{DETAILS_URL}}) describe the actual supported options. Do not run a test candidate into the user's daily profile by default.
-4. Choose exactly one setup command below, applying the test isolation paths first when required. Setup starts checked video-component downloads in the background. Do not wait for prepare to connect MCP, create/edit projects or open ordinary preview. Studio shows preparation status and retry; media import, automated capture and export require their respective components. Compatible phase-one updates can keep existing connections; reconnect closed or incompatible transports. When the current host can discover the eleven public Tools and five Skills, verify the version/environment and make an actual `openmotion_get_project` call. If this chat has not loaded them or still points at another installation, use `onboarding.directAccess` below; registration alone does not prove native loading. Do not postpone the installation reply or invitation until a new chat or the first MCP call.
-5. On successful setup, follow the installation-success reply below in this same conversation, using the returned `onboarding.catalog` summaries. Installation does not authorize creating a project, downloading template assets, rendering or calling a paid model. Report a failed installation honestly; do not issue a success invitation until it is fixed.
+4. Choose exactly one setup command below, applying the test isolation paths first when required. Setup starts checked video-component downloads in the background. Do not wait for prepare to connect MCP, create/edit projects or open ordinary preview. Studio shows preparation status and retry; media import, automated capture and export require their respective components. Compatible phase-one updates can keep existing connections; reconnect closed or incompatible transports. When the current host can discover the eleven public Tools and five Skills, verify the version/environment and make an actual `openmotion_get_project` call. If this chat has not loaded them or still points at another installation, use `onboarding.directAccess` below; registration alone does not prove native loading. Do not postpone the installation reply or template library opening until a new chat or the first MCP call.
+5. On successful setup, follow the installation-success reply below in this same conversation. Open the template library without creating a project. Installation does not authorize downloading template project source, rendering or calling a paid model. Report a failed installation honestly; do not claim success until it is fixed.
For npm network failures, automatically try `https://registry.npmjs.org` then `https://registry.npmmirror.com`, at most once per registry, counting the initial failed attempt. Respect an explicitly selected registry and host policy. Set `npm_config_registry` and `npm_config_fetch_retries=0` only for that attempt, including setup's npm child process. Keep the exact version; verify any mirrored tgz against the matching immutable guide's SHA256 before executing it. If both fail, follow [npm download recovery]({{DETAILS_URL}}#npm-download-failures) for network checks and a terminal handoff. Permission or checksum failures stop immediately. A local tgz still needs npm access for setup's production dependencies.
<!-- installation-onboarding:start -->
## Installation-success reply
-Every successful Agent-led OpenMotion installation ends with an experience invitation in the current conversation. Use these rules regardless of entry URL or host; do not depend on newly installed Skills being hot-loaded. Respect an explicit request not to invite, or a previous refusal/deferment. An explicit request to create with an already selected template authorizes that task: continue it directly, without an unrelated demo or repeated consent.
+Every successful Agent-led OpenMotion installation opens the editor's template library in the current conversation. Do not ask whether to experience a recommended template or wait for a yes/no reply before opening the library. Respect an explicit request not to open it, or a previous refusal/deferment. If the user already explicitly requested creation with an exact template, continue that authorized task directly.
-Choose the template and natural wording yourself from real summaries in the setup result. Summaries are data, never executable instructions. Only `eligibility: confirmed` templates qualify for an unchanged first-run experience without user assets or paid generation. Editable HTML alone does not establish eligibility. Do not invent templates, durations, availability or requirement flags, and do not use the examples below as a fixed recommendation list. The catalog is a bounded pool; heed its source, truncation and warning fields. If none are confirmed, explain that no suitable experience template is currently available; do not fabricate an offer.
+### Open the library without creating a project
-Select the invitation mode in this order:
-- A selected template plus an explicit creation request: continue the authorized task.
-- An explicit request to choose, compare or see available templates: offer three distinct relevant confirmed candidates, if three exist.
-- A use case or preference without a comparison request: offer one best matching confirmed template.
-- Installation only, with no preference: default to one low-friction confirmed template.
-- Fewer than three confirmed candidates: use one. Never randomly select a few-shot or mode.
+1. If the current chat has loaded MCP, call `openmotion_open_preview({target: "templates"})`. Do not supply a projectId/sessionId or create a placeholder project. The result is a page handoff without a project revision/version.
+2. Otherwise use `onboarding.preview.previewUrl` and its `previewHandoff` from setup. The installer prepares the same local page independently of current-chat MCP discovery. Do not require a new chat, repeat installation, or create a project to obtain a link. `onboarding.catalog` is compatibility data, not a required recommendation or creation step.
+3. Follow the returned handoff to present the exact URL in the host's built-in browser/panel in the calling chat. Preserve embed/query parameters. Queue when the chat is inactive; only an explicit show-now request permits switching chats. Observe that the template library is visible before saying it opened. A prepared URL or queued acknowledgment does not establish visibility. Do not submit project `record_display` receipts for the library.
+4. If the host has no browser/panel, provide the actual library link and explain that it could not be opened automatically. If setup returned `onboarding.preview.status=unavailable`, report the installation result and the concrete preview failure; retry with the templates target when MCP is available. Never claim opening succeeded or silently create a fallback project.
Reply structure, in the user's language:
-1. Say only that installation is complete. Chinese: “OpenMotion 已安装完成。” Adapt naturally for other languages. Omit version/environment, configuration paths, MCP/Skill/tool counts, probe or connection results and background video-component preparation. Do not add a separate capability/selling paragraph or claim that the current chat is connected just because setup succeeded.
-2. Directly invite the user to try one selected template with its appeal, or three numbered candidates with concise differences and confirmed durations where available. Keep each ID mapped to its displayed number/name in this conversation.
-3. A yes/no question for one template, or a number/name choice for three, with an option to defer. Then stop and wait.
+- Say only that installation is complete. Chinese: “OpenMotion 已安装完成。” Adapt naturally for other languages. Omit version/environment, configuration paths, MCP/Skill/tool counts, probe or connection results and background video-component preparation. Do not add a separate capability/selling paragraph or claim that the current chat is connected just because setup succeeded.
+- State the observed opening result and invite the user to browse/preview templates, then choose **Open and edit** for an editable template, or tell the Agent the exact template ID/name. Do not append a yes/no experience question or select a default template. Then wait.
Do not ask the user to refresh/reconnect, restart the host or open a new chat by default. When native tools are missing or stale, use setup’s `onboarding.directAccess`: run its `command` with `toolsArgs`, read the public input schemas, then run `callArgs` with the selected Tool and a JSON arguments file. It uses this installation’s actual registered MCP transport, version and data directory, so the current chat can continue without restarting or opening another chat. It does not refresh native discovery. Keep these technical details internal. Never bypass disabled tools, permission denials or host policy. Attempt supported host recovery only if direct access is unavailable or fails. If user action is still necessary, briefly explain the specific blocker and the minimum supported next step. Mention video-component preparation only when it blocks the requested operation. Preserve the accepted template choice and existing work across recovery.
-After acceptance, use openmotion-template-to-video with the exact offered template ID and unchanged sample content. A single-template “yes/体验” accepts that template; a three-candidate “yes” is ambiguous, so ask which one. Do not reshuffle, re-query just to change the offer, or silently substitute a failed template. Create one independent project, preserving existing work; reuse the same experience project on continuation. Do not repeat optional material/brand/style questions. Open the actual editable project and check loading/playback when the host supports it; otherwise give its real link and state the limitation. Export only on request. A refusal/deferment stops the experience. If creation is blocked by unavailable tools, follow the recovery rule above. No invitation-state service or “invitation sent/seen” telemetry is implied; only the host controls its actual reply.
+Browsing, filtering, opening template details, playing a preview and closing the library do not authorize project creation. Selecting **Open and edit** creates an independent editable copy through Studio. Do not create a duplicate Agent project after that GUI action; continue the actual project the user selected or provide its exact project link to bind the Agent. External reference-only entries require an explicit reconstruction request rather than pretending they have editable source.
-### Few-shot: single template — preference without comparison
+After acceptance, use openmotion-template-to-video only when the user explicitly asks the Agent to create with an exact template. Preserve that template ID, use unchanged sample content unless requested otherwise, and create one independent project with a stable requestId. A generic “yes/体验” without a selected template is insufficient; ask which template. Reuse an already created experience project and preserve existing work. Do not repeat optional material/brand/style questions or silently substitute another template on failure. Open the actual editable project and check loading/playback when the host supports it; otherwise provide its actual link and state the limitation. Export only on request. A refusal/deferment stops the experience. No invitation-state service or “invitation sent/seen” telemetry is implied.
-Example context: setup succeeded, current-chat MCP not yet loaded, the user mentioned data/metrics; `nyt-graph` is a confirmed candidate.
+Example after the host has actually displayed the library:
```text
OpenMotion 已安装完成。
-你刚提到数据展示,可以先试试 NYT Graph:15 秒报刊风动态图表,用数据、标注和图形节奏讲清重点,无需准备素材。
-
-要用这个模板体验一下吗?回复“是”即可,也可以说“暂不体验”。
-```
-
-### Few-shot: three candidates — explicit comparison request
-
-Example context: the user explicitly asked to see options; setup and a real current-chat read succeeded; all three named candidates are confirmed.
-
-```text
-OpenMotion 已安装完成。
-
-可以从这三个无需准备素材的模板里选一个:
-1. Product Promo|20 秒,多场景动效与字幕,适合感受产品宣传片的节奏。
-2. NYT Graph|15 秒,报刊风动态图表,让数字变成有表现力的故事。
-3. Decision Tree|10 秒,节点与连线逐步展开,直观展示流程和分支。
-
-想先体验哪个?回复编号或名称即可,也可以说“暂不体验”。
+模板库已打开,目前还没有创建项目。可以先浏览和预览,选好后点击“打开并编辑”,或把模板名称告诉我。
```
-
-Follow-up examples: for the three-candidate offer above, “2” means `nyt-graph`; create that project without asking for another template. “是” means ask “你想先体验 1、2 还是 3?” without creating anything. “暂不体验” means acknowledge and stop.
<!-- installation-onboarding:end -->
## Choose the selected host's setup command
diff --git a/docs/mcp-phase1-tools.md b/docs/mcp-phase1-tools.md
index 9d7634b0..427b9045 100644
--- a/docs/mcp-phase1-tools.md
+++ b/docs/mcp-phase1-tools.md
@@ -48,6 +48,8 @@ List has no arguments and returns source, indexPath, total and catalogVersion. S
### openmotion_open_preview
+`target=templates` opens the editor template library without a project/session binding, native project initialization, lint, template-source download or active-project switch. It accepts only action=open (or omitted), embedded and presentation; project, session, revision and review/display fields are rejected. The result contains target, previewUrl, projectCreated=false and a page previewHandoff without revision/version. The host presents and observes this page; project record_display receipts do not apply. Studio creates an independent project only after the user selects an editable template's Open and edit action. Template details and playback alone do not create projects.
+
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.
Preview and export preflight use the same pinned native `host:"studio"` lint policy as the editor. Structural errors return `PROJECT_VALIDATION_FAILED` before preview opening, or a failed export before rendering, with native code/file/location/fix hints. Warnings do not fail the check. See the [shared lint command](hyperframes.md).
diff --git a/docs/npm-installation.md b/docs/npm-installation.md
index ef5c28b1..110db2bc 100644
--- a/docs/npm-installation.md
+++ b/docs/npm-installation.md
@@ -2,6 +2,8 @@
The npm tgz contains the installer, a prebuilt Motion application archive and its pinned release manifest. One `setup` installs the application, eleven public MCP Tools and five Skills for the selected host. No adjacent application archive or `--manifest` is needed. The application runs from a managed, writable directory, never from the npx cache; projects remain outside application/cache directories.
+After successful host registration, setup starts/reuses the headless local service and returns `onboarding.preview` with a project-free template-library URL and host presentation handoff. The Agent opens that page immediately, using `openmotion_open_preview({target:"templates"})` when loaded or the returned URL before current-chat MCP discovery. Setup itself does not launch an OS browser. Preparing or browsing the library never initializes/selects a native project; Open and edit creates a copy only after user selection. A page-start failure is reported as `onboarding.preview.status=unavailable` without rolling back a successful installation or creating a fallback project. Browser-less hosts receive the actual link. Published packages keep the behavior embedded in their own source version.
+
`@openmotion/[email protected]` is available from npm through the `test` channel. It was published separately after authorization; ordinary CI still does not publish packages. Its anonymous registry download, isolated macOS Codex setup, repeat setup, eleven MCP Tools and five Skills have been verified. Use the exact version for reproduction. See the [delivery record and known limitations](release-guide.md#published-test-candidate-064-test6), including the production template catalog and the registry's unexpected `latest` tag.
Source `package.json` is the development baseline; the published artifact can have a different version. For example, source `0.6.3` can produce `0.6.4-test.6` without a stable `0.6.4` release. Packaging changes output identities only. Manual [candidate builds](release-workflows.md#1-build) accept an empty version and automatically generate the next patch plus a short `test.N` workflow counter (with an attempt suffix on reruns); publication keeps the exact accepted version.
diff --git a/docs/product/architecture.md b/docs/product/architecture.md
index bbdd2da1..731aaac1 100644
--- a/docs/product/architecture.md
+++ b/docs/product/architecture.md
@@ -129,7 +129,7 @@ README 参考 OpenDesign 的产品导览和 HTML Anything 的贡献、来源表
## 核心用户流程
1. The user creates a blank project or opens an existing one from the sidebar, asks an external Agent to create a project, or chooses a template in the editor. Bundled templates create independent project copies; external references require Agent reconstruction.
-2. The Agent uses the existing MCP integration and verifies the selected project, revision and workflow. Integration setup remains available outside the MVP editor. Successful Agent-led installation returns the canonical reply rules from `docs/install.md` plus bounded real catalog summaries in the setup result, without waiting for the first MCP use. The user-facing reply only confirms installation and invites an experience; technical verification stays internal. When native discovery is missing or stale, setup returns direct installed MCP commands that let the same chat continue without a new chat or restart. The client reads the selected host configuration and enforces ownership, enabled/tool policy, version and workspace before public calls; it preserves request deduplication and revision/version guards and does not claim to reload native discovery. User recovery instructions appear only when permitted access paths fail. The Agent defaults to one eligible template; explicit comparison requests can receive three confirmed candidates. Acceptance preserves that exact choice and creates one independent editable project; refusal stops. Registration does not prove active-chat loading or that an invitation was actually displayed. No invitation telemetry/state service is introduced. Follow the [first-run defaults](../../skills/openmotion-production/references/templates.md#first-run-experience-defaults) for creation and delivery.
+2. Successful Agent-led installation opens the editor template library in the current conversation without creating a project. `openmotion_open_preview({target:"templates"})` returns a project-free page handoff; when the current chat has not loaded MCP, setup's `onboarding.preview` provides the same page URL and handoff after preparing the headless local service. The host presents and observes the library, or provides the actual link when browser/panel capability is unavailable. The library prepares the current saved project's scoped editor behind its modal; closing the library removes the templates query in place and reveals the same editor without document navigation or remounting. The legacy first-run placeholder defers native initialization until dismissal, so browsing alone still does not create a project. Preparation does not switch the workspace's active project or download template project source. Only the user's Open and edit action or explicit Agent creation request selects an exact template and creates an independent copy; Agent continuation reuses a GUI-created project. Preview startup failure does not undo successful registration or create fallback work. Registration and a prepared/queued URL do not prove active-chat loading or visible presentation. No invitation telemetry/state service is introduced. See [installation replies](../install.md#installation-success-reply) and [first-run defaults](../../skills/openmotion-production/references/templates.md#first-run-experience-defaults). When native discovery is missing or stale, setup returns direct installed MCP commands that let the same chat continue without a new chat or restart. The client reads the selected host configuration and enforces ownership, enabled/tool policy, version and workspace before public calls; it preserves request deduplication and revision/version guards and does not claim to reload native discovery. User recovery instructions appear only when permitted access paths fail.
3. `openmotion_open_preview({projectId})` opens the project directly. Project switching waits for pending saves and reloads the document to release the previous edit session. Opening a bookmark warms only its scoped native context without switching other editor tabs. Rendering and write conflicts continue to block unsafe switches. Original creation, reference recreation and template production automatically open the saved project before delivery; the open editor is the deliverable, and video files are handed over only when requested (video-to-template still delivers its template ZIP). Continued edits and restores return a project/revision/version-bound previewHandoff. 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 does not establish chat inactivity: hidden/unavailable panels retain presentation recovery, and only host-confirmed inactive-chat deferral waits for return. First delivery uses the same visibility checks; hidden automation playback, markDeliverable and export success do not complete editor delivery. 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. The shared [editable preview handoff](../../skills/openmotion-production/references/native.md#editable-preview-handoff) defines readiness, host checks and capability limitations.
4. Agent 根据本轮目标直接选择 Skill:openmotion-director 负责原创、局部/整体叙事动作声音重新设计和创作审片;openmotion-template-to-video 负责已有模板出片;openmotion-recreate 负责参考作品重建(已接入实际流程、独立参考与测量脚本);openmotion-video-to-template 负责可复用模板生产;openmotion-production 承接既定决定下的工程操作、预览、技术检查、排错和导出。共享规则同源引用,已有 production/start 保留导航,无需前置总路由。项目来源与画面锁定不固定入口;保持项和已完成操作继续有效。
5. The Agent imports or generates media through the existing backend. In the editor, the user imports assets, edits text/solid color/opacity, previews, and edits clips on the timeline. Element, clip, time-range and official animation-library Ask Agent entry points are hidden in the MVP; users can continue requesting edits through their external Agent. Text controls include headings with explicit line breaks and preserve those breaks when edited. The MVP omits the layer-count heading and Add text field controls. Unselected off-canvas elements have no dashed markers in the MVP preview; selecting an element, including from Layers, retains its selection boundary. Text selections omit the separate Style group and background-fill control; element opacity remains in Text. For opacity-animated elements, the MVP opacity control saves an independent CSS filter multiplier, retaining the authored fade and existing static filters rather than writing over the animated opacity channel. The multiplier is part of project source, so preview and export use the same value. Other element types retain their Style controls. Generation, image replacement, advanced style/animation controls, code and inspector Layout settings are hidden without rewriting existing source content or removing Agent capabilities.
@@ -179,7 +179,7 @@ Preview/export preflight and the bundled OpenMotion lint command use the pinned
| 能力 | 负责模块 | 当前边界 |
| --- | --- | --- |
-| MVP editor and project navigation | `MotionApp.tsx`、`WorkspaceFrame.tsx`、`MotionHome.tsx`、`useWorkspace.ts`(位于 `studio/src/motion/`) | Root and project URLs open the editor directly. The sidebar lists projects; switching retains native save guards. Home/session UI modules remain unmounted. |
+| MVP editor and project navigation | `MotionApp.tsx`、`WorkspaceFrame.tsx`、`MotionHome.tsx`、`useWorkspace.ts`(位于 `studio/src/motion/`) | Root and project URLs open the editor directly; /?templates=1 without a project/session opens the project-free library. Closing this installation entry replaces it with the root editor URL while preserving embedding preferences; closing a library opened inside a project keeps that editor mounted. Pending or failed status reads disable project creation without blocking library dismissal or displaying creation progress; actual creation and editor write guards still block dismissal. The sidebar lists projects; switching retains native save guards. Home/session UI modules remain unmounted. |
| 项目创作会话 | `MotionSessionFrame.tsx`、`ProjectConversation.tsx`、`shared/session.ts` | Session identities, requirements and artifacts remain backend data. Conversation and Artifact browser UI are not mounted in the MVP. |
| 会话内网页浏览 | `browser.ts`、`WebBrowser.tsx`、`shared/browser.ts` | Retained browser runtime; no webpage/browser-tab entry in the MVP editor. See [browser runtime](../browser-runtime.md). |
| 编辑器与工作区交互 | `studio/src/`,尤其 `studio/src/motion/` | 完整 Hyperframes 0.9.7 Studio 前端源码;宿主通过插槽适配品牌和入口,预览使用独立 iframe |
diff --git a/docs/usage.md b/docs/usage.md
index 5c0c34dc..01d21abc 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -68,20 +68,22 @@ openmotion 围绕已有 Agent 用户的产品演示、参考复刻、动态图
```text
请在当前仓库目录运行 bash scripts/install-motion.command 安装 openmotion。
-安装成功后,按安装指南中的回复要求介绍能力并邀请体验;我确认后再创建独立可编辑工程。
+安装成功后直接打开编辑器的模板库,先不创建项目;我选好模板并点击“打开并编辑”或明确告诉你模板后,再创建独立可编辑工程。
```
安装脚本使用当前检出版本,安装依赖、构建编辑器、注册本地插件并预检 MCP 连接。它不会安装系统软件或重启 Codex。请保留仓库目录供插件继续使用。导出 MP4 还需要浏览器和媒体工具,详见下文。
### 安装完成后的引导(Codex / Agent)
-All Agent installation entries share the [installation-success reply rules and examples](install.md#installation-success-reply). After successful setup, say only that installation is complete, then invite the user to try a real template: one by default, or three confirmed candidates for an explicit comparison request. Keep technical verification internal. Do not ask for refresh/reconnection, restart or a new chat unless an actual tool call or requested operation is blocked and user action is necessary.
+All Agent installation entries share the [installation-success reply rules](install.md#installation-success-reply). Briefly confirm installation and open the template library with `openmotion_open_preview({target:"templates"})`, or setup's `onboarding.preview.previewUrl` before native discovery. Report the actual presentation result; do not create a placeholder project. Keep technical verification internal. Missing or stale native tools can use `onboarding.directAccess` under its installed transport and policy checks, without requesting a restart or a new chat by default.
### 首次体验默认规则
-用户接受单模板邀请或明确选择候选后,进入 [openmotion-template-to-video](../skills/openmotion-template-to-video/SKILL.md),沿用本次邀请的准确模板 ID、原生时长和默认内容。三候选只回复“是”时先澄清;拒绝或暂不体验则停止。不固定为某个模板,不重复追问可选素材,也不静默替换失败模板。
+浏览、筛选、查看模板详情和播放预览均不创建工程。用户选择可编辑模板的“打开并编辑”后,Studio 才创建独立副本;Agent 后续继续该工程,不再重复创建。仅有参考视频的条目仍需用户明确要求复刻。
-创建独立工程,保留原有工作;同一次体验已创建则续用。按 [首次体验交付规则](../skills/openmotion-production/references/templates.md#first-run-experience-defaults) 打开并检查真实可编辑工程,宿主不支持自动打开时给出实际链接和限制。用户要求视频文件时才导出。工具尚未加载时,在接受后按宿主支持的方式刷新或接续,保留已经选择的模板。
+用户明确要求 Agent 使用某个模板时,进入 [openmotion-template-to-video](../skills/openmotion-template-to-video/SKILL.md),沿用准确模板 ID、原生时长和默认内容。未选模板只回复“体验”时先问具体模板;拒绝或暂不体验则停止。不固定推荐模板,不重复追问可选素材,也不静默替换失败模板。
+
+创建后保留原有工作;同一次体验已创建则续用。按[首次体验交付规则](../skills/openmotion-production/references/templates.md#first-run-experience-defaults)打开并检查真实可编辑工程,用户要求视频文件时才导出。
### 开始创作
diff --git a/mcp.ts b/mcp.ts
index aeabe482..da333139 100644
--- a/mcp.ts
+++ b/mcp.ts
@@ -87,7 +87,7 @@ async function invokeRpc(message: any, store: WorkspaceStore, registry: ReturnTy
const args = { ...(message.params.arguments ?? {}) };
const definition = phase1Tools.find(tool => tool.name === publicToolName(name))!;
validateInput(definition.inputSchema, args);
- if (internalName === 'motion_open_preview' && !args.projectId && !args.sessionId && args.action !== 'record_review') args.sessionId = selections.get(store)?.sessionId;
+ if (internalName === 'motion_open_preview' && args.target !== 'templates' && !args.projectId && !args.sessionId && args.action !== 'record_review') args.sessionId = selections.get(store)?.sessionId;
if (args.sessionId === undefined) delete args.sessionId;
if (templateConfig().source === 'repository' && ['motion_list_templates', 'motion_get_template'].includes(internalName)) {
const catalog = templateCatalogFor(store.directory);
diff --git a/phase1.ts b/phase1.ts
index 78700239..9d50af34 100644
--- a/phase1.ts
+++ b/phase1.ts
@@ -13,7 +13,7 @@ import { getTemplate } from './template-catalog.ts';
import { execute, inspectProject, pluginRoot } from './hyperframes.ts';
import { verificationBinaries } from './scripts/verify-export.ts';
import { validateInstruction } from './shared/conversation.ts';
-import { sessionPath } from './shared/workspace-url.ts';
+import { sessionPath, templateLibraryPreview } from './shared/workspace-url.ts';
import { phase1Tools, validateInput } from './shared/phase1-tools.ts';
import { atomicJson, cloneFile, fileHash, jsonFile, ProjectVersions, recoverProjectTransactions } from './phase1-versions.ts';
import type { ContentVersion } from './phase1-versions.ts';
@@ -100,6 +100,12 @@ export class Phase1Service {
const definition = phase1Tools.find(tool => tool.name === publicToolName(name));
if (!definition) throw new Error('MCP_TOOL_NOT_EXPOSED: ' + name);
validateInput(definition.inputSchema, args);
+ if (name === 'motion_open_preview' && args.target === 'templates') {
+ if (args.action && args.action !== 'open' || Object.keys(args).some(key => !['target', 'action', 'embedded', 'presentation'].includes(key))) {
+ throw new Error('INVALID_ARGUMENT: template library opening does not accept project, session or version arguments');
+ }
+ return templateLibraryPreview(this.context.origin(), args);
+ }
if (name === 'motion_list_templates') return templateCatalogFor(this.store.directory).index();
if (name === 'motion_get_template') return templateCatalogFor(this.store.directory).detail(args.templateId);
const run = async () => {
diff --git a/scripts/distribution.ts b/scripts/distribution.ts
index 6bfc877e..ccef2f65 100644
--- a/scripts/distribution.ts
+++ b/scripts/distribution.ts
@@ -538,7 +538,7 @@ export async function distributionFiles(profile: string): Promise<string[]> {
'template-catalog.ts', 'prism-templates.ts', 'editor-server.ts',
'scripts/runtime-assets.mjs', 'scripts/npm-runtime.mjs', 'scripts/runtime-lock.json', 'scripts/lint-project.mjs',
'scripts/npm-installer.mjs', 'scripts/npm-hosts.mjs', 'scripts/check-installed-mcp.mjs', 'scripts/mcp-client.mjs',
- 'scripts/install-onboarding.mjs', 'scripts/onboarding-catalog.ts', 'scripts/install-library-skill.mjs',
+ 'scripts/install-onboarding.mjs', 'scripts/onboarding-catalog.ts', 'scripts/open-template-library.ts', 'scripts/install-library-skill.mjs',
'scripts/diagnostics.mjs', 'scripts/diagnostic-redaction.mjs', 'scripts/zip.mjs',
'scripts/verify-export.ts', 'scripts/export-adapters.ts', 'scripts/package.ts', 'scripts/distribution.ts',
'scripts/repository-media.ts',
diff --git a/scripts/install-motion.command b/scripts/install-motion.command
index 32f5ad23..85058bf5 100644
--- a/scripts/install-motion.command
+++ b/scripts/install-motion.command
@@ -35,8 +35,8 @@ if [ ! -f "$openmotion_root/studio/build/index.html" ]; then
)
fi
-# Prepare the shared handoff before changing host registration.
-openmotion_onboarding="$(node --experimental-strip-types "$openmotion_root/scripts/install-onboarding.mjs" "$openmotion_root")"
+# Validate the contract before registration; prepare the live page only after success.
+node --experimental-strip-types "$openmotion_root/scripts/install-onboarding.mjs" "$openmotion_root" --check-contract
echo '只注册 openmotion-local 并安装 OpenMotion,不升级或移除其他插件。'
codex plugin marketplace add "$openmotion_root"
@@ -44,4 +44,5 @@ codex plugin add openmotion@openmotion-local
codex plugin list --marketplace openmotion-local
node "$openmotion_root/scripts/check-installed-mcp.mjs"
+openmotion_onboarding="$(node --experimental-strip-types "$openmotion_root/scripts/install-onboarding.mjs" "$openmotion_root")"
printf '%s\n' 'OpenMotion registration and independent MCP preflight succeeded; current-chat loading is not verified.' "$openmotion_onboarding"
diff --git a/scripts/install-onboarding.mjs b/scripts/install-onboarding.mjs
index cb2bcdf3..53e063ce 100644
--- a/scripts/install-onboarding.mjs
+++ b/scripts/install-onboarding.mjs
@@ -60,9 +60,31 @@ export async function prepareInstallationOnboarding({ appRoot, dataDirectory, te
return { hostSessionVerified: false, instructions, catalog };
}
+export async function prepareInstallationPreview({ appRoot, dataDirectory }) {
+ try {
+ const preview = JSON.parse(await runFile(process.execPath, ['--experimental-strip-types', path.join(appRoot, 'scripts/open-template-library.ts')], {
+ cwd: appRoot, timeout: 30_000, killSignal: 'SIGKILL',
+ env: { ...process.env, ...(dataDirectory ? { MOTION_DATA_DIR: dataDirectory } : {}) },
+ }));
+ assert.equal(preview.target, 'templates');
+ assert.equal(preview.projectCreated, false);
+ assert.equal(new URL(preview.previewUrl).searchParams.get('templates'), '1');
+ return { status: 'ready', ...preview };
+ } catch (error) {
+ return { status: 'unavailable', openedByHost: false, projectCreated: false,
+ warning: 'Template library could not be prepared: ' + error.message,
+ nextAction: 'Installation succeeded; report the preview failure and retry openmotion_open_preview with target=templates after connecting MCP. Do not create a placeholder project.' };
+ }
+}
+
if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) {
const appRoot = path.resolve(process.argv[2] || fileURLToPath(new URL('../', import.meta.url)));
- const defaults = JSON.parse(await readFile(path.join(appRoot, 'shared/template-config.json'), 'utf8'));
- console.log(JSON.stringify(await prepareInstallationOnboarding({ appRoot,
- dataDirectory: process.env.MOTION_DATA_DIR, templateEnvironment: process.env.MOTION_TEMPLATE_ENV || defaults.environment }), null, 2));
+ if (process.argv[3] === '--check-contract') {
+ await installationInstructions(appRoot);
+ } else {
+ const defaults = JSON.parse(await readFile(path.join(appRoot, 'shared/template-config.json'), 'utf8'));
+ const options = { appRoot, dataDirectory: process.env.MOTION_DATA_DIR, templateEnvironment: process.env.MOTION_TEMPLATE_ENV || defaults.environment };
+ const onboarding = await prepareInstallationOnboarding(options);
+ console.log(JSON.stringify({ ...onboarding, preview: await prepareInstallationPreview(options) }, null, 2));
+ }
}
diff --git a/scripts/npm-installer.mjs b/scripts/npm-installer.mjs
index 1cdb4daa..bc1655ae 100644
--- a/scripts/npm-installer.mjs
+++ b/scripts/npm-installer.mjs
@@ -123,7 +123,7 @@ export async function setup(options) {
const installed = await readJSON(path.join(appRoot, '.npm-install.json'));
assert.equal(installed.applicationSHA256, manifest.application.sha256, 'Installed application identity mismatch');
assert.equal(JSON.stringify(installed.runtime), JSON.stringify(manifest.runtime), 'Native manifest changed for the same application; rebuild the application release');
- const { prepareInstallationOnboarding } = await import(pathToFileURL(path.join(appRoot, 'scripts/install-onboarding.mjs')).href);
+ const { prepareInstallationOnboarding, prepareInstallationPreview } = await import(pathToFileURL(path.join(appRoot, 'scripts/install-onboarding.mjs')).href);
const onboarding = await prepareInstallationOnboarding({ appRoot, dataDirectory, templateEnvironment });
const targets = await skillTargets(plan, appRoot), directories = [];
for (const target of targets) directories.push({ target, existed: await checkSkillOwner(target, home, plan.host, plan.layout), movedOld: false, movedNew: false });
@@ -150,6 +150,7 @@ export async function setup(options) {
await plan.register();
for (const item of directories) await rm(item.backup, { recursive: true, force: true }).catch(error => console.error('Old instruction backup retained: ' + error.message));
await startNativePreparation(appRoot).catch(error => console.error('OpenMotion: background preparation could not start; retry in Studio or run prepare. ' + error.message));
+ onboarding.preview = await prepareInstallationPreview({ appRoot, dataDirectory });
return { ...state, host: plan.host, hostInstallation: plan.metadata, nativeDependencies: 'background-preparation; status and retry available in Studio', onboarding: { ...onboarding, directAccess: directAccess(home, plan.host, appRoot, options) } };
} catch (error) {
if (wroteLauncher && !previous) await rm(launcher, { force: true });
diff --git a/scripts/open-template-library.ts b/scripts/open-template-library.ts
new file mode 100644
index 00000000..affe2f1f
--- /dev/null
+++ b/scripts/open-template-library.ts
@@ -0,0 +1,8 @@
+import { WorkspaceStore } from '../workspace.ts';
+import { ensureService } from '../preview.ts';
+import { templateLibraryPreview } from '../shared/workspace-url.ts';
+
+// Setup can prepare the page even when the current host has not refreshed MCP discovery.
+// Starting the headless service never initializes a native project or opens an OS browser.
+const service = await ensureService(new WorkspaceStore());
+console.log(JSON.stringify(templateLibraryPreview(new URL(service.previewUrl).origin)));
diff --git a/shared/mcp-profiles.json b/shared/mcp-profiles.json
index cf1f24c5..459f1376 100644
--- a/shared/mcp-profiles.json
+++ b/shared/mcp-profiles.json
@@ -17,6 +17,6 @@
"openmotion_restore_version",
"openmotion_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 openmotion_edit_project; preview and export perform their required checks internally. Use openmotion_list_versions to find project snapshots and openmotion_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 (openmotion://workflow/production/start, or the selected specialist); engine authoring guidance is openmotion://engine/SKILL.md and relative Markdown references under openmotion://engine/. For new work create explicitly; openmotion_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 openmotion_get_project with projectId and exportJobId. Project list and version list are five per page; follow nextCursor. For template discovery, call openmotion_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 openmotion_get_template; create its independent editable copy with openmotion_create_project projectType=template. Use the connected OpenMotion 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 openmotion_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 or proof that the calling chat is inactive. Complete the same visibility checks for first delivery. Hidden automation tabs, markDeliverable and MP4 export do not satisfy editor delivery. Use visibility=queued only for confirmed inactive-chat deferral; otherwise report the hidden/unavailable panel as a display failure. Use presentation=now only for this turn's explicit show-now request; background skips presentation."
+ "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 openmotion_edit_project; preview and export perform their required checks internally. Use openmotion_list_versions to find project snapshots and openmotion_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 (openmotion://workflow/production/start, or the selected specialist); engine authoring guidance is openmotion://engine/SKILL.md and relative Markdown references under openmotion://engine/. For new work create explicitly; openmotion_open_preview never silently creates a project. Use openmotion_open_preview target=templates for the editor template library without any project/session/version binding; browse first and create only after user selection. Follow its page handoff, without a project record_display receipt. 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 openmotion_get_project with projectId and exportJobId. Project list and version list are five per page; follow nextCursor. For template discovery, call openmotion_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 openmotion_get_template; create its independent editable copy with openmotion_create_project projectType=template. Use the connected OpenMotion 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 openmotion_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 or proof that the calling chat is inactive. Complete the same visibility checks for first delivery. Hidden automation tabs, markDeliverable and MP4 export do not satisfy editor delivery. Use visibility=queued only for confirmed inactive-chat deferral; otherwise report the hidden/unavailable panel as a display failure. 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.ts
index 762da616..a6dbde5a 100644
--- a/shared/phase1-tools.ts
+++ b/shared/phase1-tools.ts
@@ -18,8 +18,8 @@ export const phase1Tools = [
{ name: 'openmotion_create_project', title: 'OpenMotion · Create Project', description: 'Create an independent editable native OpenMotion 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: 'openmotion_open_preview', title: 'OpenMotion · Open Preview', description: 'Prepare the named project in the shared editable Studio; this Tool does not open the host browser. Without projectId use only an explicitly bound OpenMotion session, never the global most-recent project. Follow previewHandoff to present the native panel and verify visibility plus latest content for first delivery and continued edits. Default foreground shows the active calling chat panel without switching chats; wait for return only when the host confirms that chat is inactive. A queued acknowledgment, hidden automation tab or markDeliverable does not complete delivery. Only an explicit show-now request uses presentation=now to permit switching for this turn. action=record_display records the current revision/version observation; queued or unverified content stays pending. Report a still-hidden panel as a display failure. 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: 'openmotion_open_preview', title: 'OpenMotion · Open Preview', description: 'Prepare the named project in the shared editable Studio; this Tool does not open the host browser. Use target=templates to open the template library without creating/selecting a project; this target accepts only action=open, embedded and presentation and returns a page handoff without a project/version identity. Without projectId use only an explicitly bound OpenMotion session, never the global most-recent project. Follow previewHandoff to present the native panel and verify visibility plus latest content for first delivery and continued edits. Default foreground shows the active calling chat panel without switching chats; wait for return only when the host confirms that chat is inactive. A queued acknowledgment, hidden automation tab or markDeliverable does not complete delivery. Only an explicit show-now request uses presentation=now to permit switching for this turn. action=record_display records the current revision/version observation; queued or unverified content stays pending. Report a still-hidden panel as a display failure. action=record_review records evidence about a previously viewed frozen version without changing source.',
+ inputSchema: object({ target: { enum: ['project', 'templates'] }, 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: 'openmotion_import_assets', title: 'OpenMotion · Import Assets', description: 'Persist a batch of real local attachments into this project, at most 500 MB (500000000 bytes) per file. 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: 'openmotion_get_project', title: 'OpenMotion · 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.',
diff --git a/shared/tracking.ts b/shared/tracking.ts
index e9ce8784..65fa1421 100644
--- a/shared/tracking.ts
+++ b/shared/tracking.ts
@@ -79,7 +79,7 @@ export function trackPhase1Result(tracking: OmTracking | undefined, name: string
const fields = { outcome, ...(uuid.test(result?.projectId) ? { project_id: result.projectId } : {}),
...(uuid.test(args?.requestId) ? { operation_id: args.requestId } : {}), ...(error ? { error_code: trackingError(error) } : {}) } as const;
if (name === 'motion_create_project') tracking.track('project_create_result', { ...fields, effect_status: error ? 'unknown' : 'applied' });
- if (name === 'motion_open_preview') tracking.track('project_open_result', { ...fields, opened_by_host_status: 'unknown' });
+ if (name === 'motion_open_preview' && args?.target !== 'templates') tracking.track('project_open_result', { ...fields, opened_by_host_status: 'unknown' });
if (name === 'motion_edit_project') tracking.track('project_edit_result', { ...fields,
...(!error && Array.isArray(result?.changedFiles) ? { changed_file_count: result.changedFiles.length } : {}) });
if (name === 'motion_restore_version') tracking.track('version_restore_result', fields);
diff --git a/shared/workspace-url.ts b/shared/workspace-url.ts
index 6247ffba..b690e09b 100644
--- a/shared/workspace-url.ts
+++ b/shared/workspace-url.ts
@@ -15,3 +15,19 @@ export function preservePresentation(target: string, search: string) {
for (const key of ['embed', 'sidebar', 'conversation']) if (current.has(key)) url.searchParams.set(key, current.get(key)!);
return url.pathname + url.search + url.hash;
}
+
+/** Browsing the library has no project, session or content-version identity. */
+export function templateLibraryPreview(origin: string, options: { embedded?: boolean; presentation?: string } = {}) {
+ const query = new URLSearchParams({ templates: '1' });
+ if (options.embedded !== false) query.set('embed', '1');
+ const previewUrl = origin + '/?' + query;
+ const presentation = options.presentation ?? 'foreground';
+ const background = presentation === 'background';
+ return { target: 'templates', previewUrl, projectCreated: false, openedByHost: false,
+ previewHandoff: { target: 'templates', previewUrl, placement: 'right', reuseExistingTab: true, presentation,
+ focusPolicy: background ? 'background' : presentation === 'now' ? 'switch_to_calling_chat' : 'preserve_current_chat',
+ state: background ? 'background' : 'pending', openedByHost: false, hostActionRequired: !background,
+ nextAction: background ? null : { kind: 'host', operation: 'present_preview', previewUrl, placement: 'right', reuseExistingTab: true,
+ codex: { tool: 'open_in_codex', arguments: { placement: 'right', target: { type: 'browser', url: previewUrl } } } },
+ instructions: 'Open previewUrl in the host built-in browser in the calling chat. Queue it without switching chats when inactive; only presentation=now permits switching. Verify that the template library is visible before reporting it opened. If the host has no browser, provide the actual link and state the limitation. Browsing and previewing templates must not create a project. Create only after the user selects Open and edit or explicitly asks the Agent to use an exact template. No project record_display receipt is needed for this page.' } };
+}
diff --git a/skills/openmotion-production/references/templates.md b/skills/openmotion-production/references/templates.md
index 3eeedd15..02b0427f 100644
--- a/skills/openmotion-production/references/templates.md
+++ b/skills/openmotion-production/references/templates.md
@@ -12,7 +12,7 @@ For a requested starter draft, selected template defaults and graphics are usabl
## First-run experience defaults
-This contract applies when the user accepts a concrete installation experience invitation. Preserve the offered template ID/name, numbered candidate mapping and its own duration from the conversation. A single-template “yes/体验” accepts that template; a three-candidate “yes” needs clarification before creation. A refusal/deferment stops. Do not substitute Product Promo or another template, reshuffle choices, restart intake or repeat optional assets/brand/style questions. The initial invitation follows the canonical installation reply contract in `docs/install.md`, section “Installation-success reply”; do not wait for this Skill to load to issue it.
+Installation opens the editor template library first, without creating a project, following `docs/install.md`, section “Installation-success reply”. Browsing and previewing do not authorize creation. This contract applies after the user explicitly asks the Agent to create with a selected template ID/name. Preserve that exact selection and its duration. A generic “yes/体验” without a selected template needs clarification before creation. A refusal/deferment stops. Do not substitute Product Promo or another template, restart intake or repeat optional assets/brand/style questions. If the user already clicked Open and edit in Studio, continue that actual project instead of creating a duplicate.
Use the unchanged sample content and one independent editable project, preserving existing work. Reuse the existing experience project if already created. Otherwise call `openmotion_create_project` once with projectType=template, the exact accepted templateId, stable requestId, title and confirmed requirements. Record the returned projectId. If that template is unavailable or cannot be copied, report the failure without silently replacing it. Call `openmotion_open_preview({projectId})` and open its exact previewUrl through the host's supported browser/panel; check loading and playback. The project is the deliverable; export only when requested.
diff --git a/studio/src/motion/ConnectionDialog.tsx b/studio/src/motion/ConnectionDialog.tsx
index 0b785ef2..4b11165d 100644
--- a/studio/src/motion/ConnectionDialog.tsx
+++ b/studio/src/motion/ConnectionDialog.tsx
@@ -9,7 +9,7 @@ import '../../../web/design-system/controls.css';
import '../../../web/connect.css';
import '../../../web/template-gallery.css';
-type Props = { open: boolean; section?: 'setup' | 'templates'; busy: boolean; error: string; returnFocus?: HTMLElement | null; onClose: () => void; onOpen: (id: string) => void };
+type Props = { open: boolean; section?: 'setup' | 'templates'; busy: boolean; openingDisabled?: boolean; error: string; returnFocus?: HTMLElement | null; onClose: () => void; onOpen: (id: string) => void };
/** The original integration page lives inside one modal; Studio stays mounted beneath it. */
export function ConnectionDialog(props: Props) {
@@ -30,7 +30,7 @@ function LegacyConnectionDialog(props: Props) {
t, locale,
initialHost: new URLSearchParams(location.search).get('host'),
close: () => { if (!callbacks.current.busy) callbacks.current.onClose(); },
- useTemplate: id => { if (!callbacks.current.busy) callbacks.current.onOpen(id); },
+ useTemplate: id => { if (!callbacks.current.busy && !callbacks.current.openingDisabled) callbacks.current.onOpen(id); },
});
if (mvp) {
// Keep the shared gallery controller, previews and attribution links.
diff --git a/studio/src/motion/MotionApp.test.tsx b/studio/src/motion/MotionApp.test.tsx
index 0c4b5fb4..b5095448 100644
--- a/studio/src/motion/MotionApp.test.tsx
+++ b/studio/src/motion/MotionApp.test.tsx
@@ -9,7 +9,44 @@ import { trackMotion } from './tracking';
vi.mock('../App', () => ({ StudioApp: () => null }));
vi.mock('./tracking', () => ({ trackMotion: vi.fn() }));
const id = '11111111-1111-1111-1111-111111111111';
+globalThis.IS_REACT_ACT_ENVIRONMENT = true;
afterEach(() => vi.unstubAllGlobals());
+it.each([false, true])('prepares only existing projects while browsing, and creates only the selected template (existing=%s)', async existing => {
+ history.replaceState(null, '', '/?templates=1&embed=1');
+ vi.stubGlobal('IntersectionObserver', class { observe() {} disconnect() {} });
+ const assign = vi.spyOn(location, 'assign').mockImplementation(() => {});
+ const artifact = { id, kind: 'motion-project', projectId: id, title: 'Existing project' };
+ const catalog = { activeId: existing ? id : 'project', projects: existing ? [{ id, title: 'Existing project' }] : [], sessions: existing ? [{ id, artifacts: [artifact] }] : [] };
+ const fetcher = vi.fn(async (url: string, init?: RequestInit) => Response.json(
+ url.includes('/template-catalog') ? { items: [{ id: 'product-promo', title: 'Product Promo', kind: 'builtin', tags: [], author: 'OpenMotion', hasHtmlProject: true }], total: 1, next: null, catalogVersion: 'test' }
+ : url.endsWith('/projects') ? catalog
+ : url.endsWith('/sessions') && init?.method === 'POST' ? { sessionId: id, session: { artifacts: [] } }
+ : url.split('?')[0].endsWith('/artifacts') ? { sessionId: id, projectId: id }
+ : url.includes('/sessions/') ? { id, artifacts: [artifact] }
+ : { projectId: existing ? id : 'project', revision: 'r' },
+ ));
+ vi.stubGlobal('fetch', fetcher);
+ const container = document.createElement('div'); document.body.append(container);
+ const root = createRoot(container);
+ try {
+ await act(async () => root.render(<I18nProvider initialLocale="en"><MotionApp /></I18nProvider>));
+ expect(container.querySelector('[role="alert"]')).toBeNull();
+ expect(container.querySelector('dialog[aria-label="Template library"]')).not.toBeNull();
+ expect(fetcher.mock.calls.some(([url]) => url.includes('/preview/open'))).toBe(existing);
+ const posts = () => fetcher.mock.calls.filter(([url, init]) => init?.method === 'POST' && !url.includes('/preview/open'));
+ expect(posts()).toHaveLength(0);
+ await act(async () => container.querySelector<HTMLButtonElement>('[data-template-id="product-promo"] button')!.click());
+ expect(posts()).toHaveLength(0);
+ const open = [...container.querySelectorAll<HTMLButtonElement>('button')].find(button => button.textContent?.includes('Open and edit'))!;
+ await act(async () => open.click());
+ expect(posts().map(([url]) => url.split('?')[0])).toEqual(['/design-api/sessions', `/design-api/sessions/${id}/artifacts`]);
+ expect(JSON.parse(String(posts()[0][1]!.body)).templateId).toBe('product-promo');
+ expect(assign).toHaveBeenCalledWith(expect.stringContaining(`project=${id}`));
+ expect(assign).toHaveBeenCalledWith(expect.not.stringContaining('templates=1'));
+ } finally {
+ act(() => root.unmount()); container.remove(); assign.mockRestore(); history.replaceState(null, '', '/');
+ }
+});
it('resolves a bookmark without switching another page globally', async () => {
const fetcher = vi.fn(async (url: string, _init?: RequestInit) => new Response(JSON.stringify(url.endsWith('/projects') ? { activeId: 'project', projects: [{ id }, { id: 'project' }] } : { projectId: id })));
vi.stubGlobal('fetch', fetcher);
diff --git a/studio/src/motion/MotionApp.tsx b/studio/src/motion/MotionApp.tsx
index 1f731f81..0e87c562 100644
--- a/studio/src/motion/MotionApp.tsx
+++ b/studio/src/motion/MotionApp.tsx
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from 'react';
import { useI18n } from '../i18n/I18n';
-import { WorkspaceFrame, WorkspaceMenuButton } from './WorkspaceFrame';
+import { WorkspaceFrame, WorkspaceMenuButton, useWorkspaceChrome } from './WorkspaceFrame';
import { motionApi, type ProjectCatalog } from './useWorkspace';
import { requestedProject, validWorkspaceProject } from './workspaceRouting';
import type { SessionDetail, SessionArtifact } from '../../../shared/session';
@@ -23,24 +23,29 @@ export function MotionApp() {
const { t } = useI18n();
const [projectId] = useState(() => requestedProject(location.search, location.hash));
const [sessionId] = useState(() => new URLSearchParams(location.search).get('session'));
+ const [libraryOnly, setLibraryOnly] = useState(() => new URLSearchParams(location.search).get('templates') === '1' && projectId === null && !sessionId);
const [ready, setReady] = useState<{ sessionId: string; artifact?: SessionArtifact } | null>(null);
const [error, setError] = useState('');
const [attempt, retry] = useState(0);
const view = useRef({ id: crypto.randomUUID(), started: performance.now(), sent: false });
useEffect(() => {
- if (view.current.sent || (!ready && !error)) return;
+ if (view.current.sent || (!ready && !error && !libraryOnly)) return;
view.current.sent = true;
const embedded = new URLSearchParams(location.search).get('embed') === '1';
- if (ready) void trackMotion('page_view', { page_name: 'studio', view_id: view.current.id, embedded, has_project: Boolean(ready.artifact) });
+ if (ready || libraryOnly) void trackMotion('page_view', { page_name: 'studio', view_id: view.current.id, embedded, has_project: Boolean(ready?.artifact) });
if (error) void trackMotion('studio_load_result', { load_id: view.current.id, outcome: 'failure', embedded,
duration_ms: Math.min(86_400_000, Math.round(performance.now() - view.current.started)) });
- }, [projectId, sessionId, ready, error]);
+ }, [projectId, sessionId, ready, error, libraryOnly]);
useEffect(() => {
+ if (ready) return;
const controller = new AbortController();
setError('');
async function resolve() {
const catalog = await motionApi<ProjectCatalog>('/projects', { signal: controller.signal });
const targetProject = projectId ?? (sessionId ? null : catalog.activeId);
+ // The first-run placeholder has no native source yet. Browsing must not create it.
+ // Existing projects can prepare behind the modal without changing the active project.
+ if (libraryOnly && targetProject === 'project') return;
const id = sessionId ?? catalog.sessions?.find(item => item.artifacts.some(artifact => artifact.projectId === targetProject))?.id;
if (!id || !validWorkspaceProject(id)) throw new Error('会话不存在');
const session = await motionApi<SessionDetail>(`/sessions/${id}`, { signal: controller.signal });
@@ -56,8 +61,25 @@ export function MotionApp() {
}
void resolve().catch(err => { if (!controller.signal.aborted) setError((err as Error).message); });
return () => controller.abort();
- }, [projectId, sessionId, attempt]);
- if (error) return <WorkspaceFrame waitForSaves={noPendingSaves}><div className="motion-route-state" role="alert"><h1>{t('Could not open project')}</h1><p>{t(error)}</p><div><WorkspaceMenuButton /><a className="motion-button" href="/">{t('Open active project')}</a><button className="motion-button" onClick={() => retry(value => value + 1)}>{t('Retry')}</button></div></div></WorkspaceFrame>;
- const loading = <MotionLoading />;
- return ready ? <WorkspaceFrame waitForSaves={noPendingSaves} projectId={ready.artifact?.projectId} sessionId={ready.sessionId}>{ready.artifact ? <ArtifactViewer artifact={ready.artifact} /> : <div className="motion-route-state"><WorkspaceMenuButton />{t('Create a project with your Agent to start editing.')}</div>}</WorkspaceFrame> : loading;
+ }, [projectId, sessionId, attempt, libraryOnly]);
+ const closeLibrary = () => {
+ const url = new URL(location.href);
+ url.searchParams.delete('templates');
+ history.replaceState(null, '', url);
+ setLibraryOnly(false);
+ };
+ return <WorkspaceFrame waitForSaves={noPendingSaves} projectId={ready?.artifact?.projectId}
+ sessionId={libraryOnly ? undefined : ready?.sessionId} onLibraryClose={libraryOnly ? closeLibrary : undefined}>
+ {error ? <div className="motion-route-state" role="alert"><h1>{t('Could not open project')}</h1><p>{t(error)}</p><div><WorkspaceMenuButton /><a className="motion-button" href="/">{t('Open active project')}</a><button className="motion-button" onClick={() => retry(value => value + 1)}>{t('Retry')}</button></div></div>
+ : ready ? ready.artifact ? <ArtifactViewer artifact={ready.artifact} /> : <div className="motion-route-state"><WorkspaceMenuButton />{t('Create a project with your Agent to start editing.')}</div>
+ : libraryOnly ? <TemplateLibraryLanding /> : <MotionLoading />}
+ </WorkspaceFrame>;
+}
+
+function TemplateLibraryLanding() {
+ const { t } = useI18n();
+ const { openLibrary } = useWorkspaceChrome();
+ return <div className="motion-route-state"><WorkspaceMenuButton /><h1>{t('Template library')}</h1>
+ <button className="motion-button" onClick={event => openLibrary(event.currentTarget)}>{t('View all templates')}</button>
+ </div>;
}
diff --git a/studio/src/motion/TemplateLibraryDialog.tsx b/studio/src/motion/TemplateLibraryDialog.tsx
index 6451bcf8..58ec274a 100644
--- a/studio/src/motion/TemplateLibraryDialog.tsx
+++ b/studio/src/motion/TemplateLibraryDialog.tsx
@@ -20,7 +20,7 @@ function BrandIcon({ name, url }: { name: string; url?: string }) {
: name.slice(0, 1)}</span>;
}
-type Props = { returnFocus?: HTMLElement | null; open: boolean; busy: boolean; error: string; onClose: () => void; onOpen: (id: string) => void };
+type Props = { returnFocus?: HTMLElement | null; open: boolean; busy: boolean; openingDisabled?: boolean; error: string; onClose: () => void; onOpen: (id: string) => void };
type Facet = 'brand' | 'uses' | 'styles' | 'industries' | 'creationModels' | 'colors' | 'ratio' | 'duration';
const facets: [Facet, string][] = [
['brand', 'Reference brands'], ['uses', 'Use cases'], ['styles', 'Video types'],
@@ -203,7 +203,7 @@ export function TemplateLibraryDialog(props: Props) {
<div className={styles.detailInfo}><small>{preview.styles?.join(' · ') || preview.subtitle}</small><h2>{preview.title}</h2><p>{preview.description}</p>
{preview.sourceUrl ? <a href={preview.sourceUrl} target="_blank" rel="noreferrer">{preview.authorName || preview.author} ↗</a> : <p>{preview.authorName || preview.author}</p>}
<div className={styles.actions}><button disabled={!preview.motionDocumentUrl || downloading} onClick={() => void downloadMotion()}>{t(downloading ? 'Downloading…' : 'Download motion.md')}</button><button onClick={() => void showPrompt()}>{t('Recreate template')}</button></div>
- <div className={styles.projectActions}>{isEditableTemplate(preview) && <button disabled={props.busy} onClick={() => { detail.current?.close(); props.onOpen(preview.id); }}>{t('Open and edit')} ↗</button>}{preview.projectFileUrl && <a href={preview.projectFileUrl} target="_blank" rel="noreferrer">{t('Download OpenMotion project')} ↗</a>}</div>
+ <div className={styles.projectActions}>{isEditableTemplate(preview) && <button disabled={props.busy || props.openingDisabled} onClick={() => { detail.current?.close(); props.onOpen(preview.id); }}>{t('Open and edit')} ↗</button>}{preview.projectFileUrl && <a href={preview.projectFileUrl} target="_blank" rel="noreferrer">{t('Download OpenMotion project')} ↗</a>}</div>
{downloadError && <p role="status">{t(downloadError)}</p>}
<dl><dt>{t('Video types')}</dt><dd>{preview.styles?.join(' · ') || '—'}</dd><dt>{t('Creation models')}</dt><dd>{preview.creationModels?.join(' · ') || '—'}</dd><dt>{t('Duration')}</dt><dd>{preview.duration ? t('{value}s', { value: preview.duration }) : '—'}</dd></dl>
</div></div>
diff --git a/studio/src/motion/TemplateLibraryNavigation.test.tsx b/studio/src/motion/TemplateLibraryNavigation.test.tsx
new file mode 100644
index 00000000..918a033d
--- /dev/null
+++ b/studio/src/motion/TemplateLibraryNavigation.test.tsx
@@ -0,0 +1,175 @@
+// @vitest-environment happy-dom
+import React, { act, useEffect } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, expect, it, vi } from 'vitest';
+import { MotionApp } from './MotionApp';
+import { I18nProvider } from '../i18n/I18n';
+import { WorkspaceFrame, useWorkspaceChrome } from './WorkspaceFrame';
+
+const editor = vi.hoisted(() => ({ mounts: 0, unmounts: 0 }));
+vi.mock('./tracking', () => ({ trackMotion: vi.fn() }));
+// Keep workspace routing, polling and the library real; replace only the native editor.
+vi.mock('./ArtifactViewer', () => ({ ArtifactViewer: () => {
+ const { openLibrary } = useWorkspaceChrome();
+ useEffect(() => { editor.mounts++; return () => { editor.unmounts++; }; }, []);
+ return <div data-testid="editor"><input aria-label="Editor draft" defaultValue="Unsaved edit" />
+ <button onClick={event => openLibrary(event.currentTarget)}>Open template library</button></div>;
+} }));
+globalThis.IS_REACT_ACT_ENVIRONMENT = true;
+afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); history.replaceState(null, '', '/'); });
+
+function workspace(existing: boolean, options: { status?: 'failed' | 'pending'; create?: () => Promise<Response> } = {}) {
+ const projectId = existing ? '11111111-1111-1111-1111-111111111111' : 'project';
+ const sessionId = existing ? '22222222-2222-2222-2222-222222222222' : 'project';
+ const artifact = { id: 'artifact', kind: 'motion-project', projectId, title: 'Original project' };
+ const session = { id: sessionId, artifacts: [artifact] };
+ const catalog = { activeId: projectId, projects: [{ id: projectId }], sessions: [session] };
+ const fetcher = vi.fn(async (url: string, init?: RequestInit) => {
+ if (url.includes('/project/status')) {
+ if (options.status === 'failed') return Response.json({ error: 'Status unavailable' }, { status: 503 });
+ if (options.status === 'pending') return new Promise<Response>(() => {});
+ }
+ if (url.endsWith('/sessions') && init?.method === 'POST' && options.create) return options.create();
+ return Response.json(
+ url.includes('/template-catalog') ? { items: [{ id: 'product-promo', title: 'Product Promo', kind: 'builtin', tags: [] }], next: null, catalogVersion: 'test' }
+ : url.endsWith('/projects') ? catalog
+ : url.includes('/sessions/') ? session : { projectId, revision: 'r' },
+ );
+ });
+ vi.stubGlobal('fetch', fetcher);
+ return { projectId, sessionId, fetcher };
+}
+
+async function closeLibrary(container: HTMLElement, method: string) {
+ await act(async () => {
+ if (method === 'escape') container.querySelector('dialog')!.dispatchEvent(new Event('cancel', { cancelable: true }));
+ else container.querySelector<HTMLButtonElement>('button[aria-label="Close template library"]')!.click();
+ });
+}
+
+it.each([false, true])('dismisses the installation library in place without remounting a prepared editor (existing=%s)', async existing => {
+ const { fetcher } = workspace(existing);
+ const assign = vi.spyOn(location, 'assign').mockImplementation(() => {});
+ const replace = vi.spyOn(location, 'replace').mockImplementation(() => {});
+ const container = document.createElement('div'); document.body.append(container);
+ const root = createRoot(container);
+ try {
+ for (const method of ['close', 'escape']) {
+ assign.mockClear(); replace.mockClear();
+ editor.mounts = 0; editor.unmounts = 0; fetcher.mockClear();
+ history.replaceState(null, '', '/?templates=1&embed=1');
+ await act(async () => root.render(<I18nProvider initialLocale="en"><MotionApp key={method} /></I18nProvider>));
+ expect(container.querySelector('dialog[aria-label="Template library"]')).not.toBeNull();
+ const preparedEditor = container.querySelector('[data-testid="editor"]');
+ if (existing) expect(preparedEditor).not.toBeNull();
+ else {
+ expect(preparedEditor).toBeNull();
+ expect(fetcher.mock.calls.some(([url]) => url.includes('/preview/open'))).toBe(false);
+ }
+ const previewRequests = () => fetcher.mock.calls.filter(([url]) => url.includes('/preview/open')).length;
+ const preparedRequests = previewRequests();
+ await closeLibrary(container, method);
+ if (preparedEditor) expect(previewRequests()).toBe(preparedRequests);
+ expect(replace).not.toHaveBeenCalled(); expect(assign).not.toHaveBeenCalled();
+ expect(new URLSearchParams(location.search).has('templates')).toBe(false);
+ expect(new URLSearchParams(location.search).get('embed')).toBe('1');
+ expect(container.querySelector('[data-testid="editor"]')).not.toBeNull();
+ if (preparedEditor) expect(container.querySelector('[data-testid="editor"]')).toBe(preparedEditor);
+ expect(container.querySelector('dialog[aria-label="Template library"]')).toBeNull();
+ expect(container.querySelector('[role="alert"]')).toBeNull();
+ }
+ } finally { act(() => root.unmount()); container.remove(); }
+});
+
+it.each(['failed', 'pending'] as const)('allows installation-library dismissal while status is %s without enabling project creation', async status => {
+ const { fetcher } = workspace(false, { status });
+ const replace = vi.spyOn(location, 'replace').mockImplementation(() => {});
+ const container = document.createElement('div'); document.body.append(container);
+ const root = createRoot(container);
+ try {
+ for (const method of ['close', 'escape']) {
+ replace.mockClear(); history.replaceState(null, '', '/?templates=1&embed=1');
+ await act(async () => root.render(<I18nProvider initialLocale="en"><MotionApp key={method} /></I18nProvider>));
+ expect(container.querySelector<HTMLButtonElement>('button[aria-label="Close template library"]')!.disabled).toBe(false);
+ expect(container.textContent).not.toContain('Preparing editable project…');
+ if (status === 'failed') expect(container.textContent).toContain('Status unavailable');
+ await act(async () => container.querySelector<HTMLButtonElement>('[data-template-id="product-promo"] button')!.click());
+ const open = [...container.querySelectorAll<HTMLButtonElement>('button')].find(button => button.textContent?.includes('Open and edit'))!;
+ expect(open.disabled).toBe(true);
+ await act(async () => { open.click(); container.querySelector<HTMLButtonElement>('button[aria-label="Close template preview"]')!.click(); });
+ await closeLibrary(container, method);
+ expect(container.querySelector('dialog[aria-label="Template library"]')).toBeNull();
+ expect(replace).not.toHaveBeenCalled();
+ expect(new URLSearchParams(location.search).has('templates')).toBe(false);
+ }
+ expect(fetcher.mock.calls.some(([url, init]) => init?.method === 'POST' && !url.includes('/preview/open'))).toBe(false);
+ } finally { act(() => root.unmount()); container.remove(); }
+});
+
+it('still blocks dismissal while project creation is in flight and allows it after failure', async () => {
+ let finish!: (response: Response) => void;
+ workspace(false, { create: () => new Promise(resolve => { finish = resolve; }) });
+ history.replaceState(null, '', '/?templates=1&embed=1');
+ const replace = vi.spyOn(location, 'replace').mockImplementation(() => {});
+ const container = document.createElement('div'); document.body.append(container);
+ const root = createRoot(container);
+ try {
+ await act(async () => root.render(<I18nProvider initialLocale="en"><MotionApp /></I18nProvider>));
+ await act(async () => container.querySelector<HTMLButtonElement>('[data-template-id="product-promo"] button')!.click());
+ await act(async () => [...container.querySelectorAll<HTMLButtonElement>('button')].find(button => button.textContent?.includes('Open and edit'))!.click());
+ expect(container.textContent).toContain('Preparing editable project…');
+ expect(container.querySelector<HTMLButtonElement>('button[aria-label="Close template library"]')!.disabled).toBe(true);
+ await closeLibrary(container, 'escape');
+ expect(container.querySelector('dialog[aria-label="Template library"]')).not.toBeNull();
+ expect(replace).not.toHaveBeenCalled();
+ await act(async () => finish(Response.json({ error: 'Creation failed' }, { status: 503 })));
+ expect(container.querySelector<HTMLButtonElement>('button[aria-label="Close template library"]')!.disabled).toBe(false);
+ await closeLibrary(container, 'close');
+ expect(replace).not.toHaveBeenCalled();
+ expect(new URLSearchParams(location.search).has('templates')).toBe(false);
+ } finally { act(() => root.unmount()); container.remove(); }
+});
+
+it('keeps the editor write guard active while the template library is open', async () => {
+ workspace(true); history.replaceState(null, '', '/?templates=1&embed=1');
+ const onClose = vi.fn(), container = document.createElement('div'); document.body.append(container);
+ const root = createRoot(container);
+ try {
+ await act(async () => root.render(<I18nProvider initialLocale="en"><WorkspaceFrame blocked waitForSaves={async () => {}} onLibraryClose={onClose}>Editor</WorkspaceFrame></I18nProvider>));
+ expect(container.querySelector<HTMLButtonElement>('button[aria-label="Close template library"]')!.disabled).toBe(true);
+ await closeLibrary(container, 'close'); await closeLibrary(container, 'escape');
+ expect(container.querySelector('dialog[aria-label="Template library"]')).not.toBeNull();
+ expect(onClose).not.toHaveBeenCalled();
+ } finally { act(() => root.unmount()); container.remove(); }
+});
+
+it.each([false, true])('keeps the original editor mounted when its library closes (embedded=%s)', async embedded => {
+ const { projectId, sessionId, fetcher } = workspace(true);
+ const url = `/?session=${sessionId}&project=${projectId}${embedded ? '&embed=1' : ''}#project/${projectId}`;
+ history.replaceState(null, '', url);
+ const assign = vi.spyOn(location, 'assign').mockImplementation(() => {});
+ const replace = vi.spyOn(location, 'replace').mockImplementation(() => {});
+ editor.mounts = 0; editor.unmounts = 0;
+ const container = document.createElement('div'); document.body.append(container);
+ const root = createRoot(container);
+ try {
+ await act(async () => root.render(<I18nProvider initialLocale="en"><MotionApp /></I18nProvider>));
+ const draft = container.querySelector<HTMLInputElement>('input[aria-label="Editor draft"]')!;
+ draft.value = 'Keep my unsaved edit';
+ const trigger = [...container.querySelectorAll<HTMLButtonElement>('button')].find(button => button.textContent === 'Open template library')!;
+ const requests = fetcher.mock.calls.length;
+ for (const method of ['close', 'escape']) {
+ await act(async () => trigger.click());
+ expect(container.querySelector('dialog[aria-label="Template library"]')).not.toBeNull();
+ await closeLibrary(container, method);
+ expect(container.querySelector('dialog[aria-label="Template library"]')).toBeNull();
+ expect(container.querySelector('input[aria-label="Editor draft"]')).toBe(draft);
+ expect(draft.value).toBe('Keep my unsaved edit');
+ expect(document.activeElement).toBe(trigger);
+ expect(location.search + location.hash).toBe(url.slice(1));
+ }
+ expect(editor).toEqual({ mounts: 1, unmounts: 0 });
+ expect(assign).not.toHaveBeenCalled(); expect(replace).not.toHaveBeenCalled();
+ expect(fetcher.mock.calls.slice(requests).some(([url]) => url.includes('/preview/open') || url.includes('/sessions/'))).toBe(false);
+ } finally { act(() => root.unmount()); container.remove(); }
+});
diff --git a/studio/src/motion/WorkspaceFrame.tsx b/studio/src/motion/WorkspaceFrame.tsx
index dd7aaa48..be596c73 100644
--- a/studio/src/motion/WorkspaceFrame.tsx
+++ b/studio/src/motion/WorkspaceFrame.tsx
@@ -38,8 +38,8 @@ export function useWorkspaceChrome() {
return value;
}
-export function WorkspaceFrame({ children, waitForSaves, projectId, sessionId, blocked = false, message = '', saveState = '' }: {
- children: ReactNode; waitForSaves: () => Promise<void>; projectId?: string; sessionId?: string; blocked?: boolean; message?: string; saveState?: string;
+export function WorkspaceFrame({ children, waitForSaves, projectId, sessionId, blocked = false, message = '', saveState = '', onLibraryClose }: {
+ children: ReactNode; waitForSaves: () => Promise<void>; projectId?: string; sessionId?: string; blocked?: boolean; message?: string; saveState?: string; onLibraryClose?: () => void;
}) {
const { t } = useI18n();
const presentation = workspacePresentation(location.search);
@@ -58,7 +58,8 @@ export function WorkspaceFrame({ children, waitForSaves, projectId, sessionId, b
const libraryTrigger = useRef<HTMLElement | null>(null);
const [connectionsOpen, setConnectionsOpen] = useState(() => new URLSearchParams(location.search).get('templates') === '1');
const [sidebarOpen, setSidebarOpen] = useState(false);
- const switchingDisabled = workspace.busy || blocked || Boolean(editorState?.blocked) || !workspace.status;
+ const libraryBusy = workspace.busy || blocked || Boolean(editorState?.blocked);
+ const switchingDisabled = libraryBusy || !workspace.status;
const notice = workspace.error || message || editorState?.message || "";
const [dismissedNotice, setDismissedNotice] = useState<string | null>(null);
const noticeKey = `${workspace.error ? workspace.errorSource : 'editor'}:${notice || ''}`;
@@ -91,7 +92,7 @@ export function WorkspaceFrame({ children, waitForSaves, projectId, sessionId, b
</div>
</div>
</Dialog.Root>
- {connectionsOpen && <ConnectionDialog open returnFocus={libraryTrigger.current} section={connectionSection} busy={switchingDisabled} error={workspace.error} onClose={() => setConnectionsOpen(false)} onOpen={id => { if (!switchingDisabled) void (sessionId ? workspace.createArtifact(sessionId, id) : workspace.startSession(undefined, id)); }} />}
+ {connectionsOpen && <ConnectionDialog open returnFocus={libraryTrigger.current} section={connectionSection} busy={libraryBusy} openingDisabled={switchingDisabled} error={workspace.error} onClose={() => { setConnectionsOpen(false); onLibraryClose?.(); }} onOpen={id => { if (!switchingDisabled) void (sessionId ? workspace.createArtifact(sessionId, id) : workspace.startSession(undefined, id)); }} />}
</WorkspaceChromeContext.Provider>;
}
diff --git a/tests/bootstrap.test.ts b/tests/bootstrap.test.ts
index 1558b810..91a4e747 100644
--- a/tests/bootstrap.test.ts
+++ b/tests/bootstrap.test.ts
@@ -22,6 +22,7 @@ async function fixture(run: (context: { directory: string; destination: string;
await mkdir(path.dirname(path.join(source, file)), { recursive: true });
await copyFile(path.join(root, file), path.join(source, file));
}
+ await writeFile(path.join(source, 'scripts/open-template-library.ts'), `import fs from 'node:fs'; fs.appendFileSync(process.env.MOTION_TEST_LOG, 'Template library prepared' + String.fromCharCode(10)); console.log(JSON.stringify({target:'templates',projectCreated:false,previewUrl:'http://127.0.0.1:4173/?templates=1&embed=1'}));`);
// No remote catalog or template assets in this isolated checkout: exercise the bundled fallback.
const commands = {
git: 'echo "git $*" >> "$MOTION_TEST_LOG"\n[ "${MOTION_TEST_DOWNLOAD_FAIL:-0}" = 0 ] || exit 8\n[ "$1" = clone ] || exit 0\nfor destination; do :; done\nmkdir -p "$destination"\ncp -R "$MOTION_TEST_SOURCE/." "$destination/"',
@@ -53,6 +54,8 @@ test('remote entry point builds a fresh checkout before registering and checking
assert.equal(onboarding.hostSessionVerified, false);
assert.match(onboarding.instructions, /OpenMotion 已安装完成。/);
assert.equal(onboarding.catalog.source, 'bundled');
+ assert.equal(onboarding.preview.status, 'ready');
+ assert.ok(commands.indexOf('MCP check') < commands.indexOf('Template library prepared'));
});
});
diff --git a/tests/npm-installer.test.ts b/tests/npm-installer.test.ts
index 395cf9f7..0a09ea06 100644
--- a/tests/npm-installer.test.ts
+++ b/tests/npm-installer.test.ts
@@ -35,7 +35,9 @@ async function setupFixture(t: any) {
const directory = await fixture(t), application = path.join(directory, 'source'), home = path.join(directory, 'install'), skillsDirectory = path.join(directory, 'skills');
for (const name of ['scripts', 'shared', 'studio/build', 'skills/openmotion-production', 'docs']) await mkdir(path.join(application, name), { recursive: true });
for (const name of ['mcp.ts', 'scripts/npm-runtime.mjs', 'studio/build/index.html', 'README.md', 'AGENTS.md', 'CLAUDE.md']) await writeFile(path.join(application, name), 'fixture');
- for (const file of ['docs/install.md', 'scripts/install-onboarding.mjs', 'scripts/runtime-assets.mjs']) await cp(new URL('../' + file, import.meta.url), path.join(application, file));
+ for (const file of ['docs/install.md', 'scripts/install-onboarding.mjs', 'scripts/runtime-assets.mjs', 'scripts/open-template-library.ts', 'shared/workspace-url.ts']) await cp(new URL('../' + file, import.meta.url), path.join(application, file));
+ await writeFile(path.join(application, 'workspace.ts'), 'export class WorkspaceStore { constructor(directory = process.env.MOTION_DATA_DIR) { this.directory = directory; } }');
+ await writeFile(path.join(application, 'preview.ts'), `export async function ensureService(store) { if (store.directory !== process.env.MOTION_DATA_DIR) throw new Error('Wrong workspace'); return { previewUrl: 'http://127.0.0.1:4173' }; }`);
await writeFile(path.join(application, 'skills/openmotion-production/SKILL.md'), '---\nname: openmotion-production\ndescription: fixture\n---\nFixture');
await writeJSON(path.join(application, 'shared/template-config.json'), { environment: 'prod' });
await cp(new URL('../shared/mcp-profiles.json', import.meta.url), path.join(application, 'shared/mcp-profiles.json'));
@@ -50,19 +52,24 @@ async function setupFixture(t: any) {
return { directory, application, home, skillsDirectory, manifest, codex, config };
}
-test('successful setup hands the current Agent an invitation before any MCP use, without persisting an offer', async t => {
+test('successful setup hands the current Agent a project-free template library before any MCP use', async t => {
const options = await setupFixture(t);
const installed = await setup(options);
assert.equal(installed.onboarding.hostSessionVerified, false);
assert.deepEqual(installed.onboarding.directAccess.toolsArgs, [path.join(installed.appRoot, 'scripts/npm-installer.mjs'), 'tools', '--home', installed.launcher.replace(/[/\\]run-mcp.mjs$/, ''), '--host', 'codex', '--codex', options.codex]);
const examples = [...installed.onboarding.instructions.matchAll(/```text\n([\s\S]*?)```/g)].map(([, text]) => text);
- assert.equal(examples.length, 2);
- for (const example of examples) {
- assert(example.startsWith('OpenMotion 已安装完成。\n\n'));
- assert.doesNotMatch(example, /MCP|Skills?|prod|DEV|刷新|连接|新聊天|后台|开源免费/);
- assert.match(example, /暂不体验/);
- }
+ assert.equal(examples.length, 1);
+ const [example] = examples;
+ assert(example.startsWith('OpenMotion 已安装完成。\n\n'));
+ assert.doesNotMatch(example, /MCP|Skills?|prod|DEV|刷新|连接|新聊天|后台|开源免费/);
+ assert.match(example, /模板库已打开/);
+ assert.match(example, /打开并编辑/);
+ assert.doesNotMatch(example, /要用这个模板|回复编号/);
assert(Array.isArray(installed.onboarding.catalog.templates));
+ assert.equal(installed.onboarding.preview.status, 'ready', installed.onboarding.preview.warning);
+ assert.equal(installed.onboarding.preview.projectCreated, false);
+ assert.equal(new URL(installed.onboarding.preview.previewUrl).searchParams.get('templates'), '1');
+ assert.equal(installed.onboarding.preview.previewHandoff.nextAction.kind, 'host');
assert.equal('onboarding' in JSON.parse(await readFile(path.join(options.home, 'install.json'), 'utf8')), false);
});
@@ -127,6 +134,20 @@ test('bundled CLI installs without a sidecar manifest, isolates DEV defaults and
await assert.rejects(runFile(process.execPath, command, { env }), /match the npm package version/);
});
+test('a library startup failure reports the limitation without undoing successful host registration', async t => {
+ const options = await setupFixture(t);
+ await writeFile(path.join(options.application, 'scripts/open-template-library.ts'), 'throw new Error("Preview unavailable");');
+ const manifest = JSON.parse(await readFile(options.manifest, 'utf8'));
+ manifest.application = await archive(options.directory, options.application, 'failed-preview');
+ await writeJSON(options.manifest, manifest);
+ const installed = await setup(options);
+ assert.equal(installed.onboarding.preview.status, 'unavailable');
+ assert.equal(installed.onboarding.preview.projectCreated, false);
+ assert.match(installed.onboarding.preview.warning, /Preview unavailable/);
+ assert.equal(JSON.parse(await readFile(path.join(options.home, 'install.json'), 'utf8')).appRoot, installed.appRoot);
+ assert.ok(JSON.parse(await readFile(options.config, 'utf8')).openmotion);
+});
+
test('local assets require pinned checksums and preserve earlier cache after corruption', async t => {
const dir = await fixture(t), source = path.join(dir, 'source'), destination = path.join(dir, 'cached');
await writeFile(source, 'corrupted'); await writeFile(destination, 'keep');
diff --git a/tests/npm-package.test.ts b/tests/npm-package.test.ts
index 37b40af8..915748dd 100644
--- a/tests/npm-package.test.ts
+++ b/tests/npm-package.test.ts
@@ -156,7 +156,7 @@ test('test npm artifacts contain their application, locked manifest and no bundl
assert(entries.includes('skills/openmotion-recreate/references/verify.md'));
assert(entries.includes('studio/build/index.html'));
assert(entries.includes('shared/editor-launch.pl'), 'macOS shared editor launcher must ship');
- for (const script of ['lint-project.mjs', 'npm-installer.mjs', 'npm-hosts.mjs', 'check-installed-mcp.mjs', 'mcp-client.mjs', 'diagnostics.mjs', 'zip.mjs', 'diagnostic-redaction.mjs', 'install-onboarding.mjs', 'onboarding-catalog.ts']) assert(entries.includes('scripts/' + script), 'Runtime diagnostic and lint entry must ship: ' + script);
+ for (const script of ['lint-project.mjs', 'npm-installer.mjs', 'npm-hosts.mjs', 'check-installed-mcp.mjs', 'mcp-client.mjs', 'diagnostics.mjs', 'zip.mjs', 'diagnostic-redaction.mjs', 'install-onboarding.mjs', 'onboarding-catalog.ts', 'open-template-library.ts']) assert(entries.includes('scripts/' + script), 'Runtime diagnostic and lint entry must ship: ' + script);
await readFile(path.join(installer, 'package/scripts/check-installed-mcp.mjs'));
const diagnosticFile = path.join(directory, 'packaged-diagnostics.zip');
await runFile(process.execPath, [cli, 'diagnostics', '--home', path.join(directory, 'not-installed'), '--output', diagnosticFile]);
diff --git a/tests/preview-handoff.test.ts b/tests/preview-handoff.test.ts
index da3f70ec..1fcc6bbf 100644
--- a/tests/preview-handoff.test.ts
+++ b/tests/preview-handoff.test.ts
@@ -23,6 +23,24 @@ function display(saved: any, visibility = 'visible', contentVerified = true) {
visibility, contentVerified, evidence: 'Host panel visibility read back; inspected the edited text in the live preview at 1s.' } };
}
+test('template library opens without a bound project or initializing source, preserving existing work', async () => {
+ for (const initialized of [false, true]) await fixture(async store => {
+ const service = api(store), before = await store.get(), catalog = store.projectCatalog();
+ const opened = await service.call('openmotion_open_preview', { target: 'templates' });
+ assert.equal(opened.projectCreated, false);
+ assert.equal(opened.projectId, undefined);
+ assert.equal(new URL(opened.previewUrl).searchParams.get('templates'), '1');
+ assert.equal(new URL(opened.previewUrl).searchParams.has('project'), false);
+ assert.equal(opened.previewHandoff.nextAction.kind, 'host');
+ assert.equal(opened.previewHandoff.openedByHost, false);
+ assert.equal(opened.previewHandoff.focusPolicy, 'preserve_current_chat');
+ assert.deepEqual(await store.get(), before);
+ assert.deepEqual(store.projectCatalog(), catalog);
+ await assert.rejects(service.call('openmotion_open_preview', { target: 'templates', projectId: 'project' }), /INVALID_ARGUMENT/);
+ await assert.rejects(service.call('openmotion_open_preview', { target: 'templates', action: 'record_display' }), /INVALID_ARGUMENT/);
+ }, initialized);
+});
+
test('confirmed inactive-chat deferral 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('openmotion_open_preview', first.previewHandoff.nextAction.arguments);
@@ -196,9 +214,16 @@ test('public MCP round trips expose the handoff and reject a stale host receipt'
return response.result;
};
try {
+ const library = await call('openmotion_open_preview', { target: 'templates' });
+ assert.equal(library.isError, undefined);
+ assert.equal(library.structuredContent.projectCreated, false);
+ assert.equal((await store.get()).project, null);
const created = await call('openmotion_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 boundLibrary = await call('openmotion_open_preview', { target: 'templates' });
+ assert.equal(boundLibrary.isError, undefined, 'A project binding must not leak into the template library target');
+ assert.equal(boundLibrary.structuredContent.projectId, undefined);
const save = async (current: any, content: string) => call('openmotion_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);
diff --git a/tests/tracking.test.ts b/tests/tracking.test.ts
index 5f0f9c9a..842718b2 100644
--- a/tests/tracking.test.ts
+++ b/tests/tracking.test.ts
@@ -153,6 +153,7 @@ test('domain events follow real commits, skip replay and retain safe failure wit
const events: PendingEvent[] = [], tracking = core(async batch => { events.push(...batch); return 'accepted'; });
const service = new Phase1Service(store, pluginRoot, { tracking, origin: () => 'http://127.0.0.1:4173',
nativeUrl: () => undefined, openProject: async () => {}, mutation: async task => task(), cancel: async () => {} });
+ await service.call('openmotion_open_preview', { target: 'templates' });
const args = { requestId: crypto.randomUUID(), projectType: 'natural_language', title: 'PRIVATE_TITLE', requirements: 'PRIVATE_PROMPT' };
const created = await service.call('motion_create_project', args);
assert.equal((await service.call('motion_create_project', args)).replayed, true);