feat(studio): undo and redo step through the project history, whoever made the change

This commit is contained in:
Miguel Ángel
2026-09-24 22:53:54 -04:00
parent ed1e606dfd
commit f69267251d
15 changed files with 431 additions and 1868 deletions
@@ -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 write
const t = usePlayerStore.getState().elements.find((e) => e.key === "index.html#t");
expect(t?.track).toBe(1); // lane unchanged
});
@@ -13,10 +13,7 @@ afterEach(() => act(() => root?.unmount()));
function mount(result: { ok: boolean; reason?: 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,22 +39,25 @@ 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 () => {
@@ -13,7 +13,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 +39,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,11 +65,10 @@ 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") {
@@ -83,7 +81,8 @@ export function useEditHistoryActions({
forceReloadSdkSession?.();
}
await syncHistoryPreviewAfterApply({ paths: result.paths, files: result.files });
showToast(`${verb} ${result.label}`, "info");
// The history names the step itself ("Undid: Moved Title").
showToast(result.label, "info");
}
},
[
@@ -92,7 +91,6 @@ export function useEditHistoryActions({
showToast,
syncHistoryPreviewAfterApply,
waitForPendingDomEditSaves,
writeProjectFile,
serializeHistoryFiles,
onAfterUndoRedo,
activeCompPath,
@@ -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());
});
});
@@ -1,337 +1,141 @@
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";
createStudioApi,
fileContentVersion,
identifyFileWrite,
openProjectHistory,
type StudioApiAdapter,
} from "@hyperframes/studio-server";
import { consumeStudioWriteToken } from "../utils/studioFileVersion";
import { usePersistentEditHistory } 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: () => {},
});
const cleanup: Array<() => unknown> = [];
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: () => {},
});
expect(second.snapshot().canUndo).toBe(true);
expect(second.snapshot().undoLabel).toBe("Move layer");
expect(second.snapshot().undoPaths).toEqual(["index.html"]);
afterEach(async () => {
for (const step of cleanup.splice(0).reverse()) await step();
vi.unstubAllGlobals();
});
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"]);
});
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);
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" } },
});
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 Promise.all([
store.recordEdit({
label: "Move layer",
expect(file()).toBe("A");
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");
});
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();
for (const content of ["B", "C"]) {
save(content);
await act(() =>
hook().recordEdit({
label: "Dragged Title",
kind: "manual",
files: { "index.html": { before: "a", after: "b" } },
coalesceKey: "drag",
coalesceMs: 60_000,
files: { "index.html": { before: "A", after: content } },
}),
store.recordEdit({
label: "Resize layer",
kind: "manual",
files: { "index.html": { before: "b", after: "c" } },
}),
]);
expect(store.snapshot().state.undo.map((entry) => entry.label)).toEqual([
"Move layer",
"Resize layer",
]);
);
}
const undone = await act(() => hook().undo({ readFile }));
expect(undone).toMatchObject({
ok: true,
label: "Undid: Dragged Title",
files: { "index.html": { previous: "C", restored: "A" } },
});
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");
});
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",
expect(file()).toBe("A");
});
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: { "first.html": { before: "first-before", after: "first-after" } },
});
await store.recordEdit({
label: "Edit second file",
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);
});
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: { "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);
});
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" } },
});
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),
});
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);
});
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",
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" } });
});
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",
kind: "manual",
files: {
"first.html": { before: "first-before", after: "first-after" },
"second.html": { before: "second-before", after: "second-after" },
},
});
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;
},
});
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);
});
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");
});
@@ -1,51 +1,26 @@
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 { 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.
*/
/** `restored` is what the step wrote; `previous` what was on disk before it, so the preview can patch in place. */
interface ApplyRestoredFile {
previous: string;
restored: string;
@@ -59,351 +34,165 @@ interface ApplyResult {
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;
/** GET /projects/:id/history: every entry, and what Cmd+Z and Cmd+Shift+Z would revert next. */
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 };
/** How long a drag's edits keep merging into one undo step when the edit names no window. */
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> = {}) {
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json", ...headers },
body: JSON.stringify(body),
});
return response.ok ? response.json() : null;
}
async function readCurrentFileHashes(
paths: string[],
/** Reads every path, or null when one cannot be read (a file the step creates or deletes). */
async function readAll(
paths: readonly 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> = {};
): Promise<Record<string, string> | null> {
const contents: Record<string, string> = {};
for (const path of paths) {
const content = await readFile(path);
currentFiles[path] = content;
currentHashes[path] = hashEditHistoryContent(content);
const content = await readFile(path).catch(() => null);
if (content === null) return null;
contents[path] = content;
}
return { currentFiles, currentHashes };
return contents;
}
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;
}
/** Each changed file's before and after, or undefined when one is unknown: the preview then reloads. */
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]! }]),
);
}
/** When the edit Cmd+Shift+Z would redo was made: the entry its undo reverted. */
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;
}
/**
* 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.
* Studio's undo and redo over the project's history on the server: an edit claims the files it just wrote, and
* Cmd+Z / Cmd+Shift+Z step through every writer's changes by time. Without a history on the server (404) edits
* still save; they just cannot be undone.
*/
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" } };
}
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();
}
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,
),
);
},
};
}
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;
}
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());
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,
...(coalesceKey && { coalesceKey, idleMs: coalesceMs ?? DEFAULT_COALESCE_MS }),
}).catch(() => null);
heldClaimRef.current = coalesceKey && reply?.claimed ? { 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 reply = (await post(
historyUrl(projectId, "/step"),
{ direction: direction === "undo" ? "back" : "forward" },
studioWriteHeaders(),
).catch(() => null)) as HistoryResult | null;
heldClaimRef.current = null;
void refresh();
if (!reply) return { ok: false, reason: "empty" };
if (!reply.ok) return { ok: false, reason: "content-mismatch" };
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]);
// Beat edits interleave with these by edit time (useAppHotkeys): the top of each stack.
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,
@@ -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());
});
});
+17 -47
View File
@@ -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 () => {
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);
});
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 () => {
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] });
});
});
@@ -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 the
+53 -22
View File
@@ -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 EditorShel
await 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;
@@ -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 () => {
@@ -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)",
);
});
-235
View File
@@ -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),
},
};
}
@@ -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());
});
});
@@ -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);
}