Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(studio): undo and redo update the preview in place instead of reloading it (#4718)
Miguel Ángel9e1dbca7a2c2
diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.tsindex 4db2e531a0..90c7060b60 100644--- a/packages/cli/src/server/studioServer.ts+++ b/packages/cli/src/server/studioServer.ts@@ -518,6 +518,9 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {},getProjectSignature: projectSignature,+ invalidateProjectSignature: (dir: string) => {+ if (resolve(dir) === resolve(projectDir)) cachedProjectSignature = null;+ },async lint(html: string, opts?: { filePath?: string; isSubComposition?: boolean }) {const { lintHyperframeHtml } = await import("@hyperframes/lint");diff --git a/packages/studio-server/src/createStudioApi.ts b/packages/studio-server/src/createStudioApi.tsindex 7614ec3ce7..8ea882cf8f 100644--- a/packages/studio-server/src/createStudioApi.ts+++ b/packages/studio-server/src/createStudioApi.ts@@ -42,6 +42,14 @@ export function createStudioApi(adapter: StudioApiAdapter): Hono {if (c.res.status >= 403 && dirBeforeRoute && folderGone(dirBeforeRoute))replaceWithProjectDirMissing(c, hostHeaders);});+ api.use("/projects/:id/*", async function forgetSignatureAfterWrite(c, next) {+ await next();+ if (c.req.method === "GET" || c.req.method === "HEAD") return;+ const project = await Promise.resolve()+ .then(() => adapter.resolveProject(c.req.param("id")))+ .catch(() => null);+ if (project) adapter.invalidateProjectSignature?.(project.dir);+ });registerProjectRoutes(api, adapter);registerFileRoutes(api, adapter);diff --git a/packages/studio-server/src/routes/history.test.ts b/packages/studio-server/src/routes/history.test.tsindex e814d633ef..ba55a1cafb 100644--- a/packages/studio-server/src/routes/history.test.ts+++ b/packages/studio-server/src/routes/history.test.ts@@ -7,6 +7,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { createStudioApi } from "../createStudioApi";import { DELETED_VERSION, fileContentVersion, identifyFileWrite } from "../helpers/fileVersion";import { openProjectHistory, type ProjectHistory } from "../history/projectHistory";+import { createProjectSignature, resolveProjectSignature } from "../helpers/projectSignature";import type { StudioApiAdapter } from "../types";const cleanup: Array<() => unknown> = [];@@ -103,6 +104,30 @@ describe("history routes", () => {},);+ it("drop the host's cached signature before an undo answers, so the next preview is the restored build", async () => {+ const { projectDir, history } = await demoProject();+ let cached: string | null = null;+ const adapter = {+ listProjects: () => [],+ resolveProject: (id: string) => (id === "demo" ? { id, dir: projectDir } : null),+ history: () => history,+ getProjectSignature: (dir: string) => (cached ??= createProjectSignature(dir)),+ invalidateProjectSignature: () => (cached = null),+ } as unknown as StudioApiAdapter;+ const api = createStudioApi(adapter);+ const call = (path: string, body: object) =>+ api.request(`/projects/demo/history${path}`, { method: "POST", body: JSON.stringify(body) });+ const { windowId } = await (await call("/window", { label: "Retitle" })).json();+ writeFileSync(join(projectDir, "index.html"), "Bee");+ await call(`/window/${windowId}/close`, {});+ // A thumbnail request caches the edited build's signature; the watcher that clears it lags the undo.+ const edited = resolveProjectSignature(adapter, projectDir);++ expect(await (await call("/step", { direction: "back" })).json()).toMatchObject({ ok: true });+ expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toBe("A");+ expect(resolveProjectSignature(adapter, projectDir)).not.toBe(edited);+ });+it("record a Studio edit window as the person's entry, and step back undoes it", async () => {const { projectDir, call } = await demoProject();diff --git a/packages/studio-server/src/routes/preview.test.ts b/packages/studio-server/src/routes/preview.test.tsindex 2530b3412e..753cb0b8d6 100644--- a/packages/studio-server/src/routes/preview.test.ts+++ b/packages/studio-server/src/routes/preview.test.ts@@ -435,6 +435,37 @@ describe("registerPreviewRoutes", () => {expect(html).toContain("Preview");});+ it("does not keep a build under the signature a write replaced while it built", async () => {+ const projectDir = createProjectDir();+ const file = join(projectDir, "index.html");+ const edited = "<html><head></head><body>Edited</body></html>";+ writeFileSync(file, edited);+ let release = () => {};+ let gate: Promise<void> | null = new Promise<void>((resolve) => (release = resolve));+ const app = new Hono();+ registerPreviewRoutes(+ app,+ createAdapter(projectDir, {+ bundle: async () => {+ const wait = gate;+ gate = null;+ await wait;+ return readFileSync(file, "utf-8");+ },+ }),+ );++ const inFlight = app.request("http://localhost/projects/demo/preview");+ await vi.waitFor(() => expect(gate).toBeNull());+ writeFileSync(file, "<html><head></head><body>Undone!</body></html>");+ release();+ expect(await (await inFlight).text()).toContain("Undone!");+ writeFileSync(file, edited);++ const redo = await app.request("http://localhost/projects/demo/preview?_t=2");+ expect(await redo.text()).toContain("Edited");+ });+it("uses the adapter project signature when available", async () => {const projectDir = createProjectDir();const getProjectSignature = vi.fn(() => "cached-signature");diff --git a/packages/studio-server/src/routes/preview.ts b/packages/studio-server/src/routes/preview.tsindex e1a22e006d..7fd3d460cd 100644--- a/packages/studio-server/src/routes/preview.ts+++ b/packages/studio-server/src/routes/preview.ts@@ -18,6 +18,7 @@ import { isProjectRootMissing, resolveWithinProject } from "../helpers/safePath.import { getMimeType } from "../helpers/mime.js";import { buildSubCompositionHtml, hasBaseElement } from "../helpers/subComposition.js";import {+ createProjectSignature,resolveProjectAndSignature,resolveProjectSignature,} from "../helpers/projectSignature.js";@@ -372,6 +373,7 @@ export function registerPreviewRoutes(api: Hono, adapter: PreviewApiAdapter): vopreviewVariables: Record<string, unknown> | null,builtKey: string,capture: boolean,+ signature: string,): Promise<string | null> {const diskMain = resolveProjectMainHtml(project.dir, project.id);const normalizedDisk = diskMain ? ensureHfIds(diskMain.html) : null;@@ -426,8 +428,10 @@ export function registerPreviewRoutes(api: Hono, adapter: PreviewApiAdapter): vomediaCodecProbeCache,);bundled = addScenePartsManifest(bundled, [`meta[name="${PROJECT_SIGNATURE_META}"]`]);- rememberPreview(builtKey, bundled);- if (!capture) adapter.previewDocuments?.write(builtKey, bundled);+ if (createProjectSignature(project.dir) === signature) {+ rememberPreview(builtKey, bundled);+ if (!capture) adapter.previewDocuments?.write(builtKey, bundled);+ }return bundled;} catch {// Re-read disk on bundle failure so we serve the latest file content,@@ -487,7 +491,7 @@ export function registerPreviewRoutes(api: Hono, adapter: PreviewApiAdapter): vo}let pending = previewBuilds.get(builtKey);if (!pending) {- pending = buildPreview(project, previewVariables, builtKey, capture).finally(() =>+ pending = buildPreview(project, previewVariables, builtKey, capture, signature).finally(() =>previewBuilds.delete(builtKey),);previewBuilds.set(builtKey, pending);diff --git a/packages/studio-server/src/types.ts b/packages/studio-server/src/types.tsindex ac0769e51e..3d79952f15 100644--- a/packages/studio-server/src/types.ts+++ b/packages/studio-server/src/types.ts@@ -120,8 +120,9 @@ export interface StudioApiAdapter {options?: Pick<BundleOptions, "stampHfIds" | "onRead">,): Promise<string | null>;- /** Optional: cached signature for project files that should invalidate preview frame caches. */+ /** Optional: a cached `createProjectSignature(dir)`; preview caching checks builds against it. */getProjectSignature?: (projectDir: string) => string;+ invalidateProjectSignature?: (projectDir: string) => void;/** Lint a single HTML string. */lint(diff --git a/packages/studio/src/player/sceneSwap.ts b/packages/studio/src/player/sceneSwap.tsindex 9928eff119..6253218cd5 100644--- a/packages/studio/src/player/sceneSwap.ts+++ b/packages/studio/src/player/sceneSwap.ts@@ -17,6 +17,27 @@ export function onPreviewContentReplaced(};}+export function markScenesStale(iframe: HTMLIFrameElement | null, files: readonly string[]): void {+ const doc = iframe?.contentDocument;+ const meta = doc?.querySelector<HTMLMetaElement>('meta[name="hf-scene-parts"]');+ if (!doc || !meta) return;+ let parts: { shared: string; scenes: Record<string, string> };+ try {+ parts = JSON.parse(meta.content);+ } catch {+ return;+ }+ for (const file of files) {+ const hosts = doc.querySelectorAll(`[data-composition-file="${CSS.escape(file)}"]`);+ if (hosts.length === 0 && file.endsWith(".html")) parts.shared = "";+ for (const host of hosts) {+ const scene = host.closest("[data-hf-scene]")?.getAttribute("data-hf-scene");+ if (scene && scene in parts.scenes) parts.scenes[scene] = "";+ }+ }+ meta.content = JSON.stringify(parts);+}+/** Null when the preview cannot swap; rejects when superseded, cancelled or a full reload is needed. */export function sceneSwapFor(iframe: HTMLIFrameElement,diff --git a/packages/studio/src/utils/gsapUndoRestore.test.ts b/packages/studio/src/utils/gsapUndoRestore.test.tsindex 2c8aa6296b..a09ad1fa31 100644--- a/packages/studio/src/utils/gsapUndoRestore.test.ts+++ b/packages/studio/src/utils/gsapUndoRestore.test.ts@@ -259,6 +259,64 @@ describe("applyUndoRestoreToPreview", () => {expect(reloadPreview).toHaveBeenCalledTimes(1);});+ it("blanks a restored scene's live hash before reloading, so the scene swap takes it", () => {+ const { iframe, doc } = buildLiveIframe(+ `<div data-hf-scene="scene0" data-composition-file="scenes/intro.html"><h1>Rep0</h1></div>` ++ `<div data-hf-scene="scene1" data-composition-file="scenes/outro.html"></div>`,+ );+ const meta = doc.createElement("meta");+ meta.name = "hf-scene-parts";+ meta.content = JSON.stringify({ shared: "s", scenes: { scene0: "h0", scene1: "h1" } });+ doc.head.append(meta);+ let partsAtReload: unknown;+ const reloadPreview = vi.fn(() => (partsAtReload = JSON.parse(meta.content)));+ const files = {+ "scenes/intro.html": { previous: "<h1>Rep0</h1>", restored: "<h1>Alpha</h1>" },+ };+ expect(applyUndoRestoreToPreview(iframe, ROOT, files, 3, reloadPreview)).toBe("full");+ expect(partsAtReload).toEqual({ shared: "s", scenes: { scene0: "", scene1: "h1" } });++ const withRoot = {+ ...files,+ [ROOT]: { previous: wrap("<p>b</p>"), restored: wrap("<p>a</p>") },+ };+ applyUndoRestoreToPreview(iframe, ROOT, withRoot, 3, reloadPreview);+ // A restored page outside every scene forces the full reload, never a partial swap.+ expect(partsAtReload).toEqual({ shared: "", scenes: { scene0: "", scene1: "h1" } });+ });++ it("leaves the scene hashes alone on a soft restore, so the next edit can still swap", () => {+ const { iframe, doc } = buildLiveIframe(`<div id="a" style="color: red">t</div>`);+ const meta = doc.createElement("meta");+ meta.name = "hf-scene-parts";+ meta.content = JSON.stringify({ shared: "s", scenes: { scene0: "h0" } });+ doc.head.append(meta);+ const files = {+ [ROOT]: {+ previous: wrap(`<div id="a" style="color: red">t</div>`),+ restored: wrap(`<div id="a" style="color: blue">t</div>`),+ },+ };+ expect(applyUndoRestoreToPreview(iframe, ROOT, files, 3, vi.fn())).toBe("soft");+ expect(JSON.parse(meta.content)).toEqual({ shared: "s", scenes: { scene0: "h0" } });+ });++ it.each([+ ["a restored stylesheet leaves the shared hash", "styles.css", '{"shared":"s","scenes":{}}'],+ ["an unreadable manifest still reloads", "scenes/intro.html", "not json"],+ ])("%s", (_name, path, content) => {+ const { iframe, doc } = buildLiveIframe(`<div id="a">t</div>`);+ const meta = doc.createElement("meta");+ meta.name = "hf-scene-parts";+ meta.content = content;+ doc.head.append(meta);+ const reloadPreview = vi.fn();+ const files = { [path]: { previous: "a", restored: "b" } };+ expect(applyUndoRestoreToPreview(iframe, ROOT, files, 3, reloadPreview)).toBe("full");+ expect(reloadPreview).toHaveBeenCalledTimes(1);+ expect(meta.content).toBe(content);+ });+it("full-reloads when the restore touches a sub-comp, not the active comp", () => {const { iframe } = buildLiveIframe(`<div id="a">t</div>`);const reloadPreview = vi.fn();diff --git a/packages/studio/src/utils/gsapUndoRestore.ts b/packages/studio/src/utils/gsapUndoRestore.tsindex fe2f622219..0417f693d0 100644--- a/packages/studio/src/utils/gsapUndoRestore.ts+++ b/packages/studio/src/utils/gsapUndoRestore.ts@@ -8,6 +8,7 @@ import {extractGsapScriptText,findGsapScriptElements,} from "./gsapSoftReload";+import { markScenesStale } from "../player/sceneSwap";type PreviewWindow = Window & {__player?: { seek?: (t: number) => void };@@ -184,7 +185,7 @@ export function applyUndoRestoreToPreview(activeCompPath: string | null,files: Record<string, UndoRestoreFile> | undefined,currentTime: number,- reloadPreview: () => void,+ reload: () => void,): "soft" | "full" {// The master view carries a NULL activeCompPath but the root iframe shows// index.html — the codebase-wide convention (`activeCompPath || "index.html"`).@@ -192,6 +193,10 @@ export function applyUndoRestoreToPreview(// full-reloaded: the original "undo always blinks".const activeDocPath = activeCompPath ?? "index.html";const paths = files ? Object.keys(files) : [];+ const reloadPreview = () => {+ markScenesStale(iframe, paths);+ reload();+ };// Soft path only covers the single active-comp document in the root iframe.if (!iframe || !files || paths.length !== 1 || paths[0] !== activeDocPath) {reloadPreview();diff --git a/packages/studio/vite.adapter.ts b/packages/studio/vite.adapter.tsindex 87ea594d8b..b99a69970e 100644--- a/packages/studio/vite.adapter.ts+++ b/packages/studio/vite.adapter.ts@@ -64,6 +64,7 @@ export interface ProjectSignatureCache {get(projectDir: string): string;/** Drop the signature of whichever project contains `changedPath`. */invalidate(changedPath: string): void;+ forget(projectDir: string): void;}export function createProjectSignatureCache({@@ -95,6 +96,9 @@ export function createProjectSignatureCache({if (affectsProjectSignature(projectDir, changedPath)) signatures.delete(projectDir);}},+ forget(projectDir) {+ signatures.delete(resolve(projectDir));+ },};}@@ -283,6 +287,10 @@ export function createViteAdapter(return signatureCache.get(projectDir);},+ invalidateProjectSignature(projectDir: string): void {+ signatureCache.forget(projectDir);+ },+async lint(html: string, opts?: { filePath?: string; isSubComposition?: boolean }) {const mod = await server.ssrLoadModule("@hyperframes/core/lint");return await mod.lintHyperframeHtml(html, { ...opts, host: "studio" });