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.

11.0 KB
Raw Blame
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdir, writeFile, readFile } from 'node:fs/promises';
import path from 'node:path';
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;
  await mkdir(path.join(store.directory, 'sessions'), { recursive: true });
  const saved = JSON.stringify({ projectId: 'project', messages: [{ id: crypto.randomUUID(), role: 'user', content: '保留已有需求', createdAt: Date.now() }] });
  await writeFile(path.join(store.directory, 'sessions/project.json'), saved);
  const session = await store.session('project');
  assert.equal(session.mode, 'motion');
  assert.equal(session.artifacts[0].projectId, 'project');
  assert.equal(session.messages[0].content, '保留已有需求');
  await store.renameSession('project', '会话名称');
  assert.equal(store.projectCatalog().projects[0].title, '初始工程');
  assert.equal(await readFile(path.join(store.directory, 'sessions/project.json'), 'utf8'), saved);
  assert.equal((await store.get()).revision, before);
  const read = await callTool('openmotion_get_session', { sessionId: 'project' }, store) as any;
  assert.equal(read.title, '会话名称'); assert.equal(read.skill, 'openmotion-production');
  assert.deepEqual(read.artifacts, JSON.parse(JSON.stringify(session.artifacts)));
  const reply = { sessionId: 'project', id: crypto.randomUUID(), role: 'assistant', content: '已读取现有需求,接下来保留原始素材。' };
  for (let i = 0; i < 2; i++) await callTool('openmotion_append_message', reply, store);
  assert.equal((await store.session('project')).messages.length, 2);
  assert.equal((await store.session('project')).messages[1].role, 'assistant');
  assert.equal((await store.get()).revision, before);
  await assert.rejects(callTool('openmotion_append_message', { ...reply, role: 'user' }, store), /已使用/);
  await assert.rejects(callTool('openmotion_append_message', { ...reply, id: crypto.randomUUID(), role: 'system' }, store), /角色/);
  await assert.rejects(callTool('openmotion_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 }, 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 }));
  async function mutate(route: string, body: object = {}, method = 'POST') {
    const state = await store.status();
    return fetch(origin + '/motion-api' + route, { method, headers: { Origin: origin, 'Content-Type': 'application/json' }, body: JSON.stringify({ expectedRevision: state.revision, expectedProjectId: state.projectId, ...body }) });
  }
  try {
    const modes = await (await fetch(origin + '/motion-api/modes')).json();
    assert.deepEqual(modes.modes.map((item: any) => item.id), ['motion']);
    assert.equal((await mutate('/sessions', { mode: 'image' })).status, 400);
    assert.equal(store.projectCatalog().projects.length, 1);
    const created = await mutate('/sessions', { mode: 'motion', instruction: '制作新品广告', templateId: 'product-promo' });
    assert.equal(created.status, 201, await created.clone().text());
    const creation = await created.json();
    assert.equal(creation.session.artifacts.length, 0, 'conversation exists before a viewer or native project');
    assert.equal(store.projectCatalog().projects.length, 1);
    const generated = await mutate(`/sessions/${creation.sessionId}/artifacts`);
    assert.equal(generated.status, 201, await generated.clone().text());
    const first = await generated.json();
    assert.notEqual(first.sessionId, first.projectId);
    const session = await store.session(first.sessionId);
    assert.equal(session.templateId, 'product-promo');
    assert.equal(session.messages[0].content, '制作新品广告');
    assert.equal(session.artifacts.length, 1);
    const firstSource = await readFile(path.join(store.projectDirectoryFor(first.projectId), 'index.html'), 'utf8');
    const additional = await mutate(`/sessions/${session.id}/artifacts`, { title: '备用剪辑' });
    assert.equal(additional.status, 201, await additional.clone().text());
    const second = await additional.json();
    assert.equal(second.sessionId, session.id); assert.notEqual(second.projectId, first.projectId);
    assert.equal(store.projectCatalog().sessions!.length, 2, 'initial conversation plus one new conversation');
    const withArtifacts = await store.session(session.id);
    assert.equal(withArtifacts.artifacts.length, 2);
    assert.equal(withArtifacts.activeArtifactId, withArtifacts.artifacts[1].id);
    assert.equal(await readFile(path.join(store.projectDirectoryFor(first.projectId), 'index.html'), 'utf8'), firstSource);
    assert.equal((await mutate(`/sessions/${session.id}/open`, { projectId: 'project' })).status, 400);
    const revision = (await store.get()).revision;
    assert.equal((await mutate(`/sessions/${session.id}`, { title: '广告会话' }, 'PATCH')).status, 200);
    assert.equal((await store.status()).projectTitle, '备用剪辑');
    const message = { id: crypto.randomUUID(), content: '两版都保留' };
    for (let i = 0; i < 2; i++) assert.equal((await mutate(`/sessions/${session.id}/messages`, message)).status, 201);
    assert.equal((await store.session(session.id)).messages.length, 2);
    assert.equal((await store.get()).revision, revision);
    assert.equal((await store.conversation(first.projectId)).messages[1].content, message.content);
    assert.equal((await mutate('/sessions/project/open')).status, 200);
    const reopened = await mutate(`/sessions/${session.id}/open`);
    assert.equal((await reopened.json()).projectId, second.projectId);
    const restarted = new WorkspaceStore(store.directory);
    assert.equal(restarted.projectCatalog().activeSessionId, session.id);
    assert.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, 200);
    const viewer = await callTool('openmotion_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');
    assert.equal(new URL(viewer.sessionUrl).searchParams.get('session'), session.id);
    const bare = await callTool('openmotion_create_session', { mode: 'motion', instruction: '先讨论网页式动效的方向', createArtifact: false }, store) as any;
    assert.equal(bare.session.artifacts.length, 0);
    assert.equal((await store.status()).sessionId, session.id, 'native status keeps the actual artifact owner');
    assert.equal((await store.status()).activeSessionId, bare.sessionId, 'generic session selection can exist without a native artifact');
    assert.equal((await store.get()).project?.html, firstSource);
    const read = await (await fetch(`${origin}/design-api/sessions/${bare.sessionId}`)).json();
    assert.equal(read.messages[0].content, '先讨论网页式动效的方向');
    assert.equal((await mutate(`/sessions/${bare.sessionId}/open`)).status, 200);
    const pending = await mutate(`/sessions/${bare.sessionId}/artifacts`, { expectedRevision: '0'.repeat(64) });
    assert.equal(pending.status, 409);
    assert.equal((await store.session(bare.sessionId)).messages.length, 1, 'failed generation preserves the conversation');
    assert.equal((await store.session(bare.sessionId)).artifacts.length, 0);
    const finished = await callTool('openmotion_create_artifact', { sessionId: bare.sessionId, expectedRevision: (await store.get()).revision }, store) as any;
    assert.equal(finished.session.id, bare.sessionId);
    assert.equal(finished.session.artifacts.length, 1);
    assert.equal(new URL(finished.embeddedPreviewUrl).searchParams.get('embed'), '1');
    const fromCodex = await callTool('openmotion_open_preview', {}, store) as any;
    assert.equal(fromCodex.sessionId, bare.sessionId);
    assert.equal(fromCodex.projectId, finished.projectId);
    assert.equal(new URL(fromCodex.previewUrl).searchParams.get('embed'), '1');
    const full = await callTool('openmotion_open_preview', { embedded: false }, store) as any;
    assert.equal(full.previewUrl, full.sessionUrl);
    assert.equal(new URL(full.previewUrl).searchParams.has('embed'), false);
    const currentLink = await callTool('openmotion_get_project', {}, store) as any;
    assert.equal(new URL(currentLink.previewUrl).searchParams.get('embed'), '1');
    const request = { id: crypto.randomUUID(), mode: 'motion', templateId: 'decision-tree' };
    const generatedByMcp = await callTool('openmotion_create_session', request, store) as any;
    const count = store.projectCatalog().projects.length;
    const retried = await callTool('openmotion_create_session', request, store) as any;
    assert.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 published = await callTool('openmotion_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('openmotion_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);
    assert.equal(new URL(templated.previewUrl).searchParams.get('project'), templated.projectId);
  } finally { await running.close(); }
}));