Skip to content

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

fix: return OpenMotion URLs from editor handoffs (#301)

open-design-crew[bot]b5fe813ac82b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d03bbbd3..a131afa2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -138,7 +138,7 @@ jobs:
npm run build:tracking
node --experimental-strip-types --test tests/tracking.test.ts
- name: Validate standalone installation and packaging
- run: node --experimental-strip-types --test tests/install.test.ts tests/npm-installer.test.ts tests/native-runtime.test.ts tests/npm-package.test.ts tests/test-package.test.ts tests/source-install.test.ts tests/bootstrap.test.ts tests/mcp-registry.test.ts tests/mcp-runtime.test.ts tests/mcp-upgrade.test.ts tests/preview.test.ts tests/workspace-studio.test.ts tests/sync.test.ts tests/phase1.test.ts tests/preview-handoff.test.ts tests/adapters.test.ts tests/package.test.ts tests/recreate-measure.test.ts tests/workflow.test.ts tests/catalog.test.ts tests/prism-templates.test.ts tests/extension-boundary.test.ts tests/connections.test.ts tests/install-guide.test.ts tests/readme-resources.test.ts tests/motion-design-remix.test.ts
+ run: node --experimental-strip-types --test tests/install.test.ts tests/npm-installer.test.ts tests/native-runtime.test.ts tests/npm-package.test.ts tests/test-package.test.ts tests/source-install.test.ts tests/bootstrap.test.ts tests/mcp-registry.test.ts tests/mcp-runtime.test.ts tests/mcp-upgrade.test.ts tests/preview.test.ts tests/editor-urls.test.ts tests/workspace-studio.test.ts tests/sync.test.ts tests/phase1.test.ts tests/preview-handoff.test.ts tests/adapters.test.ts tests/package.test.ts tests/recreate-measure.test.ts tests/workflow.test.ts tests/catalog.test.ts tests/prism-templates.test.ts tests/extension-boundary.test.ts tests/connections.test.ts tests/install-guide.test.ts tests/readme-resources.test.ts tests/motion-design-remix.test.ts
- name: Studio regression
run: npm run test:studio -- --maxWorkers=2
- name: Build phase-one ZIP and exercise all public tools
diff --git a/docs/hyperframes.md b/docs/hyperframes.md
index 6dde3ca1..1f45261d 100644
--- a/docs/hyperframes.md
+++ b/docs/hyperframes.md
@@ -24,6 +24,8 @@ Studio 前端从上游 0.9.7 的固定 commit 迁入 `studio/src/` 并在本仓
工具所需的后台服务与编辑器启动分离:`ensureService` 以后台模式启动服务和渲染队列,不运行 `store.initialize` 或启动当前工程的 Studio。一期使用 `motion_create_project(projectType=template)` 创建选中模板工程;`motion_export_request` 携带明确 projectId、versionId、expectedRevision 和 requestId 固定快照,不启动 Studio。`motion_open_preview` 会通过同源的 `/motion-api/preview/open` 在同一个服务中启动编辑器。健康响应中 `ready` 表示服务可用,`editorReady` / `studioUrl` 表示编辑器已就绪;导出下载无需编辑器。正常直接启动开发服务器仍打开编辑器。
+Editor URL contract: application launch output, preview responses and project/template/session handoffs use the OpenMotion origin for `previewUrl` and `studioUrl`; project-specific URLs retain the requested project ID. An unstarted editor has no `studioUrl`. `/api/health` exposes the internal engine address only as `nativeStudioUrl` for diagnostics. The private Hyperframes child-process readiness protocol retains its upstream `studioUrl` field, which is consumed internally and must not become an application handoff. Preview discovery rebuilds application links from the verified OpenMotion endpoint even when a compatible older backend reports its native address as `studioUrl`. Existing running backends retain their installed HTTP behavior until they are separately updated and replaced while idle.
+
这消除了服务自己初始化/补写 `data-hf-id` 造成的陈旧版本冲突,没有规范化或忽略 revision,也不自动重试为最新 revision。快照、切换工程和源文件写入原有的外部并发保护保留。
写入链是 Agent 原生源文件 → 同一工程目录 → Studio 文件监听;人工编辑反向落在同一目录。旧 `shots[]` 仅保留在迁移读取代码中。内容 revision 覆盖源文件、媒体与上游的两份 Studio manifest,排除预览/缩略图缓存。进程间锁约束插件工具,不能把外部编辑器视为同一事务;版本拒绝可以保护读写间已经发生的改动,不能承诺与正在写盘的 Studio 完全串行。
diff --git a/docs/product/architecture.md b/docs/product/architecture.md
index 0df55f92..c2d231e5 100644
--- a/docs/product/architecture.md
+++ b/docs/product/architecture.md
@@ -249,6 +249,7 @@ The font picker offers detected local fonts, imported project fonts and fonts de
- **导出输入:** 后台任务使用不可变快照并记录期望规格;后续编辑不改变该任务的本地输入。远程媒体需要稳定复现时先导入本地。
- **后台与编辑器启动:** 仅导出启动后台服务,不初始化或补写当前工程;冷启动套模板直接创建选中的模板工程。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)。
+- **Editor URLs:** OpenMotion and its native engine listen on separate loopback endpoints. Application launchers, preview and project/template/session responses hand off the OpenMotion origin through `previewUrl` and `studioUrl`; project links retain their explicit identity. The native address is diagnostic `nativeStudioUrl` in health responses, while upstream child-process readiness fields remain internal. Preview clients reconstruct application links from verified discovery even when reusing an older compatible backend; this does not hot-reload that backend's HTTP handlers or frontend. See the [engine boundary](../hyperframes.md).
- **模型与凭据:** 配置和任务独立于工程,Key 不通过 API 返回。安装、配置、允许请求、生成成功是不同状态;任务固定发起工程,失败不静默重试。完成后的素材参与工程 revision 与导出快照。
- **并发边界:** macOS 同目录多个 MCP 连接共用后台,各自绑定工程;工作区使用一个原生 Studio 服务进程,按需保留多个工程的原生上下文;后台仍只有一个等待/运行的导出。导出固定工程与快照,重启将中断任务持久化为失败且不重放。文件锁和 revision 保护工具写入;人工与 Agent 同时编辑同一文件仍需协调,不能当作跨工具数据库事务。
- **数据归属:** 产品文档描述数据类别与流程,不复制用户的私有工程、访问凭据或个人机器配置。
diff --git a/preview.ts b/preview.ts
index d85adb43..a7bea6c3 100644
--- a/preview.ts
+++ b/preview.ts
@@ -99,7 +99,9 @@ export async function openPreview(store = new WorkspaceStore(), environment: Pre
const file = path.join(store.directory, 'preview.json'), temporary = file + '.' + crypto.randomUUID() + '.tmp';
try { await writeFile(temporary, JSON.stringify({ port: Number(new URL(editor.endpoint).port), pid: editor.pid, version: editor.version }), { mode: 0o600 }); await rename(temporary, file); }
finally { await rm(temporary, { force: true }); }
- return { ...opened, revision: (await store.get()).revision, reused: before?.instanceId === editor.instanceId,
+ return { ...opened, previewUrl: new URL(editor.endpoint).origin,
+ studioUrl: opened.editorReady ? new URL(`/#project/${store.projectId}`, editor.endpoint).href : undefined,
+ revision: (await store.get()).revision, reused: before?.instanceId === editor.instanceId,
previewTarget: 'host-built-in-browser', nextAction: 'Open the exact previewUrl in the host built-in browser when available; otherwise return the URL and mark visual/player checks as not_run. Do not start another editor or ask the user to run a terminal server.' };
}
await mkdir(store.directory, { recursive: true });
@@ -131,7 +133,7 @@ export async function openPreview(store = new WorkspaceStore(), environment: Pre
const file = path.join(store.directory, 'preview.json'); const temporary = file + '.' + crypto.randomUUID() + '.tmp';
try { await writeFile(temporary, JSON.stringify({ port, pid, version: health.version }), { mode: 0o600 }); await rename(temporary, file); }
finally { await rm(temporary, { force: true }); }
- return { previewUrl: `http://localhost:${port}`, studioUrl: health.studioUrl, hyperframesCli: health.hyperframesCli, authoringGuide: health.authoringGuide, engine: 'hyperframes', ready: true, reused, ffmpeg: health.ffmpeg, revision: (await store.get()).revision,
+ return { previewUrl: `http://localhost:${port}`, studioUrl: health.studioUrl ? `http://localhost:${port}/#project/${store.projectId}` : undefined, hyperframesCli: health.hyperframesCli, authoringGuide: health.authoringGuide, engine: 'hyperframes', ready: true, reused, ffmpeg: health.ffmpeg, revision: (await store.get()).revision,
dataDirectory: store.directory, editorReady: Boolean(health.studioUrl), browserOpened: false, previewTarget: 'host-built-in-browser',
nextAction: options.editor ? 'Use the host built-in browser to open previewUrl in this conversation. Do not ask the user to run a server or launch an external browser. If the host has no built-in browser, return the URL and state that the embedded preview is unavailable.' : 'Background service ready. Opening the editor is not required for template application or export.' };
}
diff --git a/server.ts b/server.ts
index 44e6a736..564b9e3f 100644
--- a/server.ts
+++ b/server.ts
@@ -132,7 +132,7 @@ function revision(value: unknown): asserts value is string {
if (typeof value !== 'string' || !/^[a-f0-9]{64}$/.test(value)) throw new Error('需要 motion_get_project 返回的 expectedRevision');
}
-async function openProject(store: WorkspaceStore, context: Service, expectedRevision: string, target: { templateId: string } | { projectId: string } | { title: string; instruction?: string }, expectedProjectId?: string, sessionTarget?: { sessionId?: string; title?: string; templateId?: string; instruction?: string }) {
+async function openProject(store: WorkspaceStore, context: Service, origin: string, expectedRevision: string, target: { templateId: string } | { projectId: string } | { title: string; instruction?: string }, expectedProjectId?: string, sessionTarget?: { sessionId?: string; title?: string; templateId?: string; instruction?: string }) {
if (!context.runtimeRoot) throw new Error('Hyperframes 服务尚未就绪');
if (context.switching) throw new Error('正在打开工程,请稍候');
context.switching = true;
@@ -151,7 +151,7 @@ async function openProject(store: WorkspaceStore, context: Service, expectedRevi
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 };
+ return { ...(await store.status()), studioUrl: `${origin}/#project/${id}` };
}
const directory = store.projectDirectoryFor(id);
let candidate: Studio | undefined;
@@ -170,7 +170,7 @@ async function openProject(store: WorkspaceStore, context: Service, expectedRevi
context.studio = candidate; committed = true;
await candidate.openProject?.(id);
if (oldStudio !== candidate) await oldStudio?.close();
- return { ...(await store.status()), studioUrl: candidate.url };
+ return { ...(await store.status()), studioUrl: `${origin}/#project/${id}` };
} finally {
if (!committed) {
if (candidate !== context.studio) await candidate?.close();
@@ -204,23 +204,23 @@ async function createSession(store: WorkspaceStore, data: Record<string, any>) {
}
// The HTTP, MCP and embedded clients share this mode factory; viewers do not create sessions.
-const artifactFactories: Record<CreationMode, (store: WorkspaceStore, context: Service, session: CreativeSession, data: Record<string, any>) => Promise<unknown>> = {
- motion: async (store, context, session, data) => {
+const artifactFactories: Record<CreationMode, (store: WorkspaceStore, context: Service, origin: string, session: CreativeSession, data: Record<string, any>) => Promise<unknown>> = {
+ motion: async (store, context, origin, session, data) => {
const templateId = data.templateId ?? (session.artifacts.length === 0 ? session.templateId : undefined);
const template = templateId ? await templateCatalogFor(store.directory).get(templateId) : undefined;
const title = validateProjectTitle(data.title ?? (session.artifacts.length ? `Motion ${session.artifacts.length + 1}` : session.title));
- return openProject(store, context, data.expectedRevision, template && isEditableTemplate(template) ? { templateId: template.id } : { title }, data.expectedProjectId, { sessionId: session.id, templateId: template?.id });
+ return openProject(store, context, origin, data.expectedRevision, template && isEditableTemplate(template) ? { templateId: template.id } : { title }, data.expectedProjectId, { sessionId: session.id, templateId: template?.id });
},
};
-async function createArtifact(store: WorkspaceStore, context: Service, session: CreativeSession, data: Record<string, any>) {
+async function createArtifact(store: WorkspaceStore, context: Service, origin: string, session: CreativeSession, data: Record<string, any>) {
revision(data.expectedRevision);
- return artifactFactories[creationMode(session.mode).id](store, context, session, data);
+ return artifactFactories[creationMode(session.mode).id](store, context, origin, session, data);
}
-async function legacyCreation(store: WorkspaceStore, context: Service, data: Record<string, any>) {
+async function legacyCreation(store: WorkspaceStore, context: Service, origin: string, data: Record<string, any>) {
revision(data.expectedRevision);
if ((await store.get()).revision !== data.expectedRevision || (data.expectedProjectId && store.projectCatalog().activeId !== data.expectedProjectId)) throw new Conflict();
const session = await createSession(store, data);
- return createArtifact(store, context, session, data);
+ return createArtifact(store, context, origin, session, data);
}
export async function handler(req: IncomingMessage, res: ServerResponse, store = sharedStore, context = service) {
@@ -290,7 +290,7 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store =
context.phase1 ??= new Phase1Service(authority, context.runtimeRoot, {
origin: () => new URL(editorUrl).origin,
nativeUrl: () => context.studio?.alive() ? context.studio.url : undefined,
- openProject: async projectId => { await openProject(authority, context, (await authority.get()).revision, { projectId }, authority.projectId); },
+ openProject: async projectId => { await openProject(authority, context, new URL(editorUrl).origin, (await authority.get()).revision, { projectId }, authority.projectId); },
mutation: async task => {
let release!: () => void;
context.phase1Mutation = new Promise<void>(resolve => { release = resolve; });
@@ -418,16 +418,16 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store =
if (!session.artifacts.length && !data.projectId) return json(res, 200, await store.selectSession(id));
const artifact = data.projectId ? session.artifacts.find(item => item.projectId === data.projectId) : session.artifacts.find(item => item.id === session.activeArtifactId) ?? session.artifacts[0];
if (!artifact) throw new Error('该产物不属于此会话');
- return json(res, 200, await openProject(store, context, data.expectedRevision, { projectId: artifact.projectId }, data.expectedProjectId));
+ return json(res, 200, await openProject(store, context, new URL(editorUrl).origin, data.expectedRevision, { projectId: artifact.projectId }, data.expectedProjectId));
}
- return json(res, 201, await createArtifact(store, context, session, data));
+ return json(res, 201, await createArtifact(store, context, new URL(editorUrl).origin, session, data));
}
}
if (motionRequest && url.pathname === '/api/projects' && req.method === 'POST') {
const data = await input(req); revision(data.expectedRevision);
const title = validateProjectTitle(data.title ?? `未命名项目 ${store.projectCatalog().projects.length + 1}`);
const instruction = data.instruction === undefined ? undefined : validateInstruction(data.instruction);
- return json(res, 201, await legacyCreation(store, context, { ...data, title, instruction }));
+ return json(res, 201, await legacyCreation(store, context, new URL(editorUrl).origin, { ...data, title, instruction }));
}
const conversation = motionRequest ? url.pathname.match(/^\/api\/projects\/([a-z0-9-]+)\/conversation$/) : null;
if (conversation && req.method === 'GET') return json(res, 200, await store.conversation(conversation[1]));
@@ -450,7 +450,7 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store =
const openSaved = motionRequest ? url.pathname.match(/^\/api\/projects\/([a-z0-9-]+)\/open$/) : null;
if ((openTemplate || openSaved) && req.method === 'POST') {
const data = await input(req); revision(data.expectedRevision);
- return json(res, 200, openTemplate ? await legacyCreation(store, context, { ...data, templateId: openTemplate[1] }) : await openProject(store, context, data.expectedRevision, { projectId: openSaved![1] }, data.expectedProjectId));
+ return json(res, 200, openTemplate ? await legacyCreation(store, context, new URL(editorUrl).origin, { ...data, templateId: openTemplate[1] }) : await openProject(store, context, new URL(editorUrl).origin, data.expectedRevision, { projectId: openSaved![1] }, data.expectedProjectId));
}
if (url.pathname === '/api/project/status' && req.method === 'GET') return json(res, 200, {
...await store.status(), historyRestoreError: context.phase1?.restoreErrors.get(store.projectId) ?? null,
@@ -533,14 +533,15 @@ export async function startServer(store = sharedStore, port = Number(process.env
try {
await new Promise<void>((resolve, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolve); });
} catch (error) { context.tracking?.close(); await context.studio?.close(); throw error; }
+ const origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
const gateway = gatewayFor(store);
const tick = () => {
void renderNext(store, runtimeRoot, context.tracking).catch(error => console.error(error.message));
void gateway.tick().catch(() => console.error('Model gateway queue could not be processed'));
};
const timer = setInterval(tick, 500); tick();
- return { server, get activeToolCalls() { return context.phase1?.pending ?? 0; }, openProject: async (projectId: string) => openProject(store, context, (await store.get()).revision, { projectId }, store.projectId), get studio() { return context.studio!; }, ensureStudio: context.ensureStudio,
- info: async () => ({ previewUrl: `http://127.0.0.1:${(server.address() as any).port}`, studioUrl: context.studio?.url, engine: 'hyperframes', ready: true, editorReady: Boolean(context.studio?.alive()), ffmpeg, revision: (await store.get()).revision, dataDirectory: store.directory, browserOpened: false, nativeRuntime: await nativeRuntimeStatus(pluginRoot), authoringGuide: path.join(runtimeRoot, 'node_modules/hyperframes/dist/skills/hyperframes/SKILL.md'), hyperframesCli: cliPath(runtimeRoot) }),
+ return { server, get activeToolCalls() { return context.phase1?.pending ?? 0; }, openProject: async (projectId: string) => openProject(store, context, origin, (await store.get()).revision, { projectId }, store.projectId), get studio() { return context.studio!; }, ensureStudio: context.ensureStudio,
+ info: async () => ({ previewUrl: origin, studioUrl: context.studio?.alive() ? `${origin}/#project/${store.projectId}` : undefined, engine: 'hyperframes', ready: true, editorReady: Boolean(context.studio?.alive()), ffmpeg, revision: (await store.get()).revision, dataDirectory: store.directory, browserOpened: false, nativeRuntime: await nativeRuntimeStatus(pluginRoot), authoringGuide: path.join(runtimeRoot, 'node_modules/hyperframes/dist/skills/hyperframes/SKILL.md'), hyperframesCli: cliPath(runtimeRoot) }),
close: async () => { clearInterval(timer); await context.browser?.close(); await gateway.close(); server.closeAllConnections(); server.close(); await context.studio?.close(); await closeTracking(context.tracking); } };
}
if (isMain(import.meta.url)) {
diff --git a/tests/editor-urls.test.ts b/tests/editor-urls.test.ts
new file mode 100644
index 00000000..8ccc5f30
--- /dev/null
+++ b/tests/editor-urls.test.ts
@@ -0,0 +1,73 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import path from 'node:path';
+import { startServer } from '../server.ts';
+import { pluginRoot } from '../hyperframes.ts';
+import { sharedEditorEnabled } from '../editor-runtime.ts';
+import { fixture } from './fixtures.ts';
+import { Client } from './shared-editor-client.mjs';
+
+test('HTTP project, template and session handoffs return the OpenMotion editor origin', { timeout: 30_000 }, () => fixture(async store => {
+ const running = await startServer(store, 0, { editor: false });
+ const origin = `http://127.0.0.1:${(running.server.address() as { port: number }).port}`;
+ const editor = async (value: { studioUrl?: string; projectId?: string }) => {
+ assert.ok(value.studioUrl);
+ const url = new URL(value.studioUrl);
+ assert.equal(url.origin, origin);
+ if (value.projectId) assert.equal(url.hash, `#project/${value.projectId}`);
+ assert.match(await (await fetch(url)).text(), /data-motion-studio/);
+ };
+ const post = async (route: string, data: Record<string, unknown> = {}) => {
+ const current = await store.status();
+ const response = await fetch(origin + route, { method: 'POST', headers: { Origin: origin, 'Content-Type': 'application/json' },
+ body: JSON.stringify({ expectedRevision: current.revision, expectedProjectId: current.projectId, ...data }) });
+ assert.ok(response.ok, await response.clone().text());
+ return response.json();
+ };
+ try {
+ assert.equal((await running.info()).studioUrl, undefined);
+ await editor(await post('/motion-api/preview/open'));
+ await editor(await running.info());
+ const health = await (await fetch(origin + '/api/health')).json();
+ await editor(health);
+ assert.equal(health.nativeStudioUrl, running.studio.url);
+ assert.notEqual(new URL(health.nativeStudioUrl).origin, origin);
+ await editor({ studioUrl: (await (await fetch(origin + '/api/studio')).json()).url });
+ await editor(await post('/motion-api/projects/project/open'));
+ await editor(await post('/motion-api/projects', { title: 'Another project' }));
+ await editor(await post('/motion-api/projects/project/open'));
+ const session = await post('/motion-api/sessions', { title: 'Another session' });
+ await editor(await post(`/motion-api/sessions/${session.sessionId}/artifacts`));
+ await editor(await post(`/motion-api/sessions/${session.sessionId}/open`));
+ await editor(await post('/api/templates/product-promo/open'));
+ } finally { await running.close(); }
+}));
+
+test('macOS source launchers and both MCP profiles hand off OpenMotion URLs', { skip: !sharedEditorEnabled, timeout: 60_000 }, () => fixture(async store => {
+ const clients = [new Client(store.directory), new Client(store.directory, { legacy: true })];
+ try {
+ await Promise.all(clients.map(client => client.initialize()));
+ const created = await clients[0].call('motion_create_project', { requestId: 'editor-urls', projectType: 'natural_language',
+ title: 'Editor URLs', requirements: 'Verify editor URL handoffs without generating media or exporting.' });
+ const opened = await clients[0].call('motion_open_preview', { projectId: created.projectId });
+ const origin = new URL(opened.previewUrl).origin;
+ const assertUrls = (value: Record<string, any>) => {
+ for (const field of ['previewUrl', 'studioUrl', 'sessionUrl', 'embeddedPreviewUrl', 'serverUrl']) {
+ if (value[field]) assert.equal(new URL(value[field]).origin, origin, field);
+ }
+ if (value.previewHandoff) assert.equal(new URL(value.previewHandoff.previewUrl).origin, origin);
+ };
+ assertUrls(opened);
+ assertUrls(await clients[1].call('motion_open_preview', { projectId: created.projectId }));
+ for (const entry of ['server.ts', 'preview.ts']) {
+ const { stdout } = await promisify(execFile)(process.execPath, ['--experimental-strip-types', path.join(pluginRoot, entry)], {
+ cwd: pluginRoot, env: { ...process.env, MOTION_DATA_DIR: store.directory }, timeout: 20_000 });
+ const value = JSON.parse(stdout);
+ assert.ok(value.studioUrl, entry);
+ assertUrls(value);
+ assert.equal(new URL(value.studioUrl).hash, `#project/${created.projectId}`);
+ }
+ } finally { await Promise.all(clients.map(client => client.close())); }
+}, false));
diff --git a/tests/mcp-runtime.test.ts b/tests/mcp-runtime.test.ts
index b5755f73..66053185 100644
--- a/tests/mcp-runtime.test.ts
+++ b/tests/mcp-runtime.test.ts
@@ -1,7 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
-import { mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
+import { mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { tmpdir } from 'node:os';
import { pathToFileURL } from 'node:url';
@@ -10,6 +10,7 @@ import { pluginRoot } from '../hyperframes.ts';
import { rpc } from '../mcp.ts';
import { copyRuntimeFixture } from './fixtures.ts';
import { WorkspaceStore } from '../workspace.ts';
+import { openPreview } from '../preview.ts';
async function incompatibleEditor(directory: string, changed: Record<string, unknown>, toolError?: string) {
const { data, runtime } = await editorDirectory(directory);
@@ -21,7 +22,7 @@ async function incompatibleEditor(directory: string, changed: Record<string, unk
const server = createServer(async (req, res) => {
requests.push(req.url!);
res.setHeader('Content-Type', 'application/json');
- if (req.url === '/editor-api/preview') return res.end(JSON.stringify({ previewUrl: registry.endpoint, ready: true, dataDirectory: data }));
+ if (req.url === '/editor-api/preview') return res.end(JSON.stringify({ previewUrl: registry.endpoint, studioUrl: 'http://127.0.0.1:59999/', editorReady: true, ready: true, dataDirectory: data }));
if (req.url === '/motion-api/phase1/call') {
let body = ''; for await (const chunk of req) body += chunk;
calls.push(JSON.parse(body));
@@ -42,6 +43,16 @@ const exportCall = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name
projectId: 'project', requestId: 'must-not-export', expectedRevision: '0'.repeat(64), versionId: 'unavailable', audio: 'silent',
} } };
+test('a compatible older shared backend cannot hand off its internal Studio URL', { skip: !sharedEditorEnabled }, async () => {
+ const directory = await realpath(await mkdtemp(path.join(tmpdir(), 'motion-old-preview-url-')));
+ const editor = await incompatibleEditor(directory, { build: 'older-build', mcp: { protocol: 1, tools: ['motion_open_preview'] } });
+ try {
+ const opened = await openPreview(new WorkspaceStore(directory), undefined, { editor: true, mcpTool: 'motion_open_preview' });
+ assert.equal(new URL(opened.studioUrl!).origin, new URL(editor.registry.endpoint).origin);
+ assert.equal(new URL(opened.studioUrl!).hash, '#project/project');
+ } finally { await editor.close(); await rm(directory, { recursive: true, force: true }); }
+});
+
test('MCP reports unavailable historical files as not applied', { skip: !sharedEditorEnabled }, async () => {
const directory = await mkdtemp(path.join(tmpdir(), 'motion-unavailable-version-'));
const message = 'VERSION_NOT_RESTORABLE: Historical files are missing, unreadable or corrupt: assets/audio.wav';
diff --git a/tests/preview.test.ts b/tests/preview.test.ts
index 2b757008..1e4d47f9 100644
--- a/tests/preview.test.ts
+++ b/tests/preview.test.ts
@@ -34,10 +34,12 @@ test('startup verifies the native Studio service and reuses the same workspace',
const mock = runtime(store);
const first = await openPreview(store, mock.environment);
assert.equal(first.ready, true); assert.equal(first.reused, false); assert.equal(first.browserOpened, false); assert.ok(first.studioUrl);
+ assert.equal(new URL(first.studioUrl).origin, new URL(first.previewUrl).origin, 'a legacy backend must not hand off its internal Studio URL');
assert.equal((await store.get()).project!.format, 'hyperframes');
const before = await store.get();
const second = await openPreview(new WorkspaceStore(store.directory), mock.environment);
assert.equal(second.previewUrl, first.previewUrl); assert.equal(second.reused, true);
+ assert.equal(second.studioUrl, first.studioUrl);
assert.equal(mock.launches.length, 1); assert.equal(mock.stops.length, 0);
assert.equal((await store.get()).revision, before.revision); assert.equal(await previewUrl(store), first.previewUrl);
}, false));