Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(studio-server): history can copy the files before or after any change into a folder (#4493)
Miguel Ángel7c017a08de35
diff --git a/packages/cli/src/utils/historyOwner.ts b/packages/cli/src/utils/historyOwner.tsindex e5a0c02d9d..760271df5b 100644--- a/packages/cli/src/utils/historyOwner.ts+++ b/packages/cli/src/utils/historyOwner.ts@@ -9,11 +9,13 @@ import {type HistoryListItem,type HistoryResult,type HistoryWho,+ type UndoMode,} from "@hyperframes/studio-server";+import { resolveProject } from "./project.js";import { findPreviewServerForProject, studioApiUrl } from "./studioSelectionClient.js";-export type UndoMode = "just-this" | "back-to-before";+export type { UndoMode };/** An agent's turn: its writes until `end`, or until the idle limit passes without one, are one entry of its own. */export interface Turn {diff --git a/packages/studio-server/src/history/historyId.ts b/packages/studio-server/src/history/historyId.tsindex e19dd5cbfe..38eec0483d 100644--- a/packages/studio-server/src/history/historyId.ts+++ b/packages/studio-server/src/history/historyId.ts@@ -2,7 +2,7 @@ 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");+export 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}$/;diff --git a/packages/studio-server/src/history/historyLog.ts b/packages/studio-server/src/history/historyLog.tsindex 3a8f4abc8a..0c352f1a80 100644--- a/packages/studio-server/src/history/historyLog.ts+++ b/packages/studio-server/src/history/historyLog.ts@@ -15,6 +15,8 @@ export interface HistoryFileChange {after: string | null;}+export type HistoryEntrySide = "before" | "after";+export interface HistoryEntry {id: string;who: HistoryWho;@@ -105,19 +107,29 @@ export function writeLog(file: string, log: HistoryLog): void {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);+function applyEntry(manifest: Manifest, entry: HistoryEntry, side: HistoryEntrySide): void {+ for (const file of entry.files) {+ const hash = file[side];+ if (hash === null) manifest.delete(file.path);+ else manifest.set(file.path, hash);+ }}/** 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 {+ return point === START ? new Map(log.baseline) : manifestAround(log, point, "after");+}++/** Entry `id`'s own files as it found (`before`) or left (`after`) them; the rest as earlier entries left them. */+export function manifestAround(+ log: HistoryLog,+ id: string,+ side: HistoryEntrySide,+): 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;+ applyEntry(manifest, entry, entry.id === id ? side : "after");+ if (entry.id === id) return manifest;}return null;}@@ -133,27 +145,45 @@ export function undoneIds(entries: readonly HistoryEntry[]): Set<string> {}/**- * 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.+ * What Cmd+Z (back) or Cmd+Shift+Z (forward) reverts for `mine`. Back: the newest change `mine` owns that is still+ * in effect. Forward: the newest of `mine`'s undos still in effect, while `mine` has made no change since.*/export function stepTarget(entries: readonly HistoryEntry[],direction: "back" | "forward",+ mine: (entry: HistoryEntry) => boolean,): 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;+ const owns = ownerOf(entries, byId, mine);+ const newestFirst = [...entries].reverse();+ if (direction === "back")+ return newestFirst.find((entry) => !entry.undoes && !undone.has(entry.id) && owns(entry));+ for (const entry of newestFirst) {+ if (!entry.undoes) {+ if (owns(entry)) return undefined;+ continue;+ }+ const target = byId.get(entry.undoes);+ if (mine(entry) && !undone.has(entry.id) && target && !target.undoes) return entry;}return undefined;}+/** A change is yours to step over if you made it, or your redo is what brought it back. */+function ownerOf(+ entries: readonly HistoryEntry[],+ byId: ReadonlyMap<string, HistoryEntry>,+ mine: (entry: HistoryEntry) => boolean,+): (entry: HistoryEntry) => boolean {+ const redoneBy = new Map<string, HistoryEntry>();+ for (const entry of entries) {+ const target = entry.undoes ? byId.get(entry.undoes) : undefined;+ if (target?.undoes) redoneBy.set(target.undoes, entry);+ }+ return (entry) => mine(entry) || mine(redoneBy.get(entry.id) ?? entry);+}+/*** 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.@@ -161,7 +191,7 @@ export function stepTarget(export function foldOldest(log: HistoryLog): boolean {const oldest = log.entries[0];if (!oldest || log.pins.has(oldest.id)) return false;- applyEntry(log.baseline, oldest);+ applyEntry(log.baseline, oldest, "after");log.entries.shift();return true;}diff --git a/packages/studio-server/src/history/projectHistory.test.ts b/packages/studio-server/src/history/projectHistory.test.tsindex 87c604dc61..afc8585455 100644--- a/packages/studio-server/src/history/projectHistory.test.ts+++ b/packages/studio-server/src/history/projectHistory.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+// fallow-ignore-file code-duplicationimport {cpSync,existsSync,@@ -9,12 +10,13 @@ import {renameSync,rmSync,statSync,+ symlinkSync,utimesSync,writeFileSync,} from "node:fs";import { spawnSync } from "node:child_process";import { tmpdir } from "node:os";-import { dirname, join, relative } from "node:path";+import { basename, dirname, join, relative } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";import { fileContentVersion } from "../helpers/fileVersion";import { HistoryBusyError } from "./ownerLock";@@ -30,6 +32,17 @@ afterEach(async () => {for (const step of cleanup.splice(0).reverse()) await step();});+const inside = (dir: string, path: string) => readFileSync(join(dir, path), "utf-8");++function caseInsensitive(): boolean {+ const dir = mkdtempSync(join(tmpdir(), "hf-history-case-"));+ try {+ return existsSync(dir.toUpperCase());+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}+function tempDir(prefix: string): string {const dir = mkdtempSync(join(tmpdir(), prefix));cleanup.push(() => rmSync(dir, { recursive: true, force: true }));@@ -56,6 +69,30 @@ async function project(files: Record<string, string | Buffer>, options = {}) {return { projectDir, historyRoot, history, write, read, has };}+/** Undoes the newest change still in effect, whoever made it; Cmd+Z steps only over the caller's own. */+async function undoNewest(history: ProjectHistory) {+ const newest = [...history.list()].reverse().find((entry) => !entry.undoes && !entry.undone);+ return history.undo(newest!.id, { who: you });+}++/** An agent turn writes B, C, D; the person's drag claims C (written over B) and is held when the turn closes. */+async function dragDuringTurn(+ history: ProjectHistory,+ write: (path: string, content: string) => void,+) {+ const window = await history.beginWindow(agent, "Agent turn");+ write("index.html", "B");+ await history.claim(you, "sweep", []);+ write("index.html", "C");+ await history.claim(you, "Dragged Title", ["index.html"], {+ coalesceKey: "drag",+ idleMs: 60_000,+ overwrote: { "index.html": fileContentVersion("B") },+ });+ write("index.html", "D");+ await window.close();+}+/** 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);@@ -171,6 +208,340 @@ describe("openProjectHistory", () => {expect(read("index.html")).toBe("v2");});+ it("checks out an entry's before and after into a folder, leaving the project and its history alone", async () => {+ const { history, write, read } = await project({ "index.html": "v1", "assets/a.txt": "a" });+ const second = await change(history, you, "Second", () => {+ write("index.html", "v2");+ write("extra/b.txt", "b");+ });+ await change(history, you, "Third", () => write("index.html", "v3"));++ const before = tempDir("hf-history-checkout-");+ const after = tempDir("hf-history-checkout-");+ await history.checkout(second.id, "before", before);+ await history.checkout(second.id, "after", after);+ expect([inside(before, "index.html"), inside(before, "assets/a.txt")]).toEqual(["v1", "a"]);+ expect(existsSync(join(before, "extra/b.txt"))).toBe(false);+ expect([inside(after, "index.html"), inside(after, "extra/b.txt")]).toEqual(["v2", "b"]);+ const beforeThird = join(tempDir("hf-history-checkout-"), "made-by-checkout");+ await history.checkout(history.list()[1]!.id, "before", beforeThird);+ expect([inside(beforeThird, "index.html"), inside(beforeThird, "extra/b.txt")]).toEqual([+ "v2",+ "b",+ ]);++ expect(read("index.html")).toBe("v3");+ expect(history.list()).toHaveLength(2);+ await expect(history.checkout(second.id, "after", after)).rejects.toThrow("empty folder");+ await expect(+ history.checkout("gone", "after", tempDir("hf-history-checkout-")),+ ).rejects.toThrow("no longer kept");+ });++ it("checks out each entry's own change around a drag held when an agent turn starts", async () => {+ const { history, write } = await project({ "index.html": "A" });+ const drag = (overwrote: string) =>+ history.claim(you, "Dragged Title", ["index.html"], {+ coalesceKey: "drag",+ idleMs: 60_000,+ overwrote: { "index.html": fileContentVersion(overwrote) },+ });+ write("index.html", "B");+ await drag("A");+ const window = await history.beginWindow(agent, "Agent turn");+ write("index.html", "C");+ await window.close();+ write("index.html", "D");+ await drag("C");+ await history.flush();++ const sides = async (id: string) => {+ const pair: string[] = [];+ for (const side of ["before", "after"] as const) {+ const dir = tempDir("hf-history-checkout-");+ await history.checkout(id, side, dir);+ pair.push(inside(dir, "index.html"));+ }+ return pair.join(">");+ };+ const changes = [];+ for (const entry of history.list()) changes.push(`${entry.label}: ${await sides(entry.id)}`);+ expect(changes).toEqual(["Dragged Title: A>B", "Agent turn: B>C", "Dragged Title: C>D"]);+ });++ it("logs the outside change that turned a file into a folder before the agent turn that followed", async () => {+ const { history, projectDir, write } = await project({ a: "file", "r.txt": "R0" });+ rmSync(join(projectDir, "a"));+ mkdirSync(join(projectDir, "a"));+ writeFileSync(join(projectDir, "a", "b.txt"), "b0");+ const window = await history.beginWindow(agent, "Agent turn");+ writeFileSync(join(projectDir, "a", "b.txt"), "b1");+ const turn = await window.close();+ write("r.txt", "R1");+ await history.flush();+ expect(history.list().map((entry) => entry.label)).toEqual([+ "Changed outside the app",+ "Agent turn",+ "Changed outside the app",+ ]);++ for (const [side, content] of [+ ["before", "b0"],+ ["after", "b1"],+ ] as const) {+ const dir = tempDir("hf-history-checkout-");+ await history.checkout(turn!.id, side, dir);+ expect([inside(dir, "a/b.txt"), inside(dir, "r.txt")]).toEqual([content, "R0"]);+ }+ });++ it.each([+ ["a file into a folder", { a: "file" }, "a/b.html", ["a", "a/b.html"]],+ ["a folder into a file", { "a/b.html": "b" }, "a", ["a", "a/b.html"]],+ ])(+ "checks out a turn that turned %s and idled before the next scan",+ async (_, files, made, paths) => {+ const { history, projectDir } = await project(files);+ await history.beginWindow(agent, "Agent turn", { idleMs: 60_000 });+ rmSync(join(projectDir, "a"), { recursive: true });+ mkdirSync(dirname(join(projectDir, made)), { recursive: true });+ writeFileSync(join(projectDir, made), "made");+ vi.useFakeTimers({ toFake: ["Date"] });+ try {+ vi.setSystemTime(Date.now() + 120_000);+ await history.flush();+ } finally {+ vi.useRealTimers();+ }++ const [first] = history.list();+ expect([first!.who.kind, first!.files.map((file) => file.path).sort()]).toEqual([+ "agent",+ paths,+ ]);+ const dir = tempDir("hf-history-checkout-");+ await history.checkout(first!.id, "after", dir);+ expect(inside(dir, made)).toBe("made");+ },+ );++ it("undoes and redoes a turn that turned a file into a folder", async () => {+ const { history, projectDir, read } = await project({ a: "file" });+ const turn = await change(history, agent, "Agent turn", () => {+ rmSync(join(projectDir, "a"));+ mkdirSync(join(projectDir, "a", "c"), { recursive: true });+ writeFileSync(join(projectDir, "a", "c", "b.html"), "b");+ });++ const undone = await history.undo(turn.id, { who: you });+ expect(undone.ok && read("a")).toBe("file");+ const redone = await history.undo(undone.ok ? undone.entry!.id : "", { who: you });+ expect(redone.ok && read("a/c/b.html")).toBe("b");+ });++ it("refuses an undo that would have to delete a file added since, and leaves the files alone", async () => {+ const { history, projectDir, read } = await project({ a: "file" });+ const turn = await change(history, agent, "Agent turn", () => {+ rmSync(join(projectDir, "a"));+ mkdirSync(join(projectDir, "a"));+ writeFileSync(join(projectDir, "a", "b.html"), "b");+ });+ mkdirSync(join(projectDir, "a", "sub"));+ writeFileSync(join(projectDir, "a", "sub", "new.html"), "new");+ await history.flush();+ const entries = history.list().length;++ await expect(history.undo(turn.id, { who: you })).rejects.toThrow(+ "a/sub/new.html is in the way",+ );+ expect([read("a/b.html"), read("a/sub/new.html"), history.list().length]).toEqual([+ "b",+ "new",+ entries,+ ]);+ });++ // Windows needs a privilege to create symlinks.+ it.skipIf(process.platform === "win32")(+ "refuses an undo that would have to replace a link added since, and leaves its folder alone",+ async () => {+ const { history, projectDir, read } = await project({ a: "file" });+ const turn = await change(history, agent, "Agent turn", () => {+ rmSync(join(projectDir, "a"));+ writeFileSync(join(projectDir, "c.html"), "c");+ });+ const outside = tempDir("hf-history-linked-");+ mkdirSync(join(outside, "empty"));+ symlinkSync(outside, join(projectDir, "a"), "dir");++ await expect(history.undo(turn.id, { who: you })).rejects.toThrow("a is in the way");+ expect([read("c.html"), existsSync(join(outside, "empty"))]).toEqual(["c", true]);+ },+ );++ it.skipIf(process.platform === "win32")(+ "refuses an undo that would write through a link standing where a folder was",+ async () => {+ const { history, projectDir } = await project({ "a/b.html": "b" });+ const turn = await change(history, agent, "Agent turn", () => {+ rmSync(join(projectDir, "a"), { recursive: true });+ writeFileSync(join(projectDir, "a"), "file");+ });+ rmSync(join(projectDir, "a"));+ const outside = tempDir("hf-history-linked-");+ symlinkSync(outside, join(projectDir, "a"), "dir");+ await history.flush();++ await expect(history.undo(turn.id, { who: you, mode: "just-this" })).rejects.toThrow(+ "a is in the way",+ );+ expect(existsSync(join(outside, "b.html"))).toBe(false);+ },+ );++ it.skipIf(!caseInsensitive())(+ "undoes and redoes a turn that turned file A into folder a/, and undoes the reverse",+ async () => {+ const { history, projectDir, read } = await project({ A: "file" });+ const turn = await change(history, agent, "Agent turn", () => {+ rmSync(join(projectDir, "A"));+ mkdirSync(join(projectDir, "a"));+ writeFileSync(join(projectDir, "a", "b.html"), "b");+ });++ const undone = await history.undo(turn.id, { who: you });+ expect(undone.ok && read("A")).toBe("file");+ const redone = await history.undo(undone.ok ? undone.entry!.id : "", { who: you });+ expect(redone.ok && read("a/b.html")).toBe("b");+ const reverse = await change(history, agent, "Reverse turn", () => {+ rmSync(join(projectDir, "a"), { recursive: true });+ writeFileSync(join(projectDir, "A"), "file");+ });+ const reversed = await history.undo(reverse.id, { who: you });+ expect(reversed.ok && read("a/b.html")).toBe("b");+ },+ );++ it.each([["a"], ...(caseInsensitive() ? [["A"]] : [])])(+ "logs a folder a/ moved over an agent's file %s after its turn idled out as the outside's, however old its files",+ async (file) => {+ const { history, projectDir } = await project({ [file]: "file" });+ const staged = tempDir("hf-history-folder-");+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ try {+ const window = await history.beginWindow(agent, "Agent turn", { idleMs: 50 });+ writeFileSync(join(staged, "b.html"), "b");+ for (const until = Date.now() + 150; Date.now() < until; );+ rmSync(join(projectDir, file));+ renameSync(staged, join(projectDir, "a"));+ await window.close();+ await history.flush();+ } finally {+ vi.useRealTimers();+ }++ const entries = history.list();+ expect(+ entries.map((entry) => [entry.who.kind, entry.files.map((f) => f.path).sort()]),+ ).toEqual([["outside", [file, "a/b.html"]]]);+ const dir = tempDir("hf-history-checkout-");+ await history.checkout(entries[0]!.id, "after", dir);+ expect(inside(dir, "a/b.html")).toBe("b");+ },+ );++ it("refuses the working folder as a checkout written as an empty path, and writes nothing there", async () => {+ const name = `hf-checkout-probe-${process.pid}.html`;+ cleanup.push(() => rmSync(join(process.cwd(), name), { force: true }));+ const { history, write } = await project({ [name]: "v1" });+ const entry = await change(history, you, "Second", () => write(name, "v2"));++ await expect(history.checkout(entry.id, "before", "")).rejects.toThrow("empty folder only");+ expect(existsSync(join(process.cwd(), name))).toBe(false);+ });++ // Windows needs a privilege to create symlinks.+ it.skipIf(process.platform === "win32")(+ "refuses a nonempty checkout folder reached through a link and `..`",+ async () => {+ const { history, write } = await project({ "index.html": "v1" });+ const entry = await change(history, you, "Second", () => write("index.html", "v2"));+ const out = tempDir("hf-history-out-");+ const other = tempDir("hf-history-other-");+ mkdirSync(join(other, "sub"));+ symlinkSync(join(other, "sub"), join(out, "link"), "dir");+ mkdirSync(join(out, "co"));+ writeFileSync(join(out, "co", "index.html"), "kept");++ await expect(history.checkout(entry.id, "before", `${out}/link/../co`)).rejects.toThrow(+ "empty folder only",+ );+ expect(inside(join(out, "co"), "index.html")).toBe("kept");+ },+ );++ it("refuses a checkout folder inside the project, however it is reached", async () => {+ const { history, write, projectDir, has } = await project({ "index.html": "v1" });+ const entry = await change(history, you, "Second", () => write("index.html", "v2"));+ const alias = join(tempDir("hf-history-alias-"), "alias");+ symlinkSync(projectDir, alias);++ for (const dir of [join(projectDir, "archive"), join(alias, "archive"), projectDir])+ await expect(history.checkout(entry.id, "after", dir)).rejects.toThrow("outside the project");+ expect(has("archive")).toBe(false);+ await history.flush();+ expect(history.list()).toHaveLength(1);+ });++ it.skipIf(!caseInsensitive())(+ "refuses a checkout folder inside the project spelled in other letter case",+ async () => {+ const { history, write, projectDir, has } = await project({ "index.html": "v1" });+ const entry = await change(history, you, "Second", () => write("index.html", "v2"));+ const recased = join(dirname(projectDir), basename(projectDir).toUpperCase(), "archive");++ await expect(history.checkout(entry.id, "after", recased)).rejects.toThrow(+ "outside the project",+ );+ expect(has("archive")).toBe(false);+ },+ );++ it("checks out beside the project into a folder whose name starts with the project's", async () => {+ const { history, write, projectDir } = await project({ "index.html": "v1" });+ const entry = await change(history, you, "Second", () => write("index.html", "v2"));+ const sibling = `${projectDir}-copy`;+ cleanup.push(() => rmSync(sibling, { recursive: true, force: true }));++ await history.checkout(entry.id, "after", sibling);+ expect(inside(sibling, "index.html")).toBe("v2");+ });++ it("refuses a checkout once the project folder is gone", async () => {+ const { history, write, projectDir } = await project({ "index.html": "v1" });+ const entry = await change(history, you, "Second", () => write("index.html", "v2"));+ rmSync(projectDir, { recursive: true, force: true });++ await expect(history.checkout(entry.id, "after", join(projectDir, "archive"))).rejects.toThrow(+ "project folder is gone",+ );+ expect(existsSync(projectDir)).toBe(false);+ });++ it("leaves the folder empty when a checkout fails partway, so it can be retried", async () => {+ const { history, write, historyRoot } = await project({ "a/a.txt": "a", "z.txt": "z" });+ const entry = await change(history, you, "Edit", () => write("z.txt", "z2"));+ const lost = history.peek(entry.id)!["z.txt"]!;+ const blob = readdirSync(historyRoot, { recursive: true }).find((path) =>+ String(path).endsWith(lost),+ );+ rmSync(join(historyRoot, String(blob)));++ const dir = tempDir("hf-history-checkout-");+ await expect(history.checkout(entry.id, "after", dir)).rejects.toThrow();+ expect(readdirSync(dir)).toEqual([]);+ });+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");@@ -186,7 +557,7 @@ describe("openProjectHistory", () => {const reopened = await open(moved, historyRoot);expect(reopened.projectId).toBe(history.projectId);expect(reopened.list()).toHaveLength(2);- await reopened.step("back", you);+ await undoNewest(reopened);expect(readFileSync(join(moved, "index.html"), "utf-8")).toBe("v2");const copy = tempDir("hf-history-copy-");@@ -449,13 +820,13 @@ describe("openProjectHistory", () => {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 () => {+ it("commits a window that is never closed when the history flushes, so an undo 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({+ expect(await undoNewest(history)).toMatchObject({ok: true,entry: { label: "Undid: never closed" },});@@ -570,13 +941,13 @@ describe("claim: a writer that records after writing", () => {["outside", "Changed outside the app"],["person", "Moved Title"],]);- await history.step("back", you);- expect(read("index.html"), "Cmd+Z undoes only the person's edit").toBe("B");- await history.step("back", you);+ await undoNewest(history);+ expect(read("index.html"), "undoing the turn leaves only the person's edit").toBe("B");+ await undoNewest(history);expect(read("index.html")).toBe("A");});- it("an agent's turn cut by Studio's edit becomes an entry before it and one after, so Cmd+Z walks back in order", async () => {+ it("an agent's turn cut by Studio's edit becomes an entry before it and one after, so undoing walks back in order", async () => {const { history, write, read } = await project({ "index.html": "A" });const window = await history.beginWindow(agent, "Agent turn");write("index.html", "B");@@ -595,7 +966,7 @@ describe("claim: a writer that records after writing", () => {"Agent turn",]);for (const expected of ["C", "B", "A"]) {- expect(await history.step("back", you)).toMatchObject({ ok: true });+ expect(await undoNewest(history)).toMatchObject({ ok: true });expect(read("index.html")).toBe(expected);}});@@ -625,12 +996,12 @@ describe("claim: a writer that records after writing", () => {["B", "1"],["A", "1"],]) {- expect(await history.step("back", you)).toMatchObject({ ok: true });+ expect(await undoNewest(history)).toMatchObject({ ok: true });expect([read("index.html"), read("b.js")]).toEqual([index, b]);}});- it("a held drag across an agent's write ends at that write, so Cmd+Z walks back every step", async () => {+ it("a held drag across an agent's write ends at that write, so undoing walks back every step", async () => {const { history, write, read } = await project({ "index.html": "A" });const window = await history.beginWindow(agent, "Agent turn");const drag = (overwrote: string) =>@@ -652,7 +1023,7 @@ describe("claim: a writer that records after writing", () => {await history.flush();await window.close();for (const expected of ["D", "C", "B", "A"]) {- expect(await history.step("back", you)).toMatchObject({ ok: true });+ expect(await undoNewest(history)).toMatchObject({ ok: true });expect(read("index.html")).toBe(expected);}});@@ -678,7 +1049,7 @@ describe("claim: a writer that records after writing", () => {"Dragged Title",]);for (const expected of ["C", "B", "A"]) {- expect(await history.step("back", you)).toMatchObject({ ok: true });+ expect(await undoNewest(history)).toMatchObject({ ok: true });expect(read("index.html")).toBe(expected);}});@@ -700,7 +1071,7 @@ describe("claim: a writer that records after writing", () => {await drag("C");await history.flush();for (const expected of ["C", "B", "A"]) {- expect(await history.step("back", you)).toMatchObject({ ok: true });+ expect(await undoNewest(history)).toMatchObject({ ok: true });expect(read("index.html")).toBe(expected);}});@@ -727,7 +1098,7 @@ describe("claim: a writer that records after writing", () => {["B", "1"],["A", "1"],]) {- expect(await history.step("back", you)).toMatchObject({ ok: true });+ expect(await undoNewest(history)).toMatchObject({ ok: true });expect([read("index.html"), read("r.js")]).toEqual(expected);}});@@ -755,7 +1126,7 @@ describe("claim: a writer that records after writing", () => {["B", "1"],["A", "1"],]) {- expect(await history.step("back", you)).toMatchObject({ ok: true });+ expect(await undoNewest(history)).toMatchObject({ ok: true });expect([read("index.html"), read("r.js")]).toEqual(expected);}});@@ -775,11 +1146,11 @@ describe("claim: a writer that records after writing", () => {write("index.html", "Y");await claim("X");await history.flush();- await history.step("back", you);+ await undoNewest(history);expect(read("index.html")).toBe("X");- await history.step("back", you);+ await undoNewest(history);expect(has("index.html")).toBe(false);- await history.step("back", you);+ await undoNewest(history);expect(read("index.html")).toBe("A");});@@ -806,7 +1177,7 @@ describe("claim: a writer that records after writing", () => {expect(history.list().filter((entry) => entry.label === "Dragged Title")).toHaveLength(1);});- it("a cut takes only the cut file's earlier part out of the turn, so undoing the turn reverts its other files", async () => {+ it("a person's edit during an agent turn splits the turn around it, each part logged in write order", async () => {const { history, write, read } = await project({ "index.html": "A", "b.js": "1" });const window = await history.beginWindow(agent, "Agent turn");write("index.html", "B");@@ -818,37 +1189,324 @@ describe("claim: a writer that records after writing", () => {});write("index.html", "D");const turn = await window.close();- expect(history.list()[0]!.files.map((file) => file.path)).toEqual(["index.html"]);+ expect(+ history.list().map((entry) => [entry.label, entry.files.map((file) => file.path)]),+ ).toEqual([+ ["Agent turn", ["b.js", "index.html"]],+ ["Moved Title", ["index.html"]],+ ["Agent turn", ["index.html"]],+ ]);expect(turn).toMatchObject({ id: window.id });- expect(turn!.files.map((file) => file.path)).toEqual(["b.js", "index.html"]);expect(await history.undo(turn!.id, { who: agent })).toMatchObject({ ok: true });- expect([read("index.html"), read("b.js")]).toEqual(["C", "1"]);+ expect([read("index.html"), read("b.js")]).toEqual(["C", "2"]);});- it("Cmd+Z undoes an agent's later write first when a held drag claim commits after the agent's turn", async () => {+ it("a drag claimed during an agent turn ends at the turn and is logged before the turn's last part", async () => {const { history, write, read } = await project({ "index.html": "A" });+ await dragDuringTurn(history, write);+ await history.flush();+ expect(history.list().map((entry) => entry.label)).toEqual([+ "Agent turn",+ "Dragged Title",+ "Agent turn",+ ]);+ for (const expected of ["C", "B", "A"]) {+ expect(await undoNewest(history)).toMatchObject({ ok: true });+ expect(read("index.html")).toBe(expected);+ }+ });++ it("a drag held when an agent turn starts ends there, and its next step logs after the turn's earlier writes", async () => {+ const { history, write } = await project({ "index.html": "A", "other.js": "1" });+ const drag = (overwrote: string) =>+ history.claim(you, "Dragged Title", ["index.html"], {+ coalesceKey: "drag",+ idleMs: 60_000,+ overwrote: { "index.html": fileContentVersion(overwrote) },+ });+ write("index.html", "B");+ await drag("A");+ const window = await history.beginWindow(agent, "Agent turn");+ write("other.js", "2");+ write("index.html", "C");+ await drag("B");+ await window.close();+ expect(history.list().map((entry) => entry.label)).toEqual([+ "Dragged Title",+ "Agent turn",+ "Dragged Title",+ ]);+ });++ it("logs an agent turn's writes before a second agent's overlapping turn that closes first", async () => {+ const { history, projectDir } = await project({ a: "file" });+ const first = await history.beginWindow(agent, "Agent one");+ rmSync(join(projectDir, "a"));+ mkdirSync(join(projectDir, "a"));+ writeFileSync(join(projectDir, "a", "b.txt"), "b0");+ const second = await history.beginWindow({ kind: "agent", name: "Other" }, "Agent two");+ writeFileSync(join(projectDir, "a", "b.txt"), "b1");+ const two = await second.close();+ await first.close();+ expect(history.list().map((entry) => entry.label)).toEqual(["Agent one", "Agent two"]);++ for (const [side, content] of [+ ["before", "b0"],+ ["after", "b1"],+ ] as const) {+ const dir = tempDir("hf-history-checkout-");+ await history.checkout(two!.id, side, dir);+ expect(inside(dir, "a/b.txt")).toBe(content);+ }+ });++ it("reopens after a restore run inside an open agent turn without inventing an outside change", async () => {+ const { history, write, projectDir, historyRoot } = await project({ "index.html": "A" });const window = await history.beginWindow(agent, "Agent turn");write("index.html", "B");- await history.claim(you, "sweep", []);+ await history.restore(START, you);+ await window.close();+ await history.close();++ const reopened = await open(projectDir, historyRoot);+ await reopened.flush();+ expect(reopened.list().map((entry) => entry.label)).toEqual([+ "Agent turn",+ "Restored: the start",+ ]);+ });++ it("a held drag ends when a write to another file is pending", async () => {+ const { history, write } = await project({ "index.html": "A", "r.js": "1" });+ const drag = (overwrote: string) =>+ history.claim(you, "Dragged Title", ["index.html"], {+ coalesceKey: "drag",+ idleMs: 60_000,+ overwrote: { "index.html": fileContentVersion(overwrote) },+ });+ write("index.html", "B");+ await drag("A");+ write("r.js", "2");write("index.html", "C");+ await drag("B");+ await history.flush();+ expect(history.list().map((entry) => entry.label)).toEqual([+ "Dragged Title",+ "Changed outside the app",+ "Dragged Title",+ ]);+ });++ it("Cmd+Z during an agent turn reverts the person's last edit, names it, and leaves the agent's writes", async () => {+ const { history, write, read } = await project({ "index.html": "A", "r.js": "1" });+ write("index.html", "B");+ await history.claim(you, "Moved Title", ["index.html"], {+ overwrote: { "index.html": fileContentVersion("A") },+ });+ const window = await history.beginWindow(agent, "Agent turn");+ write("r.js", "2");++ expect(history.next("back", you)?.label).toBe("Moved Title");+ expect(await history.step("back", you)).toMatchObject({ ok: true });+ expect([read("index.html"), read("r.js")]).toEqual(["A", "2"]);+ await window.close();+ expect(history.next("back", you)).toBeUndefined();+ });++ it("Cmd+Z names a held drag and reverts it", async () => {+ const { history, write, read } = await project({ "index.html": "A" });+ write("index.html", "B");await history.claim(you, "Dragged Title", ["index.html"], {coalesceKey: "drag",idleMs: 60_000,+ overwrote: { "index.html": fileContentVersion("A") },+ });++ expect(history.next("back", you)?.label).toBe("Dragged Title");+ expect(await history.step("back", you)).toMatchObject({ ok: true });+ expect(read("index.html")).toBe("A");+ });++ it("Cmd+Z names an outside edit still pending and reverts it before the person's own", async () => {+ const { history, write, read } = await project({ "index.html": "A", "r.js": "1" });+ write("index.html", "B");+ await history.claim(you, "Moved Title", ["index.html"], {+ overwrote: { "index.html": fileContentVersion("A") },+ });+ write("r.js", "2");+ history.noteChange("r.js");++ await vi.waitFor(() =>+ expect(history.next("back", you)?.label).toBe("Changed outside the app"),+ );+ expect(await history.step("back", you)).toMatchObject({+ entry: { label: "Undid: Changed outside the app" },+ });+ expect([read("index.html"), read("r.js")]).toEqual(["B", "1"]);+ });++ it("Cmd+Z names an outside edit pending over a held drag and reverts the outside edit first", async () => {+ const { history, write, read } = await project({ "index.html": "A", "r.js": "1" });+ write("index.html", "B");+ await history.claim(you, "Dragged Title", ["index.html"], {+ coalesceKey: "drag",+ idleMs: 60_000,+ overwrote: { "index.html": fileContentVersion("A") },+ });+ write("r.js", "2");+ history.noteChange("r.js");++ await vi.waitFor(() =>+ expect(history.next("back", you)?.label).toBe("Changed outside the app"),+ );+ expect(await history.step("back", you)).toMatchObject({+ entry: { label: "Undid: Changed outside the app" },+ });+ expect([read("index.html"), read("r.js")]).toEqual(["B", "1"]);+ });++ it("Cmd+Z names a window the person has open and reverts its writes", async () => {+ const { history, write, read } = await project({ "index.html": "A" });+ await history.beginWindow(you, "Moved Title");+ write("index.html", "B");+ history.noteChange("index.html");++ await vi.waitFor(() => expect(history.next("back", you)?.label).toBe("Moved Title"));+ expect(await history.step("back", you)).toMatchObject({+ entry: { label: "Undid: Moved Title" },+ });+ expect(read("index.html")).toBe("A");+ });++ it("Cmd+Shift+Z never redoes an agent's own undo of its turn", async () => {+ const { history, write } = await project({ "index.html": "A" });+ const window = await history.beginWindow(agent, "Agent turn");+ write("index.html", "B");+ await window.close();+ const [turn] = history.list();+ await history.undo(turn!.id, { who: agent });++ expect(history.next("forward", you)).toBeUndefined();+ });++ it("Cmd+Shift+Z redoes the person's edit across an agent's write to another file", async () => {+ const { history, write, read } = await project({ "index.html": "A", "r.js": "1" });+ write("index.html", "B");+ await history.claim(you, "Moved Title", ["index.html"], {+ overwrote: { "index.html": fileContentVersion("A") },+ });+ await history.step("back", you);+ const window = await history.beginWindow(agent, "Agent turn");+ write("r.js", "2");+ await window.close();++ expect(await history.step("forward", you)).toMatchObject({+ entry: { label: "Redid: Moved Title" },+ });+ expect([read("index.html"), read("r.js")]).toEqual(["B", "2"]);+ });++ it("an agent's turn the person undid and redid is the person's to Cmd+Z", async () => {+ const { history, write } = await project({ "index.html": "A" });+ const window = await history.beginWindow(agent, "Agent turn");+ write("index.html", "B");+ await window.close();+ const [turn] = history.list();+ await history.undo(turn!.id, { who: you });+ await history.step("forward", you);++ expect(history.next("back", you)?.id).toBe(turn!.id);+ });++ it("undoes a turn's parts last first and keeps the person's edit between them", async () => {+ const { history, write, read } = await project({ "index.html": "A", "b.js": "1" });+ const window = await history.beginWindow(agent, "Agent turn");+ write("index.html", "B");+ write("b.js", "2");+ await history.claim(you, "scan", []);+ write("index.html", "C");+ await history.claim(you, "Moved Title", ["index.html"], {overwrote: { "index.html": fileContentVersion("B") },});write("index.html", "D");await window.close();- await history.flush();+ const [first, , last] = history.list();+ const keep = { who: agent, mode: "keep-later-edits" } as const;++ expect(await history.undo(last!.id, keep)).toMatchObject({ ok: true });+ expect(await history.undo(first!.id, keep)).toMatchObject({ ok: true });+ expect([read("index.html"), read("b.js")]).toEqual(["C", "1"]);+ expect(await history.undo(first!.id, keep)).toEqual({ ok: true, entry: null });+ });++ it("a window opening ends a held drag even when nothing else was written", async () => {+ const { history, write } = await project({ "index.html": "A" });+ const drag = (overwrote: string) =>+ history.claim(you, "Dragged Title", ["index.html"], {+ coalesceKey: "drag",+ idleMs: 60_000,+ overwrote: { "index.html": fileContentVersion(overwrote) },+ });+ write("index.html", "B");+ await drag("A");+ const window = await history.beginWindow(agent, "Agent turn");+ write("index.html", "C");+ await drag("B");+ await window.close();+ expect(history.list().map((entry) => entry.label)).toEqual(["Dragged Title", "Dragged Title"]);+ });++ it("a drag held inside an agent turn ends when the agent writes another file", async () => {+ const { history, write } = await project({ "index.html": "A", "other.js": "1" });+ const window = await history.beginWindow(agent, "Agent turn");+ const drag = (overwrote: string) =>+ history.claim(you, "Dragged Title", ["index.html"], {+ coalesceKey: "drag",+ idleMs: 60_000,+ overwrote: { "index.html": fileContentVersion(overwrote) },+ });+ write("index.html", "B");+ await drag("A");+ write("other.js", "2");+ write("index.html", "C");+ await drag("B");+ await window.close();expect(history.list().map((entry) => entry.label)).toEqual([+ "Dragged Title","Agent turn",+ "Dragged Title",+ ]);+ });++ it("an outside write logs after a drag held before it, however long it waits", async () => {+ const { history, write } = await project({ "index.html": "A", "r.js": "1" }, { quietMs: 20 });+ write("index.html", "B");+ await history.claim(you, "Dragged Title", ["index.html"], {+ coalesceKey: "drag",+ idleMs: 60_000,+ overwrote: { "index.html": fileContentVersion("A") },+ });+ write("r.js", "2");+ history.noteChange("r.js");+ await vi.waitFor(() => expect(history.list()).toHaveLength(2));+ expect(history.list().map((entry) => entry.label)).toEqual([+ "Dragged Title",+ "Changed outside the app",+ ]);+ });++ it("reopens after a drag claimed during an agent turn without inventing an outside change", async () => {+ const { history, write, projectDir, historyRoot } = await project({ "index.html": "A" });+ await dragDuringTurn(history, write);+ await history.close();++ const reopened = await open(projectDir, historyRoot);+ await reopened.flush();+ expect(reopened.list().map((entry) => entry.label)).toEqual(["Agent turn","Dragged Title",+ "Agent turn",]);- expect(history.next("back")?.label, "the button names the step Cmd+Z takes").toBe("Agent turn");- for (const expected of ["C", "B", "A"]) {- expect(await history.step("back", you)).toMatchObject({ ok: true });- expect(read("index.html")).toBe(expected);- }});it("logs an entry with only its own fields, not its window's timer", async () => {diff --git a/packages/studio-server/src/history/projectHistory.ts b/packages/studio-server/src/history/projectHistory.tsindex 5ecc01ccce..e8b30c4423 100644--- a/packages/studio-server/src/history/projectHistory.ts+++ b/packages/studio-server/src/history/projectHistory.ts@@ -1,8 +1,18 @@import { randomUUID } from "node:crypto";-import { rm } from "node:fs/promises";-import { existsSync, mkdirSync, readFileSync } from "node:fs";+import { readdir, rm, rmdir } from "node:fs/promises";+import {+ type Dirent,+ type Stats,+ existsSync,+ lstatSync,+ statSync,+ mkdirSync,+ readdirSync,+ readFileSync,+ realpathSync,+} from "node:fs";import { homedir } from "node:os";-import { join, relative, resolve, sep } from "node:path";+import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";import { replaceFileAtomically } from "../helpers/atomicFile.js";import {DELETED_VERSION,@@ -12,11 +22,12 @@ import {} from "../helpers/fileVersion.js";import { affectsProjectSignature, listProjectFiles } from "../helpers/projectSignature.js";import { openBlobStore, type BlobStore } from "./blobStore.js";-import { projectHistoryId } from "./historyId.js";+import { ID_PATH, projectHistoryId } from "./historyId.js";import { takeHistoryOwnership } from "./ownerLock.js";import {START,foldOldest,+ manifestAround,manifestAt,readLog,saveRecord,@@ -25,6 +36,7 @@ import {undoneIds,writeLog,type HistoryEntry,+ type HistoryEntrySide,type HistoryFileChange,type HistoryLog,type HistoryWho,@@ -75,6 +87,9 @@ export interface ClosedWindow {export const MAX_WINDOW_IDLE_MS = 10 * 60_000;+export const UNDO_MODES = ["just-this", "back-to-before", "keep-later-edits"] as const;+export type UndoMode = (typeof UNDO_MODES)[number];+export interface HistoryListItem extends HistoryEntry {pinned: boolean;undone: boolean;@@ -94,8 +109,8 @@ export interface HistoryWindow {export interface ProjectHistory {readonly projectId: string;- /** Writes until close() are one entry with the window's id; a claim cutting a file out commits that file's part- * first (fresh id), returned by close() if nothing else remained. Idle windows end; overlaps go to the newest. */+ /** Writes until close() are one entry with the window's id; another writer or an operation meanwhile commits the+ * part so far first (fresh id), returned by close() if nothing else remained. Overlaps go to the newest. */beginWindow(who: HistoryWho,label: string,@@ -104,7 +119,7 @@ export interface ProjectHistory {/*** For a writer that records after writing (Studio): moves the uncommitted changes to `paths` into one entry of* `who`'s, each cut at the `overwrote` version so earlier parts stay their writer's. Same-key claims merge until- * another key, `idleMs` idle, or any operation. Null when nothing was claimed or a drag nets to nothing.+ * another key, idle, an operation, a window, or another write. Null when nothing was claimed or a drag nets to 0.*/claim(who: HistoryWho,@@ -115,19 +130,17 @@ export interface ProjectHistory {/** 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; `writeToken` labels the writes' echo. */+ /** Cmd+Z (back) and Cmd+Shift+Z (forward) over `who`'s own and outside changes; `writeToken` labels the echo. */step(direction: "back" | "forward", who: HistoryWho, options?: Writing): Promise<HistoryResult>;- /** The entry the next step reverts, as of the last scan (a step scans first). */- next(direction: "back" | "forward"): HistoryEntry | undefined;- /** A conflict (a file changed since) returns the choice; pass `mode` to take one. */- undo(- id: string,- options: { who: HistoryWho; mode?: "just-this" | "back-to-before" } & Writing,- ): Promise<HistoryResult>;+ /** The entry `who`'s next step reverts, pending changes included, as of the last scan (a step scans first). */+ next(direction: "back" | "forward", who: HistoryWho): HistoryEntry | undefined;+ /** A file changed since returns a conflict; `mode` takes a choice (keep-later-edits: null when none is left). */+ undo(id: string, options: { who: HistoryWho; mode?: UndoMode } & Writing): Promise<HistoryResult>;/** Makes the files equal what they were right after `point` (an entry id, or START). */restore(point: string, who: HistoryWho, options?: Writing): Promise<HistoryEntry | null>;/** The files at `point` without writing anything: path to hash, read through readBlob. */peek(point: string): Record<string, string> | null;+ checkout(entryId: string, side: HistoryEntrySide, emptyDir: string): Promise<void>;readBlob(hash: string): Promise<Buffer>;pin(id: string, pinned: boolean): void;onEntry(listener: (entry: HistoryEntry) => void): () => void;@@ -183,6 +196,47 @@ function splitAt(];}+const isMissingFolder = (error: unknown) =>+ ["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "");++/** Removes a folder at `dir` that holds only empty folders (inTheWay checked), so a file can take its place. */+async function removeEmptyFolders(dir: string): Promise<void> {+ let entries: Dirent[];+ try {+ entries = await readdir(dir, { withFileTypes: true });+ } catch (error) {+ if (isMissingFolder(error)) return;+ throw error;+ }+ for (const entry of entries)+ if (entry.isDirectory()) await removeEmptyFolders(join(dir, entry.name));+ await rmdir(dir);+}++/** The first file or link under folder `dir` (project path `at`) not in `deleted`; links are not followed. */+function fileLeftIn(dir: string, at: string, deleted: ReadonlySet<string>): string | undefined {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const path = `${at}/${entry.name}`;+ const left = entry.isDirectory()+ ? fileLeftIn(join(dir, entry.name), path, deleted)+ : deleted.has(path)+ ? undefined+ : path;+ if (left) return left;+ }+ return undefined;+}++/** Whether the project's disk treats `A` and `a` as one name: its history-id file answers when upper-cased. */+function ignoresCase(dir: string): boolean {+ const self = statSync(join(dir, ID_PATH), { throwIfNoEntry: false });+ const other = statSync(join(dir, ID_PATH.toUpperCase()), { throwIfNoEntry: false });+ return self !== undefined && other?.ino === self.ino && other.dev === self.dev;+}++const blocks = (removed: string, added: string) =>+ added.startsWith(`${removed}/`) || removed.startsWith(`${added}/`);+/** A window takes a write within idleMs of its last one; past that it has ended, even before its timer commits it. */const takesWrite = (window: Group, at: number) =>window.idleMs === undefined || at - (window.lastWriteAt ?? at) <= window.idleMs;@@ -197,12 +251,13 @@ function addChange(group: Group, path: string, before: string | null, after: strclass Engine {readonly dir: string;+ readonly foldsCase: boolean;readonly home: string;log: HistoryLog = { baseline: new Map(), entries: [], pins: new Set() };tracked = new Map<string, Tracked>();windows: Group[] = [];outside: Group | null = null;- /** A coalescing claim, open until another key, its idle timer, or an operation commits it. */+ /** A coalescing claim, open until another key, its idle timer, an operation, a window, or another write. */claimed: { group: Group; key: string; timer: NodeJS.Timeout } | null = null;writeToken: string | undefined;quietTimer: NodeJS.Timeout | undefined;@@ -218,6 +273,12 @@ class Engine {) {this.dir = resolve(options.projectDir);this.home = join(options.historyRoot, projectId);+ this.foldsCase = ignoresCase(this.dir);+ }++ /** A path as the project's disk compares names: folded where `A` and `a` are one name. */+ nameKey(path: string): string {+ return this.foldsCase ? path.toLowerCase() : path;}get logFile() {@@ -251,9 +312,7 @@ class Engine {}// What changed while the project was closed is one outside entry, or the closed window's.this.reopenClosedWindow();- await this.sweep();- for (const window of [...this.windows]) await this.endWindow(window);- await this.commitOutside();+ await this.settleAll();}reopenClosedWindow(): void {@@ -304,16 +363,35 @@ class Engine {const sweptAt = Date.now();const changedAt = (file: { mtimeMs: number; ctimeMs: number }) =>Math.min(sweptAt, Math.max(file.mtimeMs, file.ctimeMs));- const seen = listProjectFiles(this.dir).sort((a, b) => changedAt(a) - changedAt(b));- let changed = false;- for (const file of seen)- changed = (await this.observe(file.path, statKey(file, sweptAt), changedAt(file))) || changed;+ const seen = listProjectFiles(this.dir);const present = new Set(seen.map((file) => file.path));- for (const [path, known] of this.tracked) {- if (present.has(path)) continue;+ const removed = [...this.tracked.keys()]+ .filter((path) => !present.has(path))+ .map((path) => {+ const standing = this.standingAt(path);+ return { at: standing ? changedAt(standing.stat) : sweptAt, path, file: null };+ });+ // A file in the way of a removal (a/b over file a, or the reverse) appeared no earlier than that removal.+ const appearedAt = (file: (typeof seen)[number]) =>+ Math.max(+ changedAt(file),+ ...removed+ .filter((gone) => blocks(this.nameKey(gone.path), this.nameKey(file.path)))+ .map((gone) => gone.at),+ );+ const events = [+ ...removed,+ ...seen.map((file) => ({ at: appearedAt(file), path: file.path, file })),+ ].sort((a, b) => a.at - b.at);+ let changed = false;+ for (const { at, path, file } of events) {+ if (file) {+ changed = (await this.observe(path, statKey(file, sweptAt), at)) || changed;+ continue;+ }+ const known = this.tracked.get(path)!;this.tracked.delete(path);- const removedAt = sweptAt;- await this.record(path, known.hash, null, removedAt);+ await this.record(path, known.hash, null, at);changed = true;}if (changed) this.saveStatCache();@@ -361,15 +439,11 @@ class Engine {{ coalesceKey, idleMs, overwrote = {} }: ClaimOptions,): Promise<{ id: string } | null> {await this.sweep();- const { taken, cut } = this.takeClaimed(who, paths, overwrote);- if (!taken.length) {- // A claim under another key still ends the held one.- if (coalesceKey !== this.claimed?.key) await this.commitClaim();- return null;- }+ const taken = this.takeClaimed(who, paths, overwrote);+ if (!taken.length) return this.claimNothing(coalesceKey);const held = this.heldFor(coalesceKey, taken);if (!held) await this.commitClaim();- await this.commitOlder(cut);+ await this.commitPending();const group = held ?? this.newGroup(who, label);for (const change of taken) addChange(group, change.path, change.before, change.after);if (coalesceKey) return this.holdClaim(group, coalesceKey, idleMs);@@ -377,15 +451,29 @@ class Engine {return entry && { id: entry.id };}- async commitOlder(cut: Map<Group, string[]>): Promise<void> {- if (this.outside) cut.delete(this.outside);+ /** A claim that took nothing still ends a held claim under another key. */+ async claimNothing(coalesceKey: string | undefined): Promise<null> {+ if (coalesceKey !== this.claimed?.key) await this.commitClaim();+ return null;+ }++ /** Commits every other writer's pending changes, oldest first; open windows stay open. */+ async commitPending(): Promise<void> {await this.commitOutside();- for (const [window, paths] of cut) await this.commitCut(window, paths);+ for (const window of [...this.windows])+ if (window.changes.size) await this.commitCut(window, [...window.changes.keys()]);+ }++ pendingElsewhere(): boolean {+ return (+ Boolean(this.outside?.changes.size) || this.windows.some((open) => open.changes.size > 0)+ );}/** The held claim `taken` continues: same key, each file from its own last change, no held file changed since. */heldFor(key: string | undefined, taken: readonly HistoryFileChange[]): Group | null {- const group = key && this.claimed?.key === key ? this.claimed.group : null;+ const group =+ key && this.claimed?.key === key && !this.pendingElsewhere() ? this.claimed.group : null;const after = (path: string, before: string | null) => {const own = group?.changes.get(path);return own ? own.after : before;@@ -404,12 +492,12 @@ class Engine {return relative(this.dir, resolve(this.dir, path)).split(sep).join("/");}- /** Takes `paths`' uncommitted changes from others, cut at what `who` overwrote; `cut`: paths each group keeps. */+ /** Takes `paths`' uncommitted changes from others, cut at what `who` overwrote. */takeClaimed(who: HistoryWho,paths: readonly string[],overwrote: Readonly<Record<string, string>>,- ): { taken: HistoryFileChange[]; cut: Map<Group, string[]> } {+ ): HistoryFileChange[] {const wanted = new Set(paths.map((path) => this.logPath(path)));const at = new Map(Object.entries(overwrote).map(([path, version]) => [@@ -420,23 +508,21 @@ class Engine {const others = this.windows.filter((open) => !sameWho(open.who, who));const groups = this.outside ? [this.outside, ...others] : others;const taken: HistoryFileChange[] = [];- const cut = new Map<Group, string[]>();for (const group of groups) {for (const change of [...group.changes.values()]) {if (!wanted.has(change.path)) continue;- const [kept, claimed] = this.cutOut(group, change, at.get(change.path));+ const claimed = this.cutOut(group, change, at.get(change.path));if (claimed) taken.push(claimed);- if (kept && claimed) cut.set(group, [...(cut.get(group) ?? []), change.path]);}}- return { taken, cut };+ return taken;}cutOut(group: Group, change: HistoryFileChange, cut: string | undefined) {const [kept, claimed] = splitAt(change, cut, cut !== undefined && this.blobs.has(cut));group.changes.delete(change.path);if (kept) group.changes.set(kept.path, kept);- return [kept, claimed] as const;+ return claimed;}/** Commits the window's cut `paths` as their own entry, other files staying: a window holds one change per file,@@ -491,6 +577,7 @@ class Engine {}async commitOutside(): Promise<void> {+ if (this.outside?.changes.size) await this.commitClaim();clearTimeout(this.quietTimer);clearTimeout(this.maxTimer);const group = this.outside;@@ -500,11 +587,9 @@ class Engine {async commit(group: Group, extra: Partial<HistoryEntry> = {}): Promise<HistoryEntry | null> {if (!group.changes.size) return null;- const { id, who, label, startedAt, lastWriteAt, changes } = group;- const files = [...changes.values()].sort((a, b) => a.path.localeCompare(b.path));- const previousEnd = this.log.entries.at(-1)?.endedAt ?? 0;- const endedAt = Math.max(lastWriteAt ?? this.now(), previousEnd);- const entry: HistoryEntry = { id, who, label, startedAt, endedAt, files, ...extra };+ const pending = this.pendingEntry(group);+ const endedAt = Math.max(pending.endedAt, this.log.entries.at(-1)?.endedAt ?? 0);+ const entry: HistoryEntry = { ...pending, endedAt, ...extra };this.log.entries.push(entry);try {saveRecord(this.logFile, this.log, { type: "entry", entry });@@ -535,11 +620,11 @@ class Engine {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. */+ /** Before an operation or a window: every write is filed and every pending change committed, in write order. */async settle(): Promise<void> {await this.sweep();await this.commitClaim();- await this.commitOutside();+ await this.commitPending();}/** A watcher saw a write: one sweep per burst takes it in (a deleted folder is reported by its name alone). */@@ -558,8 +643,8 @@ class Engine {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();+ // Writes before the window opened are not this writer's, and are logged before it.+ await this.settle();const window = { ...this.newGroup(who, label), idleMs };this.windows.push(window);this.touch(window, Date.now());@@ -589,6 +674,7 @@ class Engine {async endWindow(window: Group): Promise<HistoryEntry | null> {if (!this.windows.includes(window)) return window.entry ?? null;clearTimeout(window.idleTimer);+ await this.commitClaim();this.windows = this.windows.filter((open) => open !== window);window.entry = (await this.commit(window)) ?? window.entry ?? null;return window.entry;@@ -602,6 +688,31 @@ class Engine {await this.commitOutside();}+ /** What took a removed path's place, dating its removal: an entry at the path, or a file at a folder above it. */+ standingAt(path: string): { at: string; stat: Stats } | undefined {+ const parts = path.split("/");+ for (let depth = 1; depth <= parts.length; depth += 1) {+ const at = parts.slice(0, depth).join("/");+ const stat = lstatSync(join(this.dir, at), { throwIfNoEntry: false });+ if (!stat) return undefined;+ if (at === path || !stat.isDirectory()) return { at, stat };+ }+ return undefined;+ }++ /** What a write of `path` would have to delete: a file or link at or above it, or a file in a folder at it. */+ inTheWay(path: string, deleted: ReadonlySet<string>): string | undefined {+ const standing = this.standingAt(path);+ if (!standing) return undefined;+ if (standing.stat.isSymbolicLink()) return standing.at;+ if (standing.at === path && !standing.stat.isDirectory()) return undefined;+ // On-disk names, so an entry `a` found at `A` on a case-insensitive disk matches its tracked paths.+ const real = realpathSync.native(join(this.dir, standing.at));+ const at = relative(realpathSync.native(this.dir), real).split(sep).join("/");+ if (standing.at !== path) return deleted.has(at) ? undefined : at;+ return fileLeftIn(real, at, deleted);+ }+/** Writes `target` (path to hash, null deletes) as one entry of `who`'s. */async writeAs(who: HistoryWho,@@ -609,13 +720,19 @@ class Engine {target: Map<string, string | null>,extra: Partial<HistoryEntry>,): Promise<HistoryEntry | null> {+ const changes = [...target]+ .filter(([path, hash]) => (this.tracked.get(path)?.hash ?? null) !== hash)+ .sort(([, a], [, b]) => Number(a !== null) - Number(b !== null));+ const deleted = new Set(changes.filter(([, hash]) => hash === null).map(([path]) => path));+ const blocked = changes+ .filter(([, hash]) => hash !== null)+ .map(([path]) => this.inTheWay(path, deleted))+ .find(Boolean);+ if (blocked) throw new Error(`${blocked} is in the way; move or delete it, then try again.`);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)- await this.writeProjectFile(path, hash);- }+ for (const [path, hash] of changes) await this.writeProjectFile(path, hash);await this.sweep();} finally {this.windows = this.windows.filter((open) => open !== group);@@ -632,7 +749,10 @@ class Engine {recordFileWriteReceipt(absPath, { path, version, writeToken });}if (hash === null) await rm(absPath, { force: true });- else await this.blobs.writeTo(hash, absPath);+ else {+ await removeEmptyFolders(absPath);+ await this.blobs.writeTo(hash, absPath);+ }}entry(id: string): HistoryEntry {@@ -647,11 +767,7 @@ class Engine {return `Redid: ${original?.label ?? entry.label}`;}- async undoNow(- id: string,- who: HistoryWho,- mode?: "just-this" | "back-to-before",- ): Promise<HistoryResult> {+ async undoNow(id: string, who: HistoryWho, mode?: UndoMode): Promise<HistoryResult> {const entry = this.entry(id);const changed = this.movedOn(entry);if (changed.length && !mode) return { ok: false, conflict: this.conflict(entry, changed) };@@ -663,7 +779,11 @@ class Engine {entry: await this.restoreNow(point, who, `Went back to before: ${entry.label}`),};}- const target = new Map(entry.files.map((file) => [file.path, file.before]));+ const target = new Map(+ entry.files+ .filter((file) => mode !== "keep-later-edits" || !changed.includes(file))+ .map((file) => [file.path, file.before]),+ );return {ok: true,entry: await this.writeAs(who, this.undoLabel(entry), target, { undoes: id }),@@ -674,18 +794,21 @@ class Engine {return entry.files.filter((file) => (this.tracked.get(file.path)?.hash ?? null) !== file.after);}- /** Back reverts the newest change in effect, unless its files moved on under an earlier-ending edit (a held drag- * committed after an agent's turn): then that edit, if it still applies. */- next(direction: "back" | "forward"): HistoryEntry | undefined {- const top = stepTarget(this.log.entries, direction);- const moved = new Set(top && direction === "back" ? this.movedOn(top).map((f) => f.path) : []);- if (!top || !moved.size) return top;- const undone = undoneIds(this.log.entries);- const under = this.log.entries- .slice(0, this.log.entries.indexOf(top))- .reverse()- .find((e) => !e.undoes && !undone.has(e.id) && e.files.some((f) => moved.has(f.path)));- return under && !this.movedOn(under).length ? under : top;+ next(direction: "back" | "forward", who: HistoryWho): HistoryEntry | undefined {+ // An outside change has no known author, so it is everyone's; a step commits it after the held claim.+ const mine = (author: HistoryWho) => sameWho(author, who) || sameWho(author, OUTSIDE);+ const pending = [...[...this.windows].reverse(), this.outside, this.claimed?.group].find(+ (group) => group?.changes.size && mine(group.who),+ );+ if (pending) return direction === "back" ? this.pendingEntry(pending) : undefined;+ return stepTarget(this.log.entries, direction, (entry) => mine(entry.who));+ }++ /** A pending group as the entry it becomes once committed (a window's part gets a fresh id). */+ pendingEntry(group: Group): HistoryEntry {+ const files = [...group.changes.values()].sort((a, b) => a.path.localeCompare(b.path));+ const { id, who, label, startedAt, lastWriteAt } = group;+ return { id, who, label, startedAt, endedAt: lastWriteAt ?? this.now(), files };}conflict(@@ -743,7 +866,7 @@ class Engine {},step: (direction, who, { writeToken } = {}) =>this.operation(writeToken, async () => {- const target = this.next(direction);+ const target = this.next(direction, who);return target ? this.undoNow(target.id, who) : { ok: true, entry: null };}),undo: (id, { who, mode, writeToken }) =>@@ -756,7 +879,25 @@ class Engine {const files = manifestAt(this.log, point);return files && Object.fromEntries(files);},- next: (direction) => this.next(direction),+ checkout: (entryId, side, emptyDir) =>+ this.queue(async () => {+ this.entry(entryId);+ if (!existsSync(this.dir)) throw new Error(`The project folder is gone: ${this.dir}`);+ const dest = resolve(emptyDir);+ if (isWithin(this.dir, dest))+ throw new Error(`Checkout writes outside the project only: ${dest}`);+ if ((await readdir(dest).catch(missingIsEmpty)).length > 0)+ throw new Error(`Checkout writes into an empty folder only: ${dest}`);+ const files = manifestAround(this.log, entryId, side)!;+ try {+ for (const [path, hash] of files) await this.blobs.writeTo(hash, join(dest, path));+ } catch (error) {+ for (const name of await readdir(dest).catch(() => []))+ await rm(join(dest, name), { recursive: true, force: true });+ throw error;+ }+ }),+ next: (direction, who) => this.next(direction, who),readBlob: (hash) => this.blobs.read(hash),pin: (id, pinned) => {this.entry(id);@@ -777,6 +918,19 @@ class Engine {}}+/** Compares real on-disk paths; `.native` gives a case-insensitive disk's real letter case, so no alias gets in. */+function isWithin(dir: string, path: string): boolean {+ let probe = resolve(path);+ while (!existsSync(probe) && dirname(probe) !== probe) probe = dirname(probe);+ const rel = relative(realpathSync.native(dir), realpathSync.native(probe));+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));+}++function missingIsEmpty(error: NodeJS.ErrnoException): string[] {+ if (error.code === "ENOENT") return [];+ throw error;+}+/** 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);diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.tsindex a7db3da32d..ab71351491 100644--- a/packages/studio-server/src/index.ts+++ b/packages/studio-server/src/index.ts@@ -5,6 +5,8 @@ export {DEFAULT_HISTORY_ROOT,openProjectHistory,MAX_WINDOW_IDLE_MS,+ UNDO_MODES,+ type UndoMode,type ClosedWindow,type ProjectHistory,type ProjectHistoryOptions,@@ -16,6 +18,7 @@ export { HistoryBusyError } from "./history/ownerLock.js";export {START as HISTORY_START,type HistoryEntry,+ type HistoryEntrySide,type HistoryFileChange,type HistoryWho,} from "./history/historyLog.js";diff --git a/packages/studio-server/src/routes/history.test.ts b/packages/studio-server/src/routes/history.test.tsindex 34cb5ab6b9..dfbf03a021 100644--- a/packages/studio-server/src/routes/history.test.ts+++ b/packages/studio-server/src/routes/history.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+// fallow-ignore-file code-duplicationimport { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -109,7 +110,7 @@ describe("history routes", () => {});});- it("name the step the engine takes when it steps past an entry whose file moved on", async () => {+ it("name the person's own newest change, not an agent's later write", async () => {const { projectDir, history, call } = await demoProject();const write = (text: string) => writeFileSync(join(projectDir, "index.html"), text);const agent = { kind: "agent" as const, name: "Agent" };@@ -126,7 +127,7 @@ describe("history routes", () => {write("D");await window.close();await history.flush();- expect((await (await call("")).json()).back).toMatchObject({ label: "Agent turn" });+ expect((await (await call("")).json()).back).toMatchObject({ label: "Dragged Title" });});it("label an undo's writes with Studio's write token, so their echo reads as Studio's own", async () => {diff --git a/packages/studio-server/src/routes/history.ts b/packages/studio-server/src/routes/history.tsindex d4736ec575..53fec1cf33 100644--- a/packages/studio-server/src/routes/history.ts+++ b/packages/studio-server/src/routes/history.ts@@ -3,6 +3,7 @@ import type { StudioApiAdapter } from "../types.js";import { createWriteToken } from "../helpers/fileVersion.js";import {MAX_WINDOW_IDLE_MS,+ UNDO_MODES,type HistoryWindow,type ProjectHistory,} from "../history/projectHistory.js";@@ -54,7 +55,7 @@ function versionsOf(value: unknown): Record<string, string> | undefined {/** What Cmd+Z or Cmd+Shift+Z would revert next, so Studio can name it on its buttons. */function nextStep(history: ProjectHistory, direction: "back" | "forward") {- const target = history.next(direction);+ const target = history.next(direction, YOU);if (!target) return null;const paths = target.files.map((file) => file.path);return { id: target.id, label: target.label, endedAt: target.endedAt, paths };@@ -94,8 +95,7 @@ export function registerHistoryRoutes(api: Hono, adapter: StudioApiAdapter): voi);api.post(`${base}/undo`, (c) =>withHistory(adapter, c, (history, body) => {- const mode =- body.mode === "just-this" || body.mode === "back-to-before" ? body.mode : undefined;+ const mode = UNDO_MODES.find((known) => known === body.mode);return history.undo(text(body.entryId) ?? "", { who: whoOf(body), mode, ...writing(c) });}),);@@ -146,7 +146,7 @@ export function registerHistoryRoutes(api: Hono, adapter: StudioApiAdapter): voiidleMs ? { idleMs } : undefined,);windows.set(window.id, { history, window });- // The window's id is the id of the entry it becomes (its last one, when a claim cut it).+ // The window's id is its last entry's id, unless nothing was left after its last part.return { windowId: window.id, startedAt: window.startedAt };}),);diff --git a/packages/studio/src/hooks/usePersistentEditHistory.test.ts b/packages/studio/src/hooks/usePersistentEditHistory.test.tsindex 6c1bb5e18e..61a59d7510 100644--- a/packages/studio/src/hooks/usePersistentEditHistory.test.ts+++ b/packages/studio/src/hooks/usePersistentEditHistory.test.ts@@ -1,4 +1,5 @@// @vitest-environment happy-dom+// fallow-ignore-file code-duplicationimport { act, createElement } from "react";import { createRoot } from "react-dom/client";import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";@@ -103,8 +104,7 @@ it("a drag's edits under one key undo as one step, even before the drag goes idl}),);}- // The held drag is not in the history's list yet: only its own paths say what to read before the step.- expect(hook().undoLabel).toBeUndefined();+ await vi.waitFor(() => expect(hook().undoLabel).toBe("Dragged Title"));const undone = await act(() => hook().undo({ readFile }));expect(undone).toMatchObject({ok: true,diff --git a/packages/studio/src/hooks/usePersistentEditHistory.ts b/packages/studio/src/hooks/usePersistentEditHistory.tsindex 268ddc38dd..8dc61f68cb 100644--- a/packages/studio/src/hooks/usePersistentEditHistory.ts+++ b/packages/studio/src/hooks/usePersistentEditHistory.ts@@ -120,11 +120,11 @@ function redoneAt(view: HistoryView): number | null {return view.entries.find((entry) => entry.id === undo?.undoes)?.endedAt ?? null;}-/** Studio's undo over the server's project history: an edit claims what it wrote; Cmd+Z steps every writer's. */+/** Studio's undo over the server's project history: an edit claims what it wrote; Cmd+Z steps the person's. */export function usePersistentEditHistory({ projectId }: UsePersistentEditHistoryOptions) {const [view, setView] = useState<HistoryView>(EMPTY);const [loaded, setLoaded] = useState(false);- // A coalescing claim stays on the server until its drag goes idle, so it is not in `view` yet.+ // A coalescing claim the server just took, until `refresh()` brings its entry into `view`.const heldClaimRef = useRef<{ paths: string[]; at: number } | null>(null);const projectIdRef = useRef(projectId);projectIdRef.current = projectId;