Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(studio): undo and redo step through the project history, whoever made the change (#4456)
Miguel Ángel36f8bd0e9112
diff --git a/packages/cli/src/server/studioServer.test.ts b/packages/cli/src/server/studioServer.test.tsindex 5db94c8395..08c0099d75 100644--- a/packages/cli/src/server/studioServer.test.ts+++ b/packages/cli/src/server/studioServer.test.ts@@ -1,6 +1,6 @@import { EventEmitter } from "node:events";import { afterEach, describe, expect, it, vi } from "vitest";-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { basename, join } from "node:path";import { createProjectSignature, fileContentVersion } from "@hyperframes/studio-server";@@ -665,6 +665,30 @@ describe("Studio file-change SSE", () => {}});+ it("labels the deletion an undo from Studio makes with Studio's write token", async () => {+ const projectDir = tmpProject();+ writeFileSync(join(projectDir, "index.html"), "<html>before</html>");+ server = createStudioServer({ projectDir, historyRoot: tmpProject() });+ const history = `/api/projects/${encodeURIComponent(basename(projectDir))}/history`;+ const post = (path: string, body: object, headers: Record<string, string> = {}) =>+ server!.app.request(`${history}${path}`, {+ method: "POST",+ headers: { "Content-Type": "application/json", ...headers },+ body: JSON.stringify(body),+ });+ await server.app.request(history); // opens the history, as Studio's first load does+ writeFileSync(join(projectDir, "extra.html"), "<html>added</html>");+ await post("/claim", { label: "Added a section", paths: ["extra.html"] });+ const streams = await subscribe(1);++ await post("/step", { direction: "back" }, { "X-Hyperframes-Write-Token": "studio-undo-1" });+ expect(existsSync(join(projectDir, "extra.html"))).toBe(false);+ mockWatcher.emit("change", "rename", "extra.html");++ const [payload] = await Promise.all(streams.map(nextEvent));+ expect(payload).toContain("studio-undo-1");+ });+// `/api/events` is one connection per SERVER, not per project: a tab left// open from a `preview` run whose port was later reused by a DIFFERENT// project shares this exact stream. Without `projectId` on the wire, thatdiff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.tsindex 49ba0de49c..aef4768f18 100644--- a/packages/cli/src/server/studioServer.ts+++ b/packages/cli/src/server/studioServer.ts@@ -11,7 +11,6 @@ import { existsSync, readFileSync, writeFileSync, unlinkSync } from "node:fs";import { createHash } from "node:crypto";import { fileURLToPath } from "node:url";import { resolve, join, basename } from "node:path";-import { homedir } from "node:os";import { readBundleFile } from "./readBundleFile.js";import {createProjectWatcher,@@ -41,6 +40,7 @@ import {createProjectSignature,createBackgroundRemovalJob,identifyFileWrite,+ DELETED_VERSION,fileContentVersion,getMimeType,affectsProjectSignature,@@ -53,6 +53,7 @@ import {type RenderJobState,type BackgroundRemovalRender,stampProjectHfIds,+ DEFAULT_HISTORY_ROOT,openProjectHistory,type ProjectHistory,} from "@hyperframes/studio-server";@@ -74,9 +75,6 @@ import {const STUDIO_MANUAL_EDITS_PATH = ".hyperframes/studio-manual-edits.json";-/** Where `hyperframes preview` keeps project histories: outside every project, so no tidy-up takes one away. */-const DEFAULT_HISTORY_ROOT = join(homedir(), ".cache", "hyperframes", "history");-// Under preview.ts's 3s process-exit watchdog, so shutdown() always returns// before that watchdog can fire and skip this file's browser cleanup.const RENDER_SHUTDOWN_WAIT_MS = 2_000;@@ -866,7 +864,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {// `version` ships even when no receipt matches: it is the client's only// identity for an unlabelled change, and without it every duplicate// delivery of one watcher event drains and reloads again.- const receipt = version ? identifyFileWrite(absPath, version) : null;+ const receipt = identifyFileWrite(absPath, version ?? DELETED_VERSION);// `projectId` so a stale tab — one still pointed at a project this// server no longer serves, because `hyperframes preview` reused this// port for a different folder (see ProjectUnreachableBanner's docdiff --git a/packages/studio-server/src/helpers/fileVersion.ts b/packages/studio-server/src/helpers/fileVersion.tsindex dbce9083e9..3c3a94dc66 100644--- a/packages/studio-server/src/helpers/fileVersion.ts+++ b/packages/studio-server/src/helpers/fileVersion.ts@@ -15,7 +15,19 @@ const receipts = new Map<string, StoredReceipt[]>();/** Strong content version used as both the JSON version and HTTP ETag. */export function fileContentVersion(content: string | Uint8Array): string {- return `"sha256:${createHash("sha256").update(content).digest("hex")}"`;+ return hashVersion(createHash("sha256").update(content).digest("hex"));+}++/** The version a deletion's receipt is kept under: a deleted file has no bytes to hash. */+export const DELETED_VERSION = '"deleted"';++export function hashVersion(hex: string): string {+ return `"sha256:${hex}"`;+}++/** The sha256 a version names, or undefined when it is not a content version. */+export function hashOfVersion(version: string): string | undefined {+ return /^"sha256:([0-9a-f]{64})"$/.exec(version)?.[1];}/** A validator from a file's inode, change time and size, or null while the change is under threediff --git a/packages/studio-server/src/history/blobStore.ts b/packages/studio-server/src/history/blobStore.tsindex 3c7fcca116..b23f5de0e4 100644--- a/packages/studio-server/src/history/blobStore.ts+++ b/packages/studio-server/src/history/blobStore.ts@@ -7,15 +7,17 @@ import { dirname, join } from "node:path";export interface BlobStore {/** Copies the file in (a clone where the file system can) and returns the copy's hash. */put(absPath: string): Promise<string>;+ has(hash: string): boolean;read(hash: string): Promise<Buffer>;/** Writes the blob's bytes to `absPath` by clone-or-copy and rename, so a reader never sees half a file. */writeTo(hash: string, absPath: string): Promise<void>;bytes(): number;size(hash: string): number;- /** Deletes every blob not in `keep`. */prune(keep: ReadonlySet<string>): Promise<void>;}+const BLOB_HASH = /^[0-9a-f]{64}$/;+async function hashFile(path: string): Promise<string> {const hash = createHash("sha256");for await (const chunk of createReadStream(path)) hash.update(chunk);@@ -40,7 +42,11 @@ export async function openBlobStore(dir: string): Promise<BlobStore> {for (const shard of await readdir(dir))for (const hash of await readdir(join(dir, shard)).catch(() => []))sizes.set(hash, (await stat(join(dir, shard, hash))).size);- const pathOf = (hash: string) => join(dir, hash.slice(0, 2), hash);+ const pathOf = (hash: string) => {+ // Checked where the path is joined, so no caller can read or write outside the store.+ if (!BLOB_HASH.test(hash)) throw new Error("That is not a history blob.");+ return join(dir, hash.slice(0, 2), hash);+ };let total = [...sizes.values()].reduce((sum, size) => sum + size, 0);return {@@ -62,8 +68,9 @@ export async function openBlobStore(dir: string): Promise<BlobStore> {total += size;return hash;},- read: (hash) => readFile(pathOf(hash)),- writeTo: (hash, absPath) => cloneOrCopy(pathOf(hash), absPath),+ has: (hash) => sizes.has(hash),+ read: async (hash) => readFile(pathOf(hash)),+ writeTo: async (hash, absPath) => cloneOrCopy(pathOf(hash), absPath),bytes: () => total,size: (hash) => sizes.get(hash) ?? 0,async prune(keep) {diff --git a/packages/studio-server/src/history/projectHistory.test.ts b/packages/studio-server/src/history/projectHistory.test.tsindex 9fa2d354af..f35e4bb23e 100644--- a/packages/studio-server/src/history/projectHistory.test.ts+++ b/packages/studio-server/src/history/projectHistory.test.ts@@ -13,6 +13,7 @@ import {import { tmpdir } from "node:os";import { dirname, join, relative } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";+import { fileContentVersion } from "../helpers/fileVersion";import { openProjectHistory, type ProjectHistory } from "./projectHistory";import { START, type HistoryWho } from "./historyLog";@@ -295,19 +296,16 @@ describe("openProjectHistory", () => {});describe("claim: a writer that records after writing", () => {- it("files the claimed paths' writes as the claimer's entry; other outside writes stay outside", async () => {+ it("files the claimed paths' writes as the claimer's entry; other outside writes stay outside, logged first", async () => {const { history, write, read } = await project({ "index.html": "A", "notes.md": "n" });write("index.html", "B");write("notes.md", "agent notes");const claimed = await history.claim(you, "Moved Title", ["index.html"]);- expect(history.list()).toMatchObject([- { id: claimed!.id, who: you, label: "Moved Title", files: [{ path: "index.html" }] },- ]);- await history.flush();expect(history.list().map((entry) => [entry.who.kind, entry.files[0]!.path])).toEqual([- ["person", "index.html"],["outside", "notes.md"],+ ["person", "index.html"],]);+ expect(history.list()[1]).toMatchObject({ id: claimed!.id, label: "Moved Title" });await history.undo(claimed!.id, { who: you });expect(read("index.html")).toBe("A");expect(await history.claim(you, "Nothing", ["index.html"]), "nothing left to claim").toBeNull();@@ -348,6 +346,347 @@ describe("claim: a writer that records after writing", () => {expect(history.list()).toEqual([]);});+ it("an agent's write seconds before Studio's stays the agent's, cut at the version Studio overwrote", async () => {+ const { history, write, read } = await project({ "index.html": "A" });+ write("index.html", "B");+ await history.claim(you, "sweep", []);+ write("index.html", "C");+ await history.claim(you, "Moved Title", ["index.html"], {+ overwrote: { "index.html": fileContentVersion("B") },+ });+ expect(history.list().map((entry) => [entry.who.kind, entry.label])).toEqual([+ ["outside", "Changed outside the app"],+ ["person", "Moved Title"],+ ]);+ await history.step("back", you);+ expect(read("index.html"), "Cmd+Z undoes only the person's edit").toBe("B");+ await history.step("back", you);+ expect(read("index.html")).toBe("A");+ });++ it("an agent's turn cut by Studio's edit becomes an entry before it and one after, so Cmd+Z walks back in order", async () => {+ const { history, write, read } = await project({ "index.html": "A" });+ const window = await history.beginWindow(agent, "Agent turn");+ write("index.html", "B");+ await history.claim(you, "sweep", []);+ write("index.html", "C");+ await history.claim(you, "Moved Title", ["index.html"], {+ overwrote: { "index.html": fileContentVersion("B") },+ });+ write("index.html", "D");+ expect(await window.close(), "the window still returns the entry it became").toMatchObject({+ id: window.id,+ });+ expect(history.list().map((entry) => entry.label)).toEqual([+ "Agent turn",+ "Moved Title",+ "Agent turn",+ ]);+ for (const expected of ["C", "B", "A"]) {+ expect(await history.step("back", you)).toMatchObject({ ok: true });+ expect(read("index.html")).toBe(expected);+ }+ });++ it("a cut agent turn with nothing after the cut ends as the entry it became at the cut", async () => {+ const { history, write, read } = await project({ "index.html": "A", "b.js": "1" });+ const window = await history.beginWindow(agent, "Agent turn");+ write("index.html", "B");+ await history.claim(you, "sweep", []);+ write("index.html", "C");+ write("b.js", "2");+ await history.claim(you, "Moved Title", ["index.html", "b.js"], {+ overwrote: { "index.html": fileContentVersion("B"), "b.js": fileContentVersion("1") },+ });+ write("b.js", "3");+ await history.claim(you, "Recolored", ["b.js"], {+ overwrote: { "b.js": fileContentVersion("2") },+ });+ const cutAt = history.list()[0]!;+ expect(cutAt).toMatchObject({ label: "Agent turn", who: agent });+ expect(+ await window.close(),+ "close returns the entry the window became at the cut",+ ).toMatchObject({ id: cutAt.id });+ for (const [index, b] of [+ ["C", "2"],+ ["B", "1"],+ ["A", "1"],+ ]) {+ expect(await history.step("back", you)).toMatchObject({ ok: true });+ expect([read("index.html"), read("b.js")]).toEqual([index, b]);+ }+ });++ it("a held drag across an agent's write ends at that write, so Cmd+Z walks back every step", async () => {+ const { history, write, read } = await project({ "index.html": "A" });+ const window = await history.beginWindow(agent, "Agent turn");+ const drag = (overwrote: string) =>+ history.claim(you, "Dragged Title", ["index.html"], {+ coalesceKey: "drag",+ idleMs: 60_000,+ overwrote: { "index.html": fileContentVersion(overwrote) },+ });+ // A claim under the drag's key that names no file: a scan that keeps the drag held.+ const scan = () => history.claim(you, "scan", [], { coalesceKey: "drag" });+ write("index.html", "B");+ await scan();+ write("index.html", "C");+ await drag("B");+ write("index.html", "D");+ await scan();+ write("index.html", "E");+ await drag("D");+ await history.flush();+ await window.close();+ for (const expected of ["D", "C", "B", "A"]) {+ expect(await history.step("back", you)).toMatchObject({ ok: true });+ expect(read("index.html")).toBe(expected);+ }+ });++ it("a held drag across a write made outside ends at that write too", async () => {+ const { history, write, read } = await project({ "index.html": "A" });+ const drag = (overwrote: string) =>+ history.claim(you, "Dragged Title", ["index.html"], {+ coalesceKey: "drag",+ idleMs: 60_000,+ overwrote: { "index.html": fileContentVersion(overwrote) },+ });+ write("index.html", "B");+ await drag("A");+ write("index.html", "C");+ await history.claim(you, "scan", [], { coalesceKey: "drag" });+ write("index.html", "D");+ await drag("C");+ await history.flush();+ expect(history.list().map((entry) => entry.label)).toEqual([+ "Dragged Title",+ "Changed outside the app",+ "Dragged Title",+ ]);+ for (const expected of ["C", "B", "A"]) {+ expect(await history.step("back", you)).toMatchObject({ ok: true });+ expect(read("index.html")).toBe(expected);+ }+ });++ it("a held drag across an agent turn that already closed ends at the turn too", async () => {+ const { history, write, read } = await project({ "index.html": "A" });+ const drag = (overwrote: string) =>+ history.claim(you, "Dragged Title", ["index.html"], {+ coalesceKey: "drag",+ idleMs: 60_000,+ overwrote: { "index.html": fileContentVersion(overwrote) },+ });+ write("index.html", "B");+ await drag("A");+ const window = await history.beginWindow(agent, "Agent turn");+ write("index.html", "C");+ await window.close();+ write("index.html", "D");+ await drag("C");+ await history.flush();+ for (const expected of ["C", "B", "A"]) {+ expect(await history.step("back", you)).toMatchObject({ ok: true });+ expect(read("index.html")).toBe(expected);+ }+ });++ it("a held drag ends when someone else changed a file it holds, even if its next step writes another", async () => {+ const { history, write, read } = await project({ "index.html": "A", "r.js": "1" });+ const drag = (path: string, overwrote: string) =>+ history.claim(you, "Dragged Title", [path], {+ coalesceKey: "drag",+ idleMs: 60_000,+ overwrote: { [path]: fileContentVersion(overwrote) },+ });+ write("index.html", "B");+ await drag("index.html", "A");+ const window = await history.beginWindow(agent, "Agent turn");+ write("index.html", "C");+ write("r.js", "2");+ await window.close();+ write("r.js", "3");+ await drag("r.js", "2");+ await history.flush();+ for (const expected of [+ ["C", "2"],+ ["B", "1"],+ ["A", "1"],+ ]) {+ expect(await history.step("back", you)).toMatchObject({ ok: true });+ expect([read("index.html"), read("r.js")]).toEqual(expected);+ }+ });++ it("a held drag ends when one file of its next step continues and another does not", async () => {+ const { history, write, read } = await project({ "index.html": "A", "r.js": "1" });+ const drag = (overwrote: Record<string, string>) =>+ history.claim(you, "Dragged Title", Object.keys(overwrote), {+ coalesceKey: "drag",+ idleMs: 60_000,+ overwrote: Object.fromEntries(+ Object.entries(overwrote).map(([path, text]) => [path, fileContentVersion(text)]),+ ),+ });+ write("index.html", "B");+ await drag({ "index.html": "A" });+ write("index.html", "C");+ await history.claim(you, "scan", [], { coalesceKey: "drag" });+ write("index.html", "D");+ write("r.js", "2");+ await drag({ "index.html": "C", "r.js": "1" });+ await history.flush();+ for (const expected of [+ ["C", "1"],+ ["B", "1"],+ ["A", "1"],+ ]) {+ expect(await history.step("back", you)).toMatchObject({ ok: true });+ expect([read("index.html"), read("r.js")]).toEqual(expected);+ }+ });++ it("a held claim that deleted a file ends where someone else recreated it", async () => {+ const { history, write, read, has, projectDir } = await project({ "index.html": "A" });+ const claim = (overwrote: string) =>+ history.claim(you, "Edited", ["index.html"], {+ coalesceKey: "edit",+ idleMs: 60_000,+ overwrote: { "index.html": fileContentVersion(overwrote) },+ });+ rmSync(join(projectDir, "index.html"));+ await claim("A");+ write("index.html", "X");+ await history.claim(you, "scan", [], { coalesceKey: "edit" });+ write("index.html", "Y");+ await claim("X");+ await history.flush();+ await history.step("back", you);+ expect(read("index.html")).toBe("X");+ await history.step("back", you);+ expect(has("index.html")).toBe(false);+ await history.step("back", you);+ expect(read("index.html")).toBe("A");+ });++ it("a drag stays one entry when a file it adds midway was cut from an agent's turn", async () => {+ const { history, write } = await project({ "index.html": "A", "b.js": "1" });+ const window = await history.beginWindow(agent, "Agent turn");+ write("b.js", "2");+ await history.claim(you, "scan", []);+ const drag = (paths: string[], overwrote: Record<string, string>) =>+ history.claim(you, "Dragged Title", paths, {+ coalesceKey: "drag",+ idleMs: 60_000,+ overwrote: Object.fromEntries(+ Object.entries(overwrote).map(([path, text]) => [path, fileContentVersion(text)]),+ ),+ });+ write("index.html", "B");+ await drag(["index.html"], { "index.html": "A" });+ write("index.html", "C");+ write("b.js", "3");+ await drag(["index.html", "b.js"], { "index.html": "B", "b.js": "2" });+ await history.flush();+ await window.close();+ expect(history.list().filter((entry) => entry.label === "Dragged Title")).toHaveLength(1);+ });++ it("a cut takes only the cut file's earlier part out of the turn, so undoing the turn reverts its other files", async () => {+ const { history, write, read } = await project({ "index.html": "A", "b.js": "1" });+ const window = await history.beginWindow(agent, "Agent turn");+ write("index.html", "B");+ write("b.js", "2");+ await history.claim(you, "scan", []);+ write("index.html", "C");+ await history.claim(you, "Moved Title", ["index.html"], {+ overwrote: { "index.html": fileContentVersion("B") },+ });+ write("index.html", "D");+ const turn = await window.close();+ expect(history.list()[0]!.files.map((file) => file.path)).toEqual(["index.html"]);+ expect(turn).toMatchObject({ id: window.id });+ expect(turn!.files.map((file) => file.path)).toEqual(["b.js", "index.html"]);+ expect(await history.undo(turn!.id, { who: agent })).toMatchObject({ ok: true });+ expect([read("index.html"), read("b.js")]).toEqual(["C", "1"]);+ });++ it("Cmd+Z undoes an agent's later write first when a held drag claim commits after the agent's turn", async () => {+ const { history, write, read } = await project({ "index.html": "A" });+ const window = await history.beginWindow(agent, "Agent turn");+ write("index.html", "B");+ await history.claim(you, "sweep", []);+ write("index.html", "C");+ await history.claim(you, "Dragged Title", ["index.html"], {+ coalesceKey: "drag",+ idleMs: 60_000,+ overwrote: { "index.html": fileContentVersion("B") },+ });+ write("index.html", "D");+ await window.close();+ await history.flush();+ expect(history.list().map((entry) => entry.label)).toEqual([+ "Agent turn",+ "Agent turn",+ "Dragged Title",+ ]);+ expect(history.next("back")?.label, "the button names the step Cmd+Z takes").toBe("Agent turn");+ for (const expected of ["C", "B", "A"]) {+ expect(await history.step("back", you)).toMatchObject({ ok: true });+ expect(read("index.html")).toBe(expected);+ }+ });++ it("logs an entry with only its own fields, not its window's timer", async () => {+ const { history, write } = await project({ "index.html": "A" });+ const window = await history.beginWindow(agent, "Agent turn");+ write("index.html", "B");+ await window.close();+ expect(Object.keys(history.list()[0]!).sort()).toEqual([+ "endedAt",+ "files",+ "id",+ "label",+ "pinned",+ "startedAt",+ "undone",+ "who",+ ]);+ });++ it("takes Studio's write out of an agent's open window, and leaves the agent's own writes there", async () => {+ const { history, write } = await project({ "index.html": "A", "a.js": "1" });+ const window = await history.beginWindow(agent, "Agent turn");+ write("a.js", "2");+ write("index.html", "B");+ const claimed = await history.claim(you, "Moved Title", ["index.html"]);+ const entry = await window.close();+ expect(claimed).not.toBeNull();+ expect(entry?.files.map((file) => file.path)).toEqual(["a.js"]);+ expect(history.list().find((item) => item.id === claimed!.id)?.files).toMatchObject([+ { path: "index.html" },+ ]);+ });++ it("a claim under another key that takes nothing still ends the held one", async () => {+ const { history, write } = await project({ "index.html": "A" });+ write("index.html", "B");+ await history.claim(you, "Dragged Title", ["index.html"], { coalesceKey: "drag" });+ expect(+ await history.claim(you, "Nothing", ["index.html"], { coalesceKey: "other" }),+ ).toBeNull();+ expect(history.list()).toMatchObject([{ label: "Dragged Title" }]);+ });++ it("reads no blob outside its store", async () => {+ const { history } = await project({ "index.html": "A" });+ await expect(history.readBlob("../../../../../../../../etc/hostname")).rejects.toThrow(+ "not a history blob",+ );+ });+it("a claim with another key, or its idle time, ends the coalescing claim", async () => {const { history, write } = await project({ "a.html": "A", "b.html": "B" });write("a.html", "A2");diff --git a/packages/studio-server/src/history/projectHistory.ts b/packages/studio-server/src/history/projectHistory.tsindex 3668ca6b1e..bb982aacab 100644--- a/packages/studio-server/src/history/projectHistory.ts+++ b/packages/studio-server/src/history/projectHistory.ts@@ -1,8 +1,15 @@import { randomUUID } from "node:crypto";import { rm } from "node:fs/promises";import { existsSync, mkdirSync, readFileSync } from "node:fs";+import { homedir } from "node:os";import { join, relative, resolve, sep } from "node:path";import { replaceFileAtomically } from "../helpers/atomicFile.js";+import {+ DELETED_VERSION,+ hashOfVersion,+ hashVersion,+ recordFileWriteReceipt,+} from "../helpers/fileVersion.js";import { affectsProjectSignature, listProjectFiles } from "../helpers/projectSignature.js";import { openBlobStore, type BlobStore } from "./blobStore.js";import { projectHistoryId } from "./historyId.js";@@ -23,6 +30,9 @@ import {type Manifest,} from "./historyLog.js";+/** Where hosts keep project histories unless told otherwise: outside every project, so no tidy-up takes one away. */+export const DEFAULT_HISTORY_ROOT = join(homedir(), ".cache", "hyperframes", "history");+export interface ProjectHistoryOptions {projectDir: string;/** Kept outside the project, so nothing tidying the project can take its history with it. */@@ -38,6 +48,17 @@ export interface ProjectHistoryOptions {onError?: (error: unknown) => void;}+interface ClaimOptions {+ coalesceKey?: string;+ idleMs?: number;+ /** Per path, the version (fileContentVersion) the claimer overwrote: earlier changes stay their writer's. */+ overwrote?: Readonly<Record<string, string>>;+}++interface Writing {+ writeToken?: string;+}+export interface HistoryListItem extends HistoryEntry {pinned: boolean;undone: boolean;@@ -56,39 +77,38 @@ export interface HistoryWindow {export interface ProjectHistory {readonly projectId: string;- /**- * Writes until close() are this writer's, as one entry whose id is the window's. A window with no write for- * `idleMs` (default maxGroupMs) ends by itself. ponytail: overlapping windows give a write to the newest.- */+ /** Writes until close() are one entry with the window's id; a claim cutting a file out commits that file's part+ * first (fresh id), returned by close() if nothing else remained. Idle windows end; overlaps go to the newest. */beginWindow(who: HistoryWho,label: string,options?: { idleMs?: number },): Promise<HistoryWindow>;/**- * For a writer that records after writing (Studio): takes in every write so far and moves the not yet committed- * outside changes to `paths` into one entry of `who`'s. Claims with the same coalesceKey merge until a claim with- * another key, `idleMs` (default quietMs) without one, or any operation. Null when nothing was claimed, or- * when a coalescing claim's writes net to nothing (a drag back to where it started).+ * For a writer that records after writing (Studio): moves the uncommitted changes to `paths` into one entry of+ * `who`'s, each cut at the `overwrote` version so earlier parts stay their writer's. Same-key claims merge until+ * another key, `idleMs` idle, or any operation. Null when nothing was claimed or a drag nets to nothing.*/claim(who: HistoryWho,label: string,paths: readonly string[],- options?: { coalesceKey?: string; idleMs?: number },+ options?: ClaimOptions,): Promise<{ id: string } | null>;/** A watcher saw `path` change (project-relative or absolute). */noteChange(path: string): void;list(): HistoryListItem[];- /** Cmd+Z (back) and Cmd+Shift+Z (forward), whoever made the change. */- step(direction: "back" | "forward", who: HistoryWho): Promise<HistoryResult>;+ /** Cmd+Z (back) and Cmd+Shift+Z (forward), whoever made the change; `writeToken` labels the writes' echo. */+ step(direction: "back" | "forward", who: HistoryWho, options?: Writing): Promise<HistoryResult>;+ /** The entry the next step reverts, as of the last scan (a step scans first). */+ next(direction: "back" | "forward"): HistoryEntry | undefined;/** A conflict (a file changed since) returns the choice; pass `mode` to take one. */undo(id: string,- options: { who: HistoryWho; mode?: "just-this" | "back-to-before" },+ options: { who: HistoryWho; mode?: "just-this" | "back-to-before" } & Writing,): Promise<HistoryResult>;/** Makes the files equal what they were right after `point` (an entry id, or START). */- restore(point: string, who: HistoryWho): Promise<HistoryEntry | null>;+ restore(point: string, who: HistoryWho, options?: Writing): Promise<HistoryEntry | null>;/** The files at `point` without writing anything: path to hash, read through readBlob. */peek(point: string): Record<string, string> | null;readBlob(hash: string): Promise<Buffer>;@@ -129,6 +149,22 @@ const statKey = (file: { size: number; mtimeMs: number; ctimeMs: number }, swept? "": `${file.size}:${file.mtimeMs}:${file.ctimeMs}`;+const sameWho = (a: HistoryWho, b: HistoryWho) => a.kind === b.kind && a.name === b.name;++/** Cuts a change at the overwritten `at`: [kept before it, claimed after]; `at` unknown or not kept claims all. */+function splitAt(+ change: HistoryFileChange,+ at: string | undefined,+ kept: boolean,+): [HistoryFileChange | null, HistoryFileChange | null] {+ if (at === change.after) return [change, null];+ if (!at || at === change.before || !kept) return [null, change];+ return [+ { ...change, after: at },+ { ...change, before: at },+ ];+}+/** Files one change to a group; a later change to the same path keeps the group's first "before". */function addChange(group: Group, path: string, before: string | null, after: string | null): void {const earlier = group.changes.get(path);@@ -146,6 +182,7 @@ class Engine {outside: Group | null = null;/** A coalescing claim, open until another key, its idle timer, or an operation commits it. */claimed: { group: Group; key: string; timer: NodeJS.Timeout } | null = null;+ writeToken: string | undefined;quietTimer: NodeJS.Timeout | undefined;maxTimer: NodeJS.Timeout | undefined;notedTimer: NodeJS.Timeout | null = null;@@ -274,44 +311,101 @@ class Engine {addChange(window ?? this.outsideGroup(), path, before, after);}- /**- * ponytail: a claim takes every uncommitted outside change to its paths, so another writer's write to the same file- * between Studio's write and its claim (milliseconds) folds into Studio's entry. Per-write tokens would split them.- * A write filed to another writer's open window stays that window's.- */+ /** ponytail: another's write between Studio's write and its sweep folds into Studio's entry (per-write tokens). */async claimNow(who: HistoryWho,label: string,paths: readonly string[],- { coalesceKey, idleMs }: { coalesceKey?: string; idleMs?: number },+ { coalesceKey, idleMs, overwrote = {} }: ClaimOptions,): Promise<{ id: string } | null> {await this.sweep();- const taken = this.takeOutside(paths);- if (!taken.length) return null;- const group = await this.claimGroup(who, label, coalesceKey);+ const { taken, cut } = this.takeClaimed(who, paths, overwrote);+ if (!taken.length) {+ // A claim under another key still ends the held one.+ if (coalesceKey !== this.claimed?.key) await this.commitClaim();+ return null;+ }+ const held = this.heldFor(coalesceKey, taken);+ if (!held) await this.commitClaim();+ await this.commitOlder(cut);+ const group = held ?? this.newGroup(who, label);for (const change of taken) addChange(group, change.path, change.before, change.after);if (coalesceKey) return this.holdClaim(group, coalesceKey, idleMs);const entry = await this.commit(group);return entry && { id: entry.id };}- /** The held claim when the key matches; otherwise it is committed and a new group starts. */- async claimGroup(who: HistoryWho, label: string, key: string | undefined): Promise<Group> {- if (key && this.claimed?.key === key) return this.claimed.group;- await this.commitClaim();- return this.newGroup(who, label);+ async commitOlder(cut: Map<Group, string[]>): Promise<void> {+ if (this.outside) cut.delete(this.outside);+ await this.commitOutside();+ for (const [window, paths] of cut) await this.commitCut(window, paths);}- /** Removes and returns the uncommitted outside changes to `paths` (project-relative or absolute). */- takeOutside(paths: readonly string[]): HistoryFileChange[] {- const outside = this.outside;- if (!outside) return [];- const wanted = new Set(- paths.map((path) => relative(this.dir, resolve(this.dir, path)).split(sep).join("/")),+ /** The held claim `taken` continues: same key, each change starting where the claim's own left off (no one between). */+ heldFor(key: string | undefined, taken: readonly HistoryFileChange[]): Group | null {+ const group = key && this.claimed?.key === key ? this.claimed.group : null;+ const after = (path: string, before: string | null) => {+ const own = group?.changes.get(path);+ return own ? own.after : before;+ };+ const takenPaths = new Set(taken.map((change) => change.path));+ const untouched = (change: HistoryFileChange) =>+ takenPaths.has(change.path) || (this.tracked.get(change.path)?.hash ?? null) === change.after;+ return group &&+ taken.every((change) => after(change.path, change.before) === change.before) &&+ [...group.changes.values()].every(untouched)+ ? group+ : null;+ }++ logPath(path: string): string {+ return relative(this.dir, resolve(this.dir, path)).split(sep).join("/");+ }++ /** Takes `paths`' uncommitted changes from others, cut at what `who` overwrote; `cut`: paths each group keeps. */+ takeClaimed(+ who: HistoryWho,+ paths: readonly string[],+ overwrote: Readonly<Record<string, string>>,+ ): { taken: HistoryFileChange[]; cut: Map<Group, string[]> } {+ const wanted = new Set(paths.map((path) => this.logPath(path)));+ const at = new Map(+ Object.entries(overwrote).map(([path, version]) => [+ this.logPath(path),+ hashOfVersion(version),+ ]),);- const taken = [...outside.changes.values()].filter((change) => wanted.has(change.path));- for (const change of taken) outside.changes.delete(change.path);- return taken;+ const others = this.windows.filter((open) => !sameWho(open.who, who));+ const groups = this.outside ? [this.outside, ...others] : others;+ const taken: HistoryFileChange[] = [];+ const cut = new Map<Group, string[]>();+ for (const group of groups) {+ for (const change of [...group.changes.values()]) {+ if (!wanted.has(change.path)) continue;+ const [kept, claimed] = this.cutOut(group, change, at.get(change.path));+ if (claimed) taken.push(claimed);+ if (kept && claimed) cut.set(group, [...(cut.get(group) ?? []), change.path]);+ }+ }+ return { taken, cut };+ }++ cutOut(group: Group, change: HistoryFileChange, cut: string | undefined) {+ const [kept, claimed] = splitAt(change, cut, cut !== undefined && this.blobs.has(cut));+ group.changes.delete(change.path);+ if (kept) group.changes.set(kept.path, kept);+ return [kept, claimed] as const;+ }++ /** Commits the window's cut `paths` as their own entry, other files staying: a window holds one change per file,+ * so the writer's next write to a cut file would otherwise span the claimer's edit. */+ async commitCut(window: Group, paths: readonly string[]): Promise<void> {+ const part = { ...this.newGroup(window.who, window.label), startedAt: window.startedAt };+ for (const path of paths) {+ part.changes.set(path, window.changes.get(path)!);+ window.changes.delete(path);+ }+ window.entry = await this.commit(part);}holdClaim(@@ -364,9 +458,9 @@ class Engine {async commit(group: Group, extra: Partial<HistoryEntry> = {}): Promise<HistoryEntry | null> {if (!group.changes.size) return null;- const { changes, ...rest } = group;+ const { id, who, label, startedAt, changes } = group;const files = [...changes.values()].sort((a, b) => a.path.localeCompare(b.path));- const entry: HistoryEntry = { ...rest, endedAt: this.now(), files, ...extra };+ const entry: HistoryEntry = { id, who, label, startedAt, endedAt: this.now(), files, ...extra };this.log.entries.push(entry);try {saveRecord(this.logFile, this.log, { type: "entry", entry });@@ -450,7 +544,7 @@ class Engine {if (!this.windows.includes(window)) return window.entry ?? null;clearTimeout(window.idleTimer);this.windows = this.windows.filter((open) => open !== window);- window.entry = await this.commit(window);+ window.entry = (await this.commit(window)) ?? window.entry ?? null;return window.entry;}@@ -473,9 +567,8 @@ class Engine {this.windows.push(group);try {for (const [path, hash] of target) {- if ((this.tracked.get(path)?.hash ?? null) === hash) continue;- if (hash === null) await rm(join(this.dir, path), { force: true });- else await this.blobs.writeTo(hash, join(this.dir, path));+ if ((this.tracked.get(path)?.hash ?? null) !== hash)+ await this.writeProjectFile(path, hash);}await this.sweep();} finally {@@ -484,6 +577,18 @@ class Engine {return this.commit(group, extra);}+ /** Writes one project file (null deletes it), first leaving the running operation's receipt for its echo. */+ async writeProjectFile(path: string, hash: string | null): Promise<void> {+ const absPath = join(this.dir, path);+ const { writeToken } = this;+ if (writeToken) {+ const version = hash === null ? DELETED_VERSION : hashVersion(hash);+ recordFileWriteReceipt(absPath, { path, version, writeToken });+ }+ if (hash === null) await rm(absPath, { force: true });+ else await this.blobs.writeTo(hash, absPath);+ }+entry(id: string): HistoryEntry {const entry = this.log.entries.find((candidate) => candidate.id === id);if (!entry) throw new Error("That change is no longer kept in this project's history.");@@ -502,9 +607,7 @@ class Engine {mode?: "just-this" | "back-to-before",): Promise<HistoryResult> {const entry = this.entry(id);- const changed = entry.files.filter(- (file) => (this.tracked.get(file.path)?.hash ?? null) !== file.after,- );+ const changed = this.movedOn(entry);if (changed.length && !mode) return { ok: false, conflict: this.conflict(entry, changed) };if (mode === "back-to-before") {const index = this.log.entries.indexOf(entry);@@ -521,6 +624,24 @@ class Engine {};}+ movedOn(entry: HistoryEntry): HistoryFileChange[] {+ return entry.files.filter((file) => (this.tracked.get(file.path)?.hash ?? null) !== file.after);+ }++ /** Back reverts the newest change in effect, unless its files moved on under an earlier-ending edit (a held drag+ * committed after an agent's turn): then that edit, if it still applies. */+ next(direction: "back" | "forward"): HistoryEntry | undefined {+ const top = stepTarget(this.log.entries, direction);+ const moved = new Set(top && direction === "back" ? this.movedOn(top).map((f) => f.path) : []);+ if (!top || !moved.size) return top;+ const undone = undoneIds(this.log.entries);+ const under = this.log.entries+ .slice(0, this.log.entries.indexOf(top))+ .reverse()+ .find((e) => !e.undoes && !undone.has(e.id) && e.files.some((f) => moved.has(f.path)));+ return under && !this.movedOn(under).length ? under : top;+ }+conflict(entry: HistoryEntry,changed: HistoryFileChange[],@@ -541,6 +662,19 @@ class Engine {return this.writeAs(who, label, target, { restoredTo: point });}+ /** Settles, then runs `task` with its writes labelled `writeToken`. */+ operation<T>(writeToken: string | undefined, task: () => Promise<T>): Promise<T> {+ return this.queue(async () => {+ await this.settle();+ this.writeToken = writeToken;+ try {+ return await task();+ } finally {+ this.writeToken = undefined;+ }+ });+ }+pointLabel(point: string): string {return point === START ? "the start" : this.entry(point).label;}@@ -561,26 +695,22 @@ class Engine {undone: undone.has(entry.id),}));},- step: (direction, who) =>- this.queue(async () => {- await this.settle();- const target = stepTarget(this.log.entries, direction);+ step: (direction, who, { writeToken } = {}) =>+ this.operation(writeToken, async () => {+ const target = this.next(direction);return target ? this.undoNow(target.id, who) : { ok: true, entry: null };}),- undo: (id, { who, mode }) =>- this.queue(async () => {- await this.settle();- return this.undoNow(id, who, mode);- }),- restore: (point, who) =>- this.queue(async () => {- await this.settle();- return this.restoreNow(point, who, `Restored: ${this.pointLabel(point)}`);- }),+ undo: (id, { who, mode, writeToken }) =>+ this.operation(writeToken, () => this.undoNow(id, who, mode)),+ restore: (point, who, { writeToken } = {}) =>+ this.operation(writeToken, () =>+ this.restoreNow(point, who, `Restored: ${this.pointLabel(point)}`),+ ),peek: (point) => {const files = manifestAt(this.log, point);return files && Object.fromEntries(files);},+ next: (direction) => this.next(direction),readBlob: (hash) => this.blobs.read(hash),pin: (id, pinned) => {this.entry(id);diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.tsindex bfc9ae3529..471f74bea1 100644--- a/packages/studio-server/src/index.ts+++ b/packages/studio-server/src/index.ts@@ -2,6 +2,7 @@ export { createStudioApi } from "./createStudioApi.js";export { createProjectSignature, affectsProjectSignature } from "./helpers/projectSignature.js";export { compositionsAffectedBy } from "./helpers/compositionInputs.js";export {+ DEFAULT_HISTORY_ROOT,openProjectHistory,type ProjectHistory,type ProjectHistoryOptions,@@ -52,6 +53,7 @@ export {consumeFileWriteReceipt,identifyFileWrite,fileContentVersion,+ DELETED_VERSION,settledFileTag,type FileWriteReceipt,} from "./helpers/fileVersion.js";diff --git a/packages/studio-server/src/routes/history.test.ts b/packages/studio-server/src/routes/history.test.tsindex 5e8b1240b3..a2006d610c 100644--- a/packages/studio-server/src/routes/history.test.ts+++ b/packages/studio-server/src/routes/history.test.ts@@ -1,9 +1,10 @@// @vitest-environment node-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";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 type { StudioApiAdapter } from "../types";@@ -26,10 +27,10 @@ function apiFor(projectDir: string, history?: ProjectHistory) {...(history && { history: () => history }),} as unknown as StudioApiAdapter;const api = createStudioApi(adapter);- return (path: string, body?: object) =>+ return (path: string, body?: object, headers?: Record<string, string>) =>api.request(`/projects/demo/history${path}`,- body ? { method: "POST", body: JSON.stringify(body) } : undefined,+ body ? { method: "POST", body: JSON.stringify(body), headers } : undefined,);}@@ -42,7 +43,7 @@ async function demoProject() {historyRoot: tempDir("hf-history-routes-root-"),});cleanup.push(() => history.close());- return { projectDir, call: apiFor(projectDir, history) };+ return { projectDir, history, call: apiFor(projectDir, history) };}describe("history routes", () => {@@ -79,6 +80,67 @@ describe("history routes", () => {});});+ it("name the step the engine takes when it steps past an entry whose file moved on", async () => {+ const { projectDir, history, call } = await demoProject();+ const write = (text: string) => writeFileSync(join(projectDir, "index.html"), text);+ const agent = { kind: "agent" as const, name: "Agent" };+ const you = { kind: "person" as const, name: "You" };+ const window = await history.beginWindow(agent, "Agent turn");+ write("B");+ await history.claim(you, "sweep", []);+ write("C");+ await history.claim(you, "Dragged Title", ["index.html"], {+ coalesceKey: "drag",+ idleMs: 60_000,+ overwrote: { "index.html": fileContentVersion("B") },+ });+ write("D");+ await window.close();+ await history.flush();+ expect((await (await call("")).json()).back).toMatchObject({ label: "Agent turn" });+ });++ it("label an undo's writes with Studio's write token, so their echo reads as Studio's own", async () => {+ const { projectDir, call } = await demoProject();+ writeFileSync(join(projectDir, "index.html"), "B");+ await call("/claim", { label: "Moved Title", paths: ["index.html"] });+ await call("/step", { direction: "back" }, { "X-Hyperframes-Write-Token": "studio-1" });+ expect(readFileSync(join(projectDir, "index.html"), "utf8")).toBe("A");+ expect(+ identifyFileWrite(join(projectDir, "index.html"), fileContentVersion("A")),+ ).toMatchObject({+ path: "index.html",+ writeToken: "studio-1",+ });+ });++ it("label a deletion an undo makes with Studio's write token too", async () => {+ const { projectDir, call } = await demoProject();+ writeFileSync(join(projectDir, "extra.html"), "added");+ await call("/claim", { label: "Added a section", paths: ["extra.html"] });+ await call("/step", { direction: "back" }, { "X-Hyperframes-Write-Token": "studio-2" });+ expect(existsSync(join(projectDir, "extra.html"))).toBe(false);+ expect(identifyFileWrite(join(projectDir, "extra.html"), DELETED_VERSION)).toMatchObject({+ writeToken: "studio-2",+ });+ });++ it("cap a window's idle time at ten minutes, and pass the version Studio overwrote to its claim", async () => {+ const { history, call } = await demoProject();+ const beginWindow = vi.spyOn(history, "beginWindow");+ const claim = vi.spyOn(history, "claim");+ await call("/window", { label: "Dragged", idleMs: 1e12 });+ expect(beginWindow).toHaveBeenCalledWith(expect.anything(), "Dragged", { idleMs: 600_000 });+ await call("/claim", {+ label: "Moved",+ paths: ["index.html"],+ overwrote: { "index.html": "v", x: 1 },+ });+ expect(claim).toHaveBeenCalledWith(expect.anything(), "Moved", ["index.html"], {+ overwrote: { "index.html": "v" },+ });+ });+it("claim what Studio just wrote as the person's entry, under the edit's label", async () => {const { projectDir, call } = await demoProject();writeFileSync(join(projectDir, "index.html"), "B");diff --git a/packages/studio-server/src/routes/history.ts b/packages/studio-server/src/routes/history.tsindex f4f7e7f1d5..73692e79b1 100644--- a/packages/studio-server/src/routes/history.ts+++ b/packages/studio-server/src/routes/history.ts@@ -1,7 +1,8 @@import type { Context, Hono } from "hono";import type { StudioApiAdapter } from "../types.js";+import { createWriteToken } from "../helpers/fileVersion.js";import type { HistoryWindow, ProjectHistory } from "../history/projectHistory.js";-import { stepTarget, type HistoryEntry, type HistoryWho } from "../history/historyLog.js";+import type { HistoryWho } from "../history/historyLog.js";const YOU: HistoryWho = { kind: "person", name: "You" };/** No edit waits this long between writes. */@@ -19,6 +20,12 @@ async function bodyOf(c: Context): Promise<Record<string, unknown>> {const text = (value: unknown) => (typeof value === "string" && value ? value : null);+/** Studio's write token, so the watcher's echo of an undo reads as Studio's own write. */+function writing(c: Context): { writeToken?: string } {+ const header = c.req.header("X-Hyperframes-Write-Token");+ return header ? { writeToken: createWriteToken(header) } : {};+}+/** How long a window or a coalescing claim may wait for its next write; past the cap a timer overflows. */function idleOf(body: Record<string, unknown>): number | undefined {const idleMs = body.idleMs;@@ -27,9 +34,18 @@ function idleOf(body: Record<string, unknown>): number | undefined {: undefined;}+/** `{ [path]: version }` from a request body, keeping only string pairs. */+function versionsOf(value: unknown): Record<string, string> | undefined {+ if (!value || typeof value !== "object") return undefined;+ const pairs = Object.entries(value).filter(+ (pair): pair is [string, string] => typeof pair[1] === "string",+ );+ return pairs.length ? Object.fromEntries(pairs) : undefined;+}+/** What Cmd+Z or Cmd+Shift+Z would revert next, so Studio can name it on its buttons. */-function nextStep(entries: readonly HistoryEntry[], direction: "back" | "forward") {- const target = stepTarget(entries, direction);+function nextStep(history: ProjectHistory, direction: "back" | "forward") {+ const target = history.next(direction);if (!target) return null;const paths = target.files.map((file) => file.path);return { id: target.id, label: target.label, endedAt: target.endedAt, paths };@@ -59,23 +75,25 @@ export function registerHistoryRoutes(api: Hono, adapter: StudioApiAdapter): voiapi.get(base, (c) =>withHistory(adapter, c, (history) => {const entries = history.list();- return { entries, back: nextStep(entries, "back"), forward: nextStep(entries, "forward") };+ return { entries, back: nextStep(history, "back"), forward: nextStep(history, "forward") };}),);api.post(`${base}/step`, (c) =>withHistory(adapter, c, (history, body) =>- history.step(body.direction === "forward" ? "forward" : "back", YOU),+ history.step(body.direction === "forward" ? "forward" : "back", YOU, writing(c)),),);api.post(`${base}/undo`, (c) =>withHistory(adapter, c, (history, body) => {const mode =body.mode === "just-this" || body.mode === "back-to-before" ? body.mode : undefined;- return history.undo(text(body.entryId) ?? "", { who: YOU, mode });+ return history.undo(text(body.entryId) ?? "", { who: YOU, mode, ...writing(c) });}),);api.post(`${base}/restore`, (c) =>- withHistory(adapter, c, (history, body) => history.restore(text(body.point) ?? "", YOU)),+ withHistory(adapter, c, (history, body) =>+ history.restore(text(body.point) ?? "", YOU, writing(c)),+ ),);api.get(`${base}/peek/:point`, (c) =>withHistory(adapter, c, (history) => ({ files: history.peek(c.req.param("point")) })),@@ -92,16 +110,17 @@ export function registerHistoryRoutes(api: Hono, adapter: StudioApiAdapter): voiconst paths = Array.isArray(body.paths) ? body.paths.filter((path) => text(path)) : [];const coalesceKey = text(body.coalesceKey) ?? undefined;const idleMs = idleOf(body);+ const overwrote = versionsOf(body.overwrote);const claimed = await history.claim(YOU, text(body.label) ?? "Edited in Studio", paths, {...(coalesceKey && { coalesceKey }),...(idleMs && { idleMs }),+ ...(overwrote && { overwrote }),});return { claimed };}),);api.post(`${base}/window`, (c) =>withHistory(adapter, c, async (history, body) => {- // A drag's burst of writes keeps one window open; it ends itself after idleMs without a write.const idleMs = idleOf(body);const window = await history.beginWindow(YOU,@@ -109,7 +128,7 @@ export function registerHistoryRoutes(api: Hono, adapter: StudioApiAdapter): voiidleMs ? { idleMs } : undefined,);windows.set(window.id, { history, window });- // The window's id is the id of the entry it becomes.+ // The window's id is the id of the entry it becomes (its last one, when a claim cut it).return { windowId: window.id };}),);diff --git a/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.test.tsx b/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.test.tsxindex 51b87b6f43..6f42b84148 100644--- a/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.test.tsx+++ b/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.test.tsx@@ -12,12 +12,6 @@ import {} from "./useCanvasZOrderTimelineMirror";import { makeLifecycleOpsParams } from "../../hooks/elementLifecycleOpsTestUtils";import { mountReactHarness } from "../../hooks/domSelectionTestHarness";-import {- buildEditHistoryEntry,- createEmptyEditHistory,- pushEditHistoryEntry,- type EditHistoryState,-} from "../../utils/editHistory";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -61,45 +55,40 @@ interface HarnessApi {mirror: (input: MirrorZOrderInput) => Promise<boolean>;}+interface RecordedWrite {+ label: string;+ kind: "manual" | "timeline";+ coalesceKey: string;+ after: string;+}+/*** Mount the REAL wiring pair PreviewOverlays composes — handleDomZIndexReorderCommit- * (z persist) + useCanvasZOrderTimelineMirror (lane mirror) — over a shared,- * real editHistory reducer so the undo-fold assertion exercises the actual- * pushEditHistoryEntry coalescing:+ * (z persist) + useCanvasZOrderTimelineMirror (lane mirror). The server (not this+ * test) owns folding two records that share a coalesceKey into one undo entry+ * (projectHistory.ts, "claim: a writer that records after writing"), so this harness+ * only captures what Studio sends on each write:** - the z sink mimics commitDomEditPatchBatches' recordEdit call verbatim* (kind "manual", options.coalesceKey — see useDomEditCommits.ts), and* - the move sink mimics persistTimelineBatchEdit → saveProjectFilesWithHistory* (kind "timeline", the coalesceKey forwarded through onMoveElements — see- * timelineEditingHelpers.ts / studioFileHistory.ts),- *- * with a deterministic clock inside the reducer's 300ms coalesce window.+ * timelineEditingHelpers.ts / studioFileHistory.ts).*/function mountMirrorHarness(history: {- state: EditHistoryState;- now: () => number;fileContent: { current: string };moveCoalesceKeys: string[];+ records: RecordedWrite[];}) {const record = (label: string,kind: "manual" | "timeline",coalesceKey: string,- coalesceMs: number | undefined,+ _coalesceMs: number | undefined,after: string,) => {- const entry = buildEditHistoryEntry({- id: `e-${history.now()}`,- projectId: "p",- label,- kind,- coalesceKey,- coalesceMs,- now: history.now(),- files: { "index.html": { before: history.fileContent.current, after } },- });+ history.records.push({ label, kind, coalesceKey, after });history.fileContent.current = after;- history.state = pushEditHistoryEntry(history.state, entry);};const onMoveElements: TimelineEditCallbacks["onMoveElements"] = (@@ -135,17 +124,10 @@ function mountMirrorHarness(history: {}function makeHistory() {- let tick = 1000;return {- state: createEmptyEditHistory(),- // Deterministic clock: consecutive records land 400ms apart — PAST the- // reducer's default 300ms coalesce window, as in the live flow where the- // mirror is dispatched only after the z persist's server round-trip- // resolves (real network latency exceeds 300ms). The fold must therefore- // ride the gesture's explicit coalesceMs window, not the default.- now: () => (tick += 400),fileContent: { current: "A-original" },moveCoalesceKeys: [] as string[],+ records: [] as RecordedWrite[],};}@@ -208,13 +190,12 @@ describe("useCanvasZOrderTimelineMirror", () => {// The move persist received the EXACT z coalesce key…expect(history.moveCoalesceKeys).toEqual([coalesceKey]);- // …and the real reducer folded the two records into one undo entry spanning- // pre-z "before" → post-move "after". One Cmd+Z reverts both writes.- expect(history.state.undo).toHaveLength(1);- expect(history.state.undo[0].files["index.html"]).toMatchObject({- before: "A-original",- after: "C-move",- });+ // …and both writes carry that SAME non-empty coalesceKey: that is what lets+ // the server (projectHistory.ts) fold them into one undo entry. One Cmd+Z+ // then reverts both writes.+ expect(history.records.map((r) => r.coalesceKey)).toEqual([coalesceKey, coalesceKey]);+ expect(history.records[0]?.after).toBe("B-z");+ expect(history.records[1]?.after).toBe("C-move");// Timeline UI reflects the lane change without a reload: optimistic store update.const t = usePlayerStore.getState().elements.find((e) => e.key === "index.html#t");expect(t?.track).toBe(0);@@ -265,8 +246,10 @@ describe("useCanvasZOrderTimelineMirror", () => {}expect(keys[0]).not.toBe(keys[1]); // fresh key per gesture- // Each gesture folded its own z+move pair, but the two gestures stayed apart.- expect(history.state.undo).toHaveLength(2);+ // Each gesture's z+move pair shares that gesture's own key, so the server folds+ // each pair on its own — but the two gestures never share a key, so they stay apart.+ expect(history.records).toHaveLength(4);+ expect(history.records.map((r) => r.coalesceKey)).toEqual([keys[0], keys[0], keys[1], keys[1]]);expect(history.moveCoalesceKeys).toEqual(keys);});@@ -299,7 +282,7 @@ describe("useCanvasZOrderTimelineMirror", () => {});expect(history.moveCoalesceKeys).toEqual([]); // no lane persist dispatched- expect(history.state.undo).toHaveLength(1); // just the z entry+ expect(history.records).toHaveLength(1); // just the z writeconst t = usePlayerStore.getState().elements.find((e) => e.key === "index.html#t");expect(t?.track).toBe(1); // lane unchanged});diff --git a/packages/studio/src/hooks/useEditHistoryActions.test.tsx b/packages/studio/src/hooks/useEditHistoryActions.test.tsxindex 104d3471c8..93fd878ee0 100644--- a/packages/studio/src/hooks/useEditHistoryActions.test.tsx+++ b/packages/studio/src/hooks/useEditHistoryActions.test.tsx@@ -11,12 +11,15 @@ import { useEditHistoryActions, type EditHistoryHandle } from "./useEditHistoryAlet root: Root | null = null;afterEach(() => act(() => root?.unmount()));-function mount(result: { ok: boolean; reason?: string; label?: string; paths?: string[] }) {+function mount(result: {+ ok: boolean;+ reason?: string;+ message?: string;+ label?: string;+ paths?: string[];+}) {const editHistory = {- undo: vi.fn<EditHistoryHandle["undo"]>(async (cb) => {- if (result.ok) await cb.writeFile("index.html", "before");- return result;- }),+ undo: vi.fn<EditHistoryHandle["undo"]>(async () => result),redo: vi.fn<EditHistoryHandle["redo"]>(async () => result),};const deps = {@@ -42,34 +45,48 @@ function mount(result: { ok: boolean; reason?: string; label?: string; paths?: s}describe("useEditHistoryActions", () => {- it("undo writes through the host writer, resyncs the preview and toasts the label", async () => {- const { deps, actions } = mount({ ok: true, label: "Move clip", paths: ["index.html"] });+ it("undo resyncs the preview and toasts the step as the history names it", async () => {+ const { deps, actions } = mount({ ok: true, label: "Undid: Move clip", paths: ["index.html"] });await act(() => actions.undo());expect(deps.waitForPendingDomEditSaves).toHaveBeenCalled();- expect(deps.writeProjectFile).toHaveBeenCalledWith("index.html", "before");expect(deps.onAfterUndoRedo).toHaveBeenCalled();expect(deps.forceReloadSdkSession).toHaveBeenCalled();expect(deps.syncHistoryPreviewAfterApply).toHaveBeenCalled();- expect(deps.showToast).toHaveBeenCalledWith("Undid Move clip", "info");+ expect(deps.showToast).toHaveBeenCalledWith("Undid: Move clip", "info");});it("redo reports the redone label and skips the SDK reload for other files", async () => {- const { deps, actions } = mount({ ok: true, label: "Split clip", paths: ["other.html"] });+ const { deps, actions } = mount({+ ok: true,+ label: "Redid: Split clip",+ paths: ["other.html"],+ });await act(() => actions.redo());expect(deps.forceReloadSdkSession).not.toHaveBeenCalled();- expect(deps.showToast).toHaveBeenCalledWith("Redid Split clip", "info");+ expect(deps.showToast).toHaveBeenCalledWith("Redid: Split clip", "info");});- it("explains a refused undo when the file changed on disk", async () => {- const { deps, actions } = mount({ ok: false, reason: "content-mismatch" });+ it("names the files that changed since the edit when an undo is refused", async () => {+ const { deps, actions } = mount({+ ok: false,+ reason: "content-mismatch",+ paths: ["index.html"],+ });await act(() => actions.undo());expect(deps.showToast).toHaveBeenCalledWith(- "File changed outside Studio. Undo history was not applied.",+ "Can't undo: index.html changed since that edit.","info",);expect(deps.syncHistoryPreviewAfterApply).not.toHaveBeenCalled();});+ it("says why when the history could not take the step", async () => {+ const { deps, actions } = mount({ ok: false, reason: "failed", message: "disk full" });+ await act(() => actions.undo());+ expect(deps.showToast).toHaveBeenCalledWith("Undo failed: disk full", "error");+ expect(deps.syncHistoryPreviewAfterApply).not.toHaveBeenCalled();+ });+it("waits for pending saves first and reads the motion file through the optional reader", async () => {const { deps, actions } = mount({ ok: true, label: "Move clip", paths: ["index.html"] });const order: string[] = [];diff --git a/packages/studio/src/hooks/useEditHistoryActions.ts b/packages/studio/src/hooks/useEditHistoryActions.tsindex 26efd28c95..dab2ebad7f 100644--- a/packages/studio/src/hooks/useEditHistoryActions.ts+++ b/packages/studio/src/hooks/useEditHistoryActions.ts@@ -6,6 +6,7 @@ import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordininterface HistoryResult {ok: boolean;reason?: string;+ message?: string;label?: string;paths?: string[];/** Per-file restored/previous content, used to soft-apply the preview. */@@ -13,7 +14,6 @@ interface HistoryResult {}interface HistoryFileCallbacks {readFile: (path: string) => Promise<string>;- writeFile: (path: string, content: string) => Promise<void>;serialize?: <T>(paths: readonly string[], task: () => Promise<T>) => Promise<T>;}export interface EditHistoryHandle {@@ -40,7 +40,7 @@ export interface UseEditHistoryActionsOptions {forceReloadSdkSession?: () => void;}-/** Applies one persisted file-history step: the single owner of undo/redo over project files. */+/** Takes one step of the project's history: the single owner of undo/redo over project files. */export function useEditHistoryActions({editHistory,readOptionalProjectFile,@@ -66,15 +66,21 @@ export function useEditHistoryActions({const apply = useCallback(async (direction: "undo" | "redo") => {- const [noun, verb] = direction === "undo" ? ["Undo", "Undid"] : ["Redo", "Redid"];+ const noun = direction === "undo" ? "Undo" : "Redo";await waitForPendingDomEditSaves();const result = await editHistory[direction]({readFile: readHistoryFile,- writeFile: writeProjectFile,serialize: serializeHistoryFiles,});if (!result.ok && result.reason === "content-mismatch") {- showToast(`File changed outside Studio. ${noun} history was not applied.`, "info");+ showToast(+ `Can't ${direction}: ${result.paths?.join(", ")} changed since that edit.`,+ "info",+ );+ return;+ }+ if (!result.ok && result.reason === "failed") {+ showToast(`${noun} failed: ${result.message}`, "error");return;}if (result.ok && result.label) {@@ -83,7 +89,7 @@ export function useEditHistoryActions({forceReloadSdkSession?.();}await syncHistoryPreviewAfterApply({ paths: result.paths, files: result.files });- showToast(`${verb} ${result.label}`, "info");+ showToast(result.label, "info");}},[@@ -92,7 +98,6 @@ export function useEditHistoryActions({showToast,syncHistoryPreviewAfterApply,waitForPendingDomEditSaves,- writeProjectFile,serializeHistoryFiles,onAfterUndoRedo,activeCompPath,diff --git a/packages/studio/src/hooks/usePersistentEditHistory.projectOwnership.test.tsx b/packages/studio/src/hooks/usePersistentEditHistory.projectOwnership.test.tsxdeleted file mode 100644index 3491be5a5b..0000000000--- a/packages/studio/src/hooks/usePersistentEditHistory.projectOwnership.test.tsx+++ /dev/null@@ -1,60 +0,0 @@-// @vitest-environment happy-dom-import { act } from "react";-import { createRoot } from "react-dom/client";-import { describe, expect, it } from "vitest";-import { createMemoryEditHistoryStorage } from "../utils/editHistoryStorage";-import { usePersistentEditHistory } from "./usePersistentEditHistory";--(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;--async function flushAsyncEffects(): Promise<void> {- await act(async () => {- await new Promise((resolve) => setTimeout(resolve, 0));- });-}--describe("usePersistentEditHistory project ownership", () => {- it("rejects a delayed project A recorder after project B becomes active", async () => {- const storage = createMemoryEditHistoryStorage();- const now = () => 100;- const captured: { history: ReturnType<typeof usePersistentEditHistory> | null } = {- history: null,- };-- function Probe({ projectId }: { projectId: string }) {- captured.history = usePersistentEditHistory({ projectId, storage, now });- return null;- }-- const root = createRoot(document.createElement("div"));- await act(async () => root.render(<Probe projectId="project-a" />));- await flushAsyncEffects();- const recordProjectA = captured.history?.recordEdit;- if (!recordProjectA) throw new Error("project A history did not load");-- await act(async () => root.render(<Probe projectId="project-b" />));- await expect(- recordProjectA({- label: "Delayed A edit",- kind: "manual",- files: { "index.html": { before: "A", after: "A2" } },- }),- ).rejects.toThrow("inactive project project-a");- await flushAsyncEffects();-- const recordProjectB = captured.history?.recordEdit;- if (!recordProjectB) throw new Error("project B history did not load");- await act(async () => {- await recordProjectB({- label: "B edit",- kind: "manual",- files: { "index.html": { before: "B", after: "B2" } },- });- });-- expect(await storage.get("project-a")).toBeNull();- expect((await storage.get("project-b"))?.undo.map((entry) => entry.label)).toEqual(["B edit"]);-- await act(async () => root.unmount());- });-});diff --git a/packages/studio/src/hooks/usePersistentEditHistory.test.ts b/packages/studio/src/hooks/usePersistentEditHistory.test.tsindex 76c9a8b549..eb8b0e8a2c 100644--- a/packages/studio/src/hooks/usePersistentEditHistory.test.ts+++ b/packages/studio/src/hooks/usePersistentEditHistory.test.ts@@ -1,337 +1,250 @@-import { describe, expect, it, vi } from "vitest";-import { createEmptyEditHistory } from "../utils/editHistory";-import type { EditHistoryStorageAdapter } from "../utils/editHistoryStorage";-import { createMemoryEditHistoryStorage } from "../utils/editHistoryStorage";+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot } from "react-dom/client";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, expect, it, vi } from "vitest";import {- serializeStudioFileMutation,- serializeStudioFileMutations,-} from "../utils/studioFileMutationCoordinator";-import {- createPersistentEditHistoryController,- createPersistentEditHistoryStore,-} from "./usePersistentEditHistory";--describe("createPersistentEditHistoryController", () => {- it("records history and reloads it for the same project", async () => {- const storage = createMemoryEditHistoryStorage();- const first = await createPersistentEditHistoryController({- projectId: "project-1",- storage,- now: () => 100,- onChange: () => {},- });-- await first.recordEdit({- label: "Move layer",- kind: "manual",- files: { "index.html": { before: "a", after: "b" } },- });-- const second = await createPersistentEditHistoryController({- projectId: "project-1",- storage,- now: () => 200,- onChange: () => {},- });+ createStudioApi,+ fileContentVersion,+ identifyFileWrite,+ openProjectHistory,+ type StudioApiAdapter,+} from "@hyperframes/studio-server";+import { consumeStudioWriteToken } from "../utils/studioFileVersion";+import { usePersistentEditHistory } from "./usePersistentEditHistory";++const cleanup: Array<() => unknown> = [];++afterEach(async () => {+ for (const step of cleanup.splice(0).reverse()) await step();+ vi.unstubAllGlobals();+});- expect(second.snapshot().canUndo).toBe(true);- expect(second.snapshot().undoLabel).toBe("Move layer");- expect(second.snapshot().undoPaths).toEqual(["index.html"]);+function tempDir(prefix: string): string {+ const dir = mkdtempSync(join(tmpdir(), prefix));+ cleanup.push(() => rmSync(dir, { recursive: true, force: true }));+ return dir;+}++/** The hook over the real history routes and engine, on a project whose index.html reads "A". */+async function studio({ withHistory = true } = {}) {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ const dir = tempDir("hf-studio-history-");+ writeFileSync(join(dir, "index.html"), "A");+ const history = await openProjectHistory({+ projectDir: dir,+ historyRoot: tempDir("hf-studio-history-root-"),});-- it("undo applies files through the provided callback and persists redo state", async () => {- const storage = createMemoryEditHistoryStorage();- const controller = await createPersistentEditHistoryController({- projectId: "project-1",- storage,- now: () => 100,- onChange: () => {},- });- await controller.recordEdit({- label: "Move layer",+ cleanup.push(() => history.close());+ const api = createStudioApi({+ listProjects: () => [],+ resolveProject: (id: string) => (id === "demo" ? { id, dir } : null),+ ...(withHistory && { history: () => history }),+ } as unknown as StudioApiAdapter);+ vi.stubGlobal("fetch", (url: string, init?: RequestInit) =>+ api.request(url.replace(/^\/api/, ""), init),+ );+ let hook!: ReturnType<typeof usePersistentEditHistory>;+ function Harness() {+ hook = usePersistentEditHistory({ projectId: "demo" });+ return null;+ }+ const root = createRoot(document.createElement("div"));+ await act(async () => root.render(createElement(Harness)));+ cleanup.push(() => act(() => root.unmount()));+ const file = () => readFileSync(join(dir, "index.html"), "utf8");+ const save = (content: string) => writeFileSync(join(dir, "index.html"), content);+ const readFile = async (path: string) => readFileSync(join(dir, path), "utf8");+ return { dir, hook: () => hook, file, save, readFile };+}++it("an edit Studio saved is undone and redone by the project's history, with the preview's before and after", async () => {+ const { hook, file, save, readFile } = await studio();+ save("B");+ await act(() =>+ hook().recordEdit({+ label: "Moved Title",kind: "manual",- files: { "index.html": { before: "a", after: "b" } },- });-- const result = await controller.undo({- readFile: async (path) => {- expect(path).toBe("index.html");- return "b";- },- writeFile: async (path, content) => {- expect(path).toBe("index.html");- expect(content).toBe("a");- },- });- expect(result.ok).toBe(true);- expect(result.paths).toEqual(["index.html"]);-- expect(controller.snapshot().canUndo).toBe(false);- expect(controller.snapshot().canRedo).toBe(true);- expect(controller.snapshot().redoPaths).toEqual(["index.html"]);+ files: { "index.html": { before: "A", after: "B" } },+ }),+ );+ await vi.waitFor(() => expect(hook().undoLabel).toBe("Moved Title"));++ const undone = await act(() => hook().undo({ readFile }));+ expect(undone).toEqual({+ ok: true,+ label: "Undid: Moved Title",+ paths: ["index.html"],+ files: { "index.html": { previous: "B", restored: "A" } },});+ expect(file()).toBe("A");- it("keeps in-memory history when storage saves fail", async () => {- const storage: EditHistoryStorageAdapter = {- async get() {- return null;- },- async set() {- throw new Error("IndexedDB unavailable");- },- async delete() {},- };- const controller = await createPersistentEditHistoryController({- projectId: "project-1",- storage,- now: () => 100,- onChange: () => {},- });-- await expect(- controller.recordEdit({- label: "Move layer",- kind: "manual",- files: { "index.html": { before: "a", after: "b" } },- }),- ).resolves.toBeUndefined();-- expect(controller.snapshot().canUndo).toBe(true);- });-- it("serializes concurrent record edits against the latest state", async () => {- const storage = createMemoryEditHistoryStorage();- let timestamp = 100;- const store = createPersistentEditHistoryStore({- projectId: "project-1",- storage,- initialState: createEmptyEditHistory(),- now: () => timestamp++,- onChange: () => {},- });+ await vi.waitFor(() => expect(hook().canRedo).toBe(true));+ const redone = await act(() => hook().redo({ readFile }));+ expect(redone).toMatchObject({ ok: true, label: "Redid: Moved Title" });+ expect(file()).toBe("B");+});- await Promise.all([- store.recordEdit({- label: "Move layer",- kind: "manual",- files: { "index.html": { before: "a", after: "b" } },- }),- store.recordEdit({- label: "Resize layer",+it("a drag's edits under one key undo as one step, even before the drag goes idle", async () => {+ const { hook, file, save, readFile } = await studio();+ const writes: Array<[before: string, after: string]> = [+ ["A", "B"],+ ["B", "C"],+ ];+ for (const [before, after] of writes) {+ save(after);+ await act(() =>+ hook().recordEdit({+ label: "Dragged Title",kind: "manual",- files: { "index.html": { before: "b", after: "c" } },+ coalesceKey: "drag",+ coalesceMs: 60_000,+ files: { "index.html": { before, after } },}),- ]);-- expect(store.snapshot().state.undo.map((entry) => entry.label)).toEqual([- "Move layer",- "Resize layer",- ]);- });-- it("still coalesces concurrent source edits that share a coalesce key", async () => {- const storage = createMemoryEditHistoryStorage();- let timestamp = 100;- const store = createPersistentEditHistoryStore({- projectId: "project-1",- storage,- initialState: createEmptyEditHistory(),- now: () => timestamp++,- onChange: () => {},- });-- await Promise.all([- store.recordEdit({- label: "Edit source",- kind: "source",- coalesceKey: "source:index.html",- files: { "index.html": { before: "a", after: "b" } },- }),- store.recordEdit({- label: "Edit source",- kind: "source",- coalesceKey: "source:index.html",- files: { "index.html": { before: "b", after: "c" } },- }),- ]);-- expect(store.snapshot().state.undo).toHaveLength(1);- expect(store.snapshot().state.undo[0].files["index.html"].before).toBe("a");- expect(store.snapshot().state.undo[0].files["index.html"].after).toBe("c");+ );+ }+ // The held drag is not in the history's list yet: only its own paths say what to read before the step.+ expect(hook().undoLabel).toBeUndefined();+ const undone = await act(() => hook().undo({ readFile }));+ expect(undone).toMatchObject({+ ok: true,+ label: "Undid: Dragged Title",+ files: { "index.html": { previous: "C", restored: "A" } },});+ expect(file()).toBe("A");+});- it("reads undo hashes from the live top entry during queued undo calls", async () => {- const storage = createMemoryEditHistoryStorage();- let timestamp = 100;- const store = createPersistentEditHistoryStore({- projectId: "project-1",- storage,- initialState: createEmptyEditHistory(),- now: () => timestamp++,- onChange: () => {},- });- await store.recordEdit({- label: "Edit first file",+it("an agent's edit made seconds before Studio's stays the agent's: Cmd+Z undoes only Studio's", async () => {+ const { hook, file, save, readFile } = await studio();+ save("B");+ await act(() => hook().recordEdit({ label: "sweep", kind: "manual", files: {} }));+ save("C");+ await act(() =>+ hook().recordEdit({+ label: "Moved Title",kind: "manual",- files: { "first.html": { before: "first-before", after: "first-after" } },- });- await store.recordEdit({- label: "Edit second file",- kind: "manual",- files: { "second.html": { before: "second-before", after: "second-after" } },- });-- const files: Record<string, string> = {- "first.html": "first-after",- "second.html": "second-after",- };- const readPaths: string[] = [];-- await Promise.all([- store.undo({- readFile: async (path) => {- readPaths.push(path);- return files[path];- },- writeFile: async (path, content) => {- files[path] = content;- },- }),- store.undo({- readFile: async (path) => {- readPaths.push(path);- return files[path];- },- writeFile: async (path, content) => {- files[path] = content;- },- }),- ]);-- expect(readPaths).toEqual(["second.html", "first.html"]);- expect(files).toEqual({- "first.html": "first-before",- "second.html": "second-before",- });- expect(store.snapshot().canUndo).toBe(false);- expect(store.snapshot().canRedo).toBe(true);- });+ files: { "index.html": { before: "B", after: "C" } },+ }),+ );+ expect(await act(() => hook().undo({ readFile }))).toMatchObject({ label: "Undid: Moved Title" });+ expect(file()).toBe("B");+});- it("waits for same-file mutations before checking an undo hash", async () => {- const storage = createMemoryEditHistoryStorage();- const store = createPersistentEditHistoryStore({- projectId: "project-1",- storage,- initialState: createEmptyEditHistory(),- now: () => 100,- onChange: () => {},- });- await store.recordEdit({- label: "Edit source",- kind: "source",- files: { "index.html": { before: "before", after: "after" } },- });+it("an undo's writes carry the write token Studio marked, so their echo is not read as an outside edit", async () => {+ const { dir, hook, save, readFile } = await studio();+ save("B");+ await act(() =>+ hook().recordEdit({+ label: "Moved Title",+ kind: "manual",+ files: { "index.html": { before: "A", after: "B" } },+ }),+ );+ await act(() => hook().undo({ readFile }));+ const receipt = identifyFileWrite(join(dir, "index.html"), fileContentVersion("A"));+ expect(consumeStudioWriteToken(receipt?.writeToken ?? null)).toBe(true);+});- let disk = "after";- let release!: () => void;- const blocked = new Promise<void>((resolve) => {- release = resolve;- });- const writeFile = vi.fn(async (_path: string, content: string) => {- disk = content;- });- const priorMutation = serializeStudioFileMutation(writeFile, "index.html", async () => {- await blocked;- disk = "newer-edit";- });- const readFile = vi.fn(async () => disk);- const undo = store.undo({- readFile,- writeFile,- serialize: (paths, task) => serializeStudioFileMutations(writeFile, paths, task),- });+it("without a history on the server an edit still saves, and there is nothing to undo", async () => {+ const { hook, file, save, readFile } = await studio({ withHistory: false });+ save("B");+ await act(() =>+ hook().recordEdit({+ label: "Moved Title",+ kind: "manual",+ files: { "index.html": { before: "A", after: "B" } },+ }),+ );+ expect(hook().canUndo).toBe(false);+ expect(await act(() => hook().undo({ readFile }))).toEqual({ ok: false, reason: "empty" });+ expect(file()).toBe("B");+});- await Promise.resolve();- expect(readFile).not.toHaveBeenCalled();- release();- await priorMutation;- await expect(undo).resolves.toMatchObject({ ok: false, reason: "content-mismatch" });- expect(disk).toBe("newer-edit");- expect(writeFile).not.toHaveBeenCalled();- expect(store.snapshot().canUndo).toBe(true);+/** Answers requests to `route` with `reply` instead of the engine, every other request as before; returns the undo. */+function answer(route: "/history/step" | "/history/claim", status: number, reply: object | string) {+ const real = globalThis.fetch;+ vi.stubGlobal("fetch", (url: string, init?: RequestInit) =>+ url.endsWith(route)+ ? Promise.resolve(+ new Response(typeof reply === "string" ? reply : JSON.stringify(reply), { status }),+ )+ : real(url, init),+ );+ return () => vi.stubGlobal("fetch", real);+}++it("a step the server could not take says why, instead of reading as nothing to undo", async () => {+ const { hook, readFile } = await studio();+ answer("/history/step", 500, { error: "disk full" });+ expect(await act(() => hook().undo({ readFile }))).toEqual({+ ok: false,+ reason: "failed",+ message: "disk full",});+});- it("returns per-file restored/previous content so the preview can soft-apply", async () => {- const storage = createMemoryEditHistoryStorage();- const store = createPersistentEditHistoryStore({- projectId: "project-1",- storage,- initialState: createEmptyEditHistory(),- now: () => 100,- onChange: () => {},- });- await store.recordEdit({- label: "Move layer",+it("a refused step names the files that changed since its edit", async () => {+ const { hook, save, readFile } = await studio();+ save("B");+ await act(() =>+ hook().recordEdit({+ label: "Moved Title",kind: "manual",- files: { "index.html": { before: "OLD", after: "NEW" } },- });- const disk: Record<string, string> = { "index.html": "NEW" };- const undo = await store.undo({- readFile: async (p) => disk[p],- writeFile: async (p, c) => {- disk[p] = c;- },- });- // `restored` = bytes written (the undo target), `previous` = the current live bytes.- expect(undo.files).toEqual({ "index.html": { previous: "NEW", restored: "OLD" } });-- const redo = await store.redo({- readFile: async (p) => disk[p],- writeFile: async (p, c) => {- disk[p] = c;- },- });- expect(redo.files).toEqual({ "index.html": { previous: "OLD", restored: "NEW" } });+ files: { "index.html": { before: "A", after: "B" } },+ }),+ );+ await vi.waitFor(() => expect(hook().undoLabel).toBe("Moved Title"));+ answer("/history/step", 200, { ok: false, conflict: { files: ["index.html"], newer: [] } });+ expect(await act(() => hook().undo({ readFile }))).toEqual({+ ok: false,+ reason: "content-mismatch",+ paths: ["index.html"],});+});- it("rolls back files when an undo write fails partway through", async () => {- const storage = createMemoryEditHistoryStorage();- const store = createPersistentEditHistoryStore({- projectId: "project-1",- storage,- initialState: createEmptyEditHistory(),- now: () => 100,- onChange: () => {},- });- await store.recordEdit({- label: "Edit files",+it("a claim the server refused is logged, and the write stays undoable as a change made outside", async () => {+ const { hook, file, save, readFile } = await studio();+ const logged = vi.spyOn(console, "error").mockImplementation(() => {});+ cleanup.push(() => logged.mockRestore());+ const restoreFetch = answer("/history/claim", 500, { error: "disk full" });+ save("B");+ await act(() =>+ hook().recordEdit({+ label: "Moved Title",kind: "manual",- files: {- "first.html": { before: "first-before", after: "first-after" },- "second.html": { before: "second-before", after: "second-after" },- },- });+ files: { "index.html": { before: "A", after: "B" } },+ }),+ );+ expect(logged).toHaveBeenCalledWith('"Moved Title" was not recorded as your edit: disk full');+ restoreFetch();+ expect(await act(() => hook().undo({ readFile }))).toMatchObject({+ ok: true,+ label: "Undid: Changed outside the app",+ });+ expect(file()).toBe("A");+});- const files: Record<string, string> = {- "first.html": "first-after",- "second.html": "second-after",- };- const result = store.undo({- readFile: async (path) => files[path],- writeFile: async (path, content) => {- if (path === "second.html" && content === "second-before") {- throw new Error("write failed");- }- files[path] = content;- },- });+it("a step whose reply cannot be read says so, instead of throwing", async () => {+ const { hook, readFile } = await studio();+ answer("/history/step", 200, "<html>");+ expect(await act(() => hook().undo({ readFile }))).toEqual({+ ok: false,+ reason: "failed",+ message: "The history's reply was unreadable.",+ });+});- await expect(result).rejects.toThrow("write failed");- expect(files).toEqual({- "first.html": "first-after",- "second.html": "second-after",- });- expect(store.snapshot().undoLabel).toBe("Edit files");- expect(store.snapshot().canRedo).toBe(false);+it("a step that cannot reach the server says so", async () => {+ const { hook, readFile } = await studio();+ const real = globalThis.fetch;+ vi.stubGlobal("fetch", (url: string, init?: RequestInit) =>+ url.endsWith("/history/step") ? Promise.reject(new TypeError("fetch failed")) : real(url, init),+ );+ expect(await act(() => hook().undo({ readFile }))).toEqual({+ ok: false,+ reason: "failed",+ message: "Studio could not reach its server.",});});diff --git a/packages/studio/src/hooks/usePersistentEditHistory.ts b/packages/studio/src/hooks/usePersistentEditHistory.tsindex 40d6b893ac..156bafe806 100644--- a/packages/studio/src/hooks/usePersistentEditHistory.ts+++ b/packages/studio/src/hooks/usePersistentEditHistory.ts@@ -1,51 +1,25 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import {- buildEditHistoryEntry,- createEmptyEditHistory,- hashEditHistoryContent,- pushEditHistoryEntry,- redoEditHistory,- undoEditHistory,- type BuildEditHistoryEntryInput,- type EditHistoryEntry,- type EditHistoryKind,- type EditHistoryState,- type EditHistoryTransitionResult,-} from "../utils/editHistory";-import {- createIndexedDbEditHistoryStorage,- loadEditHistoryState,- saveEditHistoryState,- type EditHistoryStorageAdapter,-} from "../utils/editHistoryStorage";+import type { HistoryListItem, HistoryResult } from "@hyperframes/studio-server";+import type { EditHistoryKind } from "../utils/editHistory";+import { studioFileContentVersion, studioWriteHeaders } from "../utils/studioFileVersion";interface RecordEditInput {label: string;kind: EditHistoryKind;coalesceKey?: string;coalesceMs?: number;- files: BuildEditHistoryEntryInput["files"];+ files: Record<string, { before: string; after: string }>;}interface ApplyCallbacks {readFile: (path: string) => Promise<string>;- writeFile: (path: string, content: string) => Promise<void>;serialize?: <T>(paths: readonly string[], task: () => Promise<T>) => Promise<T>;}export interface UsePersistentEditHistoryOptions {projectId: string | null;- storage?: EditHistoryStorageAdapter;- now?: () => number;}-/**- * Per-file content the restore just applied. `restored` is the bytes written to- * disk (the undo/redo target); `previous` is what was on disk immediately before- * (the current live preview state). The undo preview-sync diffs these to decide- * whether the restore is soft-reloadable (attributes/style/GSAP-script only) or- * needs a full iframe reload.- */interface ApplyRestoredFile {previous: string;restored: string;@@ -53,357 +27,198 @@ interface ApplyRestoredFile {interface ApplyResult {ok: boolean;- reason?: "empty" | "content-mismatch";+ /** content-mismatch: `paths` changed after the step's entry. failed: `message` says why. */+ reason?: "empty" | "content-mismatch" | "failed";+ message?: string;label?: string;paths?: string[];files?: Record<string, ApplyRestoredFile>;}-interface PersistentEditHistoryStoreOptions {- projectId: string;- storage: EditHistoryStorageAdapter;- initialState: EditHistoryState;- now?: () => number;- onChange: (state: EditHistoryState) => void;+interface NextStep {+ id: string;+ label: string;+ endedAt: number;+ paths: string[];}-type EditHistoryMutation<T> = (state: EditHistoryState) => Promise<{- state: EditHistoryState;- result: T;-}>;--/** Pair the just-written (`restored`) bytes with the pre-write (`previous`) bytes per path. */-function restoredFilesMap(- filesToWrite: Record<string, string>,- currentFiles: Record<string, string>,-): Record<string, ApplyRestoredFile> {- const out: Record<string, ApplyRestoredFile> = {};- for (const [path, restored] of Object.entries(filesToWrite)) {- out[path] = { previous: currentFiles[path] ?? "", restored };- }- return out;+interface HistoryView {+ entries: HistoryListItem[];+ back: NextStep | null;+ forward: NextStep | null;}-function createEntryId(now: number): string {- return `edit-${now.toString(36)}-${Math.random().toString(36).slice(2, 10)}`;+const EMPTY: HistoryView = { entries: [], back: null, forward: null };+const DEFAULT_COALESCE_MS = 300;++function historyUrl(projectId: string, path = ""): string {+ return `/api/projects/${encodeURIComponent(projectId)}/history${path}`;}-function snapshotEditHistoryState(state: EditHistoryState) {- const undoEntry = state.undo[state.undo.length - 1] ?? null;- const redoEntry = state.redo[state.redo.length - 1] ?? null;- return {- canUndo: Boolean(undoEntry),- canRedo: Boolean(redoEntry),- undoLabel: undoEntry?.label ?? null,- redoLabel: redoEntry?.label ?? null,- undoPaths: undoEntry ? Object.keys(undoEntry.files) : [],- redoPaths: redoEntry ? Object.keys(redoEntry.files) : [],- state,- };+async function post(+ url: string,+ body: object,+ headers: Record<string, string> = {},+): Promise<{ ok: true; body: unknown } | { ok: false; status: number; error: string }> {+ const response = await fetch(url, {+ method: "POST",+ headers: { "Content-Type": "application/json", ...headers },+ body: JSON.stringify(body),+ }).catch(() => null);+ if (!response) return { ok: false, status: 0, error: "Studio could not reach its server." };+ const reply = (await response.json().catch(() => null)) as { error?: string } | null;+ if (response.ok && reply) return { ok: true, body: reply };+ if (response.ok)+ return { ok: false, status: response.status, error: "The history's reply was unreadable." };+ return { ok: false, status: response.status, error: reply?.error ?? `HTTP ${response.status}` };}-async function readCurrentFileHashes(- paths: string[],- readFile: (path: string) => Promise<string>,-): Promise<{- currentFiles: Record<string, string>;- currentHashes: Record<string, string>;-}> {- const currentFiles: Record<string, string> = {};- const currentHashes: Record<string, string> = {};- for (const path of paths) {- const content = await readFile(path);- currentFiles[path] = content;- currentHashes[path] = hashEditHistoryContent(content);- }- return { currentFiles, currentHashes };+/** Whether a drag's claim is held open; a failed one is logged (its write lands as an outside change; 404: none). */+function claimHeld(reply: Awaited<ReturnType<typeof post>>, label: string): boolean {+ if (reply.ok) return Boolean((reply.body as { claimed: { id: string } | null } | null)?.claimed);+ if (reply.status !== 404)+ console.error(`"${label}" was not recorded as your edit: ${reply.error}`);+ return false;}-async function writeFilesWithRollback({- files,- rollbackFiles,- writeFile,-}: {- files: Record<string, string>;- rollbackFiles: Record<string, string>;- writeFile: (path: string, content: string) => Promise<void>;-}): Promise<void> {- const writtenPaths: string[] = [];- try {- for (const [path, content] of Object.entries(files)) {- await writeFile(path, content);- writtenPaths.push(path);- }- } catch (error) {- try {- for (const path of writtenPaths.reverse()) {- await writeFile(path, rollbackFiles[path]);- }- } catch (rollbackError) {- throw new AggregateError(- [error, rollbackError],- "Failed to apply edit history and rollback did not complete",- );- }- throw error;- }+async function overwroteVersions(files: RecordEditInput["files"]): Promise<Record<string, string>> {+ const pairs = await Promise.all(+ Object.entries(files).map(async ([path, { before }]) => [+ path,+ await studioFileContentVersion(before),+ ]),+ );+ return Object.fromEntries(pairs);}-/**- * Apply one undo/redo step: read current on-disk hashes, run the direction's- * transition, write the restored files with rollback, and shape the ApplyResult.- * `entry` is the stack top used to know which paths to hash before applying.- */-async function applyHistoryStep(- currentState: EditHistoryState,- entry: EditHistoryEntry | undefined,- transition: (- state: EditHistoryState,- currentHashes: Record<string, string>,- now: number,- ) => EditHistoryTransitionResult,- now: () => number,- callbacks: ApplyCallbacks,-): Promise<{ state: EditHistoryState; result: ApplyResult }> {- if (!entry) {- return { state: currentState, result: { ok: false, reason: "empty" } };+async function readAll(+ paths: readonly string[],+ readFile: (path: string) => Promise<string>,+): Promise<Record<string, string> | null> {+ const contents: Record<string, string> = {};+ for (const path of paths) {+ const content = await readFile(path).catch(() => null);+ if (content === null) return null;+ contents[path] = content;}- const paths = Object.keys(entry.files);- const apply = async (): Promise<{ state: EditHistoryState; result: ApplyResult }> => {- const { currentFiles, currentHashes } = await readCurrentFileHashes(paths, callbacks.readFile);- const result = transition(currentState, currentHashes, now());- if (!result.ok) {- return {- state: currentState,- result: { ok: false, reason: result.reason },- };- }- await writeFilesWithRollback({- files: result.filesToWrite,- rollbackFiles: currentFiles,- writeFile: callbacks.writeFile,- });- return {- state: result.state,- result: {- ok: true,- label: result.entry.label,- paths: Object.keys(result.entry.files),- files: restoredFilesMap(result.filesToWrite, currentFiles),- },- };- };- return callbacks.serialize ? callbacks.serialize(paths, apply) : apply();+ return contents;}-export function createPersistentEditHistoryStore({- projectId,- storage,- initialState,- now = Date.now,- onChange,-}: PersistentEditHistoryStoreOptions) {- let state = initialState;- let queue = Promise.resolve();-- const save = async (nextState: EditHistoryState) => {- state = nextState;- onChange(nextState);- try {- await saveEditHistoryState(storage, projectId, nextState);- } catch {- // Keep in-memory history usable when IndexedDB is unavailable.- }- };-- const mutate = async <T>(mutation: EditHistoryMutation<T>): Promise<T> => {- const run = queue.then(async () => {- const { state: nextState, result } = await mutation(state);- if (nextState !== state) await save(nextState);- return result;- });- queue = run.then(- () => undefined,- () => undefined,- );- return run;- };-- return {- snapshot: () => snapshotEditHistoryState(state),- async recordEdit(input: RecordEditInput) {- await mutate<void>(async (currentState) => {- const timestamp = now();- const entry = buildEditHistoryEntry({- ...input,- id: createEntryId(timestamp),- projectId,- now: timestamp,- });- return {- state: pushEditHistoryEntry(currentState, entry),- result: undefined,- };- });- },- async undo(callbacks: ApplyCallbacks): Promise<ApplyResult> {- return mutate<ApplyResult>((currentState) =>- applyHistoryStep(- currentState,- currentState.undo[currentState.undo.length - 1],- undoEditHistory,- now,- callbacks,- ),- );- },- async redo(callbacks: ApplyCallbacks): Promise<ApplyResult> {- return mutate<ApplyResult>((currentState) =>- applyHistoryStep(- currentState,- currentState.redo[currentState.redo.length - 1],- redoEditHistory,- now,- callbacks,- ),- );- },- };+async function restoredFiles(+ paths: readonly string[],+ previous: Record<string, string> | null,+ readFile: (path: string) => Promise<string>,+): Promise<Record<string, ApplyRestoredFile> | undefined> {+ if (!previous || paths.some((path) => !(path in previous))) return undefined;+ const restored = await readAll(paths, readFile);+ if (!restored) return undefined;+ return Object.fromEntries(+ paths.map((path) => [path, { previous: previous[path]!, restored: restored[path]! }]),+ );}-export async function createPersistentEditHistoryController({- projectId,- storage,- now = Date.now,- onChange,-}: {- projectId: string;- storage: EditHistoryStorageAdapter;- now?: () => number;- onChange: (state: EditHistoryState) => void;-}) {- let state = await loadEditHistoryState(storage, projectId);- const store = createPersistentEditHistoryStore({- projectId,- storage,- initialState: state,- now,- onChange: (nextState) => {- state = nextState;- onChange(nextState);- },- });-- return store;+function redoneAt(view: HistoryView): number | null {+ const undo = view.entries.find((entry) => entry.id === view.forward?.id);+ return view.entries.find((entry) => entry.id === undo?.undoes)?.endedAt ?? null;}-export function usePersistentEditHistory(options: UsePersistentEditHistoryOptions) {- const storage = useMemo(- () => options.storage ?? createIndexedDbEditHistoryStorage(),- [options.storage],- );- const now = options.now ?? Date.now;- const [state, setState] = useState<EditHistoryState>(() => createEmptyEditHistory());+/** Studio's undo over the server's project history: an edit claims what it wrote; Cmd+Z steps every writer's. */+export function usePersistentEditHistory({ projectId }: UsePersistentEditHistoryOptions) {+ const [view, setView] = useState<HistoryView>(EMPTY);const [loaded, setLoaded] = useState(false);- const projectId = options.projectId;- const storeRef = useRef<ReturnType<typeof createPersistentEditHistoryStore> | null>(null);- const storeProjectIdRef = useRef<string | null>(null);- const activeProjectIdRef = useRef(projectId);- activeProjectIdRef.current = projectId;+ // A coalescing claim stays on the server until its drag goes idle, so it is not in `view` yet.+ const heldClaimRef = useRef<{ paths: string[]; at: number } | null>(null);+ const projectIdRef = useRef(projectId);+ projectIdRef.current = projectId;++ const refresh = useCallback(async () => {+ if (!projectId) return;+ const response = await fetch(historyUrl(projectId)).catch(() => null);+ const next = response?.ok ? ((await response.json()) as HistoryView) : EMPTY;+ if (projectIdRef.current === projectId) setView(next);+ }, [projectId]);useEffect(() => {- let cancelled = false;- const emptyState = createEmptyEditHistory();- storeRef.current = null;- storeProjectIdRef.current = null;- setState(emptyState);+ setView(EMPTY);setLoaded(false);- if (!projectId) {- setLoaded(true);- return;- }-- loadEditHistoryState(storage, projectId)- .then((loadedState) => {- if (cancelled) return;- storeRef.current = createPersistentEditHistoryStore({- projectId,- storage,- initialState: loadedState,- now,- onChange: setState,- });- storeProjectIdRef.current = projectId;- setState(loadedState);- })- .catch(() => {- if (cancelled) return;- storeRef.current = createPersistentEditHistoryStore({- projectId,- storage,- initialState: emptyState,- now,- onChange: setState,- });- storeProjectIdRef.current = projectId;- setState(emptyState);- })- .finally(() => {- if (!cancelled) setLoaded(true);- });-- return () => {- cancelled = true;- };- }, [now, projectId, storage]);+ heldClaimRef.current = null;+ void refresh().finally(() => setLoaded(true));+ }, [refresh]);const recordEdit = useCallback(- async (input: RecordEditInput) => {+ async ({ label, coalesceKey, coalesceMs, files }: RecordEditInput) => {if (!projectId) return;- if (activeProjectIdRef.current !== projectId) {- throw new Error(`Cannot record an edit for inactive project ${projectId}`);- }- const store = storeRef.current;- if (!store) return;- if (storeProjectIdRef.current !== projectId) {- throw new Error(`Edit history store does not belong to project ${projectId}`);- }- await store.recordEdit(input);+ const paths = Object.keys(files);+ const reply = await post(historyUrl(projectId, "/claim"), {+ label,+ paths,+ overwrote: await overwroteVersions(files),+ ...(coalesceKey && { coalesceKey, idleMs: coalesceMs ?? DEFAULT_COALESCE_MS }),+ });+ heldClaimRef.current =+ claimHeld(reply, label) && coalesceKey ? { paths, at: Date.now() } : null;+ void refresh();},- [projectId],+ [projectId, refresh],);- const undo = useCallback(- async (callbacks: ApplyCallbacks): Promise<ApplyResult> => {- if (- !projectId ||- activeProjectIdRef.current !== projectId ||- storeProjectIdRef.current !== projectId- ) {- return { ok: false, reason: "empty" };- }- return storeRef.current?.undo(callbacks) ?? { ok: false, reason: "empty" };+ const step = useCallback(+ async (direction: "undo" | "redo", callbacks: ApplyCallbacks): Promise<ApplyResult> => {+ if (!projectId) return { ok: false, reason: "empty" };+ const next = direction === "undo" ? view.back : view.forward;+ const paths = [...new Set([...(next?.paths ?? []), ...(heldClaimRef.current?.paths ?? [])])];+ const run = async (): Promise<ApplyResult> => {+ const previous = await readAll(paths, callbacks.readFile);+ const posted = await post(+ historyUrl(projectId, "/step"),+ { direction: direction === "undo" ? "back" : "forward" },+ studioWriteHeaders(),+ );+ heldClaimRef.current = null;+ void refresh();+ // 404: this app keeps no history, so there is nothing to step.+ if (!posted.ok && posted.status === 404) return { ok: false, reason: "empty" };+ if (!posted.ok) return { ok: false, reason: "failed", message: posted.error };+ const reply = posted.body as HistoryResult;+ if (!reply.ok) {+ const { files } = reply.conflict;+ return { ok: false, reason: "content-mismatch", paths: files };+ }+ if (!reply.entry) return { ok: false, reason: "empty" };+ const changed = reply.entry.files.map((file) => file.path);+ return {+ ok: true,+ label: reply.entry.label,+ paths: changed,+ files: await restoredFiles(changed, previous, callbacks.readFile),+ };+ };+ return callbacks.serialize ? callbacks.serialize(paths, run) : run();},- [projectId],+ [projectId, view, refresh],);- const redo = useCallback(- async (callbacks: ApplyCallbacks): Promise<ApplyResult> => {- if (- !projectId ||- activeProjectIdRef.current !== projectId ||- storeProjectIdRef.current !== projectId- ) {- return { ok: false, reason: "empty" };- }- return storeRef.current?.redo(callbacks) ?? { ok: false, reason: "empty" };- },- [projectId],- );+ const undo = useCallback((callbacks: ApplyCallbacks) => step("undo", callbacks), [step]);+ const redo = useCallback((callbacks: ApplyCallbacks) => step("redo", callbacks), [step]);++ const state = useMemo(() => {+ const backAt = Math.max(view.back?.endedAt ?? 0, heldClaimRef.current?.at ?? 0);+ const redoAt = redoneAt(view);+ return {+ undo: backAt ? [{ createdAt: backAt }] : [],+ redo: redoAt === null ? [] : [{ createdAt: redoAt }],+ };+ }, [view]);return {loaded,- ...snapshotEditHistoryState(state),+ canUndo: Boolean(view.back),+ canRedo: Boolean(view.forward),+ undoLabel: view.back?.label,+ redoLabel: view.forward?.label,+ undoPaths: view.back?.paths ?? [],+ redoPaths: view.forward?.paths ?? [],+ state,recordEdit,undo,redo,diff --git a/packages/studio/src/hooks/useRazorSplit.history.test.tsx b/packages/studio/src/hooks/useRazorSplit.history.test.tsxindex 2665f14bef..548ba01ec8 100644--- a/packages/studio/src/hooks/useRazorSplit.history.test.tsx+++ b/packages/studio/src/hooks/useRazorSplit.history.test.tsx@@ -7,13 +7,7 @@ import { splitElementInHtml } from "@hyperframes/studio-server/source-mutation";import type { TimelineElement } from "../player";import { usePlayerStore } from "../player";import { useRazorSplit } from "./useRazorSplit";-import { createPersistentEditHistoryStore } from "./usePersistentEditHistory";-import { createMemoryEditHistoryStorage } from "../utils/editHistoryStorage";-import {- createEmptyEditHistory,- hashEditHistoryContent,- undoEditHistory,-} from "../utils/editHistory";+import type { RecordEditInput } from "./timelineEditingHelpers";import { createSplitFetchMock, mountProbe } from "./useRazorSplit.testHelpers";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -36,7 +30,10 @@ type SplitAll = (splitTime: number) => Promise<void>;interface Harness {disk: Record<string, string>;- store: ReturnType<typeof createPersistentEditHistoryStore>;+ // What the split recorded — folding, undo and undo mismatch guards are the+ // server's own tested behaviour (projectHistory.ts / projectHistory.test.ts,+ // usePersistentEditHistory.test.ts), not re-proven here via a reducer.+ records: RecordEditInput[];splitRef: { current: Split | undefined };root: ReturnType<typeof mountProbe>;expected: string;@@ -53,18 +50,7 @@ function mountRazorSplit(opts: { gsap?: boolean; previewStamp?: boolean } = {}):const disk: Record<string, string> = { "index.html": ORIGINAL };const finalContent = opts.gsap ? SPLIT_GSAP : SPLIT;const previewWrites: string[] = [];-- const storage = createMemoryEditHistoryStorage();- const store = createPersistentEditHistoryStore({- projectId: "p1",- storage,- initialState: createEmptyEditHistory(),- now: (() => {- let t = 1000;- return () => (t += 10);- })(),- onChange: () => {},- });+ const records: RecordEditInput[] = [];// Faithful stand-in for the atomic server cut: one forward file write and one// response carrying the canonical history snapshots.@@ -115,7 +101,9 @@ function mountRazorSplit(opts: { gsap?: boolean; previewStamp?: boolean } = {}):writeProjectFile: async (path, content) => {disk[path] = content;},- recordEdit: store.recordEdit,+ recordEdit: async (input) => {+ records.push(input);+ },reloadPreview: () => {if (!opts.previewStamp) return;const stamped = ensureHfIds(disk["index.html"]);@@ -134,16 +122,7 @@ function mountRazorSplit(opts: { gsap?: boolean; previewStamp?: boolean } = {}):const root = mountProbe(Component);- return { disk, store, splitRef, root, expected: finalContent, previewWrites };-}--async function undoViaDisk(harness: Pick<Harness, "disk" | "store">) {- return harness.store.undo({- readFile: async (path) => harness.disk[path],- writeFile: async (path, content) => {- harness.disk[path] = content;- },- });+ return { disk, records, splitRef, root, expected: finalContent, previewWrites };}afterEach(() => {@@ -159,15 +138,16 @@ describe("useRazorSplit — split is undoable via edit history", () => {await harness.splitRef.current!(element, 2);});- const snapshot = harness.store.snapshot().state;- const entry = snapshot.undo.at(-1)!;- const currentHash = hashEditHistoryContent(harness.disk["index.html"]);- expect(entry.files["index.html"].afterHash).toBe(currentHash);-- const undo = undoEditHistory(snapshot, { "index.html": currentHash }, 2000);- expect(undo.ok).toBe(true);- expect(undo.filesToWrite).toEqual({ "index.html": ORIGINAL });+ // The preview reload found every id already stamped, so it never made a+ // second, unrecorded write that would leave the recorded entry stale...expect(harness.previewWrites).toHaveLength(0);+ // ...meaning the split's own recorded "after" IS the disk's final content,+ // and undoing it (server-side) would restore exactly the pre-split bytes.+ expect(harness.records).toHaveLength(1);+ expect(harness.records[0]!.files["index.html"]).toEqual({+ before: ORIGINAL,+ after: harness.disk["index.html"],+ });act(() => harness.root.unmount());});@@ -182,7 +162,7 @@ describe("useRazorSplit — split is undoable via edit history", () => {act(() => harness.root.unmount());});- it("records a single 'Split timeline clip' history entry that undo restores", async () => {+ it("records a single 'Split timeline clip' entry with the exact bytes undo restores", async () => {await act(async () => {await harness.splitRef.current!(element, 2);});@@ -190,15 +170,17 @@ describe("useRazorSplit — split is undoable via edit history", () => {// The split reached disk.expect(harness.disk["index.html"]).toBe(harness.expected);- // The split must be the top of the undo stack — not a prior/other entry.- expect(harness.store.snapshot().canUndo).toBe(true);- expect(harness.store.snapshot().undoLabel).toBe("Split timeline clip");-- // Undo restores the exact pre-split file.- const result = await undoViaDisk(harness);- expect(result.ok).toBe(true);- expect(result.label).toBe("Split timeline clip");- expect(harness.disk["index.html"]).toBe(ORIGINAL);+ // Exactly one entry, correctly labeled, carrying the pre/post-split bytes —+ // what a real undo (server-side, projectHistory.ts) restores from.+ expect(harness.records).toHaveLength(1);+ expect(harness.records[0]).toMatchObject({+ label: "Split timeline clip",+ kind: "timeline",+ });+ expect(harness.records[0]!.files["index.html"]).toEqual({+ before: ORIGINAL,+ after: harness.expected,+ });});});}@@ -222,20 +204,14 @@ const batchElements: TimelineElement[] = [interface SplitAllHarness {disk: Record<string, string>;- store: ReturnType<typeof createPersistentEditHistoryStore>;+ records: RecordEditInput[];splitAllRef: { current: SplitAll | undefined };root: ReturnType<typeof mountProbe>;}function mountRazorSplitAll(failOnSplit?: number): SplitAllHarness {const disk: Record<string, string> = { ...BATCH_ORIGINALS };- const store = createPersistentEditHistoryStore({- projectId: "p1",- storage: createMemoryEditHistoryStorage(),- initialState: createEmptyEditHistory(),- now: () => 1000,- onChange: () => {},- });+ const records: RecordEditInput[] = [];let splitCount = 0;vi.stubGlobal(@@ -255,7 +231,9 @@ function mountRazorSplitAll(failOnSplit?: number): SplitAllHarness {writeProjectFile: async (path, content) => {disk[path] = content;},- recordEdit: store.recordEdit,+ recordEdit: async (input) => {+ records.push(input);+ },reloadPreview: () => {},});splitAllRef.current = handleRazorSplitAll;@@ -264,7 +242,7 @@ function mountRazorSplitAll(failOnSplit?: number): SplitAllHarness {const root = mountProbe(Component);usePlayerStore.setState({ elements: batchElements });- return { disk, store, splitAllRef, root };+ return { disk, records, splitAllRef, root };}describe("useRazorSplit — split-all batch history", () => {@@ -280,22 +258,24 @@ describe("useRazorSplit — split-all batch history", () => {return harness;}- it("records one undo entry that restores every split file", async () => {+ it("records one entry whose files cover every split file (one undo restores all of them)", async () => {const harness = await runSplitAll();- expect(harness.store.snapshot().canUndo).toBe(true);- const result = await undoViaDisk(harness);- expect(result.ok).toBe(true);- expect(harness.disk).toEqual(BATCH_ORIGINALS);- expect(harness.store.snapshot().canUndo).toBe(false);+ expect(harness.records).toHaveLength(1);+ const files = harness.records[0]!.files;+ expect(Object.keys(files).sort()).toEqual(Object.keys(BATCH_ORIGINALS).sort());+ for (const path of Object.keys(BATCH_ORIGINALS) as (keyof typeof BATCH_ORIGINALS)[]) {+ expect(files[path]?.before).toBe(BATCH_ORIGINALS[path]);+ expect(files[path]?.after).toBe(harness.disk[path]);+ }act(() => harness.root.unmount());});- it("restores completed writes and records no undo when a later split fails", async () => {+ it("restores completed writes and records no entry when a later split fails", async () => {const harness = await runSplitAll(2);expect(harness.disk).toEqual(BATCH_ORIGINALS);- expect(harness.store.snapshot().canUndo).toBe(false);+ expect(harness.records).toHaveLength(0);act(() => harness.root.unmount());});});diff --git a/packages/studio/src/hooks/useRazorSplit.test.ts b/packages/studio/src/hooks/useRazorSplit.test.tsindex 5d230fabb2..09eca846f4 100644--- a/packages/studio/src/hooks/useRazorSplit.test.ts+++ b/packages/studio/src/hooks/useRazorSplit.test.ts@@ -5,9 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { TimelineElement } from "../player";import { usePlayerStore } from "../player";import { useRazorSplit } from "./useRazorSplit";-import { createPersistentEditHistoryStore } from "./usePersistentEditHistory";-import { createEmptyEditHistory } from "../utils/editHistory";-import type { EditHistoryStorageAdapter } from "../utils/editHistoryStorage";+import type { RecordEditInput } from "./timelineEditingHelpers";import { createSplitFetchMock, mountProbe } from "./useRazorSplit.testHelpers";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -164,20 +162,14 @@ describe("useRazorSplit — sub-comp coordinate rebasing", () => {// ── Bug 1: split must resync the SDK session so undo isn't refused ────────────-const memoryStorage = (): EditHistoryStorageAdapter => {- const store = new Map<string, string>();- return {- load: async (k) => store.get(k) ?? null,- save: async (k, v) => {- store.set(k, v);- },- } as unknown as EditHistoryStorageAdapter;-};-interface UndoHarness {singleRef: { current: SingleSplit | undefined };disk: Record<string, string>;- store: ReturnType<typeof createPersistentEditHistoryStore>;+ // What the split recorded, so the server (projectHistory.ts) could fold and+ // later undo it — recording, folding and undo mismatch guards are the+ // server's own tested behaviour (projectHistory.test.ts,+ // usePersistentEditHistory.test.ts), not re-proven here via a reducer.+ records: RecordEditInput[];forceReloadSdkSession: ReturnType<typeof vi.fn>;root: ReturnType<typeof mountProbe>;}@@ -186,13 +178,7 @@ function mountRazorSplitWithHistory(): UndoHarness {const disk: Record<string, string> = {[ROOT_FILE]: `<div class="clip" id="root-clip" data-start="0" data-duration="10"></div>`,};- const store = createPersistentEditHistoryStore({- projectId: "p1",- storage: memoryStorage(),- initialState: createEmptyEditHistory(),- now: () => Date.now(),- onChange: () => {},- });+ const records: RecordEditInput[] = [];const forceReloadSdkSession = vi.fn();const fetchMock = createSplitFetchMock(disk);@@ -207,7 +193,9 @@ function mountRazorSplitWithHistory(): UndoHarness {writeProjectFile: async (path, content) => {disk[path] = content;},- recordEdit: (input) => store.recordEdit(input),+ recordEdit: async (input) => {+ records.push(input);+ },reloadPreview: () => {},forceReloadSdkSession,});@@ -215,7 +203,7 @@ function mountRazorSplitWithHistory(): UndoHarness {return null;}const root = mountProbe(Component);- return { singleRef, disk, store, forceReloadSdkSession, root };+ return { singleRef, disk, records, forceReloadSdkSession, root };}describe("useRazorSplit — undo integrity after split (Bug 1)", () => {@@ -227,13 +215,6 @@ describe("useRazorSplit — undo integrity after split (Bug 1)", () => {act(() => h.root.unmount());});- const readFile = () => ({- readFile: async (p: string) => h.disk[p],- writeFile: async (p: string, c: string) => {- h.disk[p] = c;- },- });-it("resyncs the SDK session after a split (matches every other server-write path)", async () => {await act(async () => {await h.singleRef.current!(rootElement, 4);@@ -241,25 +222,14 @@ describe("useRazorSplit — undo integrity after split (Bug 1)", () => {expect(h.forceReloadSdkSession).toHaveBeenCalledTimes(1);});- it("applies undo after a split without an external-change refusal", async () => {- await act(async () => {- await h.singleRef.current!(rootElement, 4);- });- const result = await h.store.undo(readFile());- expect(result.ok).toBe(true);- expect(result.reason).toBeUndefined();- // The file is restored to its pre-split bytes.- expect(h.disk[ROOT_FILE]).not.toContain("<!--split-->");- });-- it("still trips the guard when the file is edited externally after a split", async () => {+ it("records the split as one entry whose file carries the exact pre/post-split bytes a real undo restores", async () => {+ const before = h.disk[ROOT_FILE];await act(async () => {await h.singleRef.current!(rootElement, 4);});- // Simulate the user editing the file in their own editor after the split.- h.disk[ROOT_FILE] = `${h.disk[ROOT_FILE]}<!--hand-edit-->`;- const result = await h.store.undo(readFile());- expect(result.ok).toBe(false);- expect(result.reason).toBe("content-mismatch");+ expect(h.disk[ROOT_FILE]).toContain("<!--split-->");+ expect(h.records).toHaveLength(1);+ expect(h.records[0]).toMatchObject({ label: "Split timeline clip" });+ expect(h.records[0]!.files[ROOT_FILE]).toEqual({ before, after: h.disk[ROOT_FILE] });});});diff --git a/packages/studio/src/hooks/useStudioContextValue.ts b/packages/studio/src/hooks/useStudioContextValue.tsindex 783c51d22c..67fd368ef6 100644--- a/packages/studio/src/hooks/useStudioContextValue.ts+++ b/packages/studio/src/hooks/useStudioContextValue.ts@@ -17,7 +17,12 @@ interface StudioContextInput {setRefreshKey: React.Dispatch<React.SetStateAction<number>>;timelineElements: StudioContextValue["timelineElements"];isPlaying: boolean;- editHistory: { canUndo: boolean; canRedo: boolean; undoLabel: string; redoLabel: string };+ editHistory: {+ canUndo: boolean;+ canRedo: boolean;+ undoLabel: string | undefined;+ redoLabel: string | undefined;+ };handleUndo: StudioContextValue["handleUndo"];handleRedo: StudioContextValue["handleRedo"];// Was a second copy of the same shape, which meant every field added to thediff --git a/packages/studio/src/hostMount.test.tsx b/packages/studio/src/hostMount.test.tsxindex 77592f075d..2697d3b593 100644--- a/packages/studio/src/hostMount.test.tsx+++ b/packages/studio/src/hostMount.test.tsx@@ -8,8 +8,15 @@ import { createRoot, type Root } from "react-dom/client";import { afterEach, describe, expect, it, vi } from "vitest";// Backend/storage mocking only, standing in for a host's own server and// persistence — not part of the host's integration code under test.+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import {+ createStudioApi,+ openProjectHistory,+ type StudioApiAdapter,+} from "@hyperframes/studio-server";import { studioFileContentVersion } from "./utils/studioFileVersion";-import { createMemoryEditHistoryStorage } from "./utils/editHistoryStorage";import {flushStudioPendingEdits,useTimelineEditing,@@ -27,45 +34,66 @@ import {const ORIGINAL_HTML = '<div id="clip" data-start="0" data-track-index="0"></div>';let root: Root | null = null;-afterEach(() => {+const cleanups: Array<() => unknown> = [];+afterEach(async () => {act(() => root?.unmount());document.body.innerHTML = "";vi.unstubAllGlobals();+ for (const step of cleanups.splice(0).reverse()) await step();});-/** A minimal disk with etag-guarded PUT, faithful enough to exercise a real- * conflict: a stale If-Match gets a 409 with the current version + content. */-function stubHostProjectDisk(+function tempDir(prefix: string): string {+ const dir = mkdtempSync(join(tmpdir(), prefix));+ cleanups.push(() => rmSync(dir, { recursive: true, force: true }));+ return dir;+}++/** A project folder with etag-guarded PUT, faithful enough to exercise a real+ * conflict: a stale If-Match gets a 409 with the current version + content.+ * History requests go to the real history routes over the real engine. */+async function stubHostProjectDisk(initial: Record<string, string>,options?: { editElsewhereAfterFirstRead?: boolean },) {- const content = { ...initial };+ const dir = tempDir("hf-host-mount-");+ for (const [path, text] of Object.entries(initial)) writeFileSync(join(dir, path), text);+ const history = await openProjectHistory({+ projectDir: dir,+ historyRoot: tempDir("hf-host-mount-history-"),+ });+ cleanups.push(() => history.close());+ const api = createStudioApi({+ listProjects: () => [],+ resolveProject: (id: string) => (id === "p1" ? { id, dir } : null),+ history: () => history,+ } as unknown as StudioApiAdapter);const readsSeen = new Set<string>();+ const read = (path: string) => readFileSync(join(dir, path), "utf8");// The real backend's etag is a content hash (useProjectFileWriter derives// If-Match the same way) — an arbitrary counter here would make every// write from a host that hasn't just read the file look stale.- const versionOf = (path: string) => studioFileContentVersion(content[path]);+ const versionOf = (path: string) => studioFileContentVersion(read(path));async function handlePut(path: string, init: RequestInit | undefined) {const ifMatch = new Headers(init?.headers).get("If-Match");const currentVersion = await versionOf(path);if (ifMatch && ifMatch !== currentVersion) {- return new Response(JSON.stringify({ currentVersion, currentContent: content[path] }), {+ return new Response(JSON.stringify({ currentVersion, currentContent: read(path) }), {status: 409,});}- content[path] = String(init?.body ?? "");+ writeFileSync(join(dir, path), String(init?.body ?? ""));return new Response(JSON.stringify({ version: await versionOf(path) }), { status: 200 });}async function handleGet(path: string) {- const served = content[path];+ const served = read(path);// Simulates another writer landing between this read and the caller's// own write: content moves on right after being served once, so the// caller's hash of what it just read no longer matches disk.if (options?.editElsewhereAfterFirstRead && !readsSeen.has(path)) {readsSeen.add(path);- content[path] = `${served} <!--edited elsewhere-->`;+ writeFileSync(join(dir, path), `${served} <!--edited elsewhere-->`);}return new Response(JSON.stringify({ content: served, version: await studioFileContentVersion(served) }),@@ -74,12 +102,15 @@ function stubHostProjectDisk(}const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {- const match = String(input).match(/\/files\/([^?]+)/);- const path = match ? decodeURIComponent(match[1]) : "";+ const url = String(input);+ if (url.includes("/history")) return api.request(url.replace(/^\/api/, ""), init);+ const match = url.match(/\/files\/([^?]+)/);+ if (!match) return new Response("{}", { status: 404 });+ const path = decodeURIComponent(match[1]);return (init?.method ?? "GET") === "PUT" ? handlePut(path, init) : handleGet(path);});vi.stubGlobal("fetch", fetchMock);- return { content, fetchMock };+ return { read, fetchMock };}type TimelineEditingHandle = {@@ -108,13 +139,10 @@ function mountHost(const bannerHost = document.createElement("div");document.body.append(bannerHost);const bannerRoot = createRoot(bannerHost);- // Created once: a fresh storage object on every render would change- // usePersistentEditHistory's effect deps each time and loop forever.- const storage = createMemoryEditHistoryStorage();function Harness() {const writer = useProjectFileWriter({ projectId: "p1" });- const editHistory = usePersistentEditHistory({ projectId: "p1", storage });+ const editHistory = usePersistentEditHistory({ projectId: "p1" });const historyActions = useEditHistoryActions({editHistory,readOptionalProjectFile: writer.readOptionalProjectFile,@@ -170,7 +198,7 @@ function mountHost(describe("public export surface: a host mounting hand editing outside EditorShell", () => {it("writes a move through the history path and undo restores it", async () => {- const disk = stubHostProjectDisk({ "index.html": ORIGINAL_HTML });+ const disk = await stubHostProjectDisk({ "index.html": ORIGINAL_HTML });const iframe = document.createElement("iframe");document.body.append(iframe);iframe.contentDocument!.body.innerHTML = ORIGINAL_HTML;@@ -187,16 +215,19 @@ describe("public export surface: a host mounting hand editing outside EditorShelawait act(async () => {await timelineEditing.handleTimelineElementMove(clip, { start: 5, track: 0 });});- expect(disk.content["index.html"]).toContain('data-start="5"');+ expect(disk.read("index.html")).toContain('data-start="5"');await act(async () => {await undo();});- expect(disk.content["index.html"]).toContain('data-start="0"');+ expect(disk.read("index.html")).toContain('data-start="0"');});it("surfaces the conflict banner on a 409", async () => {- stubHostProjectDisk({ "index.html": ORIGINAL_HTML }, { editElsewhereAfterFirstRead: true });+ await stubHostProjectDisk(+ { "index.html": ORIGINAL_HTML },+ { editElsewhereAfterFirstRead: true },+ );const iframe = document.createElement("iframe");document.body.append(iframe);iframe.contentDocument!.body.innerHTML = ORIGINAL_HTML;diff --git a/packages/studio/src/player/components/timelineClipDragCommit.test.ts b/packages/studio/src/player/components/timelineClipDragCommit.test.tsindex eb87017be5..666a729722 100644--- a/packages/studio/src/player/components/timelineClipDragCommit.test.ts+++ b/packages/studio/src/player/components/timelineClipDragCommit.test.ts@@ -8,11 +8,6 @@ import {type DragCommitDeps,type TimelineMoveEdit,} from "./timelineClipDragCommit";-import {- buildEditHistoryEntry,- createEmptyEditHistory,- pushEditHistoryEntry,-} from "../../utils/editHistory";import { normalizeToZones } from "./timelineZones";import { resolveZMirrorLaneMove } from "./timelineZMirror";import type { StackingPatch } from "./timelineStackingSync";@@ -1151,48 +1146,21 @@ describe("commitDraggedClipMove", () => {return { onMoveElements, onStackingPatches };};- it("threads ONE shared coalesceKey to both the move persist and the z-sync, so the two records merge into a single undo entry", async () => {+ it("threads ONE shared coalesceKey to both the move persist and the z-sync, so the server can fold them into a single undo entry", async () => {const { onMoveElements, onStackingPatches } = commitLaneChange(overlapping());await flushMicrotasks();- // Both sides receive the SAME non-empty gesture key (second arg).+ // Both sides receive the SAME non-empty gesture key (second arg). That+ // shared, non-empty coalesceKey is what lets the server+ // (projectHistory.ts, "claim: a writer that records after writing")+ // fold the "Move timeline clips" write and the "Reorder layers" z patch,+ // both to the same file, into one undo entry — folding itself is the+ // server's own tested behaviour, not re-proven here via a reducer.const moveKey = onMoveElements.mock.calls[0][1];const zKey = onStackingPatches.mock.calls[0][1];expect(typeof moveKey).toBe("string");expect(moveKey).not.toBe("");expect(zKey).toBe(moveKey);-- // With that shared key, editHistory folds the two consecutive records (the- // "Move timeline clips" write + the "Reorder layers" z patch, same file,- // inside the coalesce window) into ONE undo entry spanning before→after.- const now = 1_000;- const moveEntry = buildEditHistoryEntry({- id: "m",- projectId: "p",- label: "Move timeline clips",- kind: "timeline",- coalesceKey: moveKey,- now,- files: { "index.html": { before: "<v0>", after: "<v1>" } },- });- const zEntry = buildEditHistoryEntry({- id: "z",- projectId: "p",- label: "Reorder layers",- kind: "timeline",- coalesceKey: zKey,- now: now + 50,- files: { "index.html": { before: "<v1>", after: "<v2>" } },- });- const state = pushEditHistoryEntry(- pushEditHistoryEntry(createEmptyEditHistory(), moveEntry),- zEntry,- );- expect(state.undo).toHaveLength(1);- expect(state.undo[0].files["index.html"]).toMatchObject({- before: "<v0>",- after: "<v2>",- });});it("distinct gestures get distinct keys (independent moves never cross-merge)", async () => {diff --git a/packages/studio/src/utils/editHistory.test.ts b/packages/studio/src/utils/editHistory.test.tsdeleted file mode 100644index cfd1d1f48d..0000000000--- a/packages/studio/src/utils/editHistory.test.ts+++ /dev/null@@ -1,534 +0,0 @@-import { describe, expect, it } from "vitest";-import {- buildEditHistoryEntry,- canApplyEditHistoryEntry,- createEmptyEditHistory,- hashEditHistoryContent,- pushEditHistoryEntry,- redoEditHistory,- undoEditHistory,-} from "./editHistory";--describe("edit history", () => {- it("pushes changed file snapshots onto undo and clears redo", () => {- const state = createEmptyEditHistory();- const entry = buildEditHistoryEntry({- projectId: "project-1",- label: "Move layer",- files: {- "index.html": {- before: '<div style="left: 0px"></div>',- after: '<div style="left: 20px"></div>',- },- },- now: 100,- id: "entry-1",- });-- const withUndo = pushEditHistoryEntry(state, entry);- const redoEntry = buildEditHistoryEntry({- projectId: "project-1",- label: "Redoable edit",- files: {- "index.html": {- before: '<div style="left: 20px"></div>',- after: '<div style="left: 40px"></div>',- },- },- now: 200,- id: "redo-entry",- });-- const next = pushEditHistoryEntry(- {- ...withUndo,- redo: [redoEntry],- },- {- ...entry,- id: "entry-2",- label: "Resize layer",- createdAt: 300,- },- );-- expect(withUndo.undo).toHaveLength(1);- expect(withUndo.redo).toHaveLength(0);- expect(next.undo.map((item) => item.label)).toEqual(["Move layer", "Resize layer"]);- expect(next.redo).toHaveLength(0);- });-- it("undo returns before contents and moves entry to redo", () => {- const entry = buildEditHistoryEntry({- projectId: "project-1",- label: "Move layer",- files: {- "index.html": { before: "before", after: "after" },- },- now: 100,- id: "entry-1",- });- const state = pushEditHistoryEntry(createEmptyEditHistory(), entry);-- const result = undoEditHistory(state, { "index.html": hashEditHistoryContent("after") }, 200);-- expect(result.ok).toBe(true);- expect(result.filesToWrite).toEqual({ "index.html": "before" });- expect(result.state.undo).toHaveLength(0);- expect(result.state.redo.map((item) => item.id)).toEqual(["entry-1"]);- });-- it("redo returns after contents and moves entry to undo", () => {- const entry = buildEditHistoryEntry({- projectId: "project-1",- label: "Move layer",- files: {- "index.html": { before: "before", after: "after" },- },- now: 100,- id: "entry-1",- });- const undone = undoEditHistory(- pushEditHistoryEntry(createEmptyEditHistory(), entry),- { "index.html": hashEditHistoryContent("after") },- 200,- ).state;-- const result = redoEditHistory(undone, { "index.html": hashEditHistoryContent("before") }, 300);-- expect(result.ok).toBe(true);- expect(result.filesToWrite).toEqual({ "index.html": "after" });- expect(result.state.undo.map((item) => item.id)).toEqual(["entry-1"]);- expect(result.state.redo).toHaveLength(0);- });-- it("blocks undo when current content hash does not match the recorded after hash", () => {- const entry = buildEditHistoryEntry({- projectId: "project-1",- label: "Move layer",- files: {- "index.html": { before: "before", after: "after" },- },- now: 100,- id: "entry-1",- });- const state = pushEditHistoryEntry(createEmptyEditHistory(), entry);-- const result = undoEditHistory(- state,- { "index.html": hashEditHistoryContent("external") },- 200,- );-- expect(result.ok).toBe(false);- expect(result.reason).toBe("content-mismatch");- expect(result.state).toBe(state);- expect(result.filesToWrite).toEqual({});- });-- it("can validate all files in a multi-file entry before applying", () => {- const entry = buildEditHistoryEntry({- projectId: "project-1",- label: "Update files",- files: {- "index.html": { before: "a", after: "b" },- "compositions/title.html": { before: "c", after: "d" },- },- now: 100,- id: "entry-1",- });-- expect(- canApplyEditHistoryEntry(entry, "undo", {- "index.html": hashEditHistoryContent("b"),- "compositions/title.html": hashEditHistoryContent("d"),- }),- ).toEqual({ ok: true });- expect(- canApplyEditHistoryEntry(entry, "undo", {- "index.html": hashEditHistoryContent("b"),- "compositions/title.html": hashEditHistoryContent("external"),- }),- ).toEqual({ ok: false, reason: "content-mismatch", path: "compositions/title.html" });- });-- it("prunes oldest undo entries when the limit is exceeded", () => {- let state = createEmptyEditHistory({ maxEntries: 2 });- for (let index = 1; index <= 3; index += 1) {- state = pushEditHistoryEntry(- state,- buildEditHistoryEntry({- projectId: "project-1",- label: `Edit ${index}`,- files: {- "index.html": { before: `${index - 1}`, after: `${index}` },- },- now: index,- id: `entry-${index}`,- }),- { maxEntries: 2 },- );- }-- expect(state.undo.map((entry) => entry.id)).toEqual(["entry-2", "entry-3"]);- });-- it("coalesces source editor edits for the same file inside the coalesce window", () => {- const first = buildEditHistoryEntry({- projectId: "project-1",- label: "Edit source",- kind: "source",- coalesceKey: "source:index.html",- files: {- "index.html": { before: "a", after: "b" },- },- now: 100,- id: "entry-1",- });- const second = buildEditHistoryEntry({- projectId: "project-1",- label: "Edit source",- kind: "source",- coalesceKey: "source:index.html",- files: {- "index.html": { before: "b", after: "c" },- },- now: 300,- id: "entry-2",- });-- const state = pushEditHistoryEntry(- pushEditHistoryEntry(createEmptyEditHistory(), first),- second,- { coalesceMs: 1000 },- );-- expect(state.undo).toHaveLength(1);- expect(state.undo[0].id).toBe("entry-2");- expect(state.undo[0].files["index.html"].before).toBe("a");- expect(state.undo[0].files["index.html"].after).toBe("c");- });-- it("merges a lane-change move with its z-reorder past the default window via entry coalesceMs", () => {- // The z entry records only after the move persist's round-trip — often >300ms.- // Both sides pass coalesceMs: 5000 with the shared gesture key so the pair- // still folds into ONE undo step.- const move = buildEditHistoryEntry({- projectId: "project-1",- label: "Move timeline clips",- kind: "timeline",- coalesceKey: "clip-lane-move:1",- coalesceMs: 5000,- files: { "index.html": { before: "a", after: "b" } },- now: 100,- id: "move-entry",- });- const zReorder = buildEditHistoryEntry({- projectId: "project-1",- label: "Reorder layers",- kind: "manual",- coalesceKey: "clip-lane-move:1",- coalesceMs: 5000,- files: { "index.html": { before: "b", after: "c" } },- now: 500,- id: "z-entry",- });-- const state = pushEditHistoryEntry(- pushEditHistoryEntry(createEmptyEditHistory(), move),- zReorder,- );-- expect(state.undo).toHaveLength(1);- expect(state.undo[0].files["index.html"].before).toBe("a");- expect(state.undo[0].files["index.html"].after).toBe("c");- });-- it("folds a slow GSAP follow-up into the timing edit via a per-entry coalesceMs override", () => {- const timing = buildEditHistoryEntry({- projectId: "project-1",- label: "Resize timeline clip",- kind: "timeline",- coalesceKey: "timeline-resize:clip",- files: { "index.html": { before: "orig", after: "timing" } },- now: 0,- id: "timing",- });- // The server GSAP rewrite lands ~2s later, past the 300ms default window, but the- // follow-up carries a large coalesceMs so undo still collapses to a single step.- const gsap = buildEditHistoryEntry({- projectId: "project-1",- label: "Resize timeline clip",- kind: "timeline",- coalesceKey: "timeline-resize:clip",- coalesceMs: 10_000,- files: { "index.html": { before: "timing", after: "timing+gsap" } },- now: 2000,- id: "gsap",- });-- const state = pushEditHistoryEntry(- pushEditHistoryEntry(createEmptyEditHistory(), timing),- gsap,- );-- expect(state.undo).toHaveLength(1);- expect(state.undo[0].files["index.html"].before).toBe("orig");- expect(state.undo[0].files["index.html"].after).toBe("timing+gsap");- });-- it("keeps timing-only files when a multi-file GSAP follow-up touches one path", () => {- const timing = buildEditHistoryEntry({- projectId: "project-1",- label: "Move timeline clips",- kind: "timeline",- coalesceKey: "timeline-group-move:a,b",- files: {- "index.html": { before: "index-before", after: "index-timing" },- "scene.html": { before: "scene-before", after: "scene-timing" },- },- now: 0,- id: "timing",- });- const gsap = buildEditHistoryEntry({- projectId: "project-1",- label: "Move timeline clips",- kind: "timeline",- coalesceKey: "timeline-group-move:a,b",- coalesceMs: 10_000,- files: {- "index.html": { before: "index-timing", after: "index-timing+gsap" },- },- now: 2000,- id: "gsap",- });-- const state = pushEditHistoryEntry(- pushEditHistoryEntry(createEmptyEditHistory(), timing),- gsap,- );-- expect(state.undo).toHaveLength(1);- expect(Object.keys(state.undo[0].files)).toEqual(["index.html", "scene.html"]);- expect(state.undo[0].files).toMatchObject({- "index.html": { before: "index-before", after: "index-timing+gsap" },- "scene.html": { before: "scene-before", after: "scene-timing" },- });- });-- it("keeps a discontinuous GSAP follow-up separate and preserves foreign bytes on undo", () => {- const timing = buildEditHistoryEntry({- projectId: "project-1",- label: "Move timeline clip",- kind: "timeline",- coalesceKey: "timeline-move:clip",- files: { "index.html": { before: "A", after: "B" } },- now: 0,- id: "timing",- });- const gsapAfterForeignWrite = buildEditHistoryEntry({- projectId: "project-1",- label: "Move timeline clip",- kind: "timeline",- coalesceKey: "timeline-move:clip",- coalesceMs: 10_000,- files: { "index.html": { before: "F", after: "G" } },- now: 2000,- id: "gsap",- });-- const state = pushEditHistoryEntry(- pushEditHistoryEntry(createEmptyEditHistory(), timing),- gsapAfterForeignWrite,- );-- expect(state.undo.map((entry) => entry.id)).toEqual(["timing", "gsap"]);- const undoGsap = undoEditHistory(state, { "index.html": hashEditHistoryContent("G") }, 3000);- expect(undoGsap.ok).toBe(true);- expect(undoGsap.filesToWrite).toEqual({ "index.html": "F" });-- const undoTiming = undoEditHistory(- undoGsap.state,- { "index.html": hashEditHistoryContent("F") },- 4000,- );- expect(undoTiming).toMatchObject({- ok: false,- reason: "content-mismatch",- filesToWrite: {},- });- });-- it("does not merge a slow follow-up without the coalesceMs override", () => {- const timing = buildEditHistoryEntry({- projectId: "project-1",- label: "Resize timeline clip",- kind: "timeline",- coalesceKey: "timeline-resize:clip",- files: { "index.html": { before: "orig", after: "timing" } },- now: 0,- id: "timing",- });- const late = buildEditHistoryEntry({- projectId: "project-1",- label: "Resize timeline clip",- kind: "timeline",- coalesceKey: "timeline-resize:clip",- files: { "index.html": { before: "timing", after: "timing+gsap" } },- now: 2000,- id: "late",- });-- const state = pushEditHistoryEntry(- pushEditHistoryEntry(createEmptyEditHistory(), timing),- late,- );-- expect(state.undo).toHaveLength(2);- });-- it("coalesces entries with the same coalesceKey within the window (prop: format)", () => {- const first = buildEditHistoryEntry({- projectId: "project-1",- label: "Edit title color",- kind: "source",- coalesceKey: "prop:title.color",- files: {- "index.html": { before: "a", after: "b" },- },- now: 100,- id: "entry-1",- });- const second = buildEditHistoryEntry({- projectId: "project-1",- label: "Edit title color",- kind: "source",- coalesceKey: "prop:title.color",- files: {- "index.html": { before: "b", after: "c" },- },- now: 200,- id: "entry-2",- });-- const state = pushEditHistoryEntry(- pushEditHistoryEntry(createEmptyEditHistory(), first),- second,- { coalesceMs: 1000 },- );-- expect(state.undo).toHaveLength(1);- expect(state.undo[0].id).toBe("entry-2");- expect(state.undo[0].files["index.html"].before).toBe("a");- expect(state.undo[0].files["index.html"].after).toBe("c");- });-- it("does not coalesce entries with different coalesceKeys (cross-prop separation)", () => {- const titleEdit = buildEditHistoryEntry({- projectId: "project-1",- label: "Edit title color",- kind: "source",- coalesceKey: "prop:title.color",- files: {- "index.html": { before: "a", after: "b" },- },- now: 100,- id: "entry-title",- });- const bodyEdit = buildEditHistoryEntry({- projectId: "project-1",- label: "Edit body color",- kind: "source",- coalesceKey: "prop:body.color",- files: {- "index.html": { before: "b", after: "c" },- },- now: 200,- id: "entry-body",- });-- const state = pushEditHistoryEntry(- pushEditHistoryEntry(createEmptyEditHistory(), titleEdit),- bodyEdit,- { coalesceMs: 1000 },- );-- expect(state.undo.map((e) => e.id)).toEqual(["entry-title", "entry-body"]);- });-- it("does not coalesce source editor edits outside the coalesce window", () => {- const first = buildEditHistoryEntry({- projectId: "project-1",- label: "Edit source",- kind: "source",- coalesceKey: "source:index.html",- files: {- "index.html": { before: "a", after: "b" },- },- now: 100,- id: "entry-1",- });- const second = buildEditHistoryEntry({- projectId: "project-1",- label: "Edit source",- kind: "source",- coalesceKey: "source:index.html",- files: {- "index.html": { before: "b", after: "c" },- },- now: 5000,- id: "entry-2",- });-- const state = pushEditHistoryEntry(- pushEditHistoryEntry(createEmptyEditHistory(), first),- second,- { coalesceMs: 1000 },- );-- expect(state.undo.map((entry) => entry.id)).toEqual(["entry-1", "entry-2"]);- });-- it("coalesces entries exactly at the coalesce boundary (delta === coalesceMs is inclusive)", () => {- const first = buildEditHistoryEntry({- projectId: "project-1",- label: "Edit source",- kind: "source",- coalesceKey: "source:index.html",- files: {- "index.html": { before: "a", after: "b" },- },- now: 100,- id: "entry-1",- });- const second = buildEditHistoryEntry({- projectId: "project-1",- label: "Edit source",- kind: "source",- coalesceKey: "source:index.html",- files: {- "index.html": { before: "b", after: "c" },- },- now: 1100, // exactly coalesceMs=1000ms after first- id: "entry-2",- });-- const state = pushEditHistoryEntry(- pushEditHistoryEntry(createEmptyEditHistory(), first),- second,- { coalesceMs: 1000 },- );-- // Boundary is <=: delta of exactly 1000ms coalesces into one entry.- expect(state.undo).toHaveLength(1);- expect(state.undo[0].id).toBe("entry-2");- expect(state.undo[0].files["index.html"].before).toBe("a");- expect(state.undo[0].files["index.html"].after).toBe("c");- });-- it.todo("gesture-start/commit collapses intermediate drag steps into one undo entry");-- it.todo(- "origin:applyPatches edits are excluded from undo stack to prevent undo loops (requires SDK session)",- );-});diff --git a/packages/studio/src/utils/editHistory.ts b/packages/studio/src/utils/editHistory.tsindex 85a42f8b7b..6cd41125da 100644--- a/packages/studio/src/utils/editHistory.ts+++ b/packages/studio/src/utils/editHistory.ts@@ -1,236 +1 @@export type EditHistoryKind = "manual" | "motion" | "timeline" | "source";--export interface EditHistoryFileSnapshot {- before: string;- after: string;- beforeHash: string;- afterHash: string;-}--export interface EditHistoryEntry {- id: string;- projectId: string;- label: string;- kind: EditHistoryKind;- coalesceKey?: string;- /** Per-entry coalesce window override (ms). Falls back to the reducer default. */- coalesceMs?: number;- createdAt: number;- files: Record<string, EditHistoryFileSnapshot>;-}--export interface EditHistoryState {- version: 1;- updatedAt: number;- undo: EditHistoryEntry[];- redo: EditHistoryEntry[];-}--export interface EditHistoryOptions {- maxEntries?: number;- coalesceMs?: number;-}--export interface BuildEditHistoryEntryInput {- id: string;- projectId: string;- label: string;- kind?: EditHistoryKind;- coalesceKey?: string;- coalesceMs?: number;- now: number;- files: Record<string, { before: string; after: string }>;-}--export type EditHistoryDirection = "undo" | "redo";--export type EditHistoryApplyCheck =- | { ok: true }- | { ok: false; reason: "content-mismatch"; path: string };--export type EditHistoryTransitionResult =- | {- ok: true;- state: EditHistoryState;- entry: EditHistoryEntry;- filesToWrite: Record<string, string>;- }- | {- ok: false;- reason: "empty" | "content-mismatch";- state: EditHistoryState;- filesToWrite: Record<string, string>;- path?: string;- };--const DEFAULT_MAX_ENTRIES = 100;-const DEFAULT_COALESCE_MS = 300;--export function hashEditHistoryContent(content: string): string {- let hash = 2166136261;- for (let index = 0; index < content.length; index += 1) {- hash ^= content.charCodeAt(index);- hash = Math.imul(hash, 16777619);- }- return (hash >>> 0).toString(16).padStart(8, "0");-}--export function createEmptyEditHistory(_options?: EditHistoryOptions): EditHistoryState {- return {- version: 1,- updatedAt: 0,- undo: [],- redo: [],- };-}--export function buildEditHistoryEntry(input: BuildEditHistoryEntryInput): EditHistoryEntry {- const files: Record<string, EditHistoryFileSnapshot> = {};- for (const [path, snapshot] of Object.entries(input.files)) {- if (snapshot.before === snapshot.after) continue;- files[path] = {- before: snapshot.before,- after: snapshot.after,- beforeHash: hashEditHistoryContent(snapshot.before),- afterHash: hashEditHistoryContent(snapshot.after),- };- }-- return {- id: input.id,- projectId: input.projectId,- label: input.label,- kind: input.kind ?? "manual",- coalesceKey: input.coalesceKey,- coalesceMs: input.coalesceMs,- createdAt: input.now,- files,- };-}--export function pushEditHistoryEntry(- state: EditHistoryState,- entry: EditHistoryEntry,- options?: EditHistoryOptions,-): EditHistoryState {- if (Object.keys(entry.files).length === 0) return state;-- // The incoming entry's own window wins so a caller can guarantee a merge even when a- // slow async step (e.g. a server GSAP rewrite) sits between the two records.- const coalesceMs = entry.coalesceMs ?? options?.coalesceMs ?? DEFAULT_COALESCE_MS;- const maxEntries = options?.maxEntries ?? DEFAULT_MAX_ENTRIES;- const previous = state.undo[state.undo.length - 1];- let undo = state.undo;-- if (- previous &&- previous.coalesceKey &&- previous.coalesceKey === entry.coalesceKey &&- entry.createdAt - previous.createdAt <= coalesceMs &&- // A shared key/window is not enough: bytes from an external writer may- // have landed between the two Studio-owned edits. Only fold a path when- // the follow-up starts from the exact output the previous entry recorded.- // Otherwise keep both entries so undo restores the foreign bytes first and- // the older entry's content check safely blocks at that ownership boundary.- Object.entries(entry.files).every(([path, snapshot]) => {- const previousSnapshot = previous.files[path];- return !previousSnapshot || previousSnapshot.after === snapshot.before;- })- ) {- // A follow-up may touch only a subset of the files in the original edit- // (for example, only one file in a multi-file timing move has GSAP). Keep- // previous-only paths in the single coalesced undo entry.- const files: Record<string, EditHistoryFileSnapshot> = { ...previous.files };- for (const [path, snapshot] of Object.entries(entry.files)) {- const previousSnapshot = previous.files[path];- files[path] = previousSnapshot- ? {- before: previousSnapshot.before,- after: snapshot.after,- beforeHash: previousSnapshot.beforeHash,- afterHash: snapshot.afterHash,- }- : snapshot;- }- undo = [...state.undo.slice(0, -1), { ...entry, files }];- } else {- undo = [...state.undo, entry];- }-- return {- version: 1,- updatedAt: entry.createdAt,- undo: undo.slice(Math.max(0, undo.length - maxEntries)),- redo: [],- };-}--export function canApplyEditHistoryEntry(- entry: EditHistoryEntry,- direction: EditHistoryDirection,- currentHashes: Record<string, string>,-): EditHistoryApplyCheck {- for (const [path, snapshot] of Object.entries(entry.files)) {- const expected = direction === "undo" ? snapshot.afterHash : snapshot.beforeHash;- if (currentHashes[path] !== expected) {- return { ok: false, reason: "content-mismatch", path };- }- }- return { ok: true };-}--export function undoEditHistory(- state: EditHistoryState,- currentHashes: Record<string, string>,- now: number,-): EditHistoryTransitionResult {- const entry = state.undo[state.undo.length - 1];- if (!entry) return { ok: false, reason: "empty", state, filesToWrite: {} };-- const check = canApplyEditHistoryEntry(entry, "undo", currentHashes);- if (!check.ok) {- return { ok: false, reason: check.reason, path: check.path, state, filesToWrite: {} };- }-- return {- ok: true,- entry,- filesToWrite: Object.fromEntries(- Object.entries(entry.files).map(([path, snapshot]) => [path, snapshot.before]),- ),- state: {- version: 1,- updatedAt: now,- undo: state.undo.slice(0, -1),- redo: [...state.redo, entry],- },- };-}--export function redoEditHistory(- state: EditHistoryState,- currentHashes: Record<string, string>,- now: number,-): EditHistoryTransitionResult {- const entry = state.redo[state.redo.length - 1];- if (!entry) return { ok: false, reason: "empty", state, filesToWrite: {} };-- const check = canApplyEditHistoryEntry(entry, "redo", currentHashes);- if (!check.ok) {- return { ok: false, reason: check.reason, path: check.path, state, filesToWrite: {} };- }-- return {- ok: true,- entry,- filesToWrite: Object.fromEntries(- Object.entries(entry.files).map(([path, snapshot]) => [path, snapshot.after]),- ),- state: {- version: 1,- updatedAt: now,- undo: [...state.undo, entry],- redo: state.redo.slice(0, -1),- },- };-}diff --git a/packages/studio/src/utils/editHistoryStorage.test.ts b/packages/studio/src/utils/editHistoryStorage.test.tsdeleted file mode 100644index be5e3a6f98..0000000000--- a/packages/studio/src/utils/editHistoryStorage.test.ts+++ /dev/null@@ -1,37 +0,0 @@-import { beforeEach, describe, expect, it } from "vitest";-import { buildEditHistoryEntry, createEmptyEditHistory, pushEditHistoryEntry } from "./editHistory";-import {- createMemoryEditHistoryStorage,- loadEditHistoryState,- saveEditHistoryState,-} from "./editHistoryStorage";--describe("edit history storage", () => {- let storage: ReturnType<typeof createMemoryEditHistoryStorage>;-- beforeEach(() => {- storage = createMemoryEditHistoryStorage();- });-- it("returns empty history for projects without persisted state", async () => {- const state = await loadEditHistoryState(storage, "project-1");-- expect(state).toEqual(createEmptyEditHistory());- });-- it("saves and loads history per project", async () => {- const entry = buildEditHistoryEntry({- id: "entry-1",- projectId: "project-1",- label: "Move layer",- files: { "index.html": { before: "a", after: "b" } },- now: 100,- });- const state = pushEditHistoryEntry(createEmptyEditHistory(), entry);-- await saveEditHistoryState(storage, "project-1", state);-- expect(await loadEditHistoryState(storage, "project-1")).toEqual(state);- expect(await loadEditHistoryState(storage, "project-2")).toEqual(createEmptyEditHistory());- });-});diff --git a/packages/studio/src/utils/editHistoryStorage.ts b/packages/studio/src/utils/editHistoryStorage.tsdeleted file mode 100644index 1266c9a8dd..0000000000--- a/packages/studio/src/utils/editHistoryStorage.ts+++ /dev/null@@ -1,99 +0,0 @@-import { createEmptyEditHistory, type EditHistoryState } from "./editHistory";--export interface EditHistoryStorageAdapter {- get(projectId: string): Promise<EditHistoryState | null>;- set(projectId: string, state: EditHistoryState): Promise<void>;- delete(projectId: string): Promise<void>;-}--const DB_NAME = "hyperframes-studio-edit-history";-const DB_VERSION = 1;-const STORE_NAME = "project-history";--export function createMemoryEditHistoryStorage(): EditHistoryStorageAdapter {- const states = new Map<string, EditHistoryState>();- return {- async get(projectId) {- return states.get(projectId) ?? null;- },- async set(projectId, state) {- states.set(projectId, structuredClone(state));- },- async delete(projectId) {- states.delete(projectId);- },- };-}--function openEditHistoryDb(): Promise<IDBDatabase> {- return new Promise((resolve, reject) => {- if (!globalThis.indexedDB) {- reject(new Error("IndexedDB is not available"));- return;- }-- const request = globalThis.indexedDB.open(DB_NAME, DB_VERSION);- request.onupgradeneeded = () => {- const db = request.result;- if (!db.objectStoreNames.contains(STORE_NAME)) {- db.createObjectStore(STORE_NAME);- }- };- request.onerror = () => reject(request.error ?? new Error("Failed to open edit history db"));- request.onsuccess = () => resolve(request.result);- });-}--function withStore<T>(- mode: IDBTransactionMode,- callback: (store: IDBObjectStore) => IDBRequest<T>,-): Promise<T> {- return openEditHistoryDb().then(- (db) =>- new Promise<T>((resolve, reject) => {- const tx = db.transaction(STORE_NAME, mode);- const request = callback(tx.objectStore(STORE_NAME));- request.onerror = () => reject(request.error ?? new Error("IndexedDB request failed"));- request.onsuccess = () => resolve(request.result);- tx.oncomplete = () => db.close();- tx.onerror = () => {- db.close();- reject(tx.error ?? new Error("IndexedDB transaction failed"));- };- }),- );-}--export function createIndexedDbEditHistoryStorage(): EditHistoryStorageAdapter {- return {- async get(projectId) {- return (- (await withStore<EditHistoryState | undefined>("readonly", (store) =>- store.get(projectId),- )) ?? null- );- },- async set(projectId, state) {- await withStore<IDBValidKey>("readwrite", (store) => store.put(state, projectId));- },- async delete(projectId) {- await withStore<undefined>("readwrite", (store) => store.delete(projectId));- },- };-}--export async function loadEditHistoryState(- storage: EditHistoryStorageAdapter,- projectId: string,-): Promise<EditHistoryState> {- const state = await storage.get(projectId);- return state ?? createEmptyEditHistory();-}--export async function saveEditHistoryState(- storage: EditHistoryStorageAdapter,- projectId: string,- state: EditHistoryState,-): Promise<void> {- await storage.set(projectId, state);-}diff --git a/packages/studio/vite.adapter.projects.test.ts b/packages/studio/vite.adapter.projects.test.tsindex bcb9b6f651..9450c1c357 100644--- a/packages/studio/vite.adapter.projects.test.ts+++ b/packages/studio/vite.adapter.projects.test.ts@@ -1,9 +1,10 @@-import { afterEach, describe, expect, it } from "vitest";+import { EventEmitter } from "node:events";+import { afterEach, describe, expect, it, vi } from "vitest";import { mkdtempSync, mkdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join, win32 } from "node:path";import { isValidProjectId } from "./src/utils/projectRouting";-import { createStudioApi } from "@hyperframes/studio-server";+import { createStudioApi, type ProjectHistory } from "@hyperframes/studio-server";import type { ViteDevServer } from "vite";import { createProjectSignatureCache, createViteAdapter } from "./vite.adapter";@@ -24,11 +25,56 @@ function fixture() {data,{} as ViteDevServer,createProjectSignatureCache({ compute: () => "test" }),+ { historyRoot: join(root, "history") },);const app = createStudioApi(adapter);return { root, data, sessions, adapter, app };}+describe("Studio's dev server keeps each project's history", () => {+ it("serves it, so an edit Studio claims is the next undo, and opens it once per project", async () => {+ const { data, adapter, app } = fixture();+ mkdirSync(join(data, "demo"));+ writeFileSync(join(data, "demo", "index.html"), "A");+ const project = adapter.resolveProject("demo")!;+ const history = await adapter.history!(project);+ expect(await adapter.history!(project)).toBe(history);+ try {+ writeFileSync(join(data, "demo", "index.html"), "B");+ const claim = await app.request("http://localhost/projects/demo/history/claim", {+ method: "POST",+ body: JSON.stringify({ label: "Moved Title", paths: ["index.html"] }),+ });+ expect(await claim.json()).toMatchObject({ claimed: { id: expect.any(String) } });+ const list = await app.request("http://localhost/projects/demo/history");+ expect(await list.json()).toMatchObject({ back: { label: "Moved Title" } });+ } finally {+ await history?.close();+ }+ });+});++describe("Studio's dev server closes the histories it opened when it stops", () => {+ it("closes each through the opener it was given, so an open edit keeps its label", async () => {+ const root = mkdtempSync(join(tmpdir(), "hf-project-history-close-"));+ roots.push(root);+ mkdirSync(join(root, "demo"));+ const httpServer = new EventEmitter();+ const close = vi.fn(async () => {});+ const openHistory = vi.fn(async () => ({ close }) as unknown as ProjectHistory);+ const adapter = createViteAdapter(+ root,+ { httpServer } as unknown as ViteDevServer,+ createProjectSignatureCache({ compute: () => "test" }),+ { openHistory },+ );+ await adapter.history!(adapter.resolveProject("demo")!);+ httpServer.emit("close");+ await vi.waitFor(() => expect(close).toHaveBeenCalledOnce());+ expect(openHistory).toHaveBeenCalledOnce();+ });+});+describe("Vite project resolution boundary", () => {it.each(["C%3A", "C%3Ademo", "..%2Fsessions", "a%2Fb", "a%5Cb", "%2E%2E%2Fsessions", "a%00b"])("rejects a router-decoded unsafe ID: %s",diff --git a/packages/studio/vite.adapter.ts b/packages/studio/vite.adapter.tsindex 4a4578c779..d47807f85c 100644--- a/packages/studio/vite.adapter.ts+++ b/packages/studio/vite.adapter.ts@@ -22,6 +22,9 @@ import {createProjectSignature,affectsProjectSignature,PREVIEW_BUNDLE_OPTIONS,+ DEFAULT_HISTORY_ROOT,+ openProjectHistory,+ type ProjectHistory,} from "@hyperframes/studio-server";import type { RegistryItem } from "@hyperframes/core/registry";import type { BundleOptions } from "@hyperframes/core/compiler";@@ -101,7 +104,16 @@ export function createViteAdapter(dataDir: string,server: ViteDevServer,signatureCache: ProjectSignatureCache,+ {+ historyRoot = DEFAULT_HISTORY_ROOT,+ openHistory = openProjectHistory,+ }: { historyRoot?: string; openHistory?: typeof openProjectHistory } = {},): StudioApiAdapter {+ const histories = new Map<string, Promise<ProjectHistory | null>>();+ // Commits any open edit when the dev server stops, so it keeps its label.+ server.httpServer?.on("close", () => {+ for (const opened of histories.values()) void opened.then((history) => history?.close());+ });let _bundler: ((dir: string, options?: BundleOptions) => Promise<string>) | null = null;let _producerModuleLoader:| (() => Promise<{@@ -200,6 +212,19 @@ export function createViteAdapter(.sort((a, b) => (a.title ?? "").localeCompare(b.title ?? ""));},+ // Studio's undo runs on the project's history: opened once per project, and a failed open stays off.+ history(project: ResolvedProject) {+ let opened = histories.get(project.dir);+ if (!opened) {+ opened = openHistory({ projectDir: project.dir, historyRoot }).catch((error: unknown) => {+ console.warn(`[studio] Project history is off for ${project.id}: ${String(error)}`);+ return null;+ });+ histories.set(project.dir, opened);+ }+ return opened;+ },+// fallow-ignore-next-line complexityresolveProject(id: string) {if (!isValidProjectId(id)) return null;diff --git a/packages/studio/vite.config.ts b/packages/studio/vite.config.tsindex 7b948df01b..62a0468a66 100644--- a/packages/studio/vite.config.ts+++ b/packages/studio/vite.config.ts@@ -15,6 +15,7 @@ import { watch } from "chokidar";import { createProjectSignatureCache, createViteAdapter } from "./vite.adapter";import { previewConfigPayload } from "./vite.preview-config";import { loadStudioServerDevModule } from "./vite.studio-server-module";+import type { openProjectHistory } from "@hyperframes/studio-server";async function loadRuntimeSourceForDev(server: import("vite").ViteDevServer,@@ -145,6 +146,8 @@ function devProjectApi(): Plugin {expectedVersion: string,) => { path: string; version: string; writeToken: string } | null;fileContentVersion: (content: string) => string;+ DELETED_VERSION: string;+ openProjectHistory: typeof openProjectHistory;} | null = null;const getApi = async () => {if (!_api) {@@ -156,13 +159,20 @@ function devProjectApi(): Plugin {>;// The cast above is the only thing standing between a renamed export and// a dev server that silently reports every Studio write as external.- for (const name of ["identifyFileWrite", "fileContentVersion"] as const) {+ for (const name of [+ "identifyFileWrite",+ "fileContentVersion",+ "openProjectHistory",+ ] as const) {if (typeof mod[name] !== "function") {throw new Error(`@hyperframes/studio-server dev module is missing ${name}()`);}}_studioServerModule = mod;- const adapter = createViteAdapter(dataDir, server, signatureCache);+ // The engine records its write receipts in this module, where the watcher below reads them.+ const adapter = createViteAdapter(dataDir, server, signatureCache, {+ openHistory: mod.openProjectHistory,+ });_api = mod.createStudioApi(adapter);}return _api;@@ -256,8 +266,9 @@ function devProjectApi(): Plugin {} catch {// A deletion has no current bytes to match a write receipt against.}- const receipt =- version && studioServer ? studioServer.identifyFileWrite(filePath, version) : null;+ const receipt = studioServer+ ? studioServer.identifyFileWrite(filePath, version ?? studioServer.DELETED_VERSION)+ : null;// First path segment under `dataDir` is the project id (`data/projects/<id>/...`).// Mirrors the CLI host's `project.id` field on the same event — see its// doc comment for why a stale tab needs this to ignore anotherdiff --git a/scripts/check-no-main-deletions.mjs b/scripts/check-no-main-deletions.mjsindex 45c49dbf24..14787b09b5 100644--- a/scripts/check-no-main-deletions.mjs+++ b/scripts/check-no-main-deletions.mjs@@ -40,6 +40,22 @@ const STORYBOARD_VIEW_REASON ="owner-directed removal of the Studio storyboard view; its only readers were deleted with it";export const ALLOWED_DELETIONS = new Map([+ [+ "packages/studio/src/utils/editHistoryStorage.ts",+ "Studio's undo moves onto the project history (studio-server); the browser IndexedDB history and its reducer are removed",+ ],+ [+ "packages/studio/src/utils/editHistoryStorage.test.ts",+ "tests for the removed IndexedDB history store",+ ],+ [+ "packages/studio/src/utils/editHistory.test.ts",+ "tests for the removed in-browser history reducer; merging and undo are tested in projectHistory.test.ts",+ ],+ [+ "packages/studio/src/hooks/usePersistentEditHistory.projectOwnership.test.tsx",+ "tests the removed per-project IndexedDB store; the hook now posts to the project's own history routes",+ ],["packages/studio/src/components/nle/TimelinePane.test.ts","its only subject, the expandedParentStart rebase wrappers, is dead code now removed",diff --git a/scripts/studio-runtime-smoke.mjs b/scripts/studio-runtime-smoke.mjsindex dc56bf532d..1638ca943e 100644--- a/scripts/studio-runtime-smoke.mjs+++ b/scripts/studio-runtime-smoke.mjs@@ -42,6 +42,7 @@ const GET_RESPONSES = new Map([[`${PROJECT_PATH}/renders`, json({ renders: [] })],[`${PROJECT_PATH}/lint`, json({ findings: [] })],[`${PROJECT_PATH}/selection`, json({ selection: null, updatedAt: null })],+ [`${PROJECT_PATH}/history`, json({ entries: [], back: null, forward: null })],["/api/registry/blocks", json([])],["/api/fonts", json({ fonts: [] })],["/api/fonts/google", json({ fonts: [] })],