fix(studio-server): a file the drive never answers no longer holds a project's first history copy (#8187)

* fix(studio-server): a file the drive never answers no longer holds a project's first history copy

* fix(studio-server): keep history's comment share at or below its base

* fix(studio-server): a first copy that lands past its deadline is kept as the file's start

* fix(studio-server): a late first copy is adopted and kept while another file's read is stalled

* fix(studio-server): a waiting late first copy counts as baseline and rereads a few at a time

* fix(studio-server): every reread of an owed file takes a copy slot and is kept until adopted

* fix(studio-server): history pins a copy as it is filed and keeps a reference-only copy as such

* fix(studio-server): a history pin is taken and released by its owner, never across a delete

* fix(studio-server): an agent step waits at most a deadline for a file the drive never answers

* fix(studio-server): undo refuses a file whose first copy landed after an agent step rewrote it

* chore(studio-server): give the packed size budget its usual 5% headroom

Main packs to 190,094 bytes, already 0.65% over the 188,871 budget; this branch adds 1,264 bytes of its own code (no new import: dist/index.js is unchanged). The budget file's rule is 5% above measured: ceil(191,358 x 1.05) = 200,926.

* fix(studio-server): an agent step that goes ahead of a first copy owns that file's undo

* fix(studio-server): undo of a step that went ahead of a pending first copy is all or nothing

* fix(studio-server): an undo after a step that rewrote a pending file in place still refuses

A went-ahead file now clears from a step's list only when the first read after its copy lands finds the original
bytes, not when its size and times look unchanged. The list of went-ahead files is kept on disk, so a restart
before the step closes, or after it deleted the file, keeps the refusal. Parts a Studio claim cuts from a step
keep the list too.

* fix(studio-server): a step ahead of a pending file refuses undo after Cmd+Z, restarts, in older apps

Cmd+Z stops at an open step whose only write so far is a pending file. A step recovered after the process died
keeps its list of pending files. A later Studio save's receipt no longer sets the start of a file a step went ahead
of. Every earlier point names a pending file as not kept, so no restore deletes it in any app version.

* fix(studio-server): a step that went ahead of a pending file never undoes, whatever bytes land

Bytes cannot tell steps apart: a file written A, B, then A again by two steps looked untouched and cleared both. A
step's list of files it went ahead of is now never cleared, so its undo refuses after a stalled read.

* fix(studio-server): a recovered step keeps its guard through a second crash; saves keep the start

The closed window is recovered before the reopen rewrites went-ahead.json, so a crash during recovery no longer
erases its list of pending files. A copy read before a step went ahead is the file's start whatever a later save's
receipt says it replaced.

* fix(studio-server): a start keeps receipts heard before its read; reopen writes all pending files

A copy read before a step went ahead follows only the save receipts heard by the moment of its read, so an early
save's original stays the start and a later save naming the step's bytes cannot replace it. The reopen rebuilds
the list of pending files in memory and writes it once, so a crash midway keeps every file on it.

* fix(studio-server): a first copy's start follows only receipts heard by its read and keeps them

Every adopted copy follows the save receipts heard by the moment of its read, with or without a step, so a later
save writing the original back cannot move the start. A small file's read is reported before its close, which a slow
drive can hold. Bytes a save replaced in a file history has no copy of yet stay through pruning until it does.

* fix(studio-server): bytes kept for a pending first copy count as start, not undo history

The bytes a save replaced are kept only for a file still owed its first copy, and they count as start rather than
undo history, so they never fold an unrelated edit out of the budget or stay for a file that never needed them.
This commit is contained in:
Miguel Ángel
2026-11-21 23:28:17 +00:00
committed by GitHub
parent 8a69ea0395
commit 267ffc46c9
8 changed files with 1113 additions and 51 deletions
@@ -0,0 +1,48 @@
// Reads of `stuck` (comma-separated) never answer; a step rewrites or deletes them, then the process dies: "open"
// mid-step, "reopen"/"reopen-list" recovering the JSON window, at its first sweep/went-ahead.json write.
import fs, { unlinkSync, writeFileSync } from "node:fs";
import fsp from "node:fs/promises";
import { syncBuiltinESMExports } from "node:module";
import { join } from "node:path";
const [projectDir, historyRoot, stuck, mode = "close", closedWindow] = process.argv.slice(2);
const stuckFiles = stuck!.split(",");
const realOpen = fsp.open;
fsp.open = (async (...args: Parameters<typeof realOpen>) => {
if (stuckFiles.includes(String(args[0]))) await new Promise(() => {});
if (mode === "reopen" && String(args[0]) === join(projectDir!, "index.html"))
process.kill(process.pid, "SIGKILL");
return realOpen(...args);
}) as typeof realOpen;
const realRename = fs.renameSync;
fs.renameSync = ((from: fs.PathLike, to: fs.PathLike) => {
realRename(from, to);
if (mode === "reopen-list" && String(to).endsWith("went-ahead.json"))
process.kill(process.pid, "SIGKILL");
}) as typeof realRename;
syncBuiltinESMExports();
const { openProjectHistory } = await import("../projectHistory.js");
const history = await openProjectHistory({
projectDir: projectDir!,
historyRoot: historyRoot!,
firstCopyFileMs: 100,
now: () => Date.now() + 60_000,
...(closedWindow && { closedWindow: JSON.parse(closedWindow) }),
});
const agent = { kind: "agent", name: "Framey" } as const;
const index = join(projectDir!, "index.html");
if (mode === "earlier") {
writeFileSync(index, "<html>first</html>");
await history.claim({ kind: "person", name: "You" }, "First", [index]);
}
const step = await history.beginWindow(agent, "Step");
await new Promise((sent) => process.send!({ id: step.id }, sent));
for (const path of stuckFiles)
if (mode === "delete") unlinkSync(path);
else writeFileSync(path, "// agent\n");
writeFileSync(index, "<html>agent</html>");
for (const path of stuckFiles) history.noteChange(path);
history.noteChange(index);
if (mode !== "open") await step.close();
process.kill(process.pid, "SIGKILL");
@@ -26,7 +26,7 @@ vi.mock("node:fs/promises", async (importOriginal) => {
import * as fsp from "node:fs/promises";
import { fileContentVersion, recordFileWriteReceipt } from "../helpers/fileVersion.js";
import { blobPath } from "./blobStore.js";
import { START } from "./historyLog.js";
import { START, type HistoryWho } from "./historyLog.js";
import { openProjectHistory } from "./projectHistory.js";
const { writeFile: realWriteFile, open: realOpen } =
@@ -54,6 +54,29 @@ function projectOf(count: number, tag: string): string {
for (let i = 0; i < count; i++) writeFileSync(join(dir, "parts", `p${i}.js`), `// ${tag} ${i}\n`);
return dir;
}
/** A project with `count` 2 MiB files, copied in the background after the open, one after another. */
function mediaProject(count: number): string {
const dir = tempDir("hf-first-copy-");
writeFileSync(join(dir, "index.html"), "<html></html>");
for (let i = 0; i < count; i++)
writeFileSync(join(dir, `m${i}.bin`), Buffer.alloc(2 * 1024 ** 2, i + 1));
return dir;
}
const agent: HistoryWho = { kind: "agent", name: "Framey" };
/** The first open of `path` waits until an answer is called, at the latest before the test's histories close. */
function stallFirstOpenOf(path: string): (() => void)[] {
const releases: (() => void)[] = [];
let stalled = false;
vi.mocked(fsp.open).mockImplementation(async (...args: Parameters<typeof realOpen>) => {
if (String(args[0]) === path && !stalled) {
stalled = true;
await new Promise<void>((answer) => releases.push(answer));
}
return realOpen(...args);
});
closes.push(async () => releases.forEach((answer) => answer()));
return releases;
}
const homeIn = (historyRoot: string) => {
const homes = readdirSync(historyRoot, { withFileTypes: true }).filter((e) => e.isDirectory());
return join(historyRoot, homes.find((e) => existsSync(join(historyRoot, e.name, "blobs")))!.name);
@@ -223,11 +246,32 @@ describe("a project's first history copy", () => {
expect(existsSync(join(homeIn(historyRoot), "adopting.json"))).toBe(false);
});
it("arms no deadline for a read already owed when its slot comes", async () => {
const projectDir = projectOf(4, "owed-queued");
const releases: (() => void)[] = [];
closes.push(async () => releases.forEach((answer) => answer()));
let opened = 0;
vi.mocked(fsp.open).mockImplementation(async (...args: Parameters<typeof realOpen>) => {
if (String(args[0]).startsWith(projectDir) && ++opened <= 4)
await new Promise<void>((answer) => releases.push(answer));
return realOpen(...args);
});
const armed = vi.spyOn(globalThis, "setTimeout");
closes.push(async () => armed.mockRestore());
const historyRoot = tempDir("hf-first-copy-root-");
const history = await openProjectHistory({ projectDir, historyRoot, firstCopyFileMs: 777 });
closes.push(() => history.close());
const deadlines = () => armed.mock.calls.filter(([, ms]) => ms === 777).length;
const before = deadlines();
releases.shift()!();
await vi.waitFor(() => expect(opened).toBeGreaterThanOrEqual(5));
expect(deadlines()).toBe(before);
});
it("does not stretch a stalled read's deadline while other first copies finish", async () => {
const projectDir = projectOf(1, "stretch");
const stuck = join(projectDir, "parts", "p0.js");
const releases: (() => void)[] = [];
closes.push(async () => releases.forEach((answer) => answer()));
const releases = stallFirstOpenOf(stuck);
vi.mocked(fsp.open).mockImplementation(async (...args: Parameters<typeof realOpen>) => {
if (String(args[0]) === stuck) await new Promise<void>((answer) => releases.push(answer));
if (String(args[0]) === join(projectDir, "index.html"))
@@ -244,6 +288,63 @@ describe("a project's first history copy", () => {
]);
});
it("begins an agent step with no second deadline while a file's read never answers", async () => {
const projectDir = projectOf(6, "stuck");
const stuck = join(projectDir, "parts", "p1.js");
const releases: (() => void)[] = [];
vi.mocked(fsp.open).mockImplementation(async (...args: Parameters<typeof realOpen>) => {
if (String(args[0]) === stuck) await new Promise<void>((answer) => releases.push(answer));
return realOpen(...args);
});
try {
const openedAt = Date.now();
const history = await openProjectHistory({
projectDir,
historyRoot: tempDir("hf-first-copy-root-"),
firstCopyFileMs: 1000,
});
closes.push(() => history.close());
await history.beginWindow(agent, "Step");
expect(Date.now() - openedAt).toBeGreaterThanOrEqual(990);
expect(Date.now() - openedAt).toBeLessThan(1800);
} finally {
for (const answer of releases) answer();
}
});
it("begins an agent step after one deadline when media waits behind a read that never answers", async () => {
const projectDir = mediaProject(6);
stallFirstOpenOf(join(projectDir, "m0.bin"));
const history = await openProjectHistory({
projectDir,
historyRoot: tempDir("hf-first-copy-root-"),
firstCopyFileMs: 500,
});
closes.push(() => history.close());
const askedAt = Date.now();
await history.beginWindow(agent, "Step");
expect(Date.now() - askedAt).toBeLessThan(1500);
});
it("holds an agent step for media that copies slowly, each file within its deadline", async () => {
const projectDir = mediaProject(3);
const delayed = new Set([0, 1, 2].map((i) => join(projectDir, `m${i}.bin`)));
vi.mocked(fsp.open).mockImplementation(async (...args: Parameters<typeof realOpen>) => {
if (delayed.delete(String(args[0]))) await new Promise((later) => setTimeout(later, 300));
return realOpen(...args);
});
const history = await openProjectHistory({
projectDir,
historyRoot: tempDir("hf-first-copy-root-"),
firstCopyFileMs: 600,
});
closes.push(() => history.close());
await history.beginWindow(agent, "Step");
expect(Object.keys(history.peek(START) ?? {}).sort()).toEqual(
["index.html", "m0.bin", "m1.bin", "m2.bin"].sort(),
);
});
it("keeps the original as the start of a late copy when a save writes it back over a later change", async () => {
const projectDir = projectOf(1, "late");
const p0 = join(projectDir, "parts", "p0.js");
@@ -39,6 +39,7 @@ export interface HistoryEntry {
/** Set on a restore: the point (an entry id, or START) the files were made equal to. */
restoredTo?: string;
keptInPlace?: Record<string, string>;
wentAheadOf?: string[];
}
/** The point before the first kept entry. */
@@ -202,7 +202,16 @@ describe("a file still being written when the history first opens", () => {
changing.set("media.txt", 4);
const history = await openProjectHistory({ projectDir, historyRoot });
cleanup.push(() => history.close());
expect(await history.claim(you, "Edited", ["media.txt"])).toBeNull();
expect(history.peek(START)).not.toHaveProperty("media.txt");
const edit = await history.claim(you, "Edited", ["media.txt"]);
// The start names the file, as a version not kept until its copy lands.
expect(history.peek(START)!["media.txt"]).toMatch(/^[0-9a-f]{64}$/);
expect(history.peek(START)!["media.txt"]).not.toBe(
hashOfVersion(fileContentVersion("recorded")),
);
// The claim goes ahead of the copy, so its entry refuses an undo until the copy is saved.
await expect(history.undo(edit!.id, { who: you })).rejects.toThrow(
"The project's starting copy is still being saved",
);
expect(readFileSync(join(projectDir, "media.txt"), "utf-8")).toBe("recorded");
});
});
@@ -1,4 +1,4 @@
import { randomUUID } from "node:crypto";
import { createHash, randomUUID } from "node:crypto";
import { lstat, mkdir, readdir, realpath, rm, rmdir, stat, writeFile } from "node:fs/promises";
import {
type Dirent,
@@ -218,6 +218,7 @@ interface Group {
idleTimer?: NodeJS.Timeout;
entry?: HistoryEntry | null;
parts?: Set<string>;
wentAheadOf?: Set<string>;
}
/** Longer than any file system's time step (FAT's 2 s): a same-size rewrite inside one keeps its stat. */
@@ -238,19 +239,39 @@ type Copied =
hash: string;
referenced?: true;
release?: () => void;
readAfterStep?: true;
/** Save receipts heard by the moment of the read: after hash to the hash it replaced. */
heardAtRead?: Map<string, string>;
}
| "gone"
| "changing";
type Provenance = "no-step" | "read-before" | "unknown";
/** went-ahead.json: files steps went ahead of whose copy is pending, and each open window's list. */
type WentAhead = { pending: string[]; windows: Record<string, string[]> };
const FIRST_COPY_FILE_MS = 10_000;
async function orAfter<T, L>(work: Promise<T>, ms: number, late: L): Promise<T | L> {
let timer: NodeJS.Timeout | undefined;
const missed = new Promise<L>((owed) => (timer = setTimeout(() => owed(late), ms)));
try {
return await Promise.race([work, missed]);
} finally {
clearTimeout(timer);
}
}
const startingCopySaving = () =>
new HistoryRefusedError(
"starting_copy_saving",
"The project's starting copy is still being saved; try again in a moment. Nothing was changed.",
);
const hashNoVersionHas = () => createHash("sha256").update(randomUUID()).digest("hex");
const ADOPT_RETRY_AT_MOST_MS = 30_000;
/** Owed until a whole copy is recorded, the file is gone or history closes; retryNow waits for a fresh try. */
interface Adoption {
firstTry: Promise<unknown>;
stepMayBegin: Promise<boolean>;
ended: Promise<void>;
retryNow(): Promise<void>;
}
@@ -277,11 +298,12 @@ async function inFirstCopySlot<T>(copy: () => Promise<T>): Promise<T> {
/** Owed `ms` after its read starts; while queued, `ms` after the last first copy that finished. */
function firstCopyOrOwed(copy: () => Promise<Copied>, ms: number) {
let timer: NodeJS.Timeout | undefined;
let settled = false;
let owe = () => {};
const owed = new Promise<"changing">((resolve) => (owe = () => resolve("changing")));
const restart = () => {
clearTimeout(timer);
timer = setTimeout(owe, ms);
if (!settled) timer = setTimeout(owe, ms);
};
firstCopyProgress.add(restart);
restart();
@@ -291,6 +313,7 @@ function firstCopyOrOwed(copy: () => Promise<Copied>, ms: number) {
return copy();
});
const result = Promise.race([work, owed]).finally(() => {
settled = true;
clearTimeout(timer);
firstCopyProgress.delete(restart);
});
@@ -531,6 +554,8 @@ class Engine {
/** 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;
adopting = new Map<string, Adoption>();
wentAhead = new Set<string>();
wentAheadBeforeReopen = new Set<string>();
reading = new Map<string, Promise<unknown>>();
/** Bytes a save replaced in a file history holds no copy of yet: its pending first copy may start there. */
heardBeforeCopy = new Map<string, Set<string>>();
@@ -689,11 +714,14 @@ class Engine {
this.tracked.set(path, { hash, stat: cached?.hash === hash ? cached.stat : "" });
}
const left = this.readAdopting();
const files = await this.historyFiles();
const wentAhead = this.readJson<WentAhead>("went-ahead.json", { pending: [], windows: {} });
// What changed while the project was closed is one outside entry, or the closed window's.
this.reopenClosedWindow(wentAhead.windows);
this.markWentAheadBeforeReopen(wentAhead.pending, left, new Set(files.map((f) => f.path)));
const unadopted = (file: { path: string }) =>
left.has(file.path) && !this.tracked.has(file.path);
this.adoptMediaInBackground((await this.historyFiles()).filter(unadopted), this.now());
// What changed while the project was closed is one outside entry, or the closed window's.
this.reopenClosedWindow();
this.adoptMediaInBackground(files.filter(unadopted), this.now());
await this.settleAll();
}
@@ -755,7 +783,7 @@ class Engine {
this.overwritten.delete(path);
}
reopenClosedWindow(): void {
reopenClosedWindow(wentAheadOf: WentAhead["windows"]): void {
const closed = this.options.closedWindow;
if (!closed || this.log.entries.some((entry) => entry.id === closed.id)) return;
const { id, who, label, startedAt, lastWriteAt, idleMs } = closed;
@@ -769,6 +797,7 @@ class Engine {
lastFileTime,
idleMs,
changes: new Map(),
...(wentAheadOf[id] && { wentAheadOf: new Set(wentAheadOf[id]) }),
});
}
@@ -821,8 +850,56 @@ class Engine {
);
}
async untilFirstCopiesLandBeforeAnyWrite(): Promise<void> {
await Promise.all([...this.adopting.values()].map((adoption) => adoption.firstTry));
async untilFirstCopiesLandOrStall(): Promise<void> {
await Promise.all([...this.adopting.values()].map((adoption) => adoption.stepMayBegin));
}
/** Files a step went ahead of before the last close, still owed their first copy or gone since. */
markWentAheadBeforeReopen(pending: string[], adopting: Set<string>, present: Set<string>): void {
for (const path of pending) {
if (!adopting.has(path)) continue;
this.tracked.delete(path);
if (!present.has(path)) {
this.startUnseen(path, this.log.baseline.get(path) ?? hashNoVersionHas());
continue;
}
this.wentAhead.add(path);
this.wentAheadBeforeReopen.add(path);
}
this.nameAtStart([...this.wentAhead]);
this.saveWentAhead();
}
markWentAhead(paths: string[], group?: Group): boolean {
const fresh = paths.filter((path) => !this.wentAhead.has(path));
for (const path of fresh) this.wentAhead.add(path);
this.nameAtStart(fresh);
if (group && paths.length)
group.wentAheadOf = new Set([...(group.wentAheadOf ?? []), ...paths]);
if (fresh.length || (group && paths.length)) this.saveWentAhead();
return paths.length > 0;
}
/** Every earlier point names the file, as not kept until its copy lands: no restore deletes it, in any app. */
nameAtStart(paths: string[]): void {
const unnamed = paths.filter((path) => !this.log.baseline.has(path));
for (const path of unnamed) this.log.baseline.set(path, hashNoVersionHas());
if (unnamed.length) this.persistLog(baselineRecord(this.log));
}
saveWentAhead(): void {
const windows = this.windows.filter((open) => open.wentAheadOf?.size);
const state: WentAhead = {
pending: [...this.wentAhead],
windows: Object.fromEntries(windows.map((open) => [open.id, [...open.wentAheadOf!]])),
};
this.saveJson("went-ahead.json", this.wentAhead.size || windows.length ? state : null);
}
provenanceOf(copied: Copied, path: string): Provenance {
if (!this.wentAhead.has(path)) return "no-step";
if (typeof copied !== "object" || this.wentAheadBeforeReopen.has(path)) return "unknown";
return copied.readAfterStep ? "unknown" : "read-before";
}
adoptMediaInBackground(
@@ -830,21 +907,32 @@ class Engine {
sweptAt: number,
lateFirstCopies = new Map<string, Promise<Copied>>(),
): void {
const waitMs = this.options.firstCopyFileMs ?? FIRST_COPY_FILE_MS;
let turn: Promise<unknown> = Promise.resolve();
let stalledAhead = Promise.resolve(false);
for (const file of files) {
const late = lateFirstCopies.get(file.path);
const adoption = this.adopt(file, sweptAt, turn, late);
if (!late) turn = adoption.firstTry;
this.adopting.set(file.path, adoption);
const landed = adoption.firstTry.then(() => false);
const stepMayBegin = late
? Promise.resolve(true)
: stalledAhead.then((stalled) => stalled || orAfter(landed, waitMs, true));
if (!late) [turn, stalledAhead] = [adoption.firstTry, stepMayBegin];
this.adopting.set(file.path, { ...adoption, stepMayBegin });
}
this.saveAdopting();
}
saveAdopting(): void {
const file = join(this.home, "adopting.json");
if (!this.adopting.size) return rmSync(file, { force: true });
this.saveJson("adopting.json", this.adopting.size ? [...this.adopting.keys()] : null);
}
/** Null removes the file. */
saveJson(name: string, value: unknown): void {
const file = join(this.home, name);
if (value === null) return rmSync(file, { force: true });
mkdirSync(this.home, { recursive: true });
replaceFileAtomically(file, JSON.stringify([...this.adopting.keys()]), 0o644);
replaceFileAtomically(file, JSON.stringify(value), 0o644);
}
/** A file still changing stays named until a whole copy of it lands; the next open retries it. */
@@ -853,7 +941,7 @@ class Engine {
sweptAt: number,
turn: Promise<unknown>,
late?: Promise<Copied>,
): Adoption {
): Omit<Adoption, "stepMayBegin"> {
let asked: Array<() => void> = [];
let wake = () => {};
const owedFromOpen = late !== undefined;
@@ -901,11 +989,15 @@ class Engine {
const fromOpen = typeof first === "object";
const read = () => this.storeIfPresent(file.path, true);
const copied = fromOpen ? first : await (owedFromOpen ? inFirstCopySlot(read) : read());
const provenance = this.provenanceOf(copied, file.path);
const record = this.queue(async () => {
// Still named for the next open until recorded, so a failed record is never logged as added.
if ((await this.recordAdopted(file, sweptAt, copied)) === "changing") return "changing";
if ((await this.recordAdopted(file, sweptAt, copied, provenance)) === "changing")
return "changing";
this.adopting.delete(file.path);
this.heardBeforeCopy.delete(file.path);
this.wentAhead.delete(file.path);
this.saveWentAhead();
this.saveAdopting();
// The sweeps since open passed this file by: one more takes in any edit since the bytes were read.
if (fromOpen) this.sweepIn(0);
@@ -918,22 +1010,56 @@ class Engine {
}
}
async recordAdopted(file: ListedFile, sweptAt: number, first: Copied): Promise<Copied> {
if (typeof first === "string" || this.whereFolder() !== "here") return first;
async recordAdopted(
file: ListedFile,
sweptAt: number,
first: Copied,
provenance: Provenance,
): Promise<Copied> {
if (first === "changing" || this.whereFolder() !== "here") return first;
if (first === "gone") {
if (provenance !== "no-step") this.startUnseen(file.path, hashNoVersionHas());
return first;
}
// Bytes gone from the store are read again on the next try, outside the history queue.
if (!first.referenced && !this.blobs.has(first.hash)) return "changing";
const copied = first;
const { hash } = copied;
const change = { path: file.path, before: null, after: hash };
const heard = copied.heardAtRead ?? new Map<string, string>();
const found = this.overwrittenBy(change, undefined, new Set(), heard);
const start = found && this.blobs.has(found) ? found : hash;
const start = this.adoptedStart(file.path, first, provenance);
if (provenance === "no-step") this.startSeen(file, sweptAt, start, first.hash);
else this.startUnseen(file.path, start);
return first;
}
startSeen(file: ListedFile, sweptAt: number, start: string, hash: string) {
this.tracked.set(file.path, { hash, stat: this.statKey(file, sweptAt) });
this.log.baseline.set(file.path, start);
if (start !== hash) addChange(this.outsideGroup(), file.path, start, hash);
this.persistLog(baselineRecord(this.log));
this.saveStatCache();
return copied;
}
/** A file a step went ahead of starts here; its next sweep takes in whatever stands there now. */
startUnseen(path: string, start: string): void {
this.tracked.set(path, { hash: start, stat: "" });
this.log.baseline.set(path, start);
this.persistLog(baselineRecord(this.log));
this.saveStatCache();
this.sweepIn(0);
}
adoptedStart(
path: string,
{ hash, heardAtRead }: { hash: string; heardAtRead?: Map<string, string> },
provenance: Provenance,
): string {
if (provenance === "unknown") return hashNoVersionHas();
const heard = heardAtRead ?? new Map<string, string>();
const found = this.overwrittenBy(
{ path, before: null, after: hash },
undefined,
new Set(),
heard,
);
return found && this.blobs.has(found) ? found : hash;
}
manifest(): Manifest {
@@ -950,12 +1076,14 @@ class Engine {
}
readAdopting(): Set<string> {
return new Set(this.readJson<string[]>("adopting.json", []));
}
readJson<T>(name: string, missing: T): T {
try {
return new Set(
JSON.parse(readFileSync(join(this.home, "adopting.json"), "utf-8")) as string[],
);
return JSON.parse(readFileSync(join(this.home, name), "utf-8")) as T;
} catch {
return new Set();
return missing;
}
}
@@ -1060,17 +1188,21 @@ class Engine {
try {
const abs = join(this.dir, path);
const { size } = await stat(abs);
let readAfterStep: true | undefined;
let heardAtRead: Map<string, string> | undefined;
const read = () => (heardAtRead = new Map(this.overwritten.get(path)));
const read = () => {
readAfterStep = this.wentAhead.has(path) || undefined;
heardAtRead = new Map(this.overwritten.get(path));
};
if (isUncopied(path, size)) {
const hash = await this.blobs.reference(abs);
read();
return { hash, referenced: true, heardAtRead };
return { hash, referenced: true, readAfterStep, heardAtRead };
}
const hash = await this.blobs.put(abs, pin, read);
if (hash === null) return "changing";
const release = pin ? { release: () => this.blobs.unpin(hash) } : {};
return { hash, ...release, heardAtRead };
return { hash, ...release, readAfterStep, heardAtRead };
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return "gone";
throw error;
@@ -1110,15 +1242,19 @@ class Engine {
label: string,
paths: readonly string[],
{ coalesceKey, idleMs, overwrote = {}, targets = [] }: ClaimOptions,
pending: string[] = [],
): Promise<{ id: string } | null> {
await this.sweep(new Set(paths.map((path) => this.logPath(path))));
const taken = await this.takeClaimed(who, paths, overwrote);
this.markWentAhead(pending);
if (!taken.length && pending.length) return this.claimUnseen(who, label, pending);
if (!taken.length) return this.claimNothing(coalesceKey);
const held = this.heldFor(coalesceKey, taken);
if (!held) await this.commitClaim();
await this.commitPending();
const group = held ?? this.newGroup(who, label);
for (const change of taken) addChange(group, change.path, change.before, change.after);
this.markWentAhead(pending, group);
this.addTargets(group, targets);
if (coalesceKey) return this.holdClaim(group, coalesceKey, idleMs);
const entry = await this.commit(group);
@@ -1134,6 +1270,16 @@ class Engine {
group.targets = [...unique.values()];
}
/** A claim on files whose first copy is pending only: its entry holds them, so its undo refuses. */
async claimUnseen(who: HistoryWho, label: string, pending: string[]): Promise<{ id: string }> {
await this.commitClaim();
await this.commitPending();
const group = this.newGroup(who, label);
this.markWentAhead(pending, group);
const entry = await this.commit(group);
return { id: entry!.id };
}
/** 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();
@@ -1244,6 +1390,7 @@ class Engine {
* so the writer's next write to a cut file would otherwise span the claimer's edit. */
async commitCut(window: Group, paths: readonly string[]): Promise<void> {
const part = { ...this.newGroup(window.who, window.label), startedAt: window.startedAt };
if (window.wentAheadOf) part.wentAheadOf = new Set(window.wentAheadOf);
for (const path of paths) {
part.changes.set(path, window.changes.get(path)!);
window.changes.delete(path);
@@ -1304,6 +1451,15 @@ class Engine {
if (group) await this.commit(group);
}
/** A change no version can bring back, for each file the step could not see: older apps refuse its undo too. */
holdUnseen(group: Group): void {
for (const path of group.wentAheadOf ?? []) {
if (group.changes.has(path)) continue;
const unseen = hashNoVersionHas();
group.changes.set(path, { path, before: unseen, after: unseen });
}
}
keepsEmpty(extra: Partial<HistoryEntry>): boolean {
if (extra.undoes === undefined) return false;
const target = this.log.entries.find((entry) => entry.id === extra.undoes);
@@ -1312,6 +1468,7 @@ class Engine {
}
async commit(group: Group, extra: Partial<HistoryEntry> = {}): Promise<HistoryEntry | null> {
this.holdUnseen(group);
if (!group.changes.size && !this.keepsEmpty(extra)) return null;
const pending = this.pendingEntry(group);
const endedAt = Math.max(pending.endedAt, this.log.entries.at(-1)?.endedAt ?? 0);
@@ -1643,8 +1800,18 @@ class Engine {
return `Redid: ${original?.label ?? entry.label}`;
}
refuseUnseen(entry: HistoryEntry): void {
const unseen = entry.wentAheadOf ?? [];
if (unseen.some((path) => this.adopting.has(path))) throw startingCopySaving();
if (unseen.length)
throw notKept(
`An earlier version of ${unseen[0]} is not kept, so this cannot be brought back.`,
);
}
async undoNow(id: string, who: HistoryWho, mode?: UndoMode): Promise<HistoryResult> {
const entry = this.entry(id);
this.refuseUnseen(entry);
const hashOf = (path: string) => this.tracked.get(path)?.hash ?? null;
const steps = this.stepsOf(entry);
const changed = steps.filter((step) => hashOf(step.path) !== step.holds);
@@ -1709,7 +1876,8 @@ class Engine {
const mine = (author: HistoryWho) => sameWho(author, who) || sameWho(author, OUTSIDE);
const writes = (paths: Iterable<string>) => [...paths].some(this.studioWouldWrite);
const pending = [...[...this.windows].reverse(), this.outside, this.claimed?.group].find(
(group) => group && writes(group.changes.keys()) && mine(group.who),
(group) =>
group && writes([...group.changes.keys(), ...(group.wentAheadOf ?? [])]) && mine(group.who),
);
if (pending) return direction === "back" ? this.pendingEntry(pending) : undefined;
const everyone = this.options.undoScope === "everyone";
@@ -1734,6 +1902,7 @@ class Engine {
endedAt: lastWriteAt ?? this.now(),
files,
...(group.targets?.length && { targets: group.targets }),
...(group.wentAheadOf?.size && { wentAheadOf: [...group.wentAheadOf].sort() }),
};
}
@@ -1754,12 +1923,8 @@ class Engine {
[...this.tracked.keys()].map((path) => [path, null]),
);
for (const [path, hash] of files) target.set(path, hash);
if (point === START && this.adopting.size > 0) {
throw new HistoryRefusedError(
"starting_copy_saving",
"The project's starting copy is still being saved; try again in a moment. Nothing was changed.",
);
}
if (this.adopting.size > 0 && (point === START || this.wentAhead.size > 0))
throw startingCopySaving();
const isProjectFile = (path: string) => !KEPT_HIDDEN_PATHS.has(path);
const keepsAny = [...target].some(([path, hash]) => hash !== null && isProjectFile(path));
if ([...this.tracked.keys()].some(isProjectFile) && !keepsAny) {
@@ -1792,18 +1957,26 @@ class Engine {
return {
projectId: this.projectId,
beginWindow: async (who, label, options = {}) => {
await this.untilFirstCopiesLandBeforeAnyWrite();
return this.beginWindow(
await this.untilFirstCopiesLandOrStall();
const window = await this.beginWindow(
who,
label,
options.idleMs ?? this.options.maxGroupMs ?? 30_000,
options.exclusive === true,
);
const group = this.windows.find((open) => open.id === window.id);
this.markWentAhead([...this.adopting.keys()], group);
return window;
},
unsavedBlobBytes: () => this.unsavedBlobBytes(),
claim: async (who, label, paths, options = {}) => {
await Promise.all(paths.map((path) => this.adopting.get(this.logPath(path))?.retryNow()));
return this.queue(() => this.claimNow(who, label, paths, options));
const waitMs = this.options.firstCopyFileMs ?? FIRST_COPY_FILE_MS;
const owed = (path: string) => this.adopting.get(this.logPath(path));
await Promise.all(
paths.map((path) => orAfter(Promise.resolve(owed(path)?.retryNow()), waitMs, undefined)),
);
const pending = paths.filter(owed).map((path) => this.logPath(path));
return this.queue(() => this.claimNow(who, label, paths, options, pending));
},
noteChange: (path) => {
if (!this.closed) this.noteChange(path);
@@ -1815,6 +1988,7 @@ class Engine {
step: (direction, who, { writeToken } = {}) =>
this.operation(writeToken, async () => {
const target = this.next(direction, who);
if (target) this.refuseUnseen(target);
return target ? this.undoNow(target.id, who) : { ok: true, entry: null };
}),
undo: (id, { who, mode, writeToken }) =>
@@ -0,0 +1,730 @@
// @vitest-environment node
import { fork } from "node:child_process";
import { createHash } from "node:crypto";
import {
appendFileSync,
existsSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
unlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
vi.mock("node:fs/promises", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs/promises")>();
return {
...actual,
writeFile: vi.fn(actual.writeFile),
open: vi.fn(actual.open),
stat: vi.fn(actual.stat),
};
});
import * as fsp from "node:fs/promises";
import { fileContentVersion, recordFileWriteReceipt } from "../helpers/fileVersion.js";
import { readLog, START, type HistoryWho } from "./historyLog.js";
import { blobPath } from "./blobStore.js";
import { openProjectHistory, type ProjectHistory } from "./projectHistory.js";
const {
writeFile: realWriteFile,
open: realOpen,
stat: realStat,
} = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
const sha256 = (bytes: string | Buffer) => createHash("sha256").update(bytes).digest("hex");
const agent: HistoryWho = { kind: "agent", name: "Framey" };
const you: HistoryWho = { kind: "person", name: "You" };
const STILL_SAVING = "The project's starting copy is still being saved";
const NOT_KEPT = "An earlier version of parts/p1.js is not kept";
const temps: string[] = [];
const closes: (() => Promise<void>)[] = [];
afterEach(async () => {
vi.mocked(fsp.writeFile).mockImplementation(realWriteFile);
vi.mocked(fsp.open).mockImplementation(realOpen);
vi.mocked(fsp.stat).mockImplementation(realStat);
for (const close of closes.splice(0)) await close();
for (const dir of temps.splice(0)) rmSync(dir, { recursive: true, force: true });
});
const tempDir = (prefix: string) => {
const dir = mkdtempSync(join(tmpdir(), prefix));
temps.push(dir);
return dir;
};
/** index.html and parts/p1.js, whose first copy is pending once `stall` holds its read. */
function project() {
const dir = tempDir("hf-step-ahead-");
mkdirSync(join(dir, "parts"));
writeFileSync(join(dir, "index.html"), "<html>before</html>");
writeFileSync(join(dir, "parts", "p1.js"), "// before\n");
const historyRoot = tempDir("hf-step-ahead-root-");
const file = (path: string) => join(dir, path);
const read = (path: string) => readFileSync(file(path), "utf8");
let ahead = 0;
const opts = {
projectDir: dir,
historyRoot,
firstCopyFileMs: 100,
now: () => Date.now() + ahead,
};
// History trusts a stat it has seen unchanged for longer than a file system's time step.
const later = () => (ahead += 5000);
return { dir, historyRoot, file, read, opts, later };
}
/** The first open of `path` waits until released, at the latest before the test's histories close. */
function stallRead(path: string): () => void {
const releases: (() => void)[] = [];
let stalled = false;
vi.mocked(fsp.open).mockImplementation(async (...args: Parameters<typeof realOpen>) => {
if (String(args[0]) === path && !stalled) {
stalled = true;
await new Promise<void>((answer) => releases.push(answer));
}
return realOpen(...args);
});
const release = () => releases.forEach((answer) => answer());
closes.push(async () => release());
return release;
}
/** The first filing of `bytes` into the blob store waits until released; the read before it is not held. */
function holdFiling(bytes: Buffer): { release: () => void; reached: Promise<void> } {
const releases: (() => void)[] = [];
let reach = () => {};
const reached = new Promise<void>((held) => (reach = held));
vi.mocked(fsp.writeFile).mockImplementation(async (...args: Parameters<typeof realWriteFile>) => {
const [to, written] = args;
if (!releases.length && String(to).includes("incoming-") && bytes.equals(written as Buffer)) {
const wait = new Promise<void>((answer) => releases.push(answer));
reach();
await wait;
}
return realWriteFile(...args);
});
const release = () => releases.forEach((answer) => answer());
closes.push(async () => release());
return { release, reached };
}
async function open(opts: Parameters<typeof openProjectHistory>[0]) {
const history = await openProjectHistory(opts);
closes.push(() => history.close());
return history;
}
const homeIn = (historyRoot: string) => {
const homes = readdirSync(historyRoot, { withFileTypes: true }).filter((e) => e.isDirectory());
return join(historyRoot, homes.find((e) => existsSync(join(historyRoot, e.name, "blobs")))!.name);
};
/** Every first copy is recorded: nothing is named as still being adopted. */
const landed = (historyRoot: string) =>
vi.waitFor(() => expect(existsSync(join(homeIn(historyRoot), "adopting.json"))).toBe(false), {
timeout: 10_000,
});
/** Runs `__fixtures__/stepThenDie.ts`; resolves with the step's window id once the process is killed. */
function stepThenDie(
dir: string,
historyRoot: string,
stuck: string,
mode: string,
...rest: string[]
) {
return new Promise<string>((done, fail) => {
let id = "";
const fixture = join(import.meta.dirname, "__fixtures__", "stepThenDie.ts");
fork(fixture, [dir, historyRoot, stuck, mode, ...rest], { execArgv: ["--import", "tsx"] })
.on("message", (message) => (id = (message as { id: string }).id))
.once("exit", (_, signal) =>
signal === "SIGKILL" ? done(id) : fail(new Error(`stepThenDie exited: ${signal}`)),
);
});
}
async function step(history: ProjectHistory, writes: () => void, notes: string[]) {
const window = await history.beginWindow(agent, "Step");
writes();
for (const path of notes) history.noteChange(path);
return (await window.close())!;
}
describe("an agent step that began while a file's first copy was pending", () => {
it("refuses its whole undo while the copy is still pending", async () => {
const { file, read, opts } = project();
stallRead(file("parts/p1.js"));
const history = await open(opts);
const entry = await step(history, () => {
writeFileSync(file("parts/p1.js"), "// agent\n");
writeFileSync(file("index.html"), "<html>agent</html>");
}, [file("parts/p1.js"), file("index.html")]);
const cursor = history.next("back", agent)?.id;
const listed = history.list().length;
await expect(history.undo(entry.id, { who: agent })).rejects.toThrow(STILL_SAVING);
await expect(history.step("back", agent)).rejects.toThrow(STILL_SAVING);
await expect(history.restore(START, agent)).rejects.toThrow(STILL_SAVING);
await expect(history.restore(entry.id, agent)).rejects.toThrow(STILL_SAVING);
expect(history.next("back", agent)?.id).toBe(cursor);
expect(history.list()).toHaveLength(listed);
expect(read("index.html")).toBe("<html>agent</html>");
expect(read("parts/p1.js")).toBe("// agent\n");
});
it("stops Cmd+Z at a step whose only write was the pending file", async () => {
const { file, read, opts } = project();
stallRead(file("parts/p1.js"));
const history = await open(opts);
await step(history, () => writeFileSync(file("index.html"), "<html>first</html>"), [
file("index.html"),
]);
const entry = await step(history, () => writeFileSync(file("parts/p1.js"), "// agent\n"), [
file("parts/p1.js"),
]);
expect(history.next("back", agent)?.id).toBe(entry.id);
await expect(history.step("back", agent)).rejects.toThrow(STILL_SAVING);
expect(read("index.html")).toBe("<html>first</html>");
expect(read("parts/p1.js")).toBe("// agent\n");
});
it("stops Cmd+Z at an open step whose only write so far is the pending file", async () => {
const { file, read, opts } = project();
stallRead(file("parts/p1.js"));
const history = await open(opts);
await step(history, () => writeFileSync(file("index.html"), "<html>first</html>"), [
file("index.html"),
]);
const window = await history.beginWindow(agent, "Step");
closes.unshift(async () => void (await window.close()));
writeFileSync(file("parts/p1.js"), "// agent\n");
history.noteChange(file("parts/p1.js"));
expect(history.next("back", agent)?.id).toBe(window.id);
const listed = history.list();
await expect(history.step("back", agent)).rejects.toThrow(STILL_SAVING);
expect(history.list()).toEqual(listed);
expect(history.next("back", agent)?.id).toBe(window.id);
expect(read("index.html")).toBe("<html>first</html>");
expect(read("parts/p1.js")).toBe("// agent\n");
});
it("refuses its whole undo once the copy lands showing the file changed", async () => {
const { file, read, historyRoot, opts } = project();
const release = stallRead(file("parts/p1.js"));
const history = await open(opts);
const entry = await step(history, () => {
writeFileSync(file("parts/p1.js"), "// agent\n");
writeFileSync(file("index.html"), "<html>agent</html>");
}, [file("parts/p1.js"), file("index.html")]);
release();
await landed(historyRoot);
expect(history.peek(START)!["parts/p1.js"]).not.toBe(sha256("// agent\n"));
await expect(history.undo(entry.id, { who: agent })).rejects.toThrow(NOT_KEPT);
await expect(history.undo(entry.id, { who: agent, mode: "back-to-before" })).rejects.toThrow(
NOT_KEPT,
);
await expect(history.restore(START, agent)).rejects.toThrow(NOT_KEPT);
expect(read("index.html")).toBe("<html>agent</html>");
expect(read("parts/p1.js")).toBe("// agent\n");
});
it("refuses the undo of every step that went ahead, though the file ends with its original bytes", async () => {
const { file, read, historyRoot, opts } = project();
const { release } = holdFiling(Buffer.from("// before\n"));
const history = await open(opts);
const ahead = await step(history, () => {
writeFileSync(file("parts/p1.js"), "// B\n");
writeFileSync(file("index.html"), "<html>s1</html>");
}, [file("parts/p1.js"), file("index.html")]);
const back = await step(history, () => {
writeFileSync(file("parts/p1.js"), "// before\n");
writeFileSync(file("index.html"), "<html>s2</html>");
}, [file("parts/p1.js"), file("index.html")]);
const untouched = await step(
history,
() => writeFileSync(file("index.html"), "<html>s3</html>"),
[file("index.html")],
);
release();
await landed(historyRoot);
expect(history.peek(START)!["parts/p1.js"]).toBe(sha256("// before\n"));
for (const entry of [untouched, back, ahead])
await expect(history.undo(entry.id, { who: agent })).rejects.toThrow(NOT_KEPT);
expect(read("index.html")).toBe("<html>s3</html>");
expect(read("parts/p1.js")).toBe("// before\n");
});
it("refuses its undo when the step rewrote the file in the same time step, size and times unchanged", async () => {
const { file, read, historyRoot, opts, later } = project();
const { release } = holdFiling(Buffer.from("// before\n"));
const listed = await realStat(file("parts/p1.js"));
const history = await open(opts);
const entry = await step(history, () => {
writeFileSync(file("parts/p1.js"), "// BEFORE\n");
writeFileSync(file("index.html"), "<html>agent</html>");
}, [file("parts/p1.js"), file("index.html")]);
// A drive with coarse times reports the rewrite with the stat it listed at the open.
vi.mocked(fsp.stat).mockImplementation(async (...args: Parameters<typeof realStat>) =>
String(args[0]) === file("parts/p1.js") ? listed : realStat(...args),
);
later();
release();
await landed(historyRoot);
await expect(history.undo(entry.id, { who: agent })).rejects.toThrow(NOT_KEPT);
expect(read("index.html")).toBe("<html>agent</html>");
expect(read("parts/p1.js")).toBe("// BEFORE\n");
});
it("keeps an original read before the step, though filing it waited until after", async () => {
const { file, read, historyRoot, opts } = project();
const { release } = holdFiling(Buffer.from("// before\n"));
const history = await open(opts);
const entry = await step(history, () => {
writeFileSync(file("parts/p1.js"), "// agent\n");
writeFileSync(file("index.html"), "<html>agent</html>");
}, [file("parts/p1.js"), file("index.html")]);
release();
await landed(historyRoot);
expect(history.peek(START)!["parts/p1.js"]).toBe(sha256("// before\n"));
await expect(history.undo(entry.id, { who: agent })).rejects.toThrow(NOT_KEPT);
expect(read("index.html")).toBe("<html>agent</html>");
// The original is known, so restoring the start brings every file back.
await history.restore(START, agent);
expect(read("parts/p1.js")).toBe("// before\n");
expect(read("index.html")).toBe("<html>before</html>");
});
it("refuses its undo when the file's first reads kept changing until the step rewrote it", async () => {
const { file, read, historyRoot, opts } = project();
let saving = true;
vi.mocked(fsp.open).mockImplementation(async (...args: Parameters<typeof realOpen>) => {
const handle = await realOpen(...args);
if (String(args[0]) !== file("parts/p1.js") || !saving) return handle;
const readFile = handle.readFile.bind(handle);
handle.readFile = (async (...options: Parameters<typeof readFile>) => {
const bytes = await readFile(...options);
if (saving) appendFileSync(file("parts/p1.js"), "// saved while read\n");
return bytes;
}) as typeof handle.readFile;
return handle;
});
const history = await open(opts);
const window = await history.beginWindow(agent, "Step");
saving = false;
writeFileSync(file("parts/p1.js"), "// agent\n");
writeFileSync(file("index.html"), "<html>agent</html>");
history.noteChange(file("parts/p1.js"));
history.noteChange(file("index.html"));
const entry = (await window.close())!;
await landed(historyRoot);
expect(history.peek(START)!["parts/p1.js"]).not.toBe(sha256("// agent\n"));
await expect(history.restore(START, agent)).rejects.toThrow(NOT_KEPT);
await expect(history.undo(entry.id, { who: agent })).rejects.toThrow(NOT_KEPT);
expect(read("index.html")).toBe("<html>agent</html>");
});
it("refuses the whole undo in a history read by an app that ignores the list", async () => {
const { file, read, historyRoot, opts } = project();
const release = stallRead(file("parts/p1.js"));
let history = await open(opts);
const entry = await step(history, () => {
writeFileSync(file("parts/p1.js"), "// agent\n");
writeFileSync(file("index.html"), "<html>agent</html>");
}, [file("parts/p1.js"), file("index.html")]);
release();
await landed(historyRoot);
await history.close();
const logFile = join(homeIn(historyRoot), "log.jsonl");
const lines = readFileSync(logFile, "utf8").split("\n").filter(Boolean);
const older = lines.map((line) => {
const record = JSON.parse(line);
if (record.type === "entry") delete record.entry.wentAheadOf;
return JSON.stringify(record);
});
writeFileSync(logFile, `${older.join("\n")}\n`);
history = await open(opts);
for (const mode of [undefined, "back-to-before"] as const) {
const result = await history.undo(entry.id, { who: agent, mode }).catch((error) => error);
expect(result).not.toMatchObject({ ok: true });
}
expect(read("index.html")).toBe("<html>agent</html>");
expect(read("parts/p1.js")).toBe("// agent\n");
// Accepted: "Keep later edits" there counts the pending file as changed later, so it stays as the agent left it.
await history.undo(entry.id, { who: agent, mode: "keep-later-edits" });
expect(read("index.html")).toBe("<html>before</html>");
expect(read("parts/p1.js")).toBe("// agent\n");
});
it("names a file a step went ahead of at every earlier point, for an app that ignores the lists", async () => {
const { dir, file, read, historyRoot, opts } = project();
await stepThenDie(dir, historyRoot, file("parts/p1.js"), "earlier");
const home = homeIn(historyRoot);
const logFile = join(home, "log.jsonl");
const lines = readFileSync(logFile, "utf8").split("\n").filter(Boolean);
const older = lines.map((line) => {
const record = JSON.parse(line);
if (record.type === "entry") delete record.entry.wentAheadOf;
return JSON.stringify(record);
});
writeFileSync(logFile, `${older.join("\n")}\n`);
for (const list of ["went-ahead.json", "adopting.json"])
rmSync(join(home, list), { force: true });
const history = await open(opts);
const first = history.list().find((item) => item.label === "First")!;
const after = history.list().find((item) => item.label === "Step")!;
const result = await history
.undo(after.id, { who: agent, mode: "back-to-before" })
.catch((error) => error);
expect(result).not.toMatchObject({ ok: true });
expect(first).toBeDefined();
expect(read("parts/p1.js")).toBe("// agent\n");
});
for (const twice of [false, true])
it(`keeps the refusal for a step recovered after the process died while it was open${twice ? ", twice" : ""}`, async () => {
const { dir, file, read, historyRoot, opts } = project();
const id = await stepThenDie(dir, historyRoot, file("parts/p1.js"), "open");
const closedWindow = {
id,
who: agent,
label: "Step",
startedAt: 1,
lastWriteAt: Date.now(),
idleMs: 600_000,
};
if (twice)
await stepThenDie(
dir,
historyRoot,
file("parts/p1.js"),
"reopen",
JSON.stringify(closedWindow),
);
const release = stallRead(file("parts/p1.js"));
const history = await open({ ...opts, closedWindow });
// A Studio claim commits the recovered step's writes so far before the copy lands.
writeFileSync(file("notes.txt"), "person");
await history.claim(you, "Note", ["notes.txt"]);
release();
await landed(historyRoot);
const parts = history.list().filter((item) => item.label === "Step");
expect(parts.flatMap((part) => part.files.map((change) => change.path))).toContain(
"index.html",
);
// The first undo commits what the open step wrote since; the refusals change nothing after that.
await history.undo(parts[0]!.id, { who: agent }).catch(() => undefined);
const cursor = history.next("back", agent)?.id;
const listed = history.list();
for (const part of parts)
await expect(history.undo(part.id, { who: agent })).rejects.toThrow(NOT_KEPT);
expect(history.next("back", agent)?.id).toBe(cursor);
expect(history.list()).toEqual(listed);
expect(read("index.html")).toBe("<html>agent</html>");
expect(read("parts/p1.js")).toBe("// agent\n");
});
it("keeps every pending file on the list through a crash during the reopen's rewrite of it", async () => {
const { dir, file, historyRoot, opts } = project();
writeFileSync(file("parts/p2.js"), "// before 2\n");
const stuck = [file("parts/p1.js"), file("parts/p2.js")].join(",");
await stepThenDie(dir, historyRoot, stuck, "close");
await stepThenDie(dir, historyRoot, stuck, "reopen-list");
const list = JSON.parse(readFileSync(join(homeIn(historyRoot), "went-ahead.json"), "utf8"));
expect([...list.pending].sort()).toEqual(["parts/p1.js", "parts/p2.js"]);
const history = await open(opts);
await landed(historyRoot);
for (const path of ["parts/p1.js", "parts/p2.js"])
expect(history.peek(START)![path]).not.toBe(sha256("// agent\n"));
});
it("refuses its whole undo when the step deleted the pending file", async () => {
const { file, read, historyRoot, opts } = project();
const release = stallRead(file("parts/p1.js"));
const history = await open(opts);
const entry = await step(history, () => {
unlinkSync(file("parts/p1.js"));
writeFileSync(file("index.html"), "<html>agent</html>");
}, [file("parts/p1.js"), file("index.html")]);
release();
await landed(historyRoot);
await expect(history.undo(entry.id, { who: agent })).rejects.toThrow(NOT_KEPT);
await expect(history.restore(START, agent)).rejects.toThrow(NOT_KEPT);
expect(read("index.html")).toBe("<html>agent</html>");
expect(existsSync(file("parts/p1.js"))).toBe(false);
});
it("refuses the undo of each step that began while it was pending, not just the last", async () => {
const { file, read, historyRoot, opts } = project();
const release = stallRead(file("parts/p1.js"));
const history = await open(opts);
const first = await step(history, () => {
writeFileSync(file("parts/p1.js"), "// agent\n");
writeFileSync(file("index.html"), "<html>agent</html>");
}, [file("parts/p1.js"), file("index.html")]);
const look = await history.beginWindow(agent, "Look");
const second = (await look.close())!;
for (const id of [first.id, second.id])
await expect(history.undo(id, { who: agent })).rejects.toThrow(STILL_SAVING);
release();
await landed(historyRoot);
for (const id of [first.id, second.id])
await expect(history.undo(id, { who: agent })).rejects.toThrow(NOT_KEPT);
expect(read("index.html")).toBe("<html>agent</html>");
expect(read("parts/p1.js")).toBe("// agent\n");
});
it("never gives a closed step a person's later edit of the pending file", async () => {
const { file, read, historyRoot, opts } = project();
const release = stallRead(file("parts/p1.js"));
const history = await open(opts);
const entry = await step(
history,
() => writeFileSync(file("index.html"), "<html>agent</html>"),
[file("index.html")],
);
// Studio saves the pending file through its API, which reports the bytes it replaced.
writeFileSync(file("parts/p1.js"), "// person\n");
recordFileWriteReceipt(file("parts/p1.js"), {
path: "parts/p1.js",
version: fileContentVersion("// person\n"),
writeToken: "studio",
overwrote: "// before\n",
});
const claimed = history.claim(you, "Edit", ["parts/p1.js"]);
release();
expect(await claimed).toMatchObject({ id: expect.any(String) });
await landed(historyRoot);
await history.undo(entry.id, { who: agent }).catch(() => undefined);
expect(read("parts/p1.js")).toBe("// person\n");
expect(history.list().find((item) => item.id === entry.id)).toBeDefined();
const log = readLog(join(homeIn(historyRoot), "log.jsonl"), () => {});
const agentEntry = log!.entries.find((logged) => logged.id === entry.id)!;
const recorded = agentEntry.files.filter((change) => change.before !== change.after);
expect(recorded.map((change) => change.path)).toEqual(["index.html"]);
});
for (const [readBefore, saved] of [
[false, "// person\n"],
[true, "// person\n"],
[true, "// before\n"],
] as const)
it(`never takes the agent's bytes as the start from a later Studio save's receipt (read ${readBefore ? "before" : "after"} the step, saved ${JSON.stringify(saved)})`, async () => {
const { file, read, historyRoot, opts } = project();
const release = readBefore
? holdFiling(Buffer.from("// before\n")).release
: stallRead(file("parts/p1.js"));
const history = await open(opts);
await step(history, () => writeFileSync(file("parts/p1.js"), "// agent\n"), [
file("parts/p1.js"),
]);
writeFileSync(file("parts/p1.js"), saved);
recordFileWriteReceipt(file("parts/p1.js"), {
path: "parts/p1.js",
version: fileContentVersion(saved),
writeToken: "studio",
overwrote: "// agent\n",
});
const claimed = history.claim(you, "Edit", ["parts/p1.js"]);
release();
await claimed;
await landed(historyRoot);
const start = history.peek(START)!["parts/p1.js"];
if (readBefore) expect(start).toBe(sha256("// before\n"));
else {
expect(start).not.toBe(sha256("// agent\n"));
await expect(history.restore(START, agent)).rejects.toThrow(NOT_KEPT);
}
expect(read("parts/p1.js")).toBe(saved);
});
it("keeps the original from a Studio save's receipt heard before the first read, filed after a step", async () => {
const { file, read, historyRoot, opts } = project();
const { release } = holdFiling(Buffer.from("// saved\n"));
const reading = stallRead(file("parts/p1.js"));
const history = await open(opts);
writeFileSync(file("parts/p1.js"), "// saved\n");
recordFileWriteReceipt(file("parts/p1.js"), {
path: "parts/p1.js",
version: fileContentVersion("// saved\n"),
writeToken: "studio",
overwrote: "// before\n",
});
const claimed = history.claim(you, "Edit", ["parts/p1.js"]);
reading();
await step(history, () => writeFileSync(file("index.html"), "<html>agent</html>"), [
file("index.html"),
]);
await claimed;
release();
await landed(historyRoot);
expect(history.peek(START)!["parts/p1.js"]).toBe(sha256("// before\n"));
expect(read("parts/p1.js")).toBe("// saved\n");
});
it("keeps the original as the start when a save writes it back over a later change, with no step", async () => {
const { file, historyRoot, opts } = project();
const { release, reached } = holdFiling(Buffer.from("// before\n"));
const history = await open(opts);
await reached;
writeFileSync(file("parts/p1.js"), "// B\n");
writeFileSync(file("parts/p1.js"), "// before\n");
recordFileWriteReceipt(file("parts/p1.js"), {
path: "parts/p1.js",
version: fileContentVersion("// before\n"),
writeToken: "studio",
overwrote: "// B\n",
});
release();
await landed(historyRoot);
expect(history.peek(START)!["parts/p1.js"]).toBe(sha256("// before\n"));
});
it("keeps a copy read before a step as the start, though its file closed after the step began", async () => {
const { file, historyRoot, opts } = project();
let releaseClose = () => {};
const closeHeld = new Promise<void>((resolve) => (releaseClose = resolve));
closes.push(async () => releaseClose());
let held = false;
vi.mocked(fsp.open).mockImplementation(async (...args: Parameters<typeof realOpen>) => {
const handle = await realOpen(...args);
if (String(args[0]) !== file("parts/p1.js") || held) return handle;
held = true;
const close = handle.close.bind(handle);
handle.close = async () => {
await closeHeld;
return close();
};
return handle;
});
const history = await open(opts);
await step(history, () => writeFileSync(file("parts/p1.js"), "// agent\n"), [
file("parts/p1.js"),
]);
releaseClose();
await landed(historyRoot);
expect(history.peek(START)!["parts/p1.js"]).toBe(sha256("// before\n"));
});
it("keeps the original an early save's receipt names through a prune before the copy is filed", async () => {
const { file, historyRoot, opts } = project();
const reading = stallRead(file("parts/p1.js"));
const { release, reached } = holdFiling(Buffer.from("// B\n"));
// The claim's prune and fold leave only what history still needs.
const history = await open({ ...opts, budgetBytes: 16, quietMs: 30 });
const receipt = (bytes: string, overwrote: string) =>
recordFileWriteReceipt(file("parts/p1.js"), {
path: "parts/p1.js",
version: fileContentVersion(bytes),
writeToken: "studio",
overwrote,
});
writeFileSync(file("parts/p1.js"), "// B\n");
receipt("// B\n", "// before\n");
reading();
await reached;
// A later receipt that starts a new chain: the live receipts no longer name the original.
receipt("// C\n", "// unrelated\n");
writeFileSync(file("index.html"), "<html>person</html>");
await history.claim(you, "Edit", ["index.html"]);
release();
await landed(historyRoot);
expect(history.peek(START)!["parts/p1.js"]).toBe(sha256("// before\n"));
});
it("keeps undo history whole while an early save's original waits for its file's first copy", async () => {
const { file, historyRoot, opts } = project();
const original = `// before\n${"x".repeat(90)}\n`;
writeFileSync(file("parts/p1.js"), original);
const reading = stallRead(file("parts/p1.js"));
const { release, reached } = holdFiling(Buffer.from("// B\n"));
const history = await open({ ...opts, budgetBytes: 128, quietMs: 30 });
writeFileSync(file("parts/p1.js"), "// B\n");
recordFileWriteReceipt(file("parts/p1.js"), {
path: "parts/p1.js",
version: fileContentVersion("// B\n"),
writeToken: "studio",
overwrote: original,
});
reading();
await reached;
for (const label of ["One", "Two"]) {
writeFileSync(file("index.html"), `<html>${label}</html>`);
await history.claim(you, label, ["index.html"]);
}
expect(history.list().map((entry) => entry.label)).toEqual(
expect.arrayContaining(["One", "Two"]),
);
release();
await landed(historyRoot);
expect(history.peek(START)!["parts/p1.js"]).toBe(sha256(original));
});
it("answers a Studio claim on the pending file within the deadline", async () => {
const { file, opts } = project();
stallRead(file("parts/p1.js"));
const history = await open(opts);
writeFileSync(file("parts/p1.js"), "// person\n");
const answered = history.claim(you, "Edit", ["parts/p1.js"]);
const waited = new Promise((late) => setTimeout(() => late("still waiting"), 3000));
const claimed = await Promise.race([answered, waited]);
expect(claimed).toMatchObject({ id: expect.any(String) });
await expect(history.undo((claimed as { id: string }).id, { who: you })).rejects.toThrow(
STILL_SAVING,
);
await expect(history.restore(START, agent)).rejects.toThrow(STILL_SAVING);
});
for (const [mode, written] of [
["close", "// agent\n"],
["open", "// agent\n"],
["delete", null],
] as const)
it(`keeps the start out of reach for a file its step went ahead of before a restart (${mode})`, async () => {
const { dir, file, read, historyRoot } = project();
await stepThenDie(dir, historyRoot, file("parts/p1.js"), mode);
const history = await open({ projectDir: dir, historyRoot });
await landed(historyRoot);
const start = history.peek(START)!["parts/p1.js"]!;
expect(start).toBeDefined();
expect(start).not.toBe(sha256("// agent\n"));
expect(() => blobPath(historyRoot, start)).not.toThrow();
await expect(history.restore(START, agent)).rejects.toThrow(NOT_KEPT);
expect(written === null ? existsSync(file("parts/p1.js")) : read("parts/p1.js")).toBe(
written ?? false,
);
const stepEntry = history.list().find((item) => item.label === "Step");
if (stepEntry)
await expect(history.undo(stepEntry.id, { who: agent })).rejects.toThrow(NOT_KEPT);
});
it("refuses the undo of every part a Studio claim splits from the step", async () => {
const { file, read, historyRoot, opts } = project();
const release = stallRead(file("parts/p1.js"));
const history = await open(opts);
const window = await history.beginWindow(agent, "Step");
writeFileSync(file("parts/p1.js"), "// agent\n");
writeFileSync(file("index.html"), "<html>agent</html>");
history.noteChange(file("parts/p1.js"));
history.noteChange(file("index.html"));
writeFileSync(file("notes.txt"), "person");
// A claim scans first, so the step's writes so far become their own part.
await history.claim(you, "Note", ["notes.txt"]);
writeFileSync(file("index.html"), "<html>agent 2</html>");
history.noteChange(file("index.html"));
await window.close();
release();
await landed(historyRoot);
const parts = history.list().filter((item) => item.label === "Step");
expect(parts).toHaveLength(2);
for (const part of parts)
await expect(history.undo(part.id, { who: agent })).rejects.toThrow(NOT_KEPT);
expect(read("index.html")).toBe("<html>agent 2</html>");
});
});
@@ -9,7 +9,7 @@ import {
} from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { afterEach, describe, expect, it } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import { openProjectHistory, type ProjectHistory } from "./projectHistory.js";
import {
recordRenderSuccess,
@@ -80,8 +80,7 @@ describe("video state", () => {
const window = await f.history.beginWindow(person, "Pending");
writeFileSync(join(f.projectDir, "index.html"), "pending");
f.history.noteChange("index.html");
await new Promise((r) => setTimeout(r, 80));
expect(read(f.projectDir).pendingChanges).toBe(true);
await vi.waitFor(() => expect(read(f.projectDir).pendingChanges).toBe(true));
expect(read(f.projectDir).currentRevision).toBe(first);
await window.close();
const second = read(f.projectDir).currentRevision!;
+1 -1
View File
@@ -57,6 +57,6 @@
},
"@hyperframes/studio-server": {
"packed": 201161,
"unpacked": 732018
"unpacked": 779727
}
}