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(studio): save SVG styles and initialize the default project

罗高c46da04aa703
diff --git a/docs/product/architecture.md b/docs/product/architecture.md
index 98f0eb84..a009109e 100644
--- a/docs/product/architecture.md
+++ b/docs/product/architecture.md
@@ -8,7 +8,7 @@ Updated: 2026-11-09. 实现基线:0.6.2;状态:下文标记为“当前”
**对外主张是 Reverse engineering for any video:让用户的本地 Agent 成为全栈视频创作者。** 以参考视频和用户品牌为起点,研究叙事、镜头、动效与声音,用 HTML/CSS/JavaScript 重建可编辑工程,补齐素材并在同一 Studio 继续剪辑、预览和渲染。产品形态仍为 **All-in-One AI-native Studio for AI editing & Motion**;真人口播、原创制作、模板改编和局部改稿继续使用各自入口,参考重建不替代其他创作流程。
-The MVP opens directly into the Motion editor with a searchable project sidebar, including `embed=1`. Home, conversation, browser tabs and integration/model settings are not exposed in this editor. Users can create a blank project from the sidebar, create through the external Agent workflow, or use the editor's template library. The underlying session, mode and Artifact model is retained, with Motion as the only executable mode and Hyperframes owning editing and export.
+The MVP opens directly into the Motion editor with a searchable project sidebar, including `embed=1`. Home, conversation, browser tabs and integration/model settings are not exposed in this editor. Users can create a blank project from the sidebar, create through the external Agent workflow, or use the editor's template library. The initial project remains in the sidebar; first opening initializes the bundled default example when its sources are absent, including after Agent-first creation. Existing sources and legacy migration safeguards are retained. The underlying session, mode and Artifact model is retained, with Motion as the only executable mode and Hyperframes owning editing and export.
会话的 Agent 推理与工具编排由用户已有的 MCP 客户端执行;本地网页保存需求、接收调用方写回的真实回复、管理产物与继续编辑,不包含内置聊天 Agent 运行器。自有 Agent、Codex 和其他 MCP 客户端共用先创建会话、后生成产物的生命周期。
diff --git a/docs/product/changes.md b/docs/product/changes.md
index 0384f7b5..2011e7ce 100644
--- a/docs/product/changes.md
+++ b/docs/product/changes.md
@@ -1,5 +1,11 @@
# 公开变更记录
+## 2026-11-12: Save SVG styles and initialize the initial project on open
+
+- SVG inline-style edits use the existing source patcher, guarded file writer and edit history when the pinned engine cannot persist SVG targets. Missing element identities and concurrent source changes still reject the edit and keep navigation blocked.
+- Opening the initial project from the sidebar or a direct preview initializes the bundled six-second example if its sources are absent. Existing edits, partial-project refusal and legacy migration safeguards remain unchanged.
+- Validation: static checks, Studio typecheck/build, 79 targeted Studio tests, 14 project/session/legacy/cold-start tests and the phase-one creation regression passed locally. Installed-host, cross-platform and human visual acceptance remain separate.
+
## 2026-11-11: Check historical media before offering MCP restoration
- **Problem and audience:** Agents and creators could be told that a historical version was restorable after its media blobs had disappeared; restoration then exposed a low-level file-copy error.
diff --git a/server.ts b/server.ts
index 884c4d69..cb5cc6ee 100644
--- a/server.ts
+++ b/server.ts
@@ -150,6 +150,7 @@ async function openProject(store: WorkspaceStore, context: Service, origin: stri
const entry = creating ? { id, title: template?.title ?? (target as { title: string }).title, templateId: template?.id, createdAt: Date.now() } : undefined;
if (!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 && id === 'project') await store.forProject(id).initializeLocked(runtimeRoot);
if (!entry && store.projectCatalog().activeId === id) {
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);
@@ -547,6 +548,7 @@ export async function startServer(store = sharedStore, port = Number(process.env
let opening: Promise<Studio> | undefined;
context.ensureStudio = async (projectId = store.projectId) => {
const scoped = store.forProject(projectId);
+ if (projectId === 'project') await scoped.initialize(runtimeRoot);
if (context.studio?.alive()) { await context.studio.openProject?.(projectId); return context.studio; }
if (!opening && context.switching) throw new Error('正在打开工程,请稍候');
if (!opening) opening = (async () => {
diff --git a/studio/src/hooks/useDomEditPersist.test.tsx b/studio/src/hooks/useDomEditPersist.test.tsx
index a279d6e2..226f4e42 100644
--- a/studio/src/hooks/useDomEditPersist.test.tsx
+++ b/studio/src/hooks/useDomEditPersist.test.tsx
@@ -14,6 +14,7 @@ import {
import type { PersistDomEditOperations } from "./domEditCommitTypes";
import { jsonResponse, requestUrl } from "./fetchStubTestUtils";
import { useDomEditPersist, type UseDomEditPersistParams } from "./useDomEditPersist";
+import { createDomEditSaveQueue } from "../utils/domEditSaveQueue";
const trackStudioEvent = vi.fn();
const reseekPreviewRuntime = vi.fn();
@@ -36,10 +37,10 @@ const selection = {
sourceFile: "index.html",
} as DomEditSelection;
-function stubServer(patchResponse: Record<string, unknown>) {
+function stubServer(patchResponse: Record<string, unknown>, source = SOURCE) {
const fetchMock = vi.fn(async (input: Parameters<typeof fetch>[0], _init?: RequestInit) => {
const url = requestUrl(input);
- if (url.includes("/api/projects/p1/files/")) return jsonResponse({ content: SOURCE });
+ if (url.includes("/api/projects/p1/files/")) return jsonResponse({ content: source });
if (url.includes("/api/projects/p1/file-mutations/patch-element/")) {
return jsonResponse(patchResponse);
}
@@ -186,6 +187,49 @@ describe("useDomEditPersist", () => {
);
});
+ it("saves an SVG connector style through the guarded writer and history, leaving navigation unblocked", async () => {
+ const source = '<template><svg><path data-hf-id="hf-card" id="connector" d="M0 0L10 10" /></svg></template>';
+ const element = document.createElementNS("http://www.w3.org/2000/svg", "path") as unknown as HTMLElement;
+ const fetchMock = stubServer({ changed: false, matched: false }, source);
+ const queue = createDomEditSaveQueue();
+ const { persist, params } = renderPersist({ queueDomEditSave: save => queue.enqueue(save) });
+ await persist({ ...selection, element, id: "connector" }, OPERATIONS, { label: "Recolor connector" });
+ const expected = source.replace('d="M0 0L10 10" />', 'd="M0 0L10 10" style="color: blue" />');
+ expect(params.writeProjectFile).toHaveBeenCalledExactlyOnceWith("index.html", expected, source);
+ expect(params.editHistory.recordEdit).toHaveBeenCalledWith(expect.objectContaining({
+ label: "Recolor connector", files: { "index.html": { before: source, after: expected } },
+ }));
+ expect(patchPosts(fetchMock)).toHaveLength(0);
+ expect(params.reloadPreview).toHaveBeenCalledOnce();
+ await expect(queue.waitForIdle()).resolves.toEqual({ status: "clean" });
+ });
+
+ it("does not retarget a missing SVG identity to an element reusing its id", async () => {
+ const source = '<svg><path data-hf-id="hf-replacement" id="connector" /></svg>';
+ const element = document.createElementNS("http://www.w3.org/2000/svg", "path") as unknown as HTMLElement;
+ stubServer({ changed: false, matched: false }, source);
+ const { persist, params } = renderPersist();
+ await expect(persist({ ...selection, element, id: "connector" }, OPERATIONS)).rejects.toBeInstanceOf(DomEditPersistUnresolvableError);
+ expect(params.writeProjectFile).not.toHaveBeenCalled();
+ expect(params.editHistory.recordEdit).not.toHaveBeenCalled();
+ });
+
+ it("retains the write conflict and blocks navigation when an SVG source changes concurrently", async () => {
+ const source = '<svg><path data-hf-id="hf-card" /></svg>';
+ const element = document.createElementNS("http://www.w3.org/2000/svg", "path") as unknown as HTMLElement;
+ stubServer({ changed: false, matched: false }, source);
+ const queue = createDomEditSaveQueue();
+ const failure = new Error("Source changed");
+ const { persist, params } = renderPersist({
+ queueDomEditSave: save => queue.enqueue(save),
+ writeProjectFile: vi.fn(async () => { throw failure; }),
+ });
+ await expect(persist({ ...selection, element }, OPERATIONS)).rejects.toBe(failure);
+ expect(params.editHistory.recordEdit).not.toHaveBeenCalled();
+ expect(params.reloadPreview).not.toHaveBeenCalled();
+ await expect(queue.waitForIdle()).resolves.toEqual({ status: "failed", error: failure });
+ });
+
it("refuses a non-finite layout value before any request, with a toast", async () => {
const fetchMock = stubServer({ changed: true });
const { persist, params } = renderPersist();
diff --git a/studio/src/hooks/useDomEditPersist.ts b/studio/src/hooks/useDomEditPersist.ts
index 6b2d7b85..3375d7a5 100644
--- a/studio/src/hooks/useDomEditPersist.ts
+++ b/studio/src/hooks/useDomEditPersist.ts
@@ -3,7 +3,7 @@ import { findUnsafeDomPatchValues } from "@hyperframes/core/studio-api/finite-mu
import { trackStudioEvent } from "../utils/studioTelemetry";
import { buildDomEditPatchTarget, type DomEditSelection } from "../components/editor/domEditing";
import type { PersistDomEditOperations } from "./domEditCommitTypes";
-import type { PatchOperation } from "../utils/sourcePatcher";
+import { applyPatchByTarget, findTagByTarget, type PatchOperation } from "../utils/sourcePatcher";
import {
DomEditPersistUnsafeValueError,
DomEditPersistPreparedWriteError,
@@ -14,6 +14,7 @@ import {
formatUnsafeFieldList,
postPatchElement,
writePreparedContent,
+ type PatchElementResponse,
} from "./useDomEditCommitsHelpers";
import { importedFontFaceCssFor } from "../utils/studioFontHelpers";
import { countStudioManualEditSave } from "../components/editor/manualEditsDom";
@@ -142,7 +143,25 @@ export function useDomEditPersist({
const originalContent = await readTarget();
if (originalContent === null) return null;
options?.validateContent?.(originalContent);
- const patchData = await postPatchElement(pid, targetPath, patchBody, showToast);
+ let patchData: PatchElementResponse;
+ if (
+ selection.element?.namespaceURI === "http://www.w3.org/2000/svg" &&
+ selection.hfId && !font &&
+ operations.length > 0 &&
+ operations.every(op => op.type === "inline-style" && op.childSelector === undefined)
+ ) {
+ // shortcut: 0.9.7's server rejects SVG; retain the normal file queue and history until upstream supports it.
+ const target = { hfId: selection.hfId };
+ const matched = findTagByTarget(originalContent, target) !== null;
+ const content = matched
+ ? operations.reduce((html, op) => applyPatchByTarget(html, target, op), originalContent)
+ : originalContent;
+ const changed = content !== originalContent;
+ if (changed) await writeProjectFile(targetPath, content, originalContent);
+ patchData = { matched, changed, content, path: targetPath };
+ } else {
+ patchData = await postPatchElement(pid, targetPath, patchBody, showToast);
+ }
if (!patchData.changed) return { patchData, patchedContent: null, finalContent: null };
const patchedContent =
diff --git a/tests/projects.test.ts b/tests/projects.test.ts
index f863c304..450bbb5e 100644
--- a/tests/projects.test.ts
+++ b/tests/projects.test.ts
@@ -1,12 +1,54 @@
import test from 'node:test';
import assert from 'node:assert/strict';
-import { readFile, readdir } from 'node:fs/promises';
+import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { startServer } from '../server.ts';
-import { WorkspaceStore } from '../workspace.ts';
+import { WorkspaceStore, createBlankProject } from '../workspace.ts';
import { inspectProject, pluginRoot, startStudio } from '../hyperframes.ts';
import { fixture } from './fixtures.ts';
+for (const entry of ['sidebar', 'direct preview'] as const) {
+ test(`missing initial project opens the bundled default through ${entry} without overwriting other projects`, { timeout: 60_000 }, () => fixture(async store => {
+ const id = crypto.randomUUID(), directory = store.projectDirectoryFor(id);
+ await createBlankProject(directory, pluginRoot, 'Agent project');
+ await store.selectProject(id, { id, title: 'Agent project' });
+ const before = await readFile(path.join(directory, 'index.html'), 'utf8');
+ assert.equal((await store.forProject('project').get()).project, null);
+ const running = await startServer(store, 0);
+ try {
+ const origin = `http://127.0.0.1:${(running.server.address() as { port: number }).port}`;
+ const stale = await fetch(origin + '/motion-api/projects/project/open', {
+ method: 'POST', headers: { Origin: origin, 'Content-Type': 'application/json' },
+ body: JSON.stringify({ expectedRevision: '0'.repeat(64), expectedProjectId: id }),
+ });
+ assert.equal(stale.status, 409);
+ assert.equal((await store.forProject('project').get()).project, null, 'stale switches cannot create defaults');
+ if (entry === 'sidebar') await running.openProject('project');
+ else await running.ensureStudio('project');
+ const initial = store.forProject('project');
+ const file = path.join(initial.projectDirectory, 'index.html');
+ const withoutStampedIds = (source: string) => source.replace(/ data-hf-id="[^"]*"/g, '');
+ assert.equal(withoutStampedIds(await readFile(file, 'utf8')), await readFile(path.join(pluginRoot, 'templates/index.html'), 'utf8'));
+ assert.ok((await initial.files()).some(file => file.path === 'compositions/first.html'));
+ assert.equal(withoutStampedIds(await readFile(path.join(directory, 'index.html'), 'utf8')), before);
+ if (entry === 'direct preview') assert.equal(store.projectId, id, 'preview warming retains active project ownership');
+ const edited = (await readFile(file, 'utf8')).replace('Motion · First story', 'My saved title');
+ await writeFile(file, edited);
+ await running.openProject(id);
+ await running.openProject('project');
+ assert.equal(await readFile(file, 'utf8'), edited, 'reopening retains existing edits');
+ } finally { await running.close(); }
+ }, false));
+}
+
+test('default initialization refuses a partial initial project without replacing its files', () => fixture(async store => {
+ await mkdir(store.projectDirectoryFor('project'), { recursive: true });
+ const note = path.join(store.projectDirectoryFor('project'), 'note.txt');
+ await writeFile(note, 'Keep this unfinished project');
+ await assert.rejects(store.initialize(pluginRoot), /已有文件但缺少 index.html/);
+ assert.equal(await readFile(note, 'utf8'), 'Keep this unfinished project');
+}, false));
+
test('project sessions create blank editable projects, isolate uploads and restore the selected project after restart', { timeout: 180_000 }, () => fixture(async store => {
let running = await startServer(store, 0);
const baseUrl = () => `http://127.0.0.1:${(running.server.address() as { port: number }).port}`;
diff --git a/workspace.ts b/workspace.ts
index dba652b7..58aaa843 100644
--- a/workspace.ts
+++ b/workspace.ts
@@ -333,26 +333,29 @@ export class WorkspaceStore {
}
async initialize(runtimeRoot: string) {
- return this.lock(async () => {
- if ((await this.get()).project) return;
- if ((await this.files()).length) throw new Error('工程目录已有文件但缺少 index.html,请先修复入口');
- const staging = path.join(this.directory, 'initialize-' + crypto.randomUUID());
- await mkdir(path.join(staging, 'assets'), { recursive: true });
+ return this.lock(() => this.initializeLocked(runtimeRoot));
+ }
+
+ // The caller must hold the workspace lock, as project switching already does.
+ async initializeLocked(runtimeRoot: string) {
+ if ((await this.get()).project) return;
+ if ((await this.files()).length) throw new Error('工程目录已有文件但缺少 index.html,请先修复入口');
+ const staging = path.join(this.directory, 'initialize-' + crypto.randomUUID());
+ await mkdir(path.join(staging, 'assets'), { recursive: true });
+ try {
+ let legacy: LegacyProject | null = null;
try {
- let legacy: LegacyProject | null = null;
- try {
- const old = JSON.parse(await readFile(path.join(this.directory, 'workspace.json'), 'utf8'));
- if (old.project) legacy = validateProject(old.project);
- } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
- if (legacy) await migrateLegacy(legacy, staging);
- else await cp(path.join(pluginRoot, 'templates'), staging, { recursive: true });
- await copyFile(path.join(runtimeRoot, 'node_modules/gsap/dist/gsap.min.js'), path.join(staging, 'assets/gsap.min.js'));
- await writeFile(path.join(staging, 'hyperframes.json'), JSON.stringify(nativeProjectConfig, null, 2));
- // The legacy workspace.json remains untouched. Never replace an existing native entry.
- try { await rename(staging, this.projectDirectory); }
- catch (error) { throw new Error('无法创建 Hyperframes 工程,已有目录保持不变', { cause: error }); }
- } finally { await rm(staging, { recursive: true, force: true }); }
- });
+ const old = JSON.parse(await readFile(path.join(this.directory, 'workspace.json'), 'utf8'));
+ if (old.project) legacy = validateProject(old.project);
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
+ if (legacy) await migrateLegacy(legacy, staging);
+ else await cp(path.join(pluginRoot, 'templates'), staging, { recursive: true });
+ await copyFile(path.join(runtimeRoot, 'node_modules/gsap/dist/gsap.min.js'), path.join(staging, 'assets/gsap.min.js'));
+ await writeFile(path.join(staging, 'hyperframes.json'), JSON.stringify(nativeProjectConfig, null, 2));
+ // The legacy workspace.json remains untouched. Never replace an existing native entry.
+ try { await rename(staging, this.projectDirectory); }
+ catch (error) { throw new Error('无法创建 Hyperframes 工程,已有目录保持不变', { cause: error }); }
+ } finally { await rm(staging, { recursive: true, force: true }); }
}
async job(id?: string): Promise<ExportJob | null> {