The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.
TypeScript agent-skillsagentic-aiai-agentsai-videobyokclaude-codecodexdeepseek-harnessdsh-plugingenerative-ailocal-firstmcpmotionmotion-graphicsmultimodalopenmotionreverse-engineeringvideo-editingvideo-generationworkbuddy
fix(motion): isolate concurrent project editors (#174)
open-design-crew[bot]7805690c4f3f
diff --git a/README.md b/README.mdindex da1d153d..92532b08 100644--- a/README.md+++ b/README.md@@ -90,6 +90,8 @@ To contribute a style, include the reference and its creator, the Motion MD, a p**Credits & release status.** openmotion uses [Hyperframes](https://github.com/heygen-com/hyperframes) for native compositions, the Studio foundation and rendering. Its [editor](studio/LICENSE) and [bundled examples](template-library/LICENSE) retain their upstream Apache-2.0 licenses. This public repository is licensed under [Apache-2.0](LICENSE); bundled components and fonts retain their notices. Development targets [`feature/motion`](https://github.com/nexu-io/html-anything/tree/feature/motion); the former HTML Anything application remains on `main` and is preserved on [`legacy`](https://github.com/nexu-io/html-anything/tree/legacy). Packages are not published. See the [repository workflow](docs/repository-migration.md).+Multiple local conversations can keep different projects open through one native Studio service. Each preview stays bound to its project; same-project writes still use revision checks. See [shared editor](docs/shared-editor.md).+## Published template catalogStudio and MCP read the same disk-cached Prism catalog. `motion_list_templates({})` returns a local JSONL index path, total and catalog version; the Agent searches that file with its own shell tools. `motion_get_template({templateId})` reads one template and its editing guide. `motion_create_project` with `projectType=template` downloads its files into a new editable project.diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.mdindex 5b6c1445..7915c374 100644--- a/docs/README.zh-CN.md+++ b/docs/README.zh-CN.md@@ -90,4 +90,6 @@**致谢与发布状态。** openmotion 使用 [Hyperframes](https://github.com/heygen-com/hyperframes) 的原生合成、Studio 基础与渲染能力。上游[编辑器](../studio/LICENSE)与[内置示例](../template-library/LICENSE)保留 Apache-2.0 许可。本公开仓库采用 [Apache-2.0](../LICENSE) 许可,随包组件和字体保留各自声明。开发目标为 [`feature/motion`](https://github.com/nexu-io/html-anything/tree/feature/motion);原 HTML Anything 应用仍在 `main`,并已留档到 [`legacy`](https://github.com/nexu-io/html-anything/tree/legacy)。当前不发布包;详见[仓库流程](repository-migration.md)。+多个本地会话可通过同一个原生 Studio 服务保留各自工程预览;页面固定对应工程,同工程写入仍受版本冲突保护。参见[共享编辑器](shared-editor.md)。+模板界面和 Agent 共用 Prism 发布目录的本地缓存。`motion_list_templates` 返回本机 JSONL 路径,由 Agent 自行检索;`motion_get_template` 读取详情,`motion_create_project` 创建可编辑副本。`npm run dev` 默认接 DEV;正式包默认接线上,DEV 包用 `npm run package:phase1 -- --template-env=dev`。环境随包保存,界面和 MCP 共用,具体配置见[模板目录](template-catalog.md)。diff --git a/docs/editor-fork.md b/docs/editor-fork.mdindex 4302afab..cf8d2d62 100644--- a/docs/editor-fork.md+++ b/docs/editor-fork.md@@ -70,7 +70,7 @@ Localization covers editor labels, tooltips, placeholders, empty/error states an`/motion-api/` 为产品 API,`/api/` 为原生 Studio API。流式代理保留文件版本头、上传体、媒体 Range、SSE 文件变化和渲染进度;只有通过本机 Host/Origin 检查的请求才会转发。-切换工程前等待原生保存队列完成,切换后重新加载文档以释放旧编辑会话。原生渲染、版本写入或写冲突期间,所有入口禁止新建、切换工程、返回首页或应用模板。空白项目和三个官方模板均创建为独立工程,原工程与素材保留。通过 URL 恢复工程时先选择服务再挂载 Studio;代理拒绝旧工程 ID 的原生请求。+切换工程前等待原生保存队列完成,切换后重新加载文档以释放旧编辑会话。原生渲染、版本写入或写冲突期间,所有入口禁止新建、切换工程、返回首页或应用模板。空白项目和三个官方模板均创建为独立工程,原工程与素材保留。通过 URL 恢复工程时只验证工程及会话归属,再挂载对应 Studio 页面;不会切换其他页面。一个原生服务进程按工程请求复用原生宿主上下文,文件版本冲突仍拒绝覆盖。新工程使用 CLI 默认的官方 Catalog。启动旧工程时,只移除先前版本误写的 `https://hyperframes.heygen.com/registry`,该地址返回 404;用户自定义 Registry 与其他配置不变。diff --git a/docs/product/architecture.md b/docs/product/architecture.mdindex 0deaf734..5fdf5549 100644--- a/docs/product/architecture.md+++ b/docs/product/architecture.md@@ -148,7 +148,7 @@ flowchart LR| 编辑会话 | 当前选区、目标元素、待放置时段、生成面板状态 | 辅助当前操作;与作品文件、持久化任务区分。当前没有完整生成表单的跨会话恢复 || 导出快照与验证 | 固定 revision、预期规格、真实 MP4、校验报告 | 证明该次导出的结果;后续编辑不能沿用旧文件的验证结论 |-- **工程真源:** HTML、CSS、JS、媒体和 Studio manifest 位于各自工程目录。新会话 ID、产物 ID 和工程 ID 分离;`projects.json` 原子保存两个索引、产物归属和当前选择。旧工程按原 ID 兼容为会话,需求继续在 `sessions/<sessionId>.json`,通过会话 HTTP 接口及一期 `motion_get_project` 暴露(旧 design_get_session 为内部兼容),独立于视频内容 revision。Agent 每次写入前读取当前工程与 revision。单服务只打开一个原生工程,旧项目请求由代理拒绝,避免跨标签页误写。+- **工程真源:** HTML、CSS、JS、媒体和 Studio manifest 位于各自工程目录。新会话 ID、产物 ID 和工程 ID 分离;`projects.json` 原子保存两个索引、产物归属和当前选择。旧工程按原 ID 兼容为会话,需求继续在 `sessions/<sessionId>.json`,通过会话 HTTP 接口及一期 `motion_get_project` 暴露(旧 design_get_session 为内部兼容),独立于视频内容 revision。Agent 每次写入前读取当前工程与 revision。一个原生服务进程按 projectId 分发多个工程;页面固定自己的工程,其他会话的打开操作不会替换它。工程状态请求也携带 projectId;未知工程和冲突身份拒绝处理。- **历史真源:** Studio 原生历史服务记录版本、checkpoint、pin 与 restore,宿主只呈现 UI,不另建版本库。恢复前等待保存并创建 checkpoint,完成后重新加载编辑会话;后续历史保留,恢复操作可以撤销。- **界面状态:** 浏览器 Tabs、左右面板与宽度按会话保存;关闭 Tab 不删除产物。原生 Dock 按工程保存,主题沿用 Studio 偏好;语言单独保存为 `motion.studio.locale`,均不写入影片源文件。- **参考数据:** 模板原始目录、封面和热度快照与用户工程分开。热度按模板 ID、视频地址和原帖身份匹配;同源片段不累加查看量。@@ -156,7 +156,7 @@ flowchart LR- **后台与编辑器启动:** 仅导出启动后台服务,不初始化或补写当前工程;冷启动套模板直接创建选中的模板工程。Studio starts when the Agent calls preview for an existing project, including the automatic handoff after production HTML is ready; the existing background service is reused. 健康检查区分服务 `ready` 与 `editorReady`,不靠自动替换 expectedRevision 消除冲突。- **服务边界:** 当前在本机回环地址运行。Model Gateway 使用本机 Codex 登录或用户自有 Atlas/fal Key 发起媒体生成,接口共用本地任务与素材入库;不托管聊天 Agent、团队协作或计费。当前使用用户自有账户接入,详见 [模型网关](../model-gateway.md)。- **模型与凭据:** 配置和任务独立于工程,Key 不通过 API 返回。安装、配置、允许请求、生成成功是不同状态;任务固定发起工程,失败不静默重试。完成后的素材参与工程 revision 与导出快照。-- **并发边界:** macOS 同目录多个 MCP 连接共用后台,各自绑定工程;工作区仍只有一个活动原生 Studio、一个等待/运行的导出。导出固定工程与快照,重启将中断任务持久化为失败且不重放。文件锁和 revision 保护工具写入;人工与 Agent 同时编辑同一文件仍需协调,不能当作跨工具数据库事务。+- **并发边界:** macOS 同目录多个 MCP 连接共用后台,各自绑定工程;工作区使用一个原生 Studio 服务进程,按需保留多个工程的原生上下文;后台仍只有一个等待/运行的导出。导出固定工程与快照,重启将中断任务持久化为失败且不重放。文件锁和 revision 保护工具写入;人工与 Agent 同时编辑同一文件仍需协调,不能当作跨工具数据库事务。- **数据归属:** 产品文档描述数据类别与流程,不复制用户的私有工程、访问凭据或个人机器配置。## 成功标准与验证diff --git a/docs/project-workspace.md b/docs/project-workspace.mdindex 71b1162a..eab4303d 100644--- a/docs/project-workspace.md+++ b/docs/project-workspace.md@@ -61,9 +61,9 @@旧 `/projects` 创建、打开、conversation 及 `/templates/:id/open` 入口继续兼容;旧 conversation API 解析到工程所属会话。新建/切换使用 `expectedRevision` 和 `expectedProjectId` 防止竞争。-一期公开 MCP 使用 [9 Tool 契约](mcp-phase1-tools.md):motion_create_project 创建会话下工程,motion_get_project 读工程/所属 sessionId/当前版本,motion_open_preview 打开明确工程。以下 design_* 与旧模板 Tool 描述保留内部兼容,不是一期公开接口。通用接口命名空间为 `/design-api`,`/motion-api` 保留别名。MCP 的 `design_create_session` 先建会话再按需生成产物;`design_create_artifact` 向已有会话生成;`design_get_session` 读取会话与 skill,`design_open_artifact` 校验归属后选择已有产物。`motion_get_project` 同时返回 `session`、`projectId` 和兼容 `conversation`;`motion_apply_template` 在指定或当前会话添加工程。Agent 写入前应先确认会话与产物身份,再使用最新 revision 操作。macOS 多个 MCP 连接按数据目录共用后台,但每条连接保留自己的工程选择,网页切换不改变已有绑定;工作区原生 Studio 仍只打开一个活动工程。详见 [共享编辑器](shared-editor.md)。+一期公开 MCP 使用 [11 Tool 契约](mcp-phase1-tools.md):motion_create_project 创建会话下工程,motion_get_project 读工程/所属 sessionId/当前版本,motion_open_preview 打开明确工程。以下 design_* 与旧模板 Tool 描述保留内部兼容,不是一期公开接口。通用接口命名空间为 `/design-api`,`/motion-api` 保留别名。MCP 的 `design_create_session` 先建会话再按需生成产物;`design_create_artifact` 向已有会话生成;`design_get_session` 读取会话与 skill,`design_open_artifact` 校验归属后选择已有产物。`motion_get_project` 同时返回 `session`、`projectId` 和兼容 `conversation`;`motion_apply_template` 在指定或当前会话添加工程。Agent 写入前应先确认会话与产物身份,再使用最新 revision 操作。macOS 多个 MCP 连接按数据目录共用后台,但每条连接保留自己的工程选择,网页切换不改变已有绑定;一个原生 Studio 服务进程可同时服务多个工程页面。详见 [共享编辑器](shared-editor.md)。-一个本地服务仍只有一个活动原生工程;多个 Artifact Tabs 是可切换的工程入口,不是同时运行多套编辑器。跨工程切换时创建候选 Studio、重查 revision、原子发布目录,再整页重建;失败保留原工程。旧工程原生 API 请求被拒绝,避免写入新目录。其他客户端切换时当前会话页跟随新的活动会话,首页保持首页。+一个本地原生服务进程按 projectId 服务多个工程,各页面的 URL 与工程保持绑定。当前页面显式切换工程时仍先保存、再整页重建;其他客户端打开工程不触发该页面跳转。activeId 只作为最近选择和旧入口的兼容默认值,不决定已打开页面的数据目标。创建时先检查源 revision 并登记工程,原生上下文启动失败时保留已登记工程供重试,不删除源文件。## 验收与待验证项diff --git a/docs/session-architecture.md b/docs/session-architecture.mdindex 7e66dfda..fb2123d7 100644--- a/docs/session-architecture.md+++ b/docs/session-architecture.md@@ -66,7 +66,7 @@ flowchart LR1. `POST /design-api/sessions` 验证模式和模板,先持久化会话及初始需求。可以只有会话、没有产物;此操作不改写当前视频。可提供稳定 UUID `id`,相同初始请求重试返回同一会话,冲突内容被拒绝。2. `POST /design-api/sessions/:id/artifacts` 根据会话模式调用 `artifactFactories`。首个产物默认使用会话所选模板,也可传具体模板;后续产物默认空白。-3. Motion 工厂建立候选工程与原生服务,重查 revision 和活动工程后,才把产物登记到该会话并切换。失败清理候选文件,但保留已创建的会话、消息和其他产物。+3. Motion 工厂建立候选工程、重查源 revision 后,把产物登记到该会话,再在同一个原生服务中按需打开该工程上下文。登记前失败清理候选文件;登记后若上下文启动失败,保留工程供重试。会话、消息和其他产物保留。4. 客户端按产物 kind 打开 Viewer。空会话中外部 Agent 创建产物后,网页轮询会打开同一所属产物;待提交草稿留在会话下。5. 后续需求和真实 Agent 回复写入同一个消息流;产物继续通过其模式工具编辑。网页不伪造模型回复或执行完成状态,也不包含聊天 Agent 运行器。@@ -127,7 +127,7 @@ macOS 的 `mcp.ts` 只负责 stdio 和连接选择,业务位于 `mcp-tools.ts`| 网页运行时 | `browser.ts`、`shared/browser.ts`、`WebBrowser.tsx` | 按会话隔离 Chromium、导航/画面/输入协议;与产物和工程状态分开 || 原生编辑桥 | `MotionStudioHost.tsx` | 向容器注册保存/渲染门禁,保留原生编辑状态 |-后续网页原型模式需要新增模式/模板与 skill 定义、具体产物资源类型、生成/打开适配器及 Viewer 注册,再验证保存与嵌入能力;不得仅在选择器加入一个没有实现的选项。会话索引、消息、宿主接入和浏览器面板继续复用。当前仍只有一个活动 Motion 原生服务;多个 Tabs 是可切换入口,不是多工程同时运行。+后续网页原型模式需要新增模式/模板与 skill 定义、具体产物资源类型、生成/打开适配器及 Viewer 注册,再验证保存与嵌入能力;不得仅在选择器加入一个没有实现的选项。会话索引、消息、宿主接入和浏览器面板继续复用。当前使用一个 Motion 原生服务进程承载多个工程上下文;各页面保留自己的 URL、状态、历史与文件通知目标。## 验收diff --git a/docs/shared-editor.md b/docs/shared-editor.mdindex cdb900bc..11aebef4 100644--- a/docs/shared-editor.md+++ b/docs/shared-editor.md@@ -1,6 +1,6 @@# 多个 Agent 共用本地编辑器-**当前分支在 macOS 上让同一数据目录中的所有 MCP 连接共用一个后台。** 每个 Agent 仍有自己的轻量 stdio 进程,工程目录、任务队列、Model Gateway 和网页服务由共享后台管理。原生 Studio 按需启动,工作区仍只打开一个原生工程、同时运行一个视频导出;这次没有增加并行 Studio 或并行渲染。+**当前分支在 macOS 上让同一数据目录中的所有 MCP 连接共用一个后台。** 每个 Agent 仍有自己的轻量 stdio 进程,工程目录、任务队列、Model Gateway 和网页服务由共享后台管理。原生 Studio 按需启动,一个服务进程与端口可以保留多个工程的原生上下文。每个页面固定自己的工程;后台仍同时运行一个视频导出。与当前主干合并后,28 个 MCP 工具全部保留(原有 27 个加视频对比);Skill 的 workflow/section 路由与文档身份沿用主干。仅导出和冷启动套模板使用后台服务入口,不先打开 Studio 或改写调用方的源文件;随后显式打开预览才按需启动编辑器。@@ -23,7 +23,7 @@ flowchart LRE --> G[同一 Model Gateway]E --> R[单个后台导出任务\n固定工程与 revision]E --> O[Studio 生命周期守卫]- O --> S[一个活动原生 Studio]+ O --> S[一个原生服务进程 / 多工程上下文]```## 启动、复用与退出@@ -67,7 +67,9 @@ MOTION_DATA_DIR=/path/to/workspace node --experimental-strip-types editor-runtim写入仍需要读取到的 `expectedRevision`。同工程同时修改只接受匹配版本,冲突返回工具错误及 `REVISION_CONFLICT`;Agent 必须重读,不自动重放写入。工程目录受现有路径校验保护,不接受目录穿越。-MCP 调用在共享后台内串行执行,HTTP 页面继续走原有保存与工程切换门禁。原生 Studio 仍只有一个活动工程;打开另一个工程会切换网页服务的原生目标,旧标签页的过时工程请求仍被拒绝。这不是 UI 与 MCP 跨多文件的数据库事务,也不合并两位编辑者的文本。+MCP 调用在共享后台内串行执行,HTTP 页面继续走原有保存与工程切换门禁。原生请求按路径中的 projectId 定位目录,状态与文件通知按工程绑定;打开另一个工程不会关闭原服务或导航其他页面。无工程路径的事件、渲染和媒体任务请求携带 projectId;多工程下缺少身份的请求拒绝处理,不猜测最近工程。这不是 UI 与 MCP 跨多文件的数据库事务,也不合并两位编辑者的文本。++冷启动的 `/#project/<id>` 书签由前端解析、校验归属后,按明确工程启动原生上下文;没有工程参数的页面请求不预先打开最近工程,避免给其他工程写入节点标识并改变 revision。原生工程打开请求最多等待 30 秒,直接启动与 macOS 守卫保持相同超时;超时释放调用队列,服务恢复后可重试,不自动重放修改。## 导出与后台强杀后的恢复@@ -104,7 +106,15 @@ sequenceDiagram| Windows / Linux 共享后台 | 未实现,保留旧行为 || 所有宿主、系统重启、断电、守卫与后台同时被杀、启动中途强杀 | 未验证 || 原生网页浏览器 Chrome 在后台 SIGKILL 后的生命周期 | 本次故障对象为 Studio 和视频渲染 Chrome,未覆盖独立网页浏览器 |-| UI/MCP 同时多文件写入的完整事务、多个 Studio/并行导出 | 未实现 |+| UI/MCP 同时多文件写入的完整事务、并行后台导出 | 未实现 || 长时间压力、自动升级、旧数据自动迁移、正式安装包目标机验收 | 未验证 |运行本项目检查使用 `npm test`、`npm run check`、`npm run typecheck:studio`、`npm run test:studio`。真实 Chrome 相关检查必须经过团队 browser-lock 的 lane 和 real 锁;新增故障脚本 `tests/shared-editor-crash.mjs` 和媒体脚本 `tests/shared-editor-media.mjs` 也遵守该要求。验收结论只覆盖实际执行命令,实际结果以当前提交的测试及 CI 为准。++## 多工程宿主的依赖与恢复边界++`shared/workspace-studio.ts` 在一个进程内按需复用锁定 Hyperframes 0.9.7 的原生宿主,保留每个工程自己的历史、预览缓存、媒体配置、文件监听和渲染任务上下文。当前完整宿主只由 CLI 打包模块导出;启动时检查版本、模块唯一性和工厂入口,不兼容时明确失败,不静默降级或重写工程。升级依赖需重新验证该入口及独立分发包。++已打开工程的上下文保留到服务退出;退出关闭所有监听、历史与子任务。不同页面编辑同一工程仍使用原生 If-Match 和工具 revision/version 冲突保护,不提供多人文本合并;工程 ID 也不代表同工程两个页面的独立选区身份。++验证入口:`tests/multi-project.test.ts` 覆盖同进程双工程、文件/预览/历史/通知和重启;`tests/multi-project-browser.mjs` 在共享 browser-lock 的 lane 与 real 锁下使用两个真实 MCP 客户端和浏览器页面。公开 MCP Tool、冷启动导出、原生媒体和守卫强杀仍单独回归。diff --git a/docs/usage.md b/docs/usage.mdindex 5db4cbf7..17cfa729 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -102,7 +102,7 @@ openmotion 围绕已有 Agent 用户的产品演示、参考复刻、动态图新工程先 `motion_create_project`;已有工程先 `motion_get_project` 明确 projectId、revision、currentVersionId,再保存或打开。`motion_open_preview({projectId})` 运行 lint 并返回真实预览 URL,由宿主内置浏览器打开。它不隐式创建新工程;无浏览器时可以手动打开返回地址。-macOS 同一数据目录中的多个 MCP 会话现在共用一个后台,每个会话保留自己的工程选择;所有会话退出后导出仍继续。新安装默认使用 `~/Library/Application Support/OpenDesign`,已有 `.motion-data` 或显式 `MOTION_DATA_DIR` 沿用;不同目录仍是不同后台。原生 Studio 和导出继续各只有一个活动实例,Windows / Linux 保留原启动方式。停止、旧服务升级和故障恢复见 [共享编辑器](shared-editor.md)。+macOS 同一数据目录中的多个 MCP 会话现在共用一个后台,每个会话保留自己的工程选择;所有会话退出后导出仍继续。新安装默认使用 `~/Library/Application Support/OpenDesign`,已有 `.motion-data` 或显式 `MOTION_DATA_DIR` 沿用;不同目录仍是不同后台。原生 Studio 使用一个服务进程支持多个工程页面;每个页面按 URL 工程读取状态和编辑,不跟随其他会话。后台导出仍只运行一个任务,Windows / Linux 保留原后台启动方式。停止、旧服务升级和故障恢复见 [共享编辑器](shared-editor.md)。仅导出时只启动后台服务,不启动 Studio 改写当前源文件;冷启动套模板也不会先创建无关 starter。随后调用 `motion_open_preview` 可在同一服务中启动编辑器。真实外部编辑仍受 revision 校验保护。diff --git a/editor-runtime.ts b/editor-runtime.tsindex 44a709be..1480a18c 100644--- a/editor-runtime.ts+++ b/editor-runtime.ts@@ -128,7 +128,7 @@ export async function serveEditor(directory: string) {if (req.url === '/editor-api/preview') {if (body.projectId !== undefined && typeof body.projectId !== 'string') throw new Error('工程编号无效');if (body.editor !== undefined && typeof body.editor !== 'boolean') throw new Error('编辑器开关无效');- if (body.editor !== false) await running.ensureStudio();+ if (body.editor !== false) await running.ensureStudio(body.projectId);if (body.editor !== false && body.projectId !== undefined && body.projectId !== store.projectId) await running.openProject(body.projectId);json(200, await running.info()); return true;}diff --git a/hyperframes.ts b/hyperframes.tsindex c53f5880..16bfa584 100644--- a/hyperframes.ts+++ b/hyperframes.ts@@ -137,7 +137,7 @@ export async function snapshotExportExpectation(runtimeRoot: string, directory:duration: info.result.duration, fps: fpsToNumber(fps.value), audio: 'optional' });}-export type Studio = { url: string; projectDirectory: string; alive: () => boolean; close: () => Promise<void> };+export type Studio = { url: string; projectDirectory: string; alive: () => boolean; close: () => Promise<void>; openProject?: (id: string) => Promise<void> };/** Repair only the nonexistent catalog URL generated by earlier Motion versions. */export async function repairGeneratedRegistry(projectDirectory: string) {const filename = path.join(projectDirectory, 'hyperframes.json');@@ -158,13 +158,15 @@ export async function repairGeneratedRegistry(projectDirectory: string) {return true;}-export async function startStudio(runtimeRoot: string, projectDirectory: string, logFile: string, port = 20_000): Promise<Studio> {+export async function startStudio(runtimeRoot: string, projectDirectory: string, logFile: string, port = 20_000, workspaceDirectory?: string): Promise<Studio> {await repairGeneratedRegistry(projectDirectory);// Keep the native service above the ports restricted by browser/Fetch runtimes.// Repeated project switches can otherwise increment a 4174 start into 4190.const studioPort = Math.max(20_000, port);const log = await open(logFile, 'a', 0o600);- const child = spawn(process.execPath, [cliPath(runtimeRoot), 'preview', projectDirectory, '--port', String(studioPort), '--foreground', '--force-new', '--no-open', '--json'], {+ const args = workspaceDirectory ? ['--experimental-strip-types', path.join(pluginRoot, 'shared/workspace-studio.ts'), runtimeRoot, workspaceDirectory, projectDirectory, String(studioPort)]+ : [cliPath(runtimeRoot), 'preview', projectDirectory, '--port', String(studioPort), '--foreground', '--force-new', '--no-open', '--json'];+ const child = spawn(process.execPath, args, {cwd: projectDirectory, env: runtimeEnv(), stdio: ['ignore', 'pipe', log.fd], windowsHide: true, detached: process.platform !== 'win32',});// Attach lifecycle listeners before yielding: an immediate spawn error must be handled.@@ -207,11 +209,14 @@ export async function startStudio(runtimeRoot: string, projectDirectory: string,});const identityUrl = new URL('/__hyperframes_config', url);const response = await fetch(identityUrl, { signal: AbortSignal.timeout(3000) });- const identity = await response.json() as { isHyperframes: boolean; projectDir: string; version: string };- if (!response.ok || !identity.isHyperframes || path.resolve(identity.projectDir) !== projectDirectory || identity.version !== HYPERFRAMES_VERSION) {+ const identity = await response.json() as { isHyperframes: boolean; projectDir: string; version: string; dataDirectory?: string };+ if (!response.ok || !identity.isHyperframes || path.resolve(identity.projectDir) !== projectDirectory || identity.version !== HYPERFRAMES_VERSION || workspaceDirectory && identity.dataDirectory !== workspaceDirectory) {throw new Error('Hyperframes Studio 的版本或工程目录不匹配');}- return { url, projectDirectory, alive: () => live, close };+ return { url, projectDirectory, alive: () => live, close, ...(workspaceDirectory ? { openProject: async (id: string) => {+ const result = await fetch(new URL('/__hyperframes_config?projectId=' + encodeURIComponent(id), url), { signal: AbortSignal.timeout(30_000) });+ if (!result.ok) throw new Error((await result.json()).error || 'Studio project could not be opened');+ } } : {}) };} catch (error) { await close(); throw error; }finally { await closingLog; }}diff --git a/phase1-versions.ts b/phase1-versions.tsindex e74ce6b9..4bfff132 100644--- a/phase1-versions.ts+++ b/phase1-versions.ts@@ -37,7 +37,7 @@ function remoteHistory(base: string): NativeHistory {if (url.protocol !== 'http:' || !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)) throw new Error('INVALID_HISTORY_OWNER');async function call(action = '', body?: unknown, binary = false) {const response = await fetch(base.replace(/\/$/, '') + action, { method: body === undefined ? 'GET' : 'POST',- headers: { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(120_000) });+ headers: { 'Content-Type': 'application/json', Origin: url.origin }, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(120_000) });if (!response.ok) throw new Error('NATIVE_HISTORY_FAILED: ' + (await response.text()).slice(0, 1200));return binary ? Buffer.from(await response.arrayBuffer()) : response.json();}diff --git a/server.ts b/server.tsindex 7e197883..f7d5c2f3 100644--- a/server.ts+++ b/server.ts@@ -26,7 +26,7 @@ import { recoverProjectTransactions } from './phase1-versions.ts';import { verifyExport } from './scripts/verify-export.ts';const sharedStore = new WorkspaceStore();-export type Service = { studio?: Studio; runtimeRoot?: string; ffmpeg?: boolean; switching?: boolean; studioPort?: number; browser?: WorkspaceBrowser; editorToken?: string; ensureStudio?: () => Promise<Studio>; launchStudio?: (directory: string, port: number) => Promise<Studio>; phase1?: Phase1Service; phase1Mutation?: Promise<void> };+export type Service = { studio?: Studio; runtimeRoot?: string; ffmpeg?: boolean; switching?: boolean; studioPort?: number; browser?: WorkspaceBrowser; editorToken?: string; ensureStudio?: (projectId?: string) => Promise<Studio>; launchStudio?: (directory: string, port: number) => Promise<Studio>; phase1?: Phase1Service; phase1Mutation?: Promise<void> };const service: Service = {};const working = new Set<string>();const runningExports = new Map<string, AbortController>();@@ -132,7 +132,8 @@ async function openProject(store: WorkspaceStore, context: Service, expectedReviif (!entry && !store.projectCatalog().projects.some(item => item.id === id)) throw new Error('工程不存在');if (sessionTarget?.sessionId && !store.projectCatalog().sessions!.some(item => item.id === sessionTarget.sessionId)) throw new Error('会话不存在');if (!entry && store.projectCatalog().activeId === id) {- if (!context.studio?.alive()) context.studio = context.launchStudio ? await context.launchStudio(store.projectDirectory, context.studioPort || 4174) : await startStudio(runtimeRoot, store.projectDirectory, path.join(store.directory, 'studio.log'), context.studioPort || 4174);+ if (!context.studio?.alive()) context.studio = context.launchStudio ? await context.launchStudio(store.projectDirectoryFor(id), context.studioPort || 4174) : await startStudio(runtimeRoot, store.projectDirectoryFor(id), path.join(store.directory, 'studio.log'), context.studioPort || 4174);+ await context.studio.openProject?.(id);await store.selectProject(id);return { ...(await store.status()), studioUrl: context.studio.url };}@@ -146,16 +147,17 @@ async function openProject(store: WorkspaceStore, context: Service, expectedReviconst oldStudio = context.studio;const oldPort = oldStudio ? Number(new URL(oldStudio.url).port) : undefined;const candidatePort = oldPort === undefined ? context.studioPort || 4174 : oldPort === 65535 ? 4174 : oldPort + 1;- candidate = context.launchStudio ? await context.launchStudio(directory, candidatePort) : await startStudio(runtimeRoot, directory, path.join(store.directory, 'studio.log'), candidatePort);+ candidate = oldStudio?.alive() && oldStudio.openProject ? oldStudio : context.launchStudio ? await context.launchStudio(directory, candidatePort) : await startStudio(runtimeRoot, directory, path.join(store.directory, 'studio.log'), candidatePort);// Native Studio writes are independent of our lock. Recheck before switching.if ((await store.get()).revision !== expectedRevision) throw new Conflict();await store.selectProject(id, entry, sessionTarget?.instruction ?? ('instruction' in target ? target.instruction : undefined), sessionTarget);context.studio = candidate; committed = true;- await oldStudio?.close();+ await candidate.openProject?.(id);+ if (oldStudio !== candidate) await oldStudio?.close();return { ...(await store.status()), studioUrl: candidate.url };} finally {if (!committed) {- await candidate?.close();+ if (candidate !== context.studio) await candidate?.close();if (creating) await rm(directory, { recursive: true, force: true });}}@@ -164,7 +166,7 @@ async function openProject(store: WorkspaceStore, context: Service, expectedRevi}async function openEditor(store: WorkspaceStore, context: Service) {- if (context.ensureStudio) { await context.ensureStudio(); return; }+ if (context.ensureStudio) { await context.ensureStudio(store.projectId); return; }if (!context.runtimeRoot) throw new Error('Hyperframes 服务尚未就绪');if (context.switching) throw new Error('正在打开工程,请稍候');if (context.studio?.alive()) return;@@ -219,15 +221,29 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store =const originalUrl = new URL(req.url || '/', 'http://localhost');const motionRequest = /^\/(?:motion|design)-api\//.test(originalUrl.pathname);const url = new URL(originalUrl);- if (context.ensureStudio && (url.pathname === '/' || url.pathname.startsWith('/sessions/'))) await context.ensureStudio();+ if (motionRequest && url.searchParams.has('projectId')) {+ const id = url.searchParams.get('projectId')!;+ if (projectHeader !== undefined && projectHeader !== id) return json(res, 400, { error: 'PROJECT_SCOPE_MISMATCH' });+ store = store.forProject(id);+ }+ if (context.ensureStudio && (url.pathname === '/' || url.pathname.startsWith('/sessions/'))) {+ const projectId = url.searchParams.get('project'), sessionId = url.searchParams.get('session');+ if (projectId !== null) {+ if (store.projectCatalog().projects.some(project => project.id === projectId)) await context.ensureStudio(projectId);+ } else if (sessionId) {+ const session = store.projectCatalog().sessions!.find(session => session.id === sessionId);+ const artifact = session?.artifacts.find(artifact => artifact.id === session.activeArtifactId) ?? session?.artifacts.at(-1);+ if (artifact) await context.ensureStudio(artifact.projectId);+ }+ }if (motionRequest) url.pathname = url.pathname.replace(/^\/(?:motion|design)-api\//, '/api/');- const editorUrl = `http://${host || 'localhost'}/#project/${store.projectCatalog().activeId}`;+ const editorUrl = `http://${host || 'localhost'}/#project/${store.projectId}`;if (motionRequest && url.pathname === '/api/phase1/call' && req.method === 'POST') {if (!context.runtimeRoot) throw new Error('RUNTIME_NOT_READY');const authority = store.workspaceStore ?? store;context.phase1 ??= new Phase1Service(authority, context.runtimeRoot, {origin: () => new URL(editorUrl).origin,- nativeUrl: projectId => context.studio?.alive() && context.studio.projectDirectory === authority.projectDirectoryFor(projectId) ? context.studio.url : undefined,+ nativeUrl: () => context.studio?.alive() ? context.studio.url : undefined,openProject: async projectId => { await openProject(authority, context, (await authority.get()).revision, { projectId }, authority.projectId); },mutation: async task => {let release!: () => void;@@ -406,10 +422,8 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store =}if (!motionRequest && (url.pathname.startsWith('/api/') || url.pathname === '/__hyperframes_config')) {if (context.phase1Mutation) await context.phase1Mutation;- // A stale tab must never write its old session into the newly selected directory.const scopedProject = url.pathname.match(/^\/api\/projects\/([^/]+)/);- if (scopedProject && decodeURIComponent(scopedProject[1]) !== store.projectCatalog().activeId) return json(res, 409, { error: '当前项目已切换,请重新打开对应会话。' });- if (context.switching && !['GET', 'HEAD'].includes(req.method || '')) return json(res, 409, { error: '正在切换项目,请稍候。' });+ if (scopedProject) store.forProject(decodeURIComponent(scopedProject[1]));if (!context.studio?.alive()) return json(res, 503, { error: '编辑服务尚未就绪' });return await proxyStudio(req, res, url, context.studio.url);}@@ -429,7 +443,7 @@ export async function startServer(store = sharedStore, port = Number(process.envconst ffmpeg = await execute(process.env.HYPERFRAMES_FFMPEG_PATH || process.env.FFMPEG_PATH || 'ffmpeg', ['-version'], pluginRoot, 5000).then(r => r.code === 0, () => false);const context: Service = { runtimeRoot, ffmpeg, studioPort: !port || port === 65535 ? 4174 : port + 1, editorToken: options.editorToken };context.launchStudio = async (directory, chosenPort) => {- if (!process.env.OPENMOTION_EDITOR_LOCK_FD) return startStudio(runtimeRoot, directory, path.join(store.directory, 'studio.log'), chosenPort);+ if (!process.env.OPENMOTION_EDITOR_LOCK_FD) return startStudio(runtimeRoot, directory, path.join(store.directory, 'studio.log'), chosenPort, store.directory);const probe = createServer();await new Promise<void>((resolve, reject) => { probe.once('error', reject); probe.listen(0, '127.0.0.1', resolve); });const available = (probe.address() as any).port;@@ -437,17 +451,20 @@ export async function startServer(store = sharedStore, port = Number(process.envreturn startOwnedStudio(store.directory, runtimeRoot, directory, path.join(store.directory, 'studio.log'), available);};let opening: Promise<Studio> | undefined;- context.ensureStudio = async () => {- if (context.studio?.alive()) return context.studio;+ context.ensureStudio = async (projectId = store.projectId) => {+ const scoped = store.forProject(projectId);+ if (context.studio?.alive()) { await context.studio.openProject?.(projectId); return context.studio; }if (!opening && context.switching) throw new Error('正在打开工程,请稍候');if (!opening) opening = (async () => {context.switching = true;await context.studio?.close();- await store.initialize(runtimeRoot);- context.studio = await context.launchStudio!(store.projectDirectory, !port || port === 65535 ? 4174 : port + 1);+ await scoped.initialize(runtimeRoot);+ context.studio = await context.launchStudio!(scoped.projectDirectory, !port || port === 65535 ? 4174 : port + 1);return context.studio;})().finally(() => { opening = undefined; context.switching = false; });- return opening;+ const studio = await opening;+ await studio.openProject?.(projectId);+ return studio;};if (options.editor !== false) await context.ensureStudio();const server = createServer((req, res) => { void (async () => { if (!options.privateHandler || !await options.privateHandler(req, res)) await handler(req, res, store, context); })().catch(error => { if (!res.headersSent) json(res, 500, { error: (error as Error).message }); else res.destroy(); }); });diff --git a/shared/owned-studio.mjs b/shared/owned-studio.mjsindex 5a9d7408..d12cbfe3 100644--- a/shared/owned-studio.mjs+++ b/shared/owned-studio.mjs@@ -33,7 +33,8 @@ export async function startOwnedStudio(root, runtimeRoot, projectDirectory, logF} else resolve(message);});});- return { url: studio.url, projectDirectory, alive: () => child.connected && child.exitCode === null && child.signalCode === null, close };+ return { url: studio.url, projectDirectory, alive: () => child.connected && child.exitCode === null && child.signalCode === null, close,+ openProject: async id => { const response = await fetch(new URL('/__hyperframes_config?projectId=' + encodeURIComponent(id), studio.url), { signal: AbortSignal.timeout(30_000) }); if (!response.ok) throw new Error((await response.json()).error || 'Studio project could not be opened'); } };} catch (error) { await close(); throw error; }}@@ -43,7 +44,7 @@ if (path.resolve(process.argv[1] || '') === filename && process.argv[2] === '--oconst lock = statSync(path.join(root, '.editor-runtime', 'runtime.lock'));if (held.dev !== lock.dev || held.ino !== lock.ino) throw new Error('Studio owner requires the editor lock');let closing = false, monitor;- const opening = startStudio(runtimeRoot, projectDirectory, logFile, Number(port));+ const opening = startStudio(runtimeRoot, projectDirectory, logFile, Number(port), root);const close = async () => {if (closing) return;closing = true;diff --git a/shared/workspace-studio.ts b/shared/workspace-studio.tsnew file mode 100644index 00000000..06cc7d73--- /dev/null+++ b/shared/workspace-studio.ts@@ -0,0 +1,92 @@+import { createServer } from 'node:http';+import { createRequire } from 'node:module';+import { readFile, readdir } from 'node:fs/promises';+import path from 'node:path';+import { pathToFileURL } from 'node:url';+import { WorkspaceStore } from '../workspace.ts';+import { HYPERFRAMES_VERSION, repairGeneratedRegistry } from '../hyperframes.ts';+import { isMain } from './entry.ts';++export async function startWorkspaceStudio(runtimeRoot: string, dataDirectory: string, initialDirectory: string, port: number) {+ const require = createRequire(path.join(runtimeRoot, 'package.json'));+ const cli = path.dirname(require.resolve('hyperframes/package.json'));+ const manifest = JSON.parse(await readFile(path.join(cli, 'package.json'), 'utf8'));+ if (manifest.version !== HYPERFRAMES_VERSION) throw new Error('Unsupported Hyperframes workspace host version');+ // shortcut: 0.9.7 exposes the complete host only in its bundle; use a public host factory when upstream provides one.+ const bundles = (await readdir(path.join(cli, 'dist'))).filter(name => /^studioServer-[\w-]+\.js$/.test(name));+ if (bundles.length !== 1) throw new Error('Hyperframes workspace host bundle is missing or ambiguous');+ const { createStudioServer } = await import(pathToFileURL(path.join(cli, 'dist', bundles[0])).href);+ if (typeof createStudioServer !== 'function') throw new Error('Hyperframes workspace host factory is unavailable');+ const { getRequestListener } = await import(pathToFileURL(require.resolve('@hono/node-server')).href);+ const store = new WorkspaceStore(dataDirectory);+ const hosts = new Map<string, Promise<any>>();+ let origin = '', closing = false;+ const hostFor = (id: string): Promise<any> => {+ store.forProject(id);+ let opening = hosts.get(id);+ if (!opening) {+ opening = (async () => {+ const scoped = store.forProject(id);+ await scoped.safePath('index.html');+ await repairGeneratedRegistry(scoped.projectDirectory);+ if (closing) throw new Error('Studio is stopping');+ return createStudioServer({ projectDir: scoped.projectDirectory, projectName: id,+ origin: () => origin, historyRoot: process.env.HYPERFRAMES_HISTORY_ROOT });+ })().catch(error => { hosts.delete(id); throw error; });+ hosts.set(id, opening);+ }+ return opening;+ };+ const json = (value: unknown, status = 200) => Response.json(value, { status, headers: { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' } });+ const fetchRequest = async (request: Request) => {+ try {+ const url = new URL(request.url);+ if (!['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)) return json({ error: 'Local hosts only' }, 403);+ if (!['GET', 'HEAD'].includes(request.method) && request.headers.get('origin') !== url.origin) return json({ error: 'Same-origin writes only' }, 403);+ if (closing) return json({ error: 'Studio is stopping' }, 503);+ const matched = url.pathname.match(/^\/api\/projects\/([^/]+)/);+ const pathId = matched ? decodeURIComponent(matched[1]) : undefined;+ const queryId = url.searchParams.get('projectId') ?? undefined;+ if (pathId && queryId && pathId !== queryId) return json({ error: 'PROJECT_SCOPE_MISMATCH' }, 400);+ const id = pathId ?? queryId;+ if (id !== undefined) store.forProject(id);+ if (url.pathname === '/__hyperframes_config') {+ if (id) await hostFor(id);+ return json({ isHyperframes: true, version: HYPERFRAMES_VERSION, pid: process.pid,+ projectDir: id ? store.projectDirectoryFor(id) : initialDirectory, dataDirectory, multiProject: true });+ }+ if (url.pathname === '/api/projects') return json({ projects: store.projectCatalog().projects.map(project => ({ id: project.id, title: project.title, dir: store.projectDirectoryFor(project.id) })) });+ const sharedResource = url.pathname === '/' || url.pathname.startsWith('/assets/') || /^\/api\/(?:runtime\.js|vendor\/|fonts|environment\/|assets\/global)/.test(url.pathname);+ const catalog = store.projectCatalog();+ const target = id ?? (catalog.projects.length === 1 || sharedResource ? catalog.projects.find(project => store.projectDirectoryFor(project.id) === initialDirectory)?.id : undefined);+ if (!target) return json({ error: 'PROJECT_NOT_BOUND: specify projectId' }, 400);+ const host = await hostFor(target);+ return await host.app.fetch(request);+ } catch (error) {+ return json({ error: error instanceof Error ? error.message : 'Studio request failed' }, /PROJECT_NOT_FOUND|ENOENT/.test(String(error)) ? 404 : 400);+ }+ };+ const server = createServer(getRequestListener(fetchRequest));+ await new Promise<void>((resolve, reject) => {+ server.once('error', (error: NodeJS.ErrnoException) => {+ if (error.code === 'EADDRINUSE') { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); }+ else reject(error);+ });+ server.listen(port, '127.0.0.1', resolve);+ });+ origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`;+ return { server, origin, close: async () => {+ closing = true;+ server.closeAllConnections(); server.close();+ const contexts = await Promise.allSettled(hosts.values());+ await Promise.all(contexts.map(async context => { if (context.status === 'fulfilled') { context.value.watcher.close(); await context.value.shutdown(); } }));+ } };+}++if (isMain(import.meta.url)) {+ const [runtimeRoot, dataDirectory, initialDirectory, port] = process.argv.slice(2);+ const running = await startWorkspaceStudio(runtimeRoot, dataDirectory, initialDirectory, Number(port));+ console.log(JSON.stringify({ ok: true, result: { ready: true, projectDir: initialDirectory, studioUrl: running.origin } }));+ const stop = () => { void running.close().finally(() => process.exit(0)); };+ process.once('SIGTERM', stop); process.once('SIGINT', stop);+}diff --git a/studio/src/components/renders/useRenderQueue.ts b/studio/src/components/renders/useRenderQueue.tsindex a544515c..e17ccdc9 100644--- a/studio/src/components/renders/useRenderQueue.ts+++ b/studio/src/components/renders/useRenderQueue.ts@@ -8,7 +8,7 @@ import { generateId } from "../../utils/generateId";import { readServerError } from "./serverError";import { ffmpegInstallMessage, useFfmpegStatus } from "./useFfmpegStatus";import { requestStudioFeedback, type FeedbackContext } from "../feedback/feedbackTrigger";-import { studioApiFetch } from "../../utils/studioApiFetch";+import { studioApiFetch, studioProjectUrl } from "../../utils/studioApiFetch";export interface RenderJob {id: string;@@ -325,7 +325,7 @@ export function useRenderQueue(activeJobRef.current = jobId;// Track progress via SSE- const es = new EventSource(`/api/render/${jobId}/progress`);+ const es = new EventSource(studioProjectUrl(`/api/render/${jobId}/progress`, projectId));eventSourceRef.current = es;es.addEventListener("progress", (event) => {diff --git a/studio/src/components/studioMediaJobs.ts b/studio/src/components/studioMediaJobs.tsindex d6e85d88..c6feb11c 100644--- a/studio/src/components/studioMediaJobs.ts+++ b/studio/src/components/studioMediaJobs.ts@@ -2,6 +2,7 @@ import type {BackgroundRemovalProgress,BackgroundRemovalResult,} from "./editor/propertyPanelTypes";+import { studioProjectUrl } from '../utils/studioApiFetch';const MEDIA_JOB_RECONNECT_TIMEOUT_MS = 15_000;const ABSOLUTE_OR_ROOT_SOURCE_RE = /^(?:[a-z][a-z0-9+.-]*:|\/)/i;@@ -66,7 +67,7 @@ export function waitForMediaJob(reject(new DOMException("Background removal was cancelled", "AbortError"));return;}- const events = new EventSource(`/api/media-jobs/${encodeURIComponent(jobId)}/progress`);+ const events = new EventSource(studioProjectUrl(`/api/media-jobs/${encodeURIComponent(jobId)}/progress`));let settled = false;let reconnectTimer: number | null = null;diff --git a/studio/src/hooks/useExternalFileChangeCoordinator.ts b/studio/src/hooks/useExternalFileChangeCoordinator.tsindex b1fa28e1..4db6bec0 100644--- a/studio/src/hooks/useExternalFileChangeCoordinator.ts+++ b/studio/src/hooks/useExternalFileChangeCoordinator.ts@@ -129,7 +129,7 @@ export function sseFileChangeChannel(onDelivery: (delivery: unknown) => void,onReconnect: () => void,): () => void {- const eventSource = new EventSource("/api/events");+ const eventSource = new EventSource(studioProjectUrl('/api/events'));eventSource.addEventListener("file-change", onDelivery);// Reopening the stream does not replay changes missed during a disconnect.let opened = false;@@ -591,3 +591,4 @@ export function useExternalFileChangeCoordinator({return { blocked, retry, useExternalFile, keepStudioFile };}+import { studioProjectUrl } from '../utils/studioApiFetch';diff --git a/studio/src/motion/MediaGateway.test.tsx b/studio/src/motion/MediaGateway.test.tsxindex 514c9bf7..eebc45da 100644--- a/studio/src/motion/MediaGateway.test.tsx+++ b/studio/src/motion/MediaGateway.test.tsx@@ -26,7 +26,7 @@ it('hides the empty guide during generation, restores it on close, and removes ivi.stubGlobal('fetch', vi.fn(async (url: string) => {if (url.includes('models/capabilities')) return Response.json({ providers: [{ id: 'codex', available: true }], routes: {} });if (url.includes('/models?')) return Response.json({ models: [model], nextOffset: null });- if (url.endsWith('project/status')) return Response.json({ projectId: 'project' });+ if (url.includes('project/status')) return Response.json({ projectId: 'project' });if (url.includes('/generations?')) return Response.json({ jobs: [job] });throw new Error('Unexpected request ' + url);}));@@ -58,17 +58,17 @@ it('hides the empty guide during generation, restores it on close, and removes iexpect(guide()!.style.visibility).toBe('');});-it('generates through the shared API, shows only completed output, and places it at the selected range with failure reporting', async () => {+it('generates for its own project while another project is globally active, then places at its selected range', async () => {vi.useFakeTimers(); usePlayerStore.setState({ timelineProjectId: 'native-project', rangeSelection: { t0: 2, t1: 7 } });const place = vi.fn().mockResolvedValue(undefined);const jobs: GenerationJob[] = []; let submitted: Record<string, unknown> | undefined;vi.stubGlobal('fetch', vi.fn(async (url: string, init?: RequestInit) => {if (url.includes('models/capabilities')) return Response.json({ providers: [{ id: 'codex', available: true }], agents: [], routes: {}, capabilities: [] });if (url.includes('/models?')) return Response.json({ models: [model], nextOffset: null });- if (url.endsWith('project/status')) return Response.json({ projectId: 'workspace-project' });+ if (url.includes('project/status')) return Response.json({ projectId: url.includes('projectId=native-project') ? 'native-project' : 'workspace-project' });if (url.endsWith('/generations') && init?.method === 'POST') {submitted = JSON.parse(init.body as string);- const job = { id: 'job-1', projectId: 'workspace-project', state: 'queued', prompt: 'a forest', model, modality: 'image', parameters: {}, createdAt: 1, updatedAt: 1, requestHash: 'hash', assets: [] } as GenerationJob;+ const job = { id: 'job-1', projectId: 'native-project', state: 'queued', prompt: 'a forest', model, modality: 'image', parameters: {}, createdAt: 1, updatedAt: 1, requestHash: 'hash', assets: [] } as GenerationJob;jobs.push(job); return Response.json({ job });}if (url.includes('/generations?')) return Response.json({ jobs });@@ -80,7 +80,7 @@ it('generates through the shared API, shows only completed output, and places itawait act(async () => button('Open generator').click());await act(async () => type('textarea[aria-label="Describe your media"]', 'a forest'));await act(async () => button('Generate').click());- expect(submitted).toMatchObject({ projectId: 'workspace-project', model: model.id, modality: 'image', parameters: { aspect_ratio: '16:9' }, usage: { compositionId: 'main' } });+ expect(submitted).toMatchObject({ projectId: 'native-project', model: model.id, modality: 'image', parameters: { aspect_ratio: '16:9' }, usage: { compositionId: 'main' } });expect(String(submitted?.idempotencyKey)).toMatch(/-0$/);expect(document.body.textContent).not.toContain('Place on timeline');jobs[0] = { ...jobs[0], state: 'completed', assets: [{ path: 'assets/generated/one.png', bytes: 1000, mimeType: 'image/png' }, { path: 'assets/generated/two.png', bytes: 1000, mimeType: 'image/png' }] };@@ -101,10 +101,10 @@ it('edits a reference with a supported model, preserves placement and applies onvi.stubGlobal('fetch', vi.fn(async (url: string, init?: RequestInit) => {if (url.includes('models/capabilities')) return Response.json({ providers: [{ id: 'codex', available: true }, { id: 'fal', available: true }], routes: { image: 'fal:flux' } });if (url.includes('/models?')) return Response.json({ models: [{ ...model, supportsImageReference: true }, { ...model, id: 'fal:flux', provider: 'fal', label: 'Flux' }], nextOffset: null });- if (url.endsWith('project/status')) return Response.json({ projectId: 'project' });+ if (url.includes('project/status')) return Response.json({ projectId: 'native' });if (url.endsWith('/generations') && init?.method === 'POST') {submitted = JSON.parse(init.body as string);- const job = { id: 'edited-image', projectId: 'project', state: 'completed', model, prompt: 'golden sunset', reference: { path: reference.path, sha256: 'test', mimeType: 'image/png', bytes: 20 }, assets: [{ path: 'assets/generated/sunset.png', mimeType: 'image/png', bytes: 20 }] } as GenerationJob;+ const job = { id: 'edited-image', projectId: 'native', state: 'completed', model, prompt: 'golden sunset', reference: { path: reference.path, sha256: 'test', mimeType: 'image/png', bytes: 20 }, assets: [{ path: 'assets/generated/sunset.png', mimeType: 'image/png', bytes: 20 }] } as GenerationJob;jobs.push(job); return Response.json({ job });}if (url.includes('/generations?')) return Response.json({ jobs });diff --git a/studio/src/motion/MediaGenerator.tsx b/studio/src/motion/MediaGenerator.tsxindex 28765576..e057fc25 100644--- a/studio/src/motion/MediaGenerator.tsx+++ b/studio/src/motion/MediaGenerator.tsx@@ -5,6 +5,7 @@ import { gatewayRequest, generateAsset, loadGateway, type GatewayStatus, type Moimport type { MediaRequest } from './MediaGatewayContext';import { useMediaPopoverPosition } from './useMediaPopoverPosition';import { useArtifactViewActive } from './ArtifactViewState';+import { requestedProject } from './workspaceRouting';export function generationParameters(model: Model, ratio: string, duration: number, extra: Record<string, unknown>) {const [w, h] = ratio.split(':').map(Number);@@ -41,9 +42,14 @@ export function MediaGenerator({ request, onClose, onSettings }: { request: Mediconst activeProjectId = usePlayerStore(s => s.timelineProjectId);const activeSession = usePlayerStore(s => s.timelineSessionEpoch);const openingSession = useRef({ projectId: activeProjectId, epoch: activeSession });+ const boundProjectId = useRef(request.target?.projectId ?? requestedProject(location.search, location.hash) ?? activeProjectId);+ const projectStatusPath = 'project/status' + (boundProjectId.current ? '?projectId=' + encodeURIComponent(boundProjectId.current) : '');useEffect(() => {let active = true;- void Promise.all([loadGateway(), gatewayRequest<{ projectId: string }>('project/status')]).then(([next, status]) => { if (active) { setData(next); setProjectId(status.projectId); } }).catch(e => { if (active) setError(e.message); });+ void Promise.all([loadGateway(), boundProjectId.current ? gatewayRequest<{ projectId: string }>(projectStatusPath) : Promise.resolve(null)]).then(([next, status]) => {+ if (status && status.projectId !== boundProjectId.current) throw new Error(t('Switch back to the original project to place this asset'));+ if (active) { setData(next); setProjectId(status?.projectId ?? ''); }+ }).catch(e => { if (active) setError(e.message); });return () => { active = false; };}, []);useEffect(() => {@@ -102,7 +108,7 @@ export function MediaGenerator({ request, onClose, onSettings }: { request: Mediasync function place(job: GenerationJob, asset: string) {if (!request.target) return;setBusy(true); setError('');- try { const current = await gatewayRequest<{ projectId: string }>('project/status'); if (current.projectId !== job.projectId) throw new Error(t('Switch back to the original project to place this asset'));+ try { const current = await gatewayRequest<{ projectId: string }>(projectStatusPath); if (current.projectId !== job.projectId) throw new Error(t('Switch back to the original project to place this asset'));await request.target.place(asset, { start, duration, track: request.placement?.track ?? 0 }); setPlaced(prev => [...prev, asset]);} catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); }}@@ -110,7 +116,7 @@ export function MediaGenerator({ request, onClose, onSettings }: { request: Mediif (!request.target?.replace || !request.selection) return;setBusy(true); setError('');try {- const current = await gatewayRequest<{ projectId: string }>('project/status');+ const current = await gatewayRequest<{ projectId: string }>(projectStatusPath);if (current.projectId !== job.projectId) throw new Error(t('Switch back to the original project to place this asset'));await request.target.replace(asset, request.selection); setReplaced(asset);} catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); }diff --git a/studio/src/motion/MotionApp.test.tsx b/studio/src/motion/MotionApp.test.tsxindex 5c4f51b9..ddb53677 100644--- a/studio/src/motion/MotionApp.test.tsx+++ b/studio/src/motion/MotionApp.test.tsx@@ -5,12 +5,12 @@ import { resolveWorkspaceProject } from './MotionApp';vi.mock('../App', () => ({ StudioApp: () => null }));const id = '11111111-1111-1111-1111-111111111111';afterEach(() => vi.unstubAllGlobals());-it('restores the bookmarked project on the server before letting the editor mount', async () => {- const fetcher = vi.fn(async (url: string) => new Response(JSON.stringify(url.endsWith('/projects') ? { activeId: 'project', projects: [{ id }, { id: 'project' }] } : url.endsWith('/status') ? { projectId: 'project', revision: 'new-revision' } : { projectId: id })));+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);await resolveWorkspaceProject(id, new AbortController().signal);- expect(fetcher.mock.calls.map(call => call[0])).toEqual(['/motion-api/projects', '/motion-api/project/status', `/motion-api/projects/${id}/open`]);- expect(JSON.parse((fetcher.mock.calls[2] as unknown as [string, RequestInit])[1].body as string)).toEqual({ expectedRevision: 'new-revision', expectedProjectId: 'project' });+ expect(fetcher.mock.calls.map(call => call[0])).toEqual(['/motion-api/projects', `/motion-api/preview/open?projectId=${id}`]);+ expect(fetcher.mock.calls[1][1]).toEqual({ method: 'POST', signal: expect.any(AbortSignal) });});it('invalid, deleted and conflicting links cannot silently open a different project', async () => {const fetcher = vi.fn(async () => new Response(JSON.stringify({ activeId: 'project', projects: [{ id: 'project' }] })));@@ -22,9 +22,14 @@ it('invalid, deleted and conflicting links cannot silently open a different projfetcher.mockImplementation(async () => new Response(JSON.stringify({ error: '正在切换' }), { status: 409 }));await expect(resolveWorkspaceProject('project', new AbortController().signal)).rejects.toThrow('正在切换');});-it('an already selected bookmark does not issue a mutation', async () => {- const fetcher = vi.fn(async () => new Response(JSON.stringify({ activeId: id, projects: [{ id }] })));+it('warms an already selected bookmark before mounting its editor', async () => {+ const fetcher = vi.fn(async (_url: string) => new Response(JSON.stringify({ activeId: id, projects: [{ id }] })));vi.stubGlobal('fetch', fetcher);await resolveWorkspaceProject(id, new AbortController().signal);- expect(fetcher).toHaveBeenCalledOnce();+ expect(fetcher.mock.calls[1][0]).toBe(`/motion-api/preview/open?projectId=${id}`);+});+it('does not mount a bookmark when its scoped native context cannot open', async () => {+ const fetcher = vi.fn(async (url: string) => new Response(JSON.stringify(url.endsWith('/projects') ? { projects: [{ id }] } : { error: 'Native opening timed out' }), { status: url.endsWith('/projects') ? 200 : 400 }));+ vi.stubGlobal('fetch', fetcher);+ await expect(resolveWorkspaceProject(id, new AbortController().signal)).rejects.toThrow('Native opening timed out');});diff --git a/studio/src/motion/MotionApp.tsx b/studio/src/motion/MotionApp.tsxindex f2fed252..f1722598 100644--- a/studio/src/motion/MotionApp.tsx+++ b/studio/src/motion/MotionApp.tsx@@ -2,7 +2,7 @@ import { useEffect, useState } from 'react';import { useI18n } from '../i18n/I18n';import { WorkspaceFrame } from './WorkspaceFrame';import { MotionHome } from './MotionHome';-import { motionApi, type ProjectCatalog, type WorkspaceStatus } from './useWorkspace';+import { motionApi, type ProjectCatalog } from './useWorkspace';import { requestedProject, validWorkspaceProject } from './workspaceRouting';import { MotionSessionFrame } from './MotionSessionFrame';import type { SessionDetail, SessionArtifact } from '../../../shared/session';@@ -14,14 +14,8 @@ export async function resolveWorkspaceProject(id: string, signal: AbortSignal) {if (!validWorkspaceProject(id)) throw new Error('项目链接无效');const catalog = await motionApi<ProjectCatalog>('/projects', { signal });if (!catalog.projects.some(project => project.id === id)) throw new Error('项目不存在,请从首页选择一个项目。');- if (catalog.activeId !== id) {- const current = await motionApi<WorkspaceStatus>('/project/status', { signal });- signal.throwIfAborted();- await motionApi<WorkspaceStatus>(`/projects/${encodeURIComponent(id)}/open`, {- method: 'POST', signal, headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ expectedRevision: current.revision, expectedProjectId: current.projectId }),- });- }+ signal.throwIfAborted();+ await motionApi('/preview/open', { method: 'POST', signal }, id);}/** Resolve the native service before mounting any editor that could read or save files. */diff --git a/studio/src/motion/useWorkspace.test.tsx b/studio/src/motion/useWorkspace.test.tsxindex 9bf3114d..f3f254b7 100644--- a/studio/src/motion/useWorkspace.test.tsx+++ b/studio/src/motion/useWorkspace.test.tsx@@ -39,7 +39,7 @@ it('waits for saves, deduplicates rapid actions and opens the new project in a nexpect(writes()).toHaveLength(0);await act(async () => { saved(); await operation; });expect(writes()).toHaveLength(1);- expect(writes()[0][0]).toBe('/motion-api/projects');+ expect(writes()[0][0]).toBe(`/motion-api/projects?projectId=${first}`);expect(JSON.parse(writes()[0][1]!.body as string)).toEqual({ expectedRevision: status.revision, expectedProjectId: first });expect(navigate).toHaveBeenCalledWith(`/?project=${second}#project/${second}`);});@@ -70,6 +70,24 @@ it('home stays home when another client switches the active project', async () =expect(navigate).toHaveBeenCalledWith('/');expect(writes()).toHaveLength(0);});+it('an existing project page polls its own project without following another client', async () => {+ const replace = vi.spyOn(window.location, 'replace').mockImplementation(() => {});+ fetcher.mockImplementation(async (url: string) => Response.json(url.endsWith('/projects')+ ? { activeId: second, projects: [{ id: first }, { id: second }] }+ : new URL(url, location.origin).searchParams.get('projectId') === first ? status : { ...status, projectId: second }));+ await mount(async () => {}, first, first);+ expect(workspace.status?.projectId).toBe(first);+ expect(replace).not.toHaveBeenCalled();+ expect(fetcher.mock.calls.some(([url]) => url === `/motion-api/project/status?projectId=${first}`)).toBe(true);+});+it('an empty conversation opens its own first artifact even when another project is globally active', async () => {+ const replace = vi.spyOn(window.location, 'replace').mockImplementation(() => {});+ fetcher.mockImplementation(async (url: string) => Response.json(url.endsWith('/projects')+ ? { projects: [], sessions: [{ id: 'conversation', artifacts: [{ id: 'artifact-a', projectId: first }], activeArtifactId: 'artifact-a' }] }+ : { ...status, projectId: second }));+ await mount(async () => {}, undefined, 'conversation');+ expect(replace).toHaveBeenCalledWith(`/?session=conversation&project=${first}&openArtifact=1#project/${first}`);+});it('keeps a home request after failure and clears it only once the project was created with that request', async () => {await mount(async () => {});localStorage.setItem('motion.home.draft.v1', 'Make a launch video');diff --git a/studio/src/motion/useWorkspace.ts b/studio/src/motion/useWorkspace.tsindex b04d47bd..2b068054 100644--- a/studio/src/motion/useWorkspace.ts+++ b/studio/src/motion/useWorkspace.ts@@ -7,8 +7,9 @@ export type SavedProject = { id: string; title: string; templateId?: string; cretype Job = { id: string; state: 'pending' | 'running' | 'completed' | 'failed'; error?: string };export type WorkspaceStatus = { revision: string; projectId: string; projectTitle: string; exportJob: Job | null; sessionId?: string };export type ProjectCatalog = { activeId: string; projects: SavedProject[]; sessions?: CreativeSession[]; activeSessionId?: string };-export async function motionApi<T>(path: string, init?: RequestInit): Promise<T> {- const response = await fetch((path.startsWith('/sessions') || path.startsWith('/modes') ? '/design-api' : '/motion-api') + path, init);+export async function motionApi<T>(path: string, init?: RequestInit, projectId?: string): Promise<T> {+ const response = await fetch((path.startsWith('/sessions') || path.startsWith('/modes') ? '/design-api' : '/motion-api') + path+ + (projectId ? (path.includes('?') ? '&' : '?') + 'projectId=' + encodeURIComponent(projectId) : ''), init);const data = await response.json();if (!response.ok) throw new Error(data.error || '本地工作室连接失败');return data as T;@@ -29,6 +30,7 @@ export function useWorkspace(waitForSaves: () => Promise<void>, projectId?: striconst [error, setError] = useState('');const acting = useRef(false);const pendingSession = useRef<{ key: string; id: string } | null>(null);+ const request = useCallback(<T,>(path: string, init?: RequestInit) => motionApi<T>(path, init, projectId), [projectId]);const updateCatalog = useCallback((catalog: ProjectCatalog) => {const ordered = [...catalog.projects].sort((a, b) => (b.openedAt ?? b.createdAt ?? 0) - (a.openedAt ?? a.createdAt ?? 0));setProjects(previous => JSON.stringify(previous) === JSON.stringify(ordered) ? previous : ordered);@@ -41,14 +43,15 @@ export function useWorkspace(waitForSaves: () => Promise<void>, projectId?: striasync function poll() {try {const [data, catalog] = await Promise.all([- motionApi<WorkspaceStatus>('/project/status', { signal: controller.signal }),+ request<WorkspaceStatus>('/project/status', { signal: controller.signal }),motionApi<ProjectCatalog>('/projects', { signal: controller.signal }),]);if (controller.signal.aborted) return;if (projectId && data.projectId !== projectId && !acting.current) {- navigateWorkspace(data.sessionId ? sessionHref(data.sessionId, data.projectId, true) : projectHref(data.projectId), true); return;+ throw new Error('工程状态与当前页面不匹配,请重新打开对应工程。');}- const generated = !projectId && sessionId ? catalog.sessions?.find(item => item.id === sessionId)?.artifacts.find(item => item.projectId === data.projectId) : undefined;+ const session = !projectId && sessionId ? catalog.sessions?.find(item => item.id === sessionId) : undefined;+ const generated = session?.artifacts.find(item => item.id === session.activeArtifactId) ?? session?.artifacts.at(-1);if (generated && !acting.current) { navigateWorkspace(sessionHref(sessionId!, generated.projectId, true), true); return; }setStatus(data); updateCatalog(catalog);} catch (err) { if (!controller.signal.aborted) setError((err as Error).message); }@@ -56,7 +59,7 @@ export function useWorkspace(waitForSaves: () => Promise<void>, projectId?: stri}void poll();return () => { controller.abort(); clearTimeout(timer); };- }, [projectId, sessionId, updateCatalog]);+ }, [projectId, sessionId, updateCatalog, request]);const transition = useCallback(async (path?: string, options?: { instruction?: string; mode?: string; templateId?: string; projectId?: string }, sessionRoute = false, revealArtifact = true) => {if (acting.current) return false;@@ -64,16 +67,16 @@ export function useWorkspace(waitForSaves: () => Promise<void>, projectId?: stritry {await waitForSaves();if (!path) { navigateWorkspace('/'); return true; }- const current = await motionApi<WorkspaceStatus>('/project/status');+ const current = await request<WorkspaceStatus>('/project/status');if (projectId && current.projectId !== projectId) throw new Error('当前项目已切换,请刷新后重试。');- const next = await motionApi<WorkspaceStatus>(path, {+ const next = await request<WorkspaceStatus>(path, {method: 'POST', ...jsonBody({ expectedRevision: current.revision, expectedProjectId: current.projectId, ...options }),});if (options?.instruction) { try { localStorage.removeItem('motion.home.draft.v1'); } catch {} }navigateWorkspace(sessionRoute && next.sessionId ? sessionHref(next.sessionId, next.projectId, revealArtifact) : projectHref(next.projectId));return true;} catch (err) { setError((err as Error).message); acting.current = false; setBusy(false); return false; }- }, [waitForSaves, projectId]);+ }, [waitForSaves, projectId, request]);const open = useCallback((kind: 'templates' | 'projects', id: string) => transition(`/${kind}/${encodeURIComponent(id)}/open`), [transition]);const create = useCallback((instruction?: string) => transition('/projects', instruction?.trim() ? { instruction: instruction.trim() } : undefined), [transition]);const home = useCallback(() => transition(), [transition]);@@ -91,8 +94,8 @@ export function useWorkspace(waitForSaves: () => Promise<void>, projectId?: stritry { localStorage.removeItem('motion.home.draft.v1'); } catch {}const existing = created.session?.artifacts.find(item => item.id === created.session.activeArtifactId) ?? created.session?.artifacts[0];if (existing) { navigateWorkspace(sessionHref(createdId, existing.projectId, true)); return true; }- const current = await motionApi<WorkspaceStatus>('/project/status');- const next = await motionApi<WorkspaceStatus>(`/sessions/${createdId}/artifacts`, { method: 'POST', ...jsonBody({ expectedRevision: current.revision, expectedProjectId: current.projectId }) });+ const current = await request<WorkspaceStatus>('/project/status');+ const next = await request<WorkspaceStatus>(`/sessions/${createdId}/artifacts`, { method: 'POST', ...jsonBody({ expectedRevision: current.revision, expectedProjectId: current.projectId }) });navigateWorkspace(sessionHref(createdId, next.projectId, true)); return true;} catch (err) {if (createdId) {@@ -101,7 +104,7 @@ export function useWorkspace(waitForSaves: () => Promise<void>, projectId?: stri}setError((err as Error).message); acting.current = false; setBusy(false); return false;}- }, [waitForSaves]);+ }, [waitForSaves, request]);const openSession = useCallback((id: string, artifactProjectId?: string) => transition(`/sessions/${encodeURIComponent(id)}/open`, artifactProjectId ? { projectId: artifactProjectId } : undefined, true, Boolean(artifactProjectId)), [transition]);const createArtifact = useCallback((id: string, templateId?: string) => transition(`/sessions/${encodeURIComponent(id)}/artifacts`, templateId ? { templateId } : undefined, true), [transition]);const renameItem = useCallback(async (id: string, title: string, kind: 'projects' | 'sessions') => {diff --git a/studio/src/utils/studioApiFetch.test.ts b/studio/src/utils/studioApiFetch.test.tsindex e952f908..968fbd68 100644--- a/studio/src/utils/studioApiFetch.test.ts+++ b/studio/src/utils/studioApiFetch.test.ts@@ -27,6 +27,17 @@ describe("studioApiFetch", () => {credentials: "omit",});});+ it('binds unscoped native requests and event URLs to the page project', async () => {+ vi.stubGlobal('location', new URL('http://localhost:5190/?project=project-a#project/project-a'));+ const fetchMock = vi.fn(async () => new Response('ok')); vi.stubGlobal('fetch', fetchMock);+ const { studioApiFetch, studioProjectUrl } = await loadWithEnv({});+ await studioApiFetch('/api/render/job-a/cancel', { method: 'POST' });+ expect(fetchMock).toHaveBeenCalledWith('/api/render/job-a/cancel?projectId=project-a', expect.objectContaining({ method: 'POST' }));+ expect(studioProjectUrl('/api/events')).toBe('/api/events?projectId=project-a');+ expect(studioProjectUrl('/api/projects/project-b/files/index.html')).toBe('/api/projects/project-b/files/index.html');+ expect(studioProjectUrl('/api/events?projectId=project-b')).toBe('/api/events?projectId=project-b');+ expect(studioProjectUrl('https://another.example/api/events')).toBe('https://another.example/api/events');+ });it.each([["the CLI or Studio dev server", "http://localhost:5190/"],diff --git a/studio/src/utils/studioApiFetch.ts b/studio/src/utils/studioApiFetch.tsindex 88990ada..d4961ab8 100644--- a/studio/src/utils/studioApiFetch.ts+++ b/studio/src/utils/studioApiFetch.ts@@ -1,4 +1,5 @@import { STUDIO_API_SAME_ORIGIN_CREDENTIALS } from "../components/editor/manualEditingAvailability";+import { parseProjectIdFromHash } from './projectRouting';const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);@@ -9,5 +10,15 @@ function studioApiCredentials(): RequestCredentials {}export function studioApiFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {- return globalThis.fetch(input, { ...init, credentials: studioApiCredentials() });+ return globalThis.fetch(typeof input === 'string' ? studioProjectUrl(input) : input, { ...init, credentials: studioApiCredentials() });+}++export function studioProjectUrl(input: string, projectId?: string | null): string {+ if (!input.startsWith('/api/') || input === '/api/projects' || input.startsWith('/api/projects/')) return input;+ const location = globalThis.location;+ const id = projectId ?? (location && (new URLSearchParams(location.search).get('project') ?? parseProjectIdFromHash(location.hash)));+ if (!id) return input;+ const url = new URL(input, 'http://studio.local');+ if (!url.searchParams.has('projectId')) url.searchParams.set('projectId', id);+ return url.pathname + url.search;}diff --git a/tests/multi-project-browser.mjs b/tests/multi-project-browser.mjsnew file mode 100644index 00000000..a4580746--- /dev/null+++ b/tests/multi-project-browser.mjs@@ -0,0 +1,125 @@+import assert from 'node:assert/strict';+import { cp, mkdtemp, mkdir, readFile, writeFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import puppeteer from 'puppeteer-core';+import { Client } from './shared-editor-client.mjs';+import { closeFixtureEditor, fixture } from './fixtures.ts';+import { ensureEditor } from '../editor-runtime.ts';++assert.ok(process.env.D4_LANE && process.env.D4_LOCK_PID, 'Run with the shared browser-lock lane and real lock');+const out = process.argv[2]; assert.ok(out && path.isAbsolute(out), 'Pass an absolute evidence directory');+await mkdir(out, { recursive: true });+const data = await mkdtemp(path.join(tmpdir(), 'motion-multi-browser-'));+const clients = [new Client(data), new Client(data)];+let browser, pages = [];+const browserEvents = [];+const film = (label, duration) => `<!doctype html><html><head><title>${label}</title><script src="assets/gsap.min.js"></script><style>body{margin:0}#main{position:relative;width:640px;height:360px;background:#18382f;color:#fff;font:700 40px sans-serif}h1{position:absolute;left:48px;top:80px}</style></head><body><div id="main" data-composition-id="main" data-start="0" data-duration="${duration}" data-width="640" data-height="360" data-fps="10"><h1 id="label">${label}</h1></div><script>window.__timelines={main:gsap.timeline({paused:true}).fromTo('#label',{x:0},{x:80,duration:${duration},ease:'none'})};</script></body></html>`;+const result = { status: 'failed', scope: 'two real MCP clients and two Chrome pages; generated local fixtures', checks: [] };+const check = (name, evidence = {}) => { result.checks.push({ name, ...evidence }); console.log('PASS ' + name); };+try {+ await Promise.all(clients.map(client => client.initialize()));+ const projects = [];+ for (const [i, label] of ['PROJECT A', 'PROJECT B'].entries()) {+ const created = await clients[i].call('motion_create_project', { requestId: 'create-' + i, projectType: 'natural_language', title: label, requirements: label });+ await clients[i].call('motion_edit_project', { projectId: created.projectId, requestId: 'write-' + i, expectedRevision: created.revision, expectedVersionId: created.currentVersionId, files: [{ path: 'index.html', content: film(label, i + 1) }] });+ projects.push(await clients[i].call('motion_open_preview', { projectId: created.projectId }));+ }+ const identities = await Promise.all(projects.map(async project => (await fetch(new URL('/__hyperframes_config?projectId=' + project.projectId, project.previewUrl))).json()));+ assert.equal(identities[0].pid, identities[1].pid);+ assert.equal(new URL(projects[0].previewUrl).origin, new URL(projects[1].previewUrl).origin);+ check('both projects use one native process and one public origin', { nativePid: identities[0].pid });+ browser = await puppeteer.launch({ executablePath: process.env.HYPERFRAMES_BROWSER_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', headless: true, userDataDir: path.join(data, 'browser-profile') });+ pages = await Promise.all(projects.map(() => browser.newPage()));+ const foreignRequests = [];+ for (const [i, page] of pages.entries()) {+ await page.setViewport({ width: 1440, height: 1000 });+ page.on('console', message => { if (['error', 'warn'].includes(message.type())) browserEvents.push({ page: i, type: message.type(), text: message.text() }); });+ page.on('response', response => { if (response.status() >= 400) browserEvents.push({ page: i, status: response.status(), url: response.url() }); });+ page.on('request', request => { const match = new URL(request.url()).pathname.match(/^\/api\/projects\/([^/]+)/); if (match && decodeURIComponent(match[1]) !== projects[i].projectId) foreignRequests.push({ page: i, url: request.url() }); });+ await page.goto(projects[i].previewUrl, { waitUntil: 'domcontentloaded' });+ }+ const waitForFilm = async (page, projectId, label) => {+ // Match returning to a conversation: background tabs may defer native paint/readiness work.+ await page.bringToFront();+ const deadline = Date.now() + 60_000;+ while (Date.now() < deadline) {+ for (const frame of page.frames()) {+ if (!frame.url().includes('/api/projects/' + projectId + '/preview')) continue;+ if (await frame.evaluate(value => document.body?.innerText.includes(value), label).catch(() => false)) {+ await page.waitForFunction(value => {+ const timeline = document.querySelector('[data-timeline-element-count]');+ return Number(timeline?.getAttribute('data-timeline-element-count')) > 0 && timeline?.textContent?.includes(value);+ }, { timeout: 30_000 }, label);+ return;+ }+ }+ await new Promise(resolve => setTimeout(resolve, 100));+ }+ throw new Error(`Preview did not converge: ${projectId} ${label}; ${page.frames().map(frame => frame.url()).join(', ')}`);+ };+ for (const [i, page] of pages.entries()) await waitForFilm(page, projects[i].projectId, ['PROJECT A', 'PROJECT B'][i]);+ await new Promise(resolve => setTimeout(resolve, 2400));+ for (const [i, page] of pages.entries()) assert.equal(new URL(page.url()).searchParams.get('project'), projects[i].projectId);+ check('two live previews and timelines retain their own project after global selection and status polling');+ const currentA = await clients[0].call('motion_get_project', { projectId: projects[0].projectId });+ await clients[0].call('motion_edit_project', { projectId: projects[0].projectId, requestId: 'update-a', expectedRevision: currentA.revision, expectedVersionId: currentA.currentVersionId, files: [{ path: 'index.html', content: film('PROJECT A UPDATED', 1) }] });+ await waitForFilm(pages[0], projects[0].projectId, 'PROJECT A UPDATED');+ await waitForFilm(pages[1], projects[1].projectId, 'PROJECT B');+ await clients[0].call('motion_open_preview', { projectId: projects[0].projectId });+ await new Promise(resolve => setTimeout(resolve, 2200));+ assert.equal(new URL(pages[1].url()).searchParams.get('project'), projects[1].projectId);+ assert.deepEqual(foreignRequests, []);+ check('MCP edits refresh A preview and timeline without changing B URL, content or request targets');+ const origin = new URL(projects[1].previewUrl).origin;+ const render = await fetch(`${origin}/api/projects/${projects[1].projectId}/render`, { method: 'POST', headers: { Origin: origin, 'Content-Type': 'application/json' }, body: JSON.stringify({ format: 'mp4', fps: 10, quality: 'draft' }) });+ assert.equal(render.status, 200, await render.clone().text());+ const nativeJob = await render.json();+ assert.ok(nativeJob.jobId);+ const cancel = projectId => fetch(`${origin}/api/render/${nativeJob.jobId}/cancel?projectId=${projectId}`, { method: 'POST', headers: { Origin: origin } });+ assert.equal((await cancel(projects[0].projectId)).status, 404, 'A cannot cancel B native render');+ const cancelled = await cancel(projects[1].projectId);+ assert.equal(cancelled.status, 200, await cancelled.clone().text());+ check('native render task cancellation resolves only in its owning project');+ await pages[0].reload({ waitUntil: 'domcontentloaded' });+ await waitForFilm(pages[0], projects[0].projectId, 'PROJECT A UPDATED');+ await waitForFilm(pages[1], projects[1].projectId, 'PROJECT B');+ check('reloading A bookmark leaves B usable');+ for (const [i, page] of pages.entries()) await page.screenshot({ path: path.join(out, `project-${i === 0 ? 'a' : 'b'}.png`) });+ await fixture(async store => {+ const a = store.projectId, b = crypto.randomUUID();+ await writeFile(path.join(store.projectDirectory, 'index.html'), film('COLD BOOKMARK A', 1));+ await cp(store.projectDirectory, store.projectDirectoryFor(b), { recursive: true });+ await store.selectProject(b, { id: b, title: 'Unopened B' });+ const before = await store.forProject(b).get();+ const sourceB = await readFile(path.join(store.projectDirectoryFor(b), 'index.html'), 'utf8');+ const editor = await ensureEditor(store.directory);+ const coldPage = await browser.newPage();+ try {+ await coldPage.setViewport({ width: 1440, height: 1000 });+ await coldPage.goto(new URL('/#project/' + a, editor.endpoint).href, { waitUntil: 'domcontentloaded' });+ await waitForFilm(coldPage, a, 'COLD BOOKMARK A');+ assert.equal(new URL(coldPage.url()).searchParams.get('project'), a);+ assert.equal(await readFile(path.join(store.projectDirectoryFor(b), 'index.html'), 'utf8'), sourceB);+ assert.equal((await store.forProject(b).get()).revision, before.revision);+ assert.equal(store.projectCatalog().activeId, b);+ await coldPage.screenshot({ path: path.join(out, 'cold-hash-bookmark.png') });+ check('cold hash-only bookmark opens A preview and timeline without touching B source, revision or remembered selection');+ } finally { await coldPage.close(); }+ });+ result.status = 'passed';+} catch (error) {+ result.error = error.stack; result.browserEvents = browserEvents; result.pages = [];+ for (const [i, page] of pages.entries()) {+ await page.screenshot({ path: path.join(out, `failure-${i}.png`) }).catch(() => {});+ result.pages.push(await page.evaluate(() => ({ url: location.href, visibility: document.visibilityState, text: document.body.innerText, timeline: document.querySelector('[data-timeline-element-count]')?.outerHTML, frames: [...document.querySelectorAll('iframe')].map(frame => frame.src) })).catch(() => null));+ }+ process.exitCode = 1; console.error(error);+}+finally {+ await browser?.close();+ await Promise.all(clients.map(client => client.close()));+ await closeFixtureEditor(data);+ await rm(data, { recursive: true, force: true });+ await writeFile(path.join(out, 'result.json'), JSON.stringify(result, null, 2));+}diff --git a/tests/multi-project.test.ts b/tests/multi-project.test.tsnew file mode 100644index 00000000..f48e3fe2--- /dev/null+++ b/tests/multi-project.test.ts@@ -0,0 +1,110 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { cp, readFile, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { startServer } from '../server.ts';+import { fixture } from './fixtures.ts';++test('one native service keeps both projects editable, scoped and recoverable after restart', { timeout: 120_000 }, () => fixture(async store => {+ const a = store.projectId, b = crypto.randomUUID();+ await cp(store.projectDirectory, store.projectDirectoryFor(b), { recursive: true });+ await store.selectProject(b, { id: b, title: 'Second' });+ await store.selectProject(a);+ let running = await startServer(store, 0);+ const base = () => `http://127.0.0.1:${(running.server.address() as { port: number }).port}`;+ const source = async (id: string) => {+ const response = await fetch(`${base()}/api/projects/${id}/files/index.html`);+ assert.equal(response.status, 200, await response.clone().text());+ return response.json();+ };+ const open = async (id: string) => {+ const current = await store.status();+ const response = await fetch(`${base()}/motion-api/projects/${id}/open`, { method: 'POST', headers: { Origin: base(), 'Content-Type': 'application/json' }, body: JSON.stringify({ expectedRevision: current.revision, expectedProjectId: current.projectId }) });+ assert.equal(response.status, 200, await response.clone().text());+ };+ try {+ const initialStudio = running.studio, initialIdentity = await (await fetch(new URL('/__hyperframes_config', initialStudio.url))).json();+ const fileA = await source(a);+ await open(b);+ assert.equal(running.studio.url, initialStudio.url, 'opening B must retain the same native service');+ assert.ok(initialStudio.alive(), 'opening B must not close A service');+ const identity = await (await fetch(new URL('/__hyperframes_config', running.studio.url))).json();+ assert.equal(identity.pid, initialIdentity.pid);+ assert.equal((await fetch(new URL('/api/events', initialStudio.url))).status, 400, 'unbound multi-project events cannot choose a recent project');+ assert.equal((await fetch(`${base()}/api/projects/${a}/files/index.html?projectId=${b}`)).status, 400, 'conflicting identities must be rejected');+ assert.equal((await fetch(new URL(`/api/projects/${a}/files/blocked.txt`, initialStudio.url), { method: 'PUT', headers: { Origin: 'http://foreign.example', 'If-None-Match': '*' }, body: 'blocked' })).status, 403);+ assert.equal((await source(a)).content, fileA.content);+ const files = await Promise.all([a, b].map(source));+ await Promise.all([a, b].map(async (id, i) => {+ const response = await fetch(`${base()}/api/projects/${id}/files/notes.txt`, { method: 'PUT', headers: { Origin: base(), 'If-None-Match': '*' }, body: `Owned by ${id}` });+ assert.equal(response.status, 200, await response.clone().text());+ const status = await (await fetch(`${base()}/motion-api/project/status?projectId=${id}`)).json();+ assert.equal(status.projectId, id, 'status must resolve the requested project');+ const preview = await fetch(`${base()}/api/projects/${id}/preview`);+ assert.equal(preview.status, 200, await preview.clone().text());+ assert.match(await preview.text(), /data-composition-id/);+ assert.equal(await readFile(path.join(store.projectDirectoryFor(id), 'notes.txt'), 'utf8'), `Owned by ${id}`);+ }));+ const writes = await Promise.all([0, 1].map(i => fetch(`${base()}/api/projects/${a}/files/index.html`, { method: 'PUT', headers: { Origin: base(), 'If-Match': files[0].version }, body: files[0].content.replace('<title>', `<title>Writer ${i} `) })));+ assert.deepEqual(writes.map(response => response.status).sort(), [200, 409], 'same-project stale writes remain protected');+ assert.equal((await source(b)).content, files[1].content, 'B source must remain untouched');+ for (const id of [a, b]) {+ const history = await fetch(`${base()}/api/projects/${id}/history`);+ assert.equal(history.status, 200, await history.clone().text());+ }+ for (const id of [crypto.randomUUID(), '..%2Fescape']) {+ assert.ok([400, 404].includes((await fetch(`${base()}/api/projects/${id}/files/index.html`)).status));+ assert.equal((await fetch(`${base()}/motion-api/project/status?projectId=${id}`)).status, 400);+ }+ await running.close();+ running = await startServer(store, 0);+ assert.match((await source(a)).content, /Writer [01]/);+ assert.equal((await source(b)).content, files[1].content);+ } finally { await running.close(); }+}));++test('file notification streams remain attached to their own project', { timeout: 45_000 }, () => fixture(async store => {+ const a = store.projectId, b = crypto.randomUUID();+ await cp(store.projectDirectory, store.projectDirectoryFor(b), { recursive: true });+ await store.selectProject(b, { id: b, title: 'B' });+ const running = await startServer(store, 0), origin = `http://127.0.0.1:${(running.server.address() as { port: number }).port}`;+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), 20_000);+ try {+ const pending = fetch(`${origin}/api/events?projectId=${a}`, { signal: controller.signal });+ // Native SSE sends headers with the first file event.+ const trigger = setInterval(() => { void writeFile(path.join(store.projectDirectoryFor(a), 'only-a.txt'), String(Date.now())); }, 250);+ try {+ const response = await pending; assert.equal(response.status, 200);+ const { value } = await response.body!.getReader().read();+ const event = new TextDecoder().decode(value);+ assert.match(event, new RegExp(`"projectId":"${a}"`));+ assert.doesNotMatch(event, new RegExp(`"projectId":"${b}"`));+ } finally { clearInterval(trigger); }+ } finally { clearTimeout(timer); controller.abort(); await running.close(); }+}));++test('a cold bookmark opens its named project without stamping another selected project', { timeout: 30_000 }, () => fixture(async store => {+ const a = store.projectId, b = crypto.randomUUID();+ await cp(store.projectDirectory, store.projectDirectoryFor(b), { recursive: true });+ await store.selectProject(b, { id: b, title: 'B' });+ const bFile = path.join(store.projectDirectoryFor(b), 'index.html');+ const beforeB = await readFile(bFile, 'utf8');+ const running = await startServer(store, 0, { editor: false });+ const origin = `http://127.0.0.1:${(running.server.address() as { port: number }).port}`;+ try {+ assert.equal((await fetch(`${origin}/?project=${crypto.randomUUID()}`)).status, 200);+ assert.equal(running.studio, undefined, 'an invalid bookmark must not open another project');+ assert.equal((await fetch(`${origin}/#project/${a}`)).status, 200);+ assert.equal(running.studio, undefined, 'a hash-only bookmark must wait for the client to bind its project');+ const opened = await fetch(`${origin}/motion-api/preview/open?projectId=${a}`, { method: 'POST', headers: { Origin: origin } });+ assert.equal(opened.status, 200, await opened.clone().text());+ const preview = await opened.json();+ assert.equal(preview.projectId, a);+ assert.equal(new URL(preview.studioUrl).hash, `#project/${a}`);+ assert.equal((await fetch(`${origin}/?project=${a}#project/${a}`)).status, 200);+ assert.equal(await readFile(bFile, 'utf8'), beforeB, 'opening A must not stamp B source');+ assert.equal((await fetch(`${origin}/api/projects/${a}/files/index.html`)).status, 200);+ assert.equal(store.projectCatalog().activeId, b, 'bookmark must not replace the remembered project');+ } finally { await running.close(); }+}));diff --git a/tests/package.test.ts b/tests/package.test.tsindex a5161b17..4c2d7730 100644--- a/tests/package.test.ts+++ b/tests/package.test.ts@@ -7,7 +7,7 @@ import { getWorkflow, workflowRegistry } from '../shared/workflow.ts';test('every distribution preserves public workflow dependencies and licenses while excluding development material', async () => {for (const profile of ['phase1', 'legacy']) {const files = new Set(await distributionFiles(profile));- for (const file of ['studio/build/index.html', 'studio/LICENSE', 'template-library/LICENSE', 'template-library/NOTICE.md', 'web/design-system/fonts/Albert-Sans-OFL.txt', 'scripts/distribution.ts', 'shared/editor-launch.pl', 'shared/workflow-entry.js', 'skills/motion-recreate/scripts/measure_frame.mjs']) assert(files.has(file), 'Missing runtime or license: ' + file);+ for (const file of ['studio/build/index.html', 'studio/LICENSE', 'template-library/LICENSE', 'template-library/NOTICE.md', 'web/design-system/fonts/Albert-Sans-OFL.txt', 'scripts/distribution.ts', 'shared/editor-launch.pl', 'shared/workspace-studio.ts', 'shared/owned-studio.mjs', 'shared/workflow-entry.js', 'skills/motion-recreate/scripts/measure_frame.mjs']) assert(files.has(file), 'Missing runtime or license: ' + file);assert(![...files].some(file => /^(?:tests\/|studio\/(?:src|tests)\/)|\.map$|publish-test-package|acceptance\.md$/.test(file)));for (const [workflow, definition] of Object.entries(workflowRegistry)) {for (const section of Object.keys(definition.sections)) {diff --git a/tests/phase1-shared.test.ts b/tests/phase1-shared.test.tsindex 9021f46d..16d686c0 100644--- a/tests/phase1-shared.test.ts+++ b/tests/phase1-shared.test.ts@@ -3,6 +3,46 @@ import assert from 'node:assert/strict';import { fixture } from './fixtures.ts';import { Client } from './shared-editor-client.mjs';import { editorRequest, readEditor, sharedEditorEnabled } from '../editor-runtime.ts';+import { stat } from 'node:fs/promises';+import path from 'node:path';++test('a stalled native project open times out and releases the other MCP client queue', { skip: !sharedEditorEnabled, timeout: 60_000 }, () => fixture(async store => {+ const clients = [new Client(store.directory), new Client(store.directory)];+ const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));+ let nativePid: number | undefined, paused = false;+ let opening: Promise<any> | undefined, listing: Promise<any> | undefined;+ try {+ await Promise.all(clients.map(client => client.initialize()));+ const projects = [];+ for (const [i, client] of clients.entries()) {+ const created = await client.call('motion_create_project', { requestId: 'timeout-' + i, projectType: 'natural_language', title: 'Project ' + i, requirements: 'Project ' + i });+ projects.push(await client.call('motion_open_preview', { projectId: created.projectId }));+ }+ const origin = new URL(projects[0].previewUrl).origin;+ nativePid = (await (await fetch(origin + '/__hyperframes_config')).json()).pid;+ process.kill(nativePid!, 'SIGSTOP'); paused = true;+ assert.ok((await clients[1].call('motion_get_project')).projects.some((project: any) => project.id === projects[1].projectId), 'listing must work without the paused native service');+ const started = Date.now();+ opening = clients[0].call('motion_open_preview', { projectId: projects[0].projectId }).then(value => ({ value }), error => ({ error }));+ const deadline = Date.now() + 10_000;+ while (!await stat(path.join(store.directory, 'workspace.lock')).catch(() => null)) {+ assert.ok(Date.now() < deadline, 'opening must enter the workspace lock');+ await pause(20);+ }+ listing = clients[1].call('motion_get_project');+ const opened = await Promise.race([opening, pause(35_000).then(() => { throw new Error('Native project open exceeded its deadline'); })]);+ assert.match(String(opened.error), /timeout|timed out/i);+ const listed = await Promise.race([listing, pause(2000).then(() => { throw new Error('Other MCP client remains blocked after opening timeout'); })]);+ assert.ok(listed.projects.some((project: any) => project.id === projects[1].projectId));+ console.log(JSON.stringify({ scenario: 'native-opening-timeout', elapsedMs: Date.now() - started, otherClientListedWhileNativePaused: true }));+ process.kill(nativePid!, 'SIGCONT'); paused = false;+ assert.equal((await clients[0].call('motion_open_preview', { projectId: projects[0].projectId })).projectId, projects[0].projectId, 'opening can be retried after native recovery');+ } finally {+ if (paused) process.kill(nativePid!, 'SIGCONT');+ await Promise.allSettled([opening, listing]);+ await Promise.all(clients.map(client => client.close()));+ }+}, false));test('real phase1 MCP clients share one editor while retaining explicit projects and conflict protection', { skip: !sharedEditorEnabled, timeout: 90_000 }, () => fixture(async store => {const clients = Array.from({ length: 3 }, () => new Client(store.directory));diff --git a/tests/projects.test.ts b/tests/projects.test.tsindex 9d740f03..f863c304 100644--- a/tests/projects.test.ts+++ b/tests/projects.test.ts@@ -54,10 +54,10 @@ test('project sessions create blank editable projects, isolate uploads and restoassert.equal(catalog.projects.length, 3);assert.equal(catalog.activeId, second.projectId);assert.ok(catalog.projects.every(item => item.id === 'project' || item.openedAt));- // An old tab's native endpoints may not resolve to the newly active native directory.+ // An older page still resolves its own directory; writes still require its file version.for (const method of ['GET', 'PUT']) {const stale = await fetch(`${baseUrl()}/api/projects/${first.projectId}/files/index.html`, { method, headers: { Origin: baseUrl(), 'Content-Type': 'text/html' }, ...(method === 'PUT' ? { body: firstSource } : {}) });- assert.equal(stale.status, 409);+ assert.equal(stale.status, method === 'GET' ? 200 : 428);}assert.equal((await mutate('/motion-api/projects', { expectedRevision: initial.revision })).status, 409);assert.equal((await mutate('/motion-api/projects', { expectedRevision: (await store.get()).revision, expectedProjectId: first.projectId })).status, 409);diff --git a/tests/sessions.test.ts b/tests/sessions.test.tsindex de3e8f82..3bd4552f 100644--- a/tests/sessions.test.ts+++ b/tests/sessions.test.ts@@ -6,6 +6,7 @@ import { fixture } from './fixtures.ts';import { startServer } from '../server.ts';import { WorkspaceStore } from '../workspace.ts';import { callTool } from '../mcp.ts';+import { catalogUrl, contents, mockPrism } from './prism-fixture.ts';test('legacy projects and conversation files become sessions without changing project sources', () => fixture(async store => {const before = (await store.get()).revision;@@ -33,7 +34,9 @@ test('legacy projects and conversation files become sessions without changing prawait assert.rejects(callTool('design_open_artifact', { sessionId: 'project', artifactId: 'foreign', expectedRevision: before }, store), /不属于/);}));-test('Motion sessions own multiple independent artifacts and restore the last selected artifact', { timeout: 180_000 }, () => fixture(async store => {+test('Motion sessions own multiple independent artifacts and restore the last selected artifact', { timeout: 180_000 }, t => fixture(async store => {+ const originalFetch = globalThis.fetch, prism = mockPrism();+ t.mock.method(globalThis, 'fetch', (input, init) => String(input) === catalogUrl || String(input).startsWith('https://r.open-design.ai/files/') ? prism.request(input, init) : originalFetch(input, init));const running = await startServer(store, 0);const origin = `http://127.0.0.1:${(running.server.address() as { port: number }).port}`;await writeFile(path.join(store.directory, 'preview.json'), JSON.stringify({ port: (running.server.address() as { port: number }).port }));@@ -86,7 +89,7 @@ test('Motion sessions own multiple independent artifacts and restore the last seassert.equal((await restarted.session(session.id)).title, '广告会话');assert.equal((await restarted.session(session.id)).artifacts.length, 2);const stale = await fetch(`${origin}/api/projects/${first.projectId}/files/index.html`);- assert.equal(stale.status, 409);+ assert.equal(stale.status, 200);const viewer = await callTool('design_open_artifact', { sessionId: session.id, artifactId: withArtifacts.artifacts[0].id, expectedRevision: (await store.get()).revision }, store) as any;assert.equal(viewer.projectId, first.projectId);assert.equal(new URL(viewer.previewUrl).searchParams.get('embed'), '1');@@ -123,11 +126,12 @@ test('Motion sessions own multiple independent artifacts and restore the last seassert.equal(retried.sessionId, generatedByMcp.session.id);assert.equal(retried.projectId, generatedByMcp.projectId);assert.equal(store.projectCatalog().projects.length, count, 'retrying creation cannot duplicate artifacts');- const reference = await callTool('design_create_session', { mode: 'motion', templateId: 'hf-moment-M953' }, store) as any;- assert.equal(reference.session.artifacts[0].templateId, 'hf-moment-M953');- assert.equal(reference.session.templateId, 'hf-moment-M953');- assert.equal(new URL(reference.previewUrl).searchParams.get('embed'), '1');- assert.doesNotMatch((await store.get()).project!.html!, /class="clip"/, 'external reference starts as an editable blank, not an unrelated sample');+ const published = await callTool('design_create_session', { mode: 'motion', templateId: 'test-motion-1' }, store) as any;+ assert.equal(published.session.artifacts[0].templateId, 'test-motion-1');+ assert.equal(published.session.templateId, 'test-motion-1');+ assert.equal(new URL(published.previewUrl).searchParams.get('embed'), '1');+ assert.match((await store.get()).project!.html!, /Prism template/, 'published templates retain their source instead of starting as a blank project');+ assert.equal(await readFile(path.join(store.projectDirectory, 'animation.js'), 'utf8'), contents['animation.js']);const templated = await callTool('motion_apply_template', { expectedRevision: (await store.get()).revision, templateId: 'decision-tree' }, store) as any;assert.equal(new URL(templated.previewUrl).searchParams.get('embed'), '1');assert.equal(new URL(templated.sessionUrl).searchParams.has('embed'), false);diff --git a/tests/shared-editor-crash.mjs b/tests/shared-editor-crash.mjsindex 612b8a09..278d4e9e 100644--- a/tests/shared-editor-crash.mjs+++ b/tests/shared-editor-crash.mjs@@ -28,7 +28,7 @@ assert.ok(processes().some(p => p.pid === process.pid && p.command.includes(pathfunction role(p) {if (/owned-studio\.mjs --owner /.test(p.command)) return 'studio-owner';- if (/hyperframes\.mjs preview /.test(p.command)) return 'studio';+ if (/hyperframes\.mjs preview |shared\/workspace-studio\.ts /.test(p.command)) return 'studio';if (/hyperframes\.mjs render /.test(p.command)) return 'renderer';if (/Google Chrome|chrome-headless|chromium|chrome_crashpad/.test(p.command)) return 'chrome';if (/(?:^|\/)ffmpeg(?:\s|$)/.test(p.command)) return 'ffmpeg';diff --git a/tests/shared-editor-media.mjs b/tests/shared-editor-media.mjsindex 7322ecbf..c1ecf3a3 100644--- a/tests/shared-editor-media.mjs+++ b/tests/shared-editor-media.mjs@@ -33,14 +33,14 @@ try {checked('two MCP clients reuse the same real Hyperframes Studio', { previewUrl: previews[0].previewUrl, projectId: project.projectId, instanceId: identities[0].instanceId, daemonPid: identities[0].pid, engineVersion: nativeIdentity.version });const processes = () => execFileSync('ps', ['-ww', '-axo', 'pid=,command='], { encoding: 'utf8' }).split('\n').map(line => line.match(/^\s*(\d+)\s+(.*)$/)).filter(Boolean).map(m => ({ pid: Number(m[1]), command: m[2] }));- const oldStudio = processes().find(p => p.command.includes('hyperframes.mjs preview ' + edited.project.directory));+ const oldStudio = processes().find(p => p.command.includes('shared/workspace-studio.ts ') && p.command.includes(root));const oldOwner = processes().find(p => p.command.includes('owned-studio.mjs --owner ' + root) && p.command.includes(edited.project.directory));assert.ok(oldStudio && oldOwner);process.kill(oldStudio.pid, 'SIGTERM');for (let attempt = 0; attempt < 60 && processes().some(p => p.pid === oldOwner.pid); attempt++) await pause(50);assert.ok(!processes().some(p => p.pid === oldOwner.pid), 'Owner must notice Studio exit');const reopened = await clients[0].call('motion_open_preview', { projectId: project.projectId });- const newStudio = processes().find(p => p.command.includes('hyperframes.mjs preview ' + edited.project.directory));+ const newStudio = processes().find(p => p.command.includes('shared/workspace-studio.ts ') && p.command.includes(root));assert.ok(newStudio); assert.notEqual(newStudio.pid, oldStudio.pid);assert.equal((await clients[1].call('motion_open_preview', { projectId: project.projectId })).previewUrl, reopened.previewUrl);const reopenedIdentity = await (await fetch(new URL('/__hyperframes_config', reopened.previewUrl))).json();@@ -52,7 +52,10 @@ try {await cp(catalogStore.projectDirectory, catalogStore.projectDirectoryFor(otherId), { recursive: true });await catalogStore.lock(async () => { await catalogStore.selectProject(otherId, { id: otherId, title: 'Other project' }); await catalogStore.selectProject(project.projectId); });await clients[1].call('motion_open_preview', { projectId: otherId });- assert.equal((await (await fetch(new URL('/__hyperframes_config', reopened.previewUrl))).json()).projectDir, catalogStore.projectDirectoryFor(otherId));+ const otherIdentity = await (await fetch(new URL('/__hyperframes_config?projectId=' + otherId, reopened.previewUrl))).json();+ assert.equal(otherIdentity.projectDir, catalogStore.projectDirectoryFor(otherId));+ assert.equal(otherIdentity.pid, reopenedIdentity.pid, 'both projects must use the same native process');+ assert.equal((await fetch(new URL('/api/projects/' + project.projectId + '/files/index.html', reopened.previewUrl))).status, 200);await clients[0].call('motion_open_preview');assert.equal((await (await fetch(new URL('/__hyperframes_config', reopened.previewUrl))).json()).projectDir, edited.project.directory);assert.equal((await clients[1].call('motion_get_project')).projectId, otherId);diff --git a/tests/templates.test.ts b/tests/templates.test.tsindex 55ba9ec7..fbf54164 100644--- a/tests/templates.test.ts+++ b/tests/templates.test.ts@@ -30,13 +30,14 @@ test('official templates open in native Studio, preserve edits and switch the prconst response = await post(`/api/templates/${template.id}/open`, before.revision);assert.equal(response.status, 200, await response.clone().text());const openedProject = await response.json();- assert.notEqual(openedProject.projectId, 'project'); assert.equal(previousStudio.alive(), false);+ assert.notEqual(openedProject.projectId, 'project'); assert.equal(previousStudio.alive(), true);+ assert.equal(running.studio.url, previousStudio.url);const agent = await callTool('motion_get_project', {}, new WorkspaceStore(store.directory));assert.equal(agent.project!.directory, store.projectDirectory); assert.match(agent.project!.html!, new RegExp(template.title));assert.equal(agent.project!.files.some(file => file.path === 'assets/gsap.min.js'), true);const lint = await inspectProject(pluginRoot, store.projectDirectory, 'lint'); assert.equal(lint.exitCode, 0, JSON.stringify(lint.result));const nativeBase = new URL(openedProject.studioUrl).origin;- const identity = await (await fetch(nativeBase + '/__hyperframes_config')).json(); assert.equal(identity.projectDir, store.projectDirectory);+ const identity = await (await fetch(nativeBase + '/__hyperframes_config?projectId=' + openedProject.projectId)).json(); assert.equal(identity.projectDir, store.projectDirectory);const fileUrl = `${nativeBase}/api/projects/${openedProject.projectId}/files/index.html`;const file = await (await fetch(fileUrl)).json();assert.equal(typeof file.content, 'string');diff --git a/tests/workspace-studio.test.ts b/tests/workspace-studio.test.tsnew file mode 100644index 00000000..6591b1bc--- /dev/null+++ b/tests/workspace-studio.test.ts@@ -0,0 +1,24 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { startWorkspaceStudio } from '../shared/workspace-studio.ts';++test('workspace host refuses unsupported, missing, ambiguous and incompatible native factories before serving', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'motion-host-contract-'));+ const cli = path.join(root, 'node_modules/hyperframes');+ const manifest = path.join(cli, 'package.json');+ try {+ await mkdir(path.join(cli, 'dist'), { recursive: true });+ const writeVersion = version => writeFile(manifest, JSON.stringify({ name: 'hyperframes', type: 'module', version }));+ await writeVersion('0.9.8');+ await assert.rejects(startWorkspaceStudio(root, root, root, 0), /Unsupported/);+ await writeVersion('0.9.7');+ await assert.rejects(startWorkspaceStudio(root, root, root, 0), /missing or ambiguous/);+ await writeFile(path.join(cli, 'dist/studioServer-first.js'), 'export const other = true;');+ await assert.rejects(startWorkspaceStudio(root, root, root, 0), /factory is unavailable/);+ await writeFile(path.join(cli, 'dist/studioServer-second.js'), 'export const other = true;');+ await assert.rejects(startWorkspaceStudio(root, root, root, 0), /missing or ambiguous/);+ } finally { await rm(root, { recursive: true, force: true }); }+});