Skip to content

Write HTML. Render video. Built for agents.

feat(studio-server): every write to a project is kept in a history that can be undone or restored (#4431)

Miguel Ángel56c48a79beca
diff --git a/packages/studio-server/src/createStudioApi.ts b/packages/studio-server/src/createStudioApi.ts
index cf5e676097..ce8d625160 100644
--- a/packages/studio-server/src/createStudioApi.ts
+++ b/packages/studio-server/src/createStudioApi.ts
@@ -12,6 +12,7 @@ import { registerRegistryRoutes } from "./routes/registry.js";
import { registerSelectionRoutes } from "./routes/selection.js";
import { registerMediaRoutes } from "./routes/media.js";
import { registerGlobalAssetRoutes } from "./routes/globalAssets.js";
+import { registerHistoryRoutes } from "./routes/history.js";
/**
* Create a Hono sub-app with all studio API routes.
@@ -34,6 +35,7 @@ export function createStudioApi(adapter: StudioApiAdapter): Hono {
registerFontRoutes(api);
registerRegistryRoutes(api, adapter);
registerGlobalAssetRoutes(api);
+ registerHistoryRoutes(api, adapter);
return api;
}
diff --git a/packages/studio-server/src/helpers/projectSignature.ts b/packages/studio-server/src/helpers/projectSignature.ts
index 8336919797..4787015f0b 100644
--- a/packages/studio-server/src/helpers/projectSignature.ts
+++ b/packages/studio-server/src/helpers/projectSignature.ts
@@ -176,6 +176,26 @@ function createProjectFingerprint(projectDir: string, files: ProjectSignatureFil
return hash.digest("hex").slice(0, 24);
}
+function collectProjectFiles(normalizedProjectDir: string): ProjectSignatureFile[] {
+ const collected: ProjectSignatureFile[] = [];
+ collectProjectSignatureFiles(normalizedProjectDir, normalizedProjectDir, collected);
+ collectProjectSignatureManifestFiles(normalizedProjectDir, collected);
+ return collected;
+}
+
+/** The files a project is made of (the signature's set: source plus Studio's two manifests), paths with `/`. */
+export function listProjectFiles(
+ projectDir: string,
+): Array<{ path: string; size: number; mtimeMs: number; ctimeMs: number }> {
+ const normalizedProjectDir = resolve(projectDir);
+ return collectProjectFiles(normalizedProjectDir).map((entry) => ({
+ path: relative(normalizedProjectDir, entry.file).split(sep).join("/"),
+ size: entry.size,
+ mtimeMs: entry.mtimeMs,
+ ctimeMs: entry.ctimeMs,
+ }));
+}
+
/**
* Resolve the project signature through the adapter's cached path when the host
* provides one (the CLI invalidates its cache from the file watcher), falling
@@ -204,9 +224,7 @@ export function createProjectSignature(
excluding: ReadonlySet<string> = new Set(),
): string {
const normalizedProjectDir = resolve(projectDir);
- const collected: ProjectSignatureFile[] = [];
- collectProjectSignatureFiles(normalizedProjectDir, normalizedProjectDir, collected);
- collectProjectSignatureManifestFiles(normalizedProjectDir, collected);
+ const collected = collectProjectFiles(normalizedProjectDir);
const files = collected.filter(
(entry) => !excluding.has(relative(normalizedProjectDir, entry.file).split(sep).join("/")),
);
diff --git a/packages/studio-server/src/history/blobStore.ts b/packages/studio-server/src/history/blobStore.ts
new file mode 100644
index 0000000000..3c7fcca116
--- /dev/null
+++ b/packages/studio-server/src/history/blobStore.ts
@@ -0,0 +1,78 @@
+import { createHash, randomUUID } from "node:crypto";
+import { constants, createReadStream } from "node:fs";
+import { copyFile, mkdir, readdir, readFile, rename, rm, stat } from "node:fs/promises";
+import { dirname, join } from "node:path";
+
+/** File contents stored once by sha256, text and binary alike. */
+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>;
+ 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>;
+}
+
+async function hashFile(path: string): Promise<string> {
+ const hash = createHash("sha256");
+ for await (const chunk of createReadStream(path)) hash.update(chunk);
+ return hash.digest("hex");
+}
+
+async function cloneOrCopy(from: string, to: string): Promise<void> {
+ await mkdir(dirname(to), { recursive: true });
+ const temp = `${to}.${randomUUID()}.tmp`;
+ try {
+ await copyFile(from, temp, constants.COPYFILE_FICLONE);
+ await rename(temp, to);
+ } catch (error) {
+ await rm(temp, { force: true });
+ throw error;
+ }
+}
+
+export async function openBlobStore(dir: string): Promise<BlobStore> {
+ const sizes = new Map<string, number>();
+ await mkdir(dir, { recursive: true });
+ 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);
+ let total = [...sizes.values()].reduce((sum, size) => sum + size, 0);
+
+ return {
+ async put(absPath) {
+ // Hash the copy, not the source, so a write racing the copy can never file bytes under the wrong hash.
+ const temp = join(dir, `incoming-${randomUUID()}`);
+ // Recreated if removed while open, so a missing folder is never mistaken for a deleted project file.
+ await mkdir(dir, { recursive: true });
+ await copyFile(absPath, temp, constants.COPYFILE_FICLONE);
+ const hash = await hashFile(temp);
+ if (sizes.has(hash)) {
+ await rm(temp, { force: true });
+ return hash;
+ }
+ await mkdir(dirname(pathOf(hash)), { recursive: true });
+ const size = (await stat(temp)).size;
+ await rename(temp, pathOf(hash));
+ sizes.set(hash, size);
+ total += size;
+ return hash;
+ },
+ read: (hash) => readFile(pathOf(hash)),
+ writeTo: (hash, absPath) => cloneOrCopy(pathOf(hash), absPath),
+ bytes: () => total,
+ size: (hash) => sizes.get(hash) ?? 0,
+ async prune(keep) {
+ for (const [hash, size] of sizes) {
+ if (keep.has(hash)) continue;
+ await rm(pathOf(hash), { force: true });
+ sizes.delete(hash);
+ total -= size;
+ }
+ },
+ };
+}
diff --git a/packages/studio-server/src/history/historyId.ts b/packages/studio-server/src/history/historyId.ts
new file mode 100644
index 0000000000..e19dd5cbfe
--- /dev/null
+++ b/packages/studio-server/src/history/historyId.ts
@@ -0,0 +1,42 @@
+import { randomUUID } from "node:crypto";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join, resolve } from "node:path";
+
+const ID_PATH = join(".hyperframes", "history-id");
+/** The only shape minted here; the id is project content and becomes a path, so nothing else is trusted. */
+const ID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+
+function readId(projectDir: string): string | null {
+ try {
+ const id = readFileSync(join(projectDir, ID_PATH), "utf-8").trim();
+ return ID_SHAPE.test(id) ? id : null;
+ } catch {
+ return null;
+ }
+}
+
+function recordedDir(historyDir: string): string | null {
+ try {
+ return JSON.parse(readFileSync(join(historyDir, "project.json"), "utf-8")).dir ?? null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The project's history id, kept in the project so a rename or move keeps its history. A folder whose id is
+ * still carried by the folder that history was recorded for is a copy, and gets an id of its own.
+ */
+export function projectHistoryId(projectDir: string, historyRoot: string): string {
+ const dir = resolve(projectDir);
+ let id = readId(dir);
+ const was = id && recordedDir(join(historyRoot, id));
+ if (!id || (was && was !== dir && existsSync(was) && readId(was) === id)) {
+ id = randomUUID();
+ mkdirSync(join(dir, ".hyperframes"), { recursive: true });
+ writeFileSync(join(dir, ID_PATH), `${id}\n`);
+ }
+ mkdirSync(join(historyRoot, id), { recursive: true });
+ writeFileSync(join(historyRoot, id, "project.json"), JSON.stringify({ dir }));
+ return id;
+}
diff --git a/packages/studio-server/src/history/historyLog.ts b/packages/studio-server/src/history/historyLog.ts
new file mode 100644
index 0000000000..3a8f4abc8a
--- /dev/null
+++ b/packages/studio-server/src/history/historyLog.ts
@@ -0,0 +1,178 @@
+import { closeSync, constants, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
+import { dirname } from "node:path";
+import { replaceFileAtomically } from "../helpers/atomicFile.js";
+
+export interface HistoryWho {
+ kind: "person" | "agent" | "outside";
+ /** Shown in the History list: "You", the agent's name, "Outside". */
+ name: string;
+}
+
+/** A file's sha256 before and after; null is "did not exist", so a create or delete undoes like any edit. */
+export interface HistoryFileChange {
+ path: string;
+ before: string | null;
+ after: string | null;
+}
+
+export interface HistoryEntry {
+ id: string;
+ who: HistoryWho;
+ label: string;
+ startedAt: number;
+ endedAt: number;
+ files: HistoryFileChange[];
+ /** Set on an undo: the entry it reverted. Redo is undoing the undo. */
+ undoes?: string;
+ /** Set on a restore: the point (an entry id, or START) the files were made equal to. */
+ restoredTo?: string;
+}
+
+/** The point before the first kept entry. */
+export const START = "start";
+
+/** Path to hash. */
+export type Manifest = Map<string, string>;
+
+export interface HistoryLog {
+ baseline: Manifest;
+ entries: HistoryEntry[];
+ pins: Set<string>;
+}
+
+type LogRecord =
+ | { type: "baseline"; files: Record<string, string> }
+ | { type: "entry"; entry: HistoryEntry }
+ | { type: "pin"; id: string; pinned: boolean };
+
+function parseRecord(line: string): LogRecord | null {
+ try {
+ return JSON.parse(line);
+ } catch {
+ return null;
+ }
+}
+
+/** `onUnreadable` hears of a damaged line; a torn last line (a crash mid-append) is expected and dropped quietly. */
+export function readLog(file: string, onUnreadable: (line: number) => void): HistoryLog | null {
+ let text: string;
+ try {
+ text = readFileSync(file, "utf-8");
+ } catch {
+ return null;
+ }
+ const log: HistoryLog = { baseline: new Map(), entries: [], pins: new Set() };
+ const lines = text.split("\n");
+ lines.forEach((line, index) => {
+ const record = line ? parseRecord(line) : null;
+ if (record) applyRecord(log, record);
+ else if (line && index < lines.length - 1) onUnreadable(index + 1);
+ });
+ return log;
+}
+
+function applyRecord(log: HistoryLog, record: LogRecord): void {
+ if (record.type === "baseline") log.baseline = new Map(Object.entries(record.files));
+ else if (record.type === "entry") log.entries.push(record.entry);
+ else if (record.pinned) log.pins.add(record.id);
+ else log.pins.delete(record.id);
+}
+
+/** Appends `record`, already applied to `log`; a log file that is gone is written whole, so a restart replays it. */
+export function saveRecord(file: string, log: HistoryLog, record: LogRecord): void {
+ let fd: number;
+ try {
+ // No O_CREAT: an append never creates a log that would lack its baseline.
+ fd = openSync(file, constants.O_WRONLY | constants.O_APPEND);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ return writeLog(file, log);
+ }
+ try {
+ writeSync(fd, `${JSON.stringify(record)}\n`);
+ } finally {
+ closeSync(fd);
+ }
+}
+
+export function writeLog(file: string, log: HistoryLog): void {
+ const records: LogRecord[] = [
+ { type: "baseline", files: Object.fromEntries(log.baseline) },
+ ...log.entries.map((entry) => ({ type: "entry" as const, entry })),
+ ...[...log.pins].map((id) => ({ type: "pin" as const, id, pinned: true })),
+ ];
+ mkdirSync(dirname(file), { recursive: true });
+ replaceFileAtomically(file, records.map((r) => `${JSON.stringify(r)}\n`).join(""), 0o644);
+}
+
+function applyEntry(manifest: Manifest, entry: HistoryEntry): void {
+ for (const file of entry.files)
+ if (file.after === null) manifest.delete(file.path);
+ else manifest.set(file.path, file.after);
+}
+
+/** The files as they were right after `point`. Null when that point is no longer kept. */
+export function manifestAt(log: HistoryLog, point: string): Manifest | null {
+ const manifest = new Map(log.baseline);
+ if (point === START) return manifest;
+ for (const entry of log.entries) {
+ applyEntry(manifest, entry);
+ if (entry.id === point) return manifest;
+ }
+ return null;
+}
+
+/** Entries currently reverted: an undo that is itself in effect reverts its target. */
+export function undoneIds(entries: readonly HistoryEntry[]): Set<string> {
+ const undone = new Set<string>();
+ for (let i = entries.length - 1; i >= 0; i -= 1) {
+ const entry = entries[i]!;
+ if (entry.undoes && !undone.has(entry.id)) undone.add(entry.undoes);
+ }
+ return undone;
+}
+
+/**
+ * What Cmd+Z (back) or Cmd+Shift+Z (forward) reverts, whoever made the change. Back: the newest change still in
+ * effect. Forward: the newest undo of a change that is still in effect, while no change has been made since.
+ */
+export function stepTarget(
+ entries: readonly HistoryEntry[],
+ direction: "back" | "forward",
+): HistoryEntry | undefined {
+ const undone = undoneIds(entries);
+ const byId = new Map(entries.map((entry) => [entry.id, entry]));
+ for (let i = entries.length - 1; i >= 0; i -= 1) {
+ const entry = entries[i]!;
+ const isChange = !entry.undoes;
+ if (direction === "back" && isChange && !undone.has(entry.id)) return entry;
+ if (direction !== "forward") continue;
+ if (isChange) return undefined;
+ const target = byId.get(entry.undoes!);
+ if (!undone.has(entry.id) && target && !target.undoes) return entry;
+ }
+ return undefined;
+}
+
+/**
+ * Folds the oldest entry into the baseline unless it is pinned. ponytail: an old pin therefore holds everything
+ * after it; per-point snapshots would lift that. Returns whether one was folded.
+ */
+export function foldOldest(log: HistoryLog): boolean {
+ const oldest = log.entries[0];
+ if (!oldest || log.pins.has(oldest.id)) return false;
+ applyEntry(log.baseline, oldest);
+ log.entries.shift();
+ return true;
+}
+
+/** Every hash a kept point can still need. */
+export function referencedHashes(log: HistoryLog, current: Manifest): Set<string> {
+ const keep = new Set([...log.baseline.values(), ...current.values()]);
+ for (const entry of log.entries)
+ for (const file of entry.files) {
+ if (file.before) keep.add(file.before);
+ if (file.after) keep.add(file.after);
+ }
+ return keep;
+}
diff --git a/packages/studio-server/src/history/projectHistory.test.ts b/packages/studio-server/src/history/projectHistory.test.ts
new file mode 100644
index 0000000000..e789c61d6b
--- /dev/null
+++ b/packages/studio-server/src/history/projectHistory.test.ts
@@ -0,0 +1,295 @@
+// @vitest-environment node
+import {
+ cpSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, relative } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { openProjectHistory, type ProjectHistory } from "./projectHistory";
+import { START, type HistoryWho } from "./historyLog";
+
+const you: HistoryWho = { kind: "person", name: "You" };
+const agent: HistoryWho = { kind: "agent", name: "Agent" };
+const cleanup: Array<() => unknown> = [];
+
+afterEach(async () => {
+ for (const step of cleanup.splice(0).reverse()) await step();
+});
+
+function tempDir(prefix: string): string {
+ const dir = mkdtempSync(join(tmpdir(), prefix));
+ cleanup.push(() => rmSync(dir, { recursive: true, force: true }));
+ return dir;
+}
+
+async function open(projectDir: string, historyRoot: string, options = {}) {
+ const history = await openProjectHistory({ projectDir, historyRoot, ...options });
+ cleanup.push(() => history.close());
+ return history;
+}
+
+async function project(files: Record<string, string | Buffer>, options = {}) {
+ const projectDir = tempDir("hf-history-project-");
+ const historyRoot = tempDir("hf-history-root-");
+ const write = (path: string, content: string | Buffer) => {
+ mkdirSync(dirname(join(projectDir, path)), { recursive: true });
+ writeFileSync(join(projectDir, path), content);
+ };
+ for (const [path, content] of Object.entries(files)) write(path, content);
+ const history = await open(projectDir, historyRoot, options);
+ const read = (path: string) => readFileSync(join(projectDir, path), "utf-8");
+ const has = (path: string) => existsSync(join(projectDir, path));
+ return { projectDir, historyRoot, history, write, read, has };
+}
+
+/** Runs `writes` inside a window of `who`'s and returns the entry it became. */
+async function change(history: ProjectHistory, who: HistoryWho, label: string, writes: () => void) {
+ const window = await history.beginWindow(who, label);
+ writes();
+ const entry = await window.close();
+ if (!entry) throw new Error("the window recorded nothing");
+ return entry;
+}
+
+describe("openProjectHistory", () => {
+ it("records a write nobody announced as one outside entry, and undo puts the bytes back as a new entry", async () => {
+ const { history, write, read, projectDir } = await project(
+ { "index.html": "<h1>Hello</h1>", "assets/logo.png": Buffer.from([1, 2, 3]) },
+ { quietMs: 30 },
+ );
+ write("index.html", "<h1>Bye</h1>");
+ write("assets/logo.png", Buffer.from([9, 9]));
+ history.noteChange("index.html");
+ history.noteChange(join(projectDir, "assets/logo.png"));
+
+ await vi.waitFor(() => expect(history.list()).toHaveLength(1));
+ const [outside] = history.list();
+ expect(outside).toMatchObject({ who: { kind: "outside" }, label: "Changed outside the app" });
+ expect(outside!.files.map((file) => file.path)).toEqual(["assets/logo.png", "index.html"]);
+
+ const undone = await history.undo(outside!.id, { who: you });
+ expect(undone).toMatchObject({ ok: true, entry: { label: "Undid: Changed outside the app" } });
+ expect(read("index.html")).toBe("<h1>Hello</h1>");
+ expect([...readFileSync(join(projectDir, "assets/logo.png"))]).toEqual([1, 2, 3]);
+ expect(history.list().find((entry) => entry.id === outside!.id)?.undone).toBe(true);
+
+ expect(await history.step("forward", you)).toMatchObject({
+ entry: { label: "Redid: Changed outside the app" },
+ });
+ expect(read("index.html")).toBe("<h1>Bye</h1>");
+ await history.step("back", you);
+ expect(read("index.html")).toBe("<h1>Hello</h1>");
+ expect(history.list()).toHaveLength(4);
+ });
+
+ it("gives a window's writes to its writer, and undoes a create, a delete and Studio's manifest", async () => {
+ const { history, write, read, has, projectDir } = await project({
+ "index.html": "<h1>Hello</h1>",
+ "old.css": "h1 {}",
+ });
+ expect(await (await history.beginWindow(agent, "nothing")).close()).toBeNull();
+
+ const entry = await change(history, agent, "add Flash Through White", () => {
+ write("index.html", "<h1>Flash</h1>");
+ write("new.html", "<p>new</p>");
+ write(".hyperframes/studio-manual-edits.json", "{}");
+ rmSync(join(projectDir, "old.css"));
+ });
+ expect(entry.who).toEqual(agent);
+ expect(entry.files.map((file) => [file.path, !!file.before, !!file.after])).toEqual([
+ [".hyperframes/studio-manual-edits.json", false, true],
+ ["index.html", true, true],
+ ["new.html", false, true],
+ ["old.css", true, false],
+ ]);
+
+ expect((await history.undo(entry.id, { who: you })).ok).toBe(true);
+ expect(read("index.html")).toBe("<h1>Hello</h1>");
+ expect(read("old.css")).toBe("h1 {}");
+ expect(has("new.html")).toBe(false);
+ expect(has(".hyperframes/studio-manual-edits.json")).toBe(false);
+ });
+
+ it("names a file changed since and the newer change, then takes 'undo just this' when asked", async () => {
+ const { history, write, read } = await project({ "index.html": "A", "notes.txt": "n1" });
+ const first = await change(history, you, "Title", () => {
+ write("index.html", "B");
+ write("notes.txt", "n2");
+ });
+ const newer = await change(history, agent, "Retitle", () => write("index.html", "C"));
+
+ expect(await history.undo(first.id, { who: you })).toEqual({
+ ok: false,
+ conflict: { files: ["index.html"], newer: [newer.id] },
+ });
+ expect([read("index.html"), read("notes.txt")]).toEqual(["C", "n2"]);
+
+ expect((await history.undo(first.id, { who: you, mode: "just-this" })).ok).toBe(true);
+ expect([read("index.html"), read("notes.txt")]).toEqual(["A", "n1"]);
+ });
+
+ it("'go back to before this' reverts the change and everything after it as one entry", async () => {
+ const { history, write, read, has } = await project({ "index.html": "A" });
+ const first = await change(history, you, "Title", () => write("index.html", "B"));
+ await change(history, agent, "Extra", () => {
+ write("index.html", "C");
+ write("extra.txt", "x");
+ });
+
+ const back = await history.undo(first.id, { who: you, mode: "back-to-before" });
+ expect(back).toMatchObject({ ok: true, entry: { restoredTo: START } });
+ expect(read("index.html")).toBe("A");
+ expect(has("extra.txt")).toBe(false);
+ });
+
+ it("restores any point, and peek reads a point's bytes without writing", async () => {
+ const { history, write, read } = await project({ "index.html": "v1" });
+ const second = await change(history, you, "Second", () => write("index.html", "v2"));
+ await change(history, you, "Third", () => write("index.html", "v3"));
+
+ const at = (point: string) => history.peek(point)!["index.html"]!;
+ expect((await history.readBlob(at(second.id))).toString()).toBe("v2");
+ expect((await history.readBlob(at(START))).toString()).toBe("v1");
+ expect(read("index.html")).toBe("v3");
+
+ const restored = await history.restore(second.id, you);
+ expect(restored).toMatchObject({ label: "Restored: Second", restoredTo: second.id });
+ expect(read("index.html")).toBe("v2");
+ });
+
+ it("keeps the history across a move and a reopen, and a copy of the folder starts its own", async () => {
+ const { history, write, projectDir, historyRoot } = await project({ "index.html": "v1" });
+ write("index.html", "v2");
+ await history.flush();
+ const moved = `${projectDir}-moved`;
+ renameSync(projectDir, moved);
+ cleanup.push(() => rmSync(moved, { recursive: true, force: true }));
+ await history.flush();
+ expect(history.list(), "a moved folder is not every file deleted").toHaveLength(1);
+ await history.close();
+ writeFileSync(join(moved, "index.html"), "v3");
+
+ const reopened = await open(moved, historyRoot);
+ expect(reopened.projectId).toBe(history.projectId);
+ expect(reopened.list()).toHaveLength(2);
+ await reopened.step("back", you);
+ expect(readFileSync(join(moved, "index.html"), "utf-8")).toBe("v2");
+
+ const copy = tempDir("hf-history-copy-");
+ cpSync(moved, copy, { recursive: true });
+ const copied = await open(copy, historyRoot);
+ expect(copied.projectId).not.toBe(history.projectId);
+ expect(copied.list()).toEqual([]);
+ });
+
+ it("rewrites a history folder removed while open, so a reopen still has the change", async () => {
+ const { history, write, projectDir, historyRoot } = await project({ "index.html": "v1" });
+ const earlier = await change(history, you, "Second", () => write("index.html", "v2"));
+ rmSync(historyRoot, { recursive: true, force: true });
+ const entry = await change(history, you, "Third", () => write("index.html", "v3"));
+ await history.close();
+
+ const reopened = await open(projectDir, historyRoot);
+ expect(reopened.list().map((kept) => kept.id)).toEqual([earlier.id, entry.id]);
+ const hash = reopened.peek(entry.id)!["index.html"]!;
+ expect((await reopened.readBlob(hash)).toString()).toBe("v3");
+ });
+
+ it("reports a damaged log line and keeps every line around it", async () => {
+ const { history, write, projectDir, historyRoot } = await project({ "index.html": "v1" });
+ await change(history, you, "Second", () => write("index.html", "v2"));
+ await change(history, you, "Third", () => write("index.html", "v3"));
+ await history.close();
+ const logFile = join(historyRoot, history.projectId, "log.jsonl");
+ const lines = readFileSync(logFile, "utf-8").split("\n");
+ writeFileSync(logFile, [lines[0], "{not json", ...lines.slice(1)].join("\n"));
+
+ const onError = vi.fn();
+ const reopened = await open(projectDir, historyRoot, { onError });
+ expect(onError).toHaveBeenCalledOnce();
+ expect(String(onError.mock.calls[0]![0])).toMatch(/line 2 /);
+ expect(reopened.list().map((kept) => kept.label)).toEqual(["Second", "Third"]);
+ });
+
+ it("mints its own id when the project's history-id is anything else, so a project cannot pick where history is written", async () => {
+ const projectDir = tempDir("hf-history-project-");
+ const historyRoot = tempDir("hf-history-root-");
+ const victim = tempDir("hf-history-victim-");
+ writeFileSync(join(projectDir, "index.html"), "v1");
+ writeFileSync(join(victim, "project.json"), '{"precious":true}');
+ mkdirSync(join(projectDir, ".hyperframes"));
+ writeFileSync(join(projectDir, ".hyperframes", "history-id"), relative(historyRoot, victim));
+
+ const history = await open(projectDir, historyRoot);
+ expect(history.projectId).toMatch(/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/);
+ expect(readdirSync(victim)).toEqual(["project.json"]);
+ expect(readFileSync(join(victim, "project.json"), "utf-8")).toBe('{"precious":true}');
+ const idFile = join(projectDir, ".hyperframes", "history-id");
+ expect(readFileSync(idFile, "utf-8").trim()).toBe(history.projectId);
+ });
+
+ it("commits a window that is never closed when the history flushes, so Cmd+Z still reaches its writes", async () => {
+ const { history, write, read } = await project({ "index.html": "a" });
+ await history.beginWindow(agent, "never closed");
+ write("index.html", "b, an outside edit");
+ await history.flush();
+ expect(history.list()).toHaveLength(1);
+ expect(await history.step("back", you)).toMatchObject({
+ ok: true,
+ entry: { label: "Undid: never closed" },
+ });
+ expect(read("index.html")).toBe("a");
+ });
+
+ it("ends a window idle past its lifetime, so later writes are the outside's", async () => {
+ const { history, write } = await project({ "index.html": "a" });
+ const window = await history.beginWindow(agent, "Short", { idleMs: 40 });
+ write("index.html", "b");
+ await vi.waitFor(() => expect(history.list()).toHaveLength(1));
+ write("index.html", "c");
+ await history.flush();
+ expect(history.list().map((entry) => [entry.label, entry.who.kind])).toEqual([
+ ["Short", "agent"],
+ ["Changed outside the app", "outside"],
+ ]);
+ expect((await window.close())?.id).toBe(window.id);
+ });
+
+ it("keeps the history of a small edit in a project larger than its budget", async () => {
+ const { history, write } = await project(
+ { "media.bin": Buffer.alloc(4096, 1), "index.html": "a" },
+ { budgetBytes: 2048 },
+ );
+ await change(history, you, "Title", () => write("index.html", "b"));
+ expect(history.list()).toHaveLength(1);
+ });
+
+ it("past its budget folds the oldest entries away and deletes their bytes, but never past a pin", async () => {
+ const { history, write, read } = await project(
+ { "index.html": "a".repeat(40) },
+ { budgetBytes: 50 },
+ );
+ const pinned = await change(history, you, "B", () => write("index.html", "b".repeat(40)));
+ history.pin(pinned.id, true);
+ await change(history, you, "C", () => write("index.html", "c".repeat(40)));
+ expect(history.list()).toHaveLength(2);
+
+ history.pin(pinned.id, false);
+ const last = await change(history, you, "D", () => write("index.html", "d".repeat(40)));
+ expect(history.list().map((entry) => entry.id)).toEqual([last.id]);
+ expect(history.peek(pinned.id)).toBeNull();
+ await expect(history.readBlob(history.peek(START)!["index.html"]!)).resolves.toEqual(
+ Buffer.from("c".repeat(40)),
+ );
+ expect((await history.undo(last.id, { who: you })).ok).toBe(true);
+ expect(read("index.html")).toBe("c".repeat(40));
+ });
+});
diff --git a/packages/studio-server/src/history/projectHistory.ts b/packages/studio-server/src/history/projectHistory.ts
new file mode 100644
index 0000000000..ac7eaef6fe
--- /dev/null
+++ b/packages/studio-server/src/history/projectHistory.ts
@@ -0,0 +1,529 @@
+import { randomUUID } from "node:crypto";
+import { rm } from "node:fs/promises";
+import { existsSync, mkdirSync, readFileSync } from "node:fs";
+import { join, resolve } from "node:path";
+import { replaceFileAtomically } from "../helpers/atomicFile.js";
+import { affectsProjectSignature, listProjectFiles } from "../helpers/projectSignature.js";
+import { openBlobStore, type BlobStore } from "./blobStore.js";
+import { projectHistoryId } from "./historyId.js";
+import {
+ START,
+ foldOldest,
+ manifestAt,
+ readLog,
+ saveRecord,
+ referencedHashes,
+ stepTarget,
+ undoneIds,
+ writeLog,
+ type HistoryEntry,
+ type HistoryFileChange,
+ type HistoryLog,
+ type HistoryWho,
+ type Manifest,
+} from "./historyLog.js";
+
+export interface ProjectHistoryOptions {
+ projectDir: string;
+ /** Kept outside the project, so nothing tidying the project can take its history with it. */
+ historyRoot: string;
+ now?: () => number;
+ /** Writes with no window open group into one entry until this long without another (default 2 s)... */
+ quietMs?: number;
+ /** ...or this long after the first (default 30 s). */
+ maxGroupMs?: number;
+ /** Past this many stored bytes the oldest unpinned entries are folded away (default 2 GB). */
+ budgetBytes?: number;
+ /** A sweep or commit that a watcher or timer started failed. */
+ onError?: (error: unknown) => void;
+}
+
+export interface HistoryListItem extends HistoryEntry {
+ pinned: boolean;
+ undone: boolean;
+}
+
+export type HistoryResult =
+ | { ok: true; entry: HistoryEntry | null }
+ | { ok: false; conflict: { files: string[]; newer: string[] } };
+
+export interface HistoryWindow {
+ readonly id: string;
+ /** Records everything written since the window opened as one entry (null when nothing changed); after the window
+ * ended by itself or by flush, returns the entry it became. */
+ close(): Promise<HistoryEntry | null>;
+}
+
+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.
+ */
+ beginWindow(
+ who: HistoryWho,
+ label: string,
+ options?: { idleMs?: number },
+ ): Promise<HistoryWindow>;
+ /** 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>;
+ /** 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" },
+ ): 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>;
+ /** 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>;
+ pin(id: string, pinned: boolean): void;
+ onEntry(listener: (entry: HistoryEntry) => void): () => void;
+ /** Takes in every pending write and commits every open window and the outside group. */
+ flush(): Promise<void>;
+ close(): Promise<void>;
+}
+
+const OUTSIDE: HistoryWho = { kind: "outside", name: "Outside" };
+const OUTSIDE_LABEL = "Changed outside the app";
+
+interface Tracked {
+ hash: string;
+ stat: string;
+}
+
+interface Group {
+ id: string;
+ who: HistoryWho;
+ label: string;
+ startedAt: number;
+ changes: Map<string, HistoryFileChange>;
+ /** Windows only: the idle lifetime, its timer, and the entry it became once ended. */
+ idleMs?: number;
+ idleTimer?: NodeJS.Timeout;
+ entry?: HistoryEntry | null;
+}
+
+/**
+ * A stat is only trusted once the file is older than any file system's timestamp tick (git's "racily clean"): a
+ * same-size rewrite inside one tick keeps its size, mtime and ctime. "" is never trusted, so the file is re-hashed.
+ */
+const RACY_MS = 2000;
+const statKey = (file: { size: number; mtimeMs: number; ctimeMs: number }, sweptAt: number) =>
+ sweptAt - Math.max(file.mtimeMs, file.ctimeMs) < RACY_MS
+ ? ""
+ : `${file.size}:${file.mtimeMs}:${file.ctimeMs}`;
+
+class Engine {
+ readonly dir: string;
+ readonly home: string;
+ log: HistoryLog = { baseline: new Map(), entries: [], pins: new Set() };
+ tracked = new Map<string, Tracked>();
+ windows: Group[] = [];
+ outside: Group | null = null;
+ quietTimer: NodeJS.Timeout | undefined;
+ maxTimer: NodeJS.Timeout | undefined;
+ notedTimer: NodeJS.Timeout | null = null;
+ listeners = new Set<(entry: HistoryEntry) => void>();
+ tail: Promise<unknown> = Promise.resolve();
+
+ constructor(
+ readonly options: ProjectHistoryOptions,
+ readonly projectId: string,
+ readonly blobs: BlobStore,
+ ) {
+ this.dir = resolve(options.projectDir);
+ this.home = join(options.historyRoot, projectId);
+ }
+
+ get logFile() {
+ return join(this.home, "log.jsonl");
+ }
+
+ now(): number {
+ return (this.options.now ?? Date.now)();
+ }
+
+ /** One operation at a time, in order: sweeps, windows and undos never interleave. */
+ queue<T>(task: () => Promise<T>): Promise<T> {
+ const run = this.tail.then(task);
+ this.tail = run.catch(() => undefined);
+ return run;
+ }
+
+ async start(): Promise<void> {
+ const log = readLog(this.logFile, (line) =>
+ this.options.onError?.(
+ new Error(`History log line ${line} could not be read and was skipped.`),
+ ),
+ );
+ if (!log) return this.firstOpen();
+ this.log = log;
+ const cache = this.readStatCache();
+ const last = this.log.entries.at(-1)?.id ?? START;
+ for (const [path, hash] of manifestAt(this.log, last) ?? []) {
+ const cached = cache.get(path);
+ this.tracked.set(path, { hash, stat: cached?.hash === hash ? cached.stat : "" });
+ }
+ // What changed while the project was closed is one outside entry.
+ await this.sweep();
+ await this.commitOutside();
+ }
+
+ async firstOpen(): Promise<void> {
+ const sweptAt = Date.now();
+ for (const file of listProjectFiles(this.dir))
+ this.tracked.set(file.path, {
+ hash: await this.blobs.put(join(this.dir, file.path)),
+ stat: statKey(file, sweptAt),
+ });
+ this.log.baseline = this.manifest();
+ writeLog(this.logFile, this.log);
+ this.saveStatCache();
+ }
+
+ manifest(): Manifest {
+ return new Map([...this.tracked].map(([path, file]) => [path, file.hash]));
+ }
+
+ readStatCache(): Map<string, Tracked> {
+ try {
+ const files = JSON.parse(readFileSync(join(this.home, "stat.json"), "utf-8"));
+ return new Map(Object.entries(files as Record<string, Tracked>));
+ } catch {
+ return new Map();
+ }
+ }
+
+ saveStatCache(): void {
+ const files = JSON.stringify(Object.fromEntries(this.tracked));
+ mkdirSync(this.home, { recursive: true });
+ replaceFileAtomically(join(this.home, "stat.json"), files, 0o644);
+ }
+
+ /**
+ * Takes in every write since the last sweep and files each change to its writer. ponytail: always the whole
+ * project (a stat per file, a hash only when the stat moved); per-path sweeps if projects reach tens of thousands.
+ */
+ async sweep(): Promise<void> {
+ // A missing project folder was moved or removed, not emptied: that is no change to its files.
+ if (!existsSync(this.dir)) return;
+ const sweptAt = Date.now();
+ const seen = listProjectFiles(this.dir);
+ let changed = false;
+ for (const file of seen)
+ changed = (await this.observe(file.path, statKey(file, sweptAt))) || changed;
+ const present = new Set(seen.map((file) => file.path));
+ for (const [path, known] of this.tracked) {
+ if (present.has(path)) continue;
+ this.tracked.delete(path);
+ this.record(path, known.hash, null);
+ changed = true;
+ }
+ if (changed) this.saveStatCache();
+ }
+
+ /** The file's hash once copied in; null when it was removed before the copy (the next sweep records that). */
+ async storeIfPresent(path: string): Promise<string | null> {
+ try {
+ return await this.blobs.put(join(this.dir, path));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
+ throw error;
+ }
+ }
+
+ async observe(path: string, stat: string): Promise<boolean> {
+ const known = this.tracked.get(path) ?? { hash: null, stat: null };
+ if (stat && known.stat === stat) return false;
+ const hash = await this.storeIfPresent(path);
+ if (hash === null) return false;
+ this.tracked.set(path, { hash, stat });
+ if (known.hash !== hash) this.record(path, known.hash, hash);
+ return known.hash !== hash || known.stat !== stat;
+ }
+
+ record(path: string, before: string | null, after: string | null): void {
+ const window = this.windows.at(-1);
+ if (window) this.touch(window);
+ const group = window ?? this.outsideGroup();
+ const earlier = group.changes.get(path);
+ const from = earlier ? earlier.before : before;
+ if (from === after) group.changes.delete(path);
+ else group.changes.set(path, { path, before: from, after });
+ }
+
+ outsideGroup(): Group {
+ const { quietMs = 2000, maxGroupMs = 30_000 } = this.options;
+ const closeIn = (ms: number) => {
+ const timer = setTimeout(() => this.background(() => this.commitOutside()), ms);
+ timer.unref?.();
+ return timer;
+ };
+ if (!this.outside) {
+ this.outside = this.newGroup(OUTSIDE, OUTSIDE_LABEL);
+ this.maxTimer = closeIn(maxGroupMs);
+ }
+ clearTimeout(this.quietTimer);
+ this.quietTimer = closeIn(quietMs);
+ return this.outside;
+ }
+
+ newGroup(who: HistoryWho, label: string): Group {
+ return { id: randomUUID(), who, label, startedAt: this.now(), changes: new Map() };
+ }
+
+ async commitOutside(): Promise<void> {
+ clearTimeout(this.quietTimer);
+ clearTimeout(this.maxTimer);
+ const group = this.outside;
+ this.outside = null;
+ if (group) await this.commit(group);
+ }
+
+ async commit(group: Group, extra: Partial<HistoryEntry> = {}): Promise<HistoryEntry | null> {
+ if (!group.changes.size) return null;
+ const { changes, ...rest } = group;
+ const files = [...changes.values()].sort((a, b) => a.path.localeCompare(b.path));
+ const entry: HistoryEntry = { ...rest, endedAt: this.now(), files, ...extra };
+ this.log.entries.push(entry);
+ try {
+ saveRecord(this.logFile, this.log, { type: "entry", entry });
+ } catch (error) {
+ this.log.entries.pop();
+ throw error;
+ }
+ for (const listener of this.listeners) listener(entry);
+ await this.keepWithinBudget();
+ return entry;
+ }
+
+ /** Stored bytes beyond what the current files need: a project larger than the budget still keeps its history. */
+ historyBytes(): number {
+ let current = 0;
+ for (const hash of new Set([...this.tracked.values()].map((file) => file.hash)))
+ current += this.blobs.size(hash);
+ return this.blobs.bytes() - current;
+ }
+
+ async keepWithinBudget(): Promise<void> {
+ const budget = this.options.budgetBytes ?? 2 * 1024 ** 3;
+ let folded = false;
+ while (this.historyBytes() > budget && foldOldest(this.log)) {
+ folded = true;
+ await this.blobs.prune(referencedHashes(this.log, this.manifest()));
+ }
+ if (folded) writeLog(this.logFile, this.log);
+ }
+
+ /** Before an operation: every write so far is filed, and the outside group is closed so it sorts first. */
+ async settle(): Promise<void> {
+ await this.sweep();
+ await this.commitOutside();
+ }
+
+ /** A watcher saw a write: one sweep per burst takes it in (a deleted folder is reported by its name alone). */
+ noteChange(path: string): void {
+ if (this.notedTimer || !affectsProjectSignature(this.dir, resolve(this.dir, path))) return;
+ this.notedTimer = setTimeout(() => {
+ this.notedTimer = null;
+ this.background(() => this.sweep());
+ }, 20);
+ this.notedTimer.unref?.();
+ }
+
+ background(task: () => Promise<unknown>): void {
+ this.queue(task).catch((error) => this.options.onError?.(error));
+ }
+
+ beginWindow(who: HistoryWho, label: string, idleMs: number): Promise<HistoryWindow> {
+ return this.queue(async () => {
+ // Writes before the window opened are not this writer's.
+ await this.sweep();
+ const window = { ...this.newGroup(who, label), idleMs };
+ this.windows.push(window);
+ this.touch(window);
+ return { id: window.id, close: () => this.queue(() => this.sweepAndEnd(window)) };
+ });
+ }
+
+ /** A window with no write for its idleMs ends, so a close that never comes cannot hold every later write. */
+ touch(window: Group): void {
+ clearTimeout(window.idleTimer);
+ if (window.idleMs === undefined || !Number.isFinite(window.idleMs)) return;
+ window.idleTimer = setTimeout(
+ () => this.background(() => this.sweepAndEnd(window)),
+ window.idleMs,
+ );
+ window.idleTimer.unref?.();
+ }
+
+ async sweepAndEnd(window: Group): Promise<HistoryEntry | null> {
+ await this.sweep();
+ return this.endWindow(window);
+ }
+
+ /** Commits an open window once; ending it again returns the entry it became. */
+ async endWindow(window: Group): Promise<HistoryEntry | null> {
+ 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);
+ return window.entry;
+ }
+
+ /** Every pending write, open window and outside group, committed: for flush and close. */
+ async settleAll(): Promise<void> {
+ await this.sweep();
+ for (const window of [...this.windows]) await this.endWindow(window);
+ await this.commitOutside();
+ }
+
+ /** Writes `target` (path to hash, null deletes) as one entry of `who`'s. */
+ async writeAs(
+ who: HistoryWho,
+ label: string,
+ target: Map<string, string | null>,
+ extra: Partial<HistoryEntry>,
+ ): Promise<HistoryEntry | null> {
+ const group = this.newGroup(who, label);
+ 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));
+ }
+ await this.sweep();
+ } finally {
+ this.windows = this.windows.filter((open) => open !== group);
+ }
+ return this.commit(group, extra);
+ }
+
+ 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.");
+ return entry;
+ }
+
+ undoLabel(entry: HistoryEntry): string {
+ if (!entry.undoes) return `Undid: ${entry.label}`;
+ const original = this.log.entries.find((candidate) => candidate.id === entry.undoes);
+ return `Redid: ${original?.label ?? entry.label}`;
+ }
+
+ async undoNow(
+ id: string,
+ who: HistoryWho,
+ 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,
+ );
+ if (changed.length && !mode) return { ok: false, conflict: this.conflict(entry, changed) };
+ if (mode === "back-to-before") {
+ const index = this.log.entries.indexOf(entry);
+ const point = index > 0 ? this.log.entries[index - 1]!.id : START;
+ return {
+ ok: true,
+ entry: await this.restoreNow(point, who, `Went back to before: ${entry.label}`),
+ };
+ }
+ const target = new Map(entry.files.map((file) => [file.path, file.before]));
+ return {
+ ok: true,
+ entry: await this.writeAs(who, this.undoLabel(entry), target, { undoes: id }),
+ };
+ }
+
+ conflict(
+ entry: HistoryEntry,
+ changed: HistoryFileChange[],
+ ): { files: string[]; newer: string[] } {
+ const paths = new Set(changed.map((file) => file.path));
+ const after = this.log.entries.slice(this.log.entries.indexOf(entry) + 1);
+ const newer = after.filter((later) => later.files.some((file) => paths.has(file.path)));
+ return { files: [...paths], newer: newer.map((later) => later.id) };
+ }
+
+ async restoreNow(point: string, who: HistoryWho, label: string): Promise<HistoryEntry | null> {
+ const files = manifestAt(this.log, point);
+ if (!files) throw new Error("That point is no longer kept in this project's history.");
+ const target = new Map<string, string | null>(
+ [...this.tracked.keys()].map((path) => [path, null]),
+ );
+ for (const [path, hash] of files) target.set(path, hash);
+ return this.writeAs(who, label, target, { restoredTo: point });
+ }
+
+ pointLabel(point: string): string {
+ return point === START ? "the start" : this.entry(point).label;
+ }
+
+ api(): ProjectHistory {
+ return {
+ projectId: this.projectId,
+ beginWindow: (who, label, options = {}) =>
+ this.beginWindow(who, label, options.idleMs ?? this.options.maxGroupMs ?? 30_000),
+ noteChange: (path) => this.noteChange(path),
+ list: () => {
+ const undone = undoneIds(this.log.entries);
+ return this.log.entries.map((entry) => ({
+ ...entry,
+ pinned: this.log.pins.has(entry.id),
+ undone: undone.has(entry.id),
+ }));
+ },
+ step: (direction, who) =>
+ this.queue(async () => {
+ await this.settle();
+ const target = stepTarget(this.log.entries, 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)}`);
+ }),
+ peek: (point) => {
+ const files = manifestAt(this.log, point);
+ return files && Object.fromEntries(files);
+ },
+ readBlob: (hash) => this.blobs.read(hash),
+ pin: (id, pinned) => {
+ this.entry(id);
+ if (pinned) this.log.pins.add(id);
+ else this.log.pins.delete(id);
+ saveRecord(this.logFile, this.log, { type: "pin", id, pinned });
+ },
+ onEntry: (listener) => {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ },
+ flush: () => this.queue(() => this.settleAll()),
+ close: async () => {
+ if (this.notedTimer) clearTimeout(this.notedTimer);
+ await this.queue(() => this.settleAll());
+ },
+ };
+ }
+}
+
+/** Opens a project's history: every write to its files becomes an entry that can be undone or restored. */
+export async function openProjectHistory(options: ProjectHistoryOptions): Promise<ProjectHistory> {
+ const projectId = projectHistoryId(options.projectDir, options.historyRoot);
+ const blobs = await openBlobStore(join(options.historyRoot, projectId, "blobs"));
+ const engine = new Engine(options, projectId, blobs);
+ await engine.queue(() => engine.start());
+ return engine.api();
+}
diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.ts
index 0943a871e4..670301c401 100644
--- a/packages/studio-server/src/index.ts
+++ b/packages/studio-server/src/index.ts
@@ -1,6 +1,20 @@
export { createStudioApi } from "./createStudioApi.js";
export { createProjectSignature, affectsProjectSignature } from "./helpers/projectSignature.js";
export { compositionsAffectedBy } from "./helpers/compositionInputs.js";
+export {
+ openProjectHistory,
+ type ProjectHistory,
+ type ProjectHistoryOptions,
+ type HistoryListItem,
+ type HistoryResult,
+ type HistoryWindow,
+} from "./history/projectHistory.js";
+export {
+ START as HISTORY_START,
+ type HistoryEntry,
+ type HistoryFileChange,
+ type HistoryWho,
+} from "./history/historyLog.js";
export type {
StudioApiAdapter,
ResolvedProject,
diff --git a/packages/studio-server/src/routes/history.test.ts b/packages/studio-server/src/routes/history.test.ts
new file mode 100644
index 0000000000..847d54c2af
--- /dev/null
+++ b/packages/studio-server/src/routes/history.test.ts
@@ -0,0 +1,88 @@
+// @vitest-environment node
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import { createStudioApi } from "../createStudioApi";
+import { openProjectHistory, type ProjectHistory } from "../history/projectHistory";
+import type { StudioApiAdapter } from "../types";
+
+const cleanup: Array<() => unknown> = [];
+
+afterEach(async () => {
+ for (const step of cleanup.splice(0).reverse()) await step();
+});
+
+function tempDir(prefix: string): string {
+ const dir = mkdtempSync(join(tmpdir(), prefix));
+ cleanup.push(() => rmSync(dir, { recursive: true, force: true }));
+ return dir;
+}
+
+function apiFor(projectDir: string, history?: ProjectHistory) {
+ const adapter = {
+ listProjects: () => [],
+ resolveProject: (id: string) => (id === "demo" ? { id, dir: projectDir } : null),
+ ...(history && { history: () => history }),
+ } as unknown as StudioApiAdapter;
+ const api = createStudioApi(adapter);
+ return (path: string, body?: object) =>
+ api.request(
+ `/projects/demo/history${path}`,
+ body ? { method: "POST", body: JSON.stringify(body) } : undefined,
+ );
+}
+
+describe("history routes", () => {
+ it("record a Studio edit window as the person's entry, and step back undoes it", async () => {
+ const projectDir = tempDir("hf-history-routes-");
+ writeFileSync(join(projectDir, "index.html"), "A");
+ const history = await openProjectHistory({
+ projectDir,
+ historyRoot: tempDir("hf-history-routes-root-"),
+ });
+ cleanup.push(() => history.close());
+ const call = apiFor(projectDir, history);
+
+ const { windowId } = await (await call("/window", { label: "Moved Title" })).json();
+ writeFileSync(join(projectDir, "index.html"), "B");
+ const { entry } = await (await call(`/window/${windowId}/close`, {})).json();
+ expect(entry).toMatchObject({ label: "Moved Title", who: { kind: "person", name: "You" } });
+
+ const step = await (await call("/step", { direction: "back" })).json();
+ expect(step).toMatchObject({ ok: true, entry: { label: "Undid: Moved Title" } });
+ expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toBe("A");
+ expect((await (await call("")).json()).entries).toHaveLength(2);
+ });
+
+ it("refuse to close a window through another project's route", async () => {
+ const projects = new Map<string, { dir: string; history: ProjectHistory }>();
+ for (const id of ["demo", "other"]) {
+ const dir = tempDir("hf-history-routes-");
+ writeFileSync(join(dir, "index.html"), "A");
+ const history = await openProjectHistory({
+ projectDir: dir,
+ historyRoot: tempDir("hf-history-routes-root-"),
+ });
+ cleanup.push(() => history.close());
+ projects.set(id, { dir, history });
+ }
+ const api = createStudioApi({
+ listProjects: () => [],
+ resolveProject: (id: string) =>
+ projects.has(id) ? { id, dir: projects.get(id)!.dir } : null,
+ history: (project: { id: string }) => projects.get(project.id)!.history,
+ } as unknown as StudioApiAdapter);
+ const post = (id: string, path: string, body: object) =>
+ api.request(`/projects/${id}/history${path}`, { method: "POST", body: JSON.stringify(body) });
+
+ const { windowId } = await (await post("demo", "/window", { label: "Moved Title" })).json();
+ expect((await post("other", `/window/${windowId}/close`, {})).status).toBe(409);
+ expect((await post("demo", `/window/${windowId}/close`, {})).status).toBe(200);
+ });
+
+ it("answer 404 when the host keeps no history for the project", async () => {
+ const call = apiFor(tempDir("hf-history-routes-none-"));
+ expect((await call("")).status).toBe(404);
+ });
+});
diff --git a/packages/studio-server/src/routes/history.ts b/packages/studio-server/src/routes/history.ts
new file mode 100644
index 0000000000..b3eb3fef2f
--- /dev/null
+++ b/packages/studio-server/src/routes/history.ts
@@ -0,0 +1,83 @@
+import type { Context, Hono } from "hono";
+import type { StudioApiAdapter } from "../types.js";
+import type { HistoryWindow, ProjectHistory } from "../history/projectHistory.js";
+import type { HistoryWho } from "../history/historyLog.js";
+
+const YOU: HistoryWho = { kind: "person", name: "You" };
+
+async function historyOf(adapter: StudioApiAdapter, c: Context): Promise<ProjectHistory | null> {
+ const project = await adapter.resolveProject(c.req.param("id") ?? "");
+ return project ? ((await adapter.history?.(project)) ?? null) : null;
+}
+
+async function bodyOf(c: Context): Promise<Record<string, unknown>> {
+ const body = await c.req.json().catch(() => null);
+ return body && typeof body === "object" ? (body as Record<string, unknown>) : {};
+}
+
+const text = (value: unknown) => (typeof value === "string" && value ? value : null);
+
+/** Runs `task` on the project's history; no history is a 404, an engine refusal ("no longer kept") a 409. */
+async function withHistory(
+ adapter: StudioApiAdapter,
+ c: Context,
+ task: (history: ProjectHistory, body: Record<string, unknown>) => Promise<unknown> | unknown,
+) {
+ const history = await historyOf(adapter, c);
+ if (!history) return c.json({ error: "This project has no history here." }, 404);
+ try {
+ return c.json((await task(history, await bodyOf(c))) ?? null);
+ } catch (error) {
+ return c.json({ error: error instanceof Error ? error.message : String(error) }, 409);
+ }
+}
+
+/** Studio's history: list, Cmd+Z and Shift+Z, undo with the conflict choice, restore, peek, pin, edit windows. */
+export function registerHistoryRoutes(api: Hono, adapter: StudioApiAdapter): void {
+ // ponytail: a window whose close never arrives ends itself when idle; its entry here stays until the server stops.
+ const windows = new Map<string, { history: ProjectHistory; window: HistoryWindow }>();
+ const base = "/projects/:id/history";
+
+ api.get(base, (c) => withHistory(adapter, c, (history) => ({ entries: history.list() })));
+ api.post(`${base}/step`, (c) =>
+ withHistory(adapter, c, (history, body) =>
+ history.step(body.direction === "forward" ? "forward" : "back", YOU),
+ ),
+ );
+ 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 });
+ }),
+ );
+ api.post(`${base}/restore`, (c) =>
+ withHistory(adapter, c, (history, body) => history.restore(text(body.point) ?? "", YOU)),
+ );
+ api.get(`${base}/peek/:point`, (c) =>
+ withHistory(adapter, c, (history) => ({ files: history.peek(c.req.param("point")) })),
+ );
+ api.post(`${base}/pin`, (c) =>
+ withHistory(adapter, c, (history, body) => {
+ history.pin(text(body.entryId) ?? "", body.pinned === true);
+ return { ok: true };
+ }),
+ );
+ api.post(`${base}/window`, (c) =>
+ withHistory(adapter, c, async (history, body) => {
+ const window = await history.beginWindow(YOU, text(body.label) ?? "Edited in Studio");
+ windows.set(window.id, { history, window });
+ // The window's id is the id of the entry it becomes.
+ return { windowId: window.id };
+ }),
+ );
+ api.post(`${base}/window/:windowId/close`, (c) =>
+ withHistory(adapter, c, async (history) => {
+ const id = c.req.param("windowId") ?? "";
+ const held = windows.get(id);
+ if (held?.history !== history) throw new Error("That window is not open in this project.");
+ windows.delete(id);
+ return { entry: await held.window.close() };
+ }),
+ );
+}
diff --git a/packages/studio-server/src/types.ts b/packages/studio-server/src/types.ts
index 3280a8638b..fd377e4227 100644
--- a/packages/studio-server/src/types.ts
+++ b/packages/studio-server/src/types.ts
@@ -1,5 +1,6 @@
import type { CanvasResolution } from "@hyperframes/parsers";
import type { RegistryItem } from "@hyperframes/core";
+import type { ProjectHistory } from "./history/projectHistory.js";
/** Resolved info about a single project. */
export interface ResolvedProject {
@@ -106,6 +107,12 @@ export interface StudioApiAdapter {
/** Resolve a project ID (or session ID) to its directory. Returns null if not found. */
resolveProject(id: string): Promise<ResolvedProject | null> | ResolvedProject | null;
+ /**
+ * Optional: the project's history (openProjectHistory), one per project for the host's lifetime. Without it
+ * the history routes answer 404.
+ */
+ history?: (project: ResolvedProject) => Promise<ProjectHistory | null> | ProjectHistory | null;
+
/** Bundle a project directory into a single HTML string. Returns null if unavailable. */
bundle(projectDir: string): Promise<string | null>;