feat(studio-server): undo is per author, and a turn part undoes alone keeping later edits

This commit is contained in:
Miguel Angel Simon Sierra
2026-09-25 17:10:33 -04:00
parent 5af83aa40e
commit cadf54d642
8 changed files with 209 additions and 60 deletions
+3 -2
View File
@@ -9,12 +9,13 @@ import {
type HistoryListItem,
type HistoryResult,
type HistoryWho,
type UndoMode,
} from "@hyperframes/studio-server";
export type { UndoMode };
import { resolveProject } from "./project.js";
import { findPreviewServerForProject, studioApiUrl } from "./studioSelectionClient.js";
export type UndoMode = "just-this" | "back-to-before";
/** 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 {
via: "preview" | "direct";
@@ -151,17 +151,30 @@ export function undoneIds(entries: readonly HistoryEntry[]): Set<string> {
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]));
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);
}
// A change is yours to step over if you made it, or your redo is what brought it back.
const owns = (entry: HistoryEntry) => mine(entry) || mine(redoneBy.get(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;
if (direction === "back") {
if (isChange && !undone.has(entry.id) && owns(entry)) return entry;
continue;
}
if (isChange) {
if (owns(entry)) return undefined;
continue;
}
const target = byId.get(entry.undoes!);
if (!undone.has(entry.id) && target && !target.undoes) return entry;
if (mine(entry) && !undone.has(entry.id) && target && !target.undoes) return entry;
}
return undefined;
}
@@ -68,6 +68,12 @@ 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,
@@ -365,7 +371,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-");
@@ -634,7 +640,7 @@ describe("openProjectHistory", () => {
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" },
});
@@ -749,9 +755,9 @@ describe("claim: a writer that records after writing", () => {
["outside", "Changed outside the app"],
["person", "Moved Title"],
]);
await history.step("back", you);
await undoNewest(history);
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")).toBe("A");
});
@@ -774,7 +780,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);
}
});
@@ -804,7 +810,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("b.js")]).toEqual([index, b]);
}
});
@@ -831,7 +837,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);
}
});
@@ -857,7 +863,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);
}
});
@@ -879,7 +885,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);
}
});
@@ -906,7 +912,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);
}
});
@@ -934,7 +940,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);
}
});
@@ -954,11 +960,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");
});
@@ -1018,9 +1024,8 @@ describe("claim: a writer that records after writing", () => {
"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(await undoNewest(history)).toMatchObject({ ok: true });
expect(read("index.html")).toBe(expected);
}
});
@@ -1106,6 +1111,131 @@ describe("claim: a writer that records after writing", () => {
]);
});
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("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();
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);
@@ -77,6 +77,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;
@@ -96,8 +99,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,
@@ -106,7 +109,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, an operation, or a window opening or closing. Null when nothing was claimed.
* another key, idle, an operation, a window opening or closing, or another write. Null when a drag nets to nothing.
*/
claim(
who: HistoryWho,
@@ -117,15 +120,12 @@ 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;
/** 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 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>;
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. */
@@ -497,6 +497,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;
@@ -654,14 +655,12 @@ 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) };
const kept =
mode === "keep-later-edits" ? new Set(changed.map((file) => file.path)) : new Set();
if (mode === "back-to-before") {
const index = this.log.entries.indexOf(entry);
const point = index > 0 ? this.log.entries[index - 1]!.id : START;
@@ -670,7 +669,9 @@ 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) => !kept.has(file.path)).map((file) => [file.path, file.before]),
);
return {
ok: true,
entry: await this.writeAs(who, this.undoLabel(entry), target, { undoes: id }),
@@ -681,18 +682,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: 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.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. */
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(
@@ -750,7 +754,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 }) =>
@@ -780,7 +784,7 @@ class Engine {
throw error;
}
}),
next: (direction) => this.next(direction),
next: (direction, who) => this.next(direction, who),
readBlob: (hash) => this.blobs.read(hash),
pin: (id, pinned) => {
this.entry(id);
+2
View File
@@ -5,6 +5,8 @@ export {
DEFAULT_HISTORY_ROOT,
openProjectHistory,
MAX_WINDOW_IDLE_MS,
UNDO_MODES,
type UndoMode,
type ClosedWindow,
type ProjectHistory,
type ProjectHistoryOptions,
@@ -109,7 +109,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 +126,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 () => {
+4 -4
View File
@@ -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): voi
idleMs ? { 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 };
}),
);
@@ -103,8 +103,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,