mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-26 00:57:05 +00:00
fix(studio-server): a save asked to be recorded keeps its own undo step beside an import (#8585)
* fix(studio-server): a save asked to be recorded keeps its own undo step beside an import * fix(studio-server): a waiting save keeps its step past a failed entry or an open agent window
This commit is contained in:
@@ -48,6 +48,21 @@ const mediaCopy = vi.hoisted(() => ({
|
||||
copies: [] as string[],
|
||||
fails: null as ((copy: number) => boolean) | null,
|
||||
}));
|
||||
// A test can make the history log refuse its next entries, as a full disk does.
|
||||
const logWrites = vi.hoisted(() => ({ fails: 0 }));
|
||||
vi.mock("./historyLog", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("./historyLog")>();
|
||||
return {
|
||||
...real,
|
||||
saveRecord: ((...args) => {
|
||||
if (logWrites.fails > 0 && args[2].type === "entry") {
|
||||
logWrites.fails -= 1;
|
||||
throw new Error("The disk is full.");
|
||||
}
|
||||
return real.saveRecord(...args);
|
||||
}) satisfies typeof real.saveRecord,
|
||||
};
|
||||
});
|
||||
vi.mock("./blobStore", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("./blobStore")>();
|
||||
return {
|
||||
@@ -81,6 +96,7 @@ const cleanup: Array<() => unknown> = [];
|
||||
afterEach(async () => {
|
||||
for (const step of cleanup.splice(0).reverse()) await step();
|
||||
Object.assign(mediaCopy, { held: null, entered: null, stored: null, copies: [], fails: null });
|
||||
logWrites.fails = 0;
|
||||
});
|
||||
|
||||
const inside = (dir: string, path: string) => readFileSync(join(dir, path), "utf-8");
|
||||
@@ -1982,24 +1998,68 @@ describe("claim: a writer that records after writing", () => {
|
||||
utimesSync(file, new Date(Date.now() - 60_000), new Date(Date.now() - 60_000));
|
||||
|
||||
// fails without the fix: the import's claim logged the save as a change from outside, the save's own claim then
|
||||
// found nothing, and Cmd+Z took back the import instead of the edit.
|
||||
// found nothing, and Cmd+Z took back the import instead of the edit. Both files share one modified time, as two
|
||||
// writes a few milliseconds apart do on a file system with a coarse clock.
|
||||
it("a save made while an import is still taken in keeps its own step: Cmd+Z undoes the edit, the media stays", async () => {
|
||||
const { history, write, read, has, projectDir } = await project(
|
||||
{ "index.html": "<h1>Hello</h1>" },
|
||||
{ quietMs: 60_000 },
|
||||
);
|
||||
write("assets/logo.png", "png");
|
||||
backdate(join(projectDir, "assets/logo.png"));
|
||||
write("index.html", "<h1>Two</h1>");
|
||||
const at = new Date();
|
||||
for (const file of ["assets/logo.png", "index.html"])
|
||||
utimesSync(join(projectDir, file), at, at);
|
||||
await pendingOutside(history, "index.html");
|
||||
await history.claim(you, "Imported media", ["assets/logo.png"]);
|
||||
await history.claim(you, "Edited", ["index.html"]);
|
||||
await Promise.all([
|
||||
history.claim(you, "Imported media", ["assets/logo.png"]),
|
||||
history.claim(you, "Edited", ["index.html"]),
|
||||
]);
|
||||
expect(history.list().map((entry) => entry.label)).toEqual(["Imported media", "Edited"]);
|
||||
expect(await history.step("back", you)).toMatchObject({ ok: true });
|
||||
expect(read("index.html")).toBe("<h1>Hello</h1>");
|
||||
expect(has("assets/logo.png")).toBe(true);
|
||||
});
|
||||
|
||||
// fails without the fix: the import's failed entry took the waiting save's change with it; the save recorded nothing.
|
||||
it("a save waiting behind an import that fails to record still records its own step", async () => {
|
||||
const { history, write } = await project(
|
||||
{ "index.html": "<h1>Hello</h1>", "notes.md": "n" },
|
||||
{ quietMs: 60_000 },
|
||||
);
|
||||
write("notes.md", "agent notes");
|
||||
write("assets/logo.png", "png");
|
||||
write("index.html", "<h1>Two</h1>");
|
||||
await pendingOutside(history, "index.html");
|
||||
logWrites.fails = 1;
|
||||
const [imported, edited] = await Promise.allSettled([
|
||||
history.claim(you, "Imported media", ["assets/logo.png"]),
|
||||
history.claim(you, "Edited", ["index.html"]),
|
||||
]);
|
||||
expect(imported.status).toBe("rejected");
|
||||
expect(edited).toMatchObject({ status: "fulfilled", value: { id: expect.any(String) } });
|
||||
expect(history.list().map((entry) => entry.label)).toContain("Edited");
|
||||
});
|
||||
|
||||
// fails without the fix: the import cut the whole agent window into its entry, the save's change with it.
|
||||
it("a save caught inside an open agent window keeps its own step when an import's claim runs first", async () => {
|
||||
const { history, write, read } = await project(
|
||||
{ "index.html": "<h1>Hello</h1>" },
|
||||
{ quietMs: 60_000 },
|
||||
);
|
||||
const window = await history.beginWindow(agent, "Agent turn");
|
||||
write("assets/logo.png", "png");
|
||||
write("index.html", "<h1>Two</h1>");
|
||||
await Promise.all([
|
||||
history.claim(you, "Imported media", ["assets/logo.png"]),
|
||||
history.claim(you, "Edited", ["index.html"]),
|
||||
]);
|
||||
await window.close();
|
||||
expect(history.list().map((entry) => entry.label)).toEqual(["Imported media", "Edited"]);
|
||||
expect(await history.step("back", you)).toMatchObject({ ok: true });
|
||||
expect(read("index.html")).toBe("<h1>Hello</h1>");
|
||||
});
|
||||
|
||||
it("a change made before a claim's own files is still logged ahead of the claim", async () => {
|
||||
const { history, write, projectDir } = await project(
|
||||
{ "index.html": "v1" },
|
||||
|
||||
@@ -554,6 +554,7 @@ 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>();
|
||||
claimsAsked = new Map<string, number>();
|
||||
wentAhead = new Set<string>();
|
||||
wentAheadBeforeReopen = new Set<string>();
|
||||
reading = new Map<string, Promise<unknown>>();
|
||||
@@ -1256,7 +1257,7 @@ class Engine {
|
||||
if (!taken.length) return this.claimNothing(coalesceKey);
|
||||
const held = this.heldFor(coalesceKey, taken);
|
||||
if (!held) await this.commitClaim();
|
||||
await this.commitPendingWrittenBefore(taken);
|
||||
await this.commitPendingUnasked();
|
||||
const group = held ?? this.newGroup(who, label);
|
||||
for (const change of taken) addChange(group, change.path, change.before, change.after);
|
||||
this.markWentAhead(pending, group);
|
||||
@@ -1291,30 +1292,36 @@ class Engine {
|
||||
return null;
|
||||
}
|
||||
|
||||
async commitPendingWrittenBefore(taken: readonly HistoryFileChange[]): Promise<void> {
|
||||
const writtenAt = Math.max(
|
||||
...(await Promise.all(taken.map((change) => this.mtimeOf(change.path)))),
|
||||
async commitPendingUnasked(): Promise<void> {
|
||||
const asked = [...(this.outside?.changes.values() ?? [])].filter((change) =>
|
||||
this.claimsAsked.has(change.path),
|
||||
);
|
||||
const later: HistoryFileChange[] = [];
|
||||
if (Number.isFinite(writtenAt))
|
||||
for (const change of [...(this.outside?.changes.values() ?? [])])
|
||||
if ((await this.mtimeOf(change.path)) > writtenAt) later.push(change);
|
||||
for (const change of later) this.outside!.changes.delete(change.path);
|
||||
await this.commitPending();
|
||||
if (!later.length) return;
|
||||
const outside = this.outsideGroup();
|
||||
for (const change of later) outside.changes.set(change.path, change);
|
||||
for (const change of asked) this.outside!.changes.delete(change.path);
|
||||
try {
|
||||
await this.commitPending((path) => this.claimsAsked.has(path));
|
||||
} finally {
|
||||
if (asked.length) {
|
||||
const outside = this.outsideGroup();
|
||||
for (const change of asked) outside.changes.set(change.path, change);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async mtimeOf(path: string): Promise<number> {
|
||||
return (await stat(join(this.dir, path)).catch(() => null))?.mtimeMs ?? -Infinity;
|
||||
countAsked(paths: readonly string[], step: 1 | -1): void {
|
||||
for (const path of paths) {
|
||||
const left = (this.claimsAsked.get(path) ?? 0) + step;
|
||||
if (left > 0) this.claimsAsked.set(path, left);
|
||||
else this.claimsAsked.delete(path);
|
||||
}
|
||||
}
|
||||
|
||||
/** Commits every other writer's pending changes, oldest first; open windows stay open. */
|
||||
async commitPending(): Promise<void> {
|
||||
async commitPending(keep: (path: string) => boolean = () => false): Promise<void> {
|
||||
await this.commitOutside();
|
||||
for (const window of [...this.windows])
|
||||
if (window.changes.size) await this.commitCut(window, [...window.changes.keys()]);
|
||||
for (const window of [...this.windows]) {
|
||||
const cut = [...window.changes.keys()].filter((path) => !keep(path));
|
||||
if (cut.length) await this.commitCut(window, cut);
|
||||
}
|
||||
}
|
||||
|
||||
pendingElsewhere(): boolean {
|
||||
@@ -1995,17 +2002,28 @@ class Engine {
|
||||
unsavedBlobBytes: () => this.unsavedBlobBytes(),
|
||||
claim: async (who, label, paths, options = {}) => {
|
||||
const owed = (path: string) => this.adopting.get(this.logPath(path));
|
||||
await Promise.all(
|
||||
paths.map((path) =>
|
||||
orAfter(
|
||||
Promise.resolve(owed(path)?.retryNow()),
|
||||
this.firstCopyWaitMs(this.logPath(path)),
|
||||
undefined,
|
||||
const named = paths.map((path) => this.logPath(path));
|
||||
this.countAsked(named, 1);
|
||||
let queued = false;
|
||||
try {
|
||||
await Promise.all(
|
||||
paths.map((path) =>
|
||||
orAfter(
|
||||
Promise.resolve(owed(path)?.retryNow()),
|
||||
this.firstCopyWaitMs(this.logPath(path)),
|
||||
undefined,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const pending = paths.filter(owed).map((path) => this.logPath(path));
|
||||
return this.queue(() => this.claimNow(who, label, paths, options, pending));
|
||||
);
|
||||
const pending = paths.filter(owed).map((path) => this.logPath(path));
|
||||
queued = true;
|
||||
return this.queue(() => {
|
||||
this.countAsked(named, -1);
|
||||
return this.claimNow(who, label, paths, options, pending);
|
||||
});
|
||||
} finally {
|
||||
if (!queued) this.countAsked(named, -1);
|
||||
}
|
||||
},
|
||||
noteChange: (path) => {
|
||||
if (!this.closed) this.noteChange(path);
|
||||
|
||||
Reference in New Issue
Block a user