Skip to content

Write HTML. Render video. Built for agents.

fix(studio-server): time history idle limits on one clock so a slow machine cannot flip them (#4924)

Miguel Ángel9123628d947f
diff --git a/packages/cli/src/commands/history.test.ts b/packages/cli/src/commands/history.test.ts
index 4b0f5fa9e3..4cbcc500cf 100644
--- a/packages/cli/src/commands/history.test.ts
+++ b/packages/cli/src/commands/history.test.ts
@@ -7,6 +7,7 @@ import {
readFileSync,
renameSync,
rmSync,
+ utimesSync,
writeFileSync,
} from "node:fs";
import type { AddressInfo } from "node:net";
@@ -27,7 +28,9 @@ import { consumeCommandResult } from "../utils/commandResult.js";
import { historyDeps, withOwner } from "../utils/historyOwner.js";
import historyCommand from "./history.js";
-const pause = (ms: number) => new Promise((settle) => setTimeout(settle, ms));
+/** History's clock, a day ahead of the file system's, so each write is dated by the mtime it is stamped with. */
+const clock = { at: 0 };
+const advance = (ms: number) => void (clock.at += ms);
const tracked = vi.hoisted(() => [] as Array<{ action: string; via: string }>);
vi.mock("../telemetry/events.js", () => ({
@@ -52,7 +55,12 @@ function project() {
historyDeps.historyRoot = tempDir("hf-history-cli-root-");
historyDeps.findServer = async () => null;
historyDeps.turnIdleMs = 60_000;
- const write = (path: string, text: string) => writeFileSync(join(dir, path), text);
+ clock.at = Date.now() + 86_400_000;
+ historyDeps.now = () => clock.at;
+ const write = (path: string, text: string) => {
+ writeFileSync(join(dir, path), text);
+ utimesSync(join(dir, path), clock.at / 1000, clock.at / 1000);
+ };
const read = (path: string) => readFileSync(join(dir, path), "utf-8");
const files = () => [read("index.html"), read("notes.html")];
async function hf(...args: string[]) {
@@ -83,6 +91,7 @@ async function preview(dir: string) {
const history = await openProjectHistory({
projectDir: dir,
historyRoot: historyDeps.historyRoot,
+ now: () => historyDeps.now(),
quietMs: 20,
});
const adapter = {
@@ -145,7 +154,7 @@ describe.each(["direct", "preview"])("hyperframes history (%s)", (mode) => {
it("an agent's labelled turn, a person's edit after it: --since shows both, undo of the turn keeps the edit", async () => {
const { json, hf, turn, personWrites, files } = await setup();
- const startedAt = new Date(Date.now() - 1).toISOString();
+ const startedAt = new Date(clock.at - 1).toISOString();
await turn("claude", "Bigger title", "index.html", "A2");
await personWrites("notes.html", "N2");
@@ -173,7 +182,7 @@ describe.each(["direct", "preview"])("hyperframes history (%s)", (mode) => {
historyDeps.turnIdleMs = 300;
await hf("begin", "--who", "claude", "--label", "Retitle");
write("index.html", "A2");
- await pause(600);
+ advance(600);
await personWrites("notes.html", "N2");
const undo = await hf("undo", "--who", "claude");
@@ -295,7 +304,7 @@ describe("hyperframes history, one owner", () => {
who: { kind: "agent", name: "claude" },
label: "Retitle",
startedAt: 1,
- lastWriteAt: Date.now(),
+ lastWriteAt: clock.at,
};
writeFileSync(join(dir, ".hyperframes", "history-turn.json"), JSON.stringify(turn));
write("index.html", "A2");
@@ -336,12 +345,12 @@ describe("hyperframes history, one owner", () => {
historyDeps.turnIdleMs = 1000;
// Each write 600 ms after the one before, past 1000 ms in all.
await hf("begin", "--who", "claude", "--label", "Retitle");
- await pause(600);
+ advance(600);
write("index.html", "2");
await hf(); // a command mid-turn files the turn so far; the rest counts from index.html
- await pause(600);
+ advance(600);
write("notes.html", "2");
- await pause(600);
+ advance(600);
write("extra.html", "2");
await hf("end");
const entries = (await json()).entries.reverse();
@@ -360,7 +369,7 @@ describe("hyperframes history, one owner", () => {
await turn("claude", "Earlier", "notes.html", "N2");
await hf("begin", "--who", "claude", "--label", "Retitle");
// The only change lands past the idle limit (the person's edit over the agent's), so it is Outside.
- await pause(700);
+ advance(700);
write("index.html", "A2");
const refused = await hf("undo", "--who", "claude");
diff --git a/packages/cli/src/commands/history.ts b/packages/cli/src/commands/history.ts
index 3b88a4be8f..f8ccce3dc1 100644
--- a/packages/cli/src/commands/history.ts
+++ b/packages/cli/src/commands/history.ts
@@ -18,6 +18,7 @@ import { setCommandExitCode } from "../utils/commandResult.js";
import {
Refusal,
endTurn,
+ historyDeps,
lastTurnParts,
withOwner as withHistoryOwner,
writeTurn,
@@ -103,7 +104,7 @@ function since(entries: HistoryListItem[], ref: string, who: HistoryWho): Histor
}
function ago(at: number): string {
- const seconds = Math.max(0, Math.round((Date.now() - at) / 1000));
+ const seconds = Math.max(0, Math.round((historyDeps.now() - at) / 1000));
if (seconds < 60) return `${seconds}s ago`;
if (seconds < 3600) return `${Math.round(seconds / 60)}m ago`;
if (seconds < 86_400) return `${Math.round(seconds / 3600)}h ago`;
diff --git a/packages/cli/src/utils/historyOwner.ts b/packages/cli/src/utils/historyOwner.ts
index 341b4d96b8..e9204c81bf 100644
--- a/packages/cli/src/utils/historyOwner.ts
+++ b/packages/cli/src/utils/historyOwner.ts
@@ -49,6 +49,7 @@ export const historyDeps = {
findServer: (projectDir: string) => findPreviewServerForProject(projectDir),
/** A turn with no write for this long has ended, through a preview or not. */
turnIdleMs: MAX_WINDOW_IDLE_MS,
+ now: () => Date.now(),
};
/** A refusal is the caller's to fix: commands print its message, never a stack. */
@@ -140,7 +141,7 @@ function previewOwner(route: (path: string) => string): Owner {
pin: async (id, pinned) => void (await json("/pin", { entryId: id, pinned })),
begin: async (who, label) => {
const opened = await json("/window", { who, label, idleMs: historyDeps.turnIdleMs });
- return { id: opened.windowId, startedAt: opened.startedAt ?? Date.now() };
+ return { id: opened.windowId, startedAt: opened.startedAt ?? historyDeps.now() };
},
// A preview restarted since begin committed the window on its way down.
end: (id) =>
@@ -155,6 +156,7 @@ async function directOwner(projectDir: string, turn: Turn | null): Promise<Owner
const history = await openProjectHistory({
projectDir,
historyRoot: historyDeps.historyRoot,
+ now: () => historyDeps.now(),
pruneGoneProjectsBudgetMs: 1000,
// A turn begun through a preview that has since stopped is still the agent's, until its idle limit.
...(turn && {
@@ -177,7 +179,7 @@ async function directOwner(projectDir: string, turn: Turn | null): Promise<Owner
restore: (point, who) => history.restore(point, who),
pin: async (id, pinned) => history.pin(id, pinned),
// Opening filed every earlier write; the turn's own writes are filed to it when the next open passes it.
- begin: async () => ({ id: randomUUID(), startedAt: Date.now() }),
+ begin: async () => ({ id: randomUUID(), startedAt: historyDeps.now() }),
end: async (id) => history.list().find((entry) => entry.id === id) ?? null,
close: () => history.close(),
};
diff --git a/packages/studio-server/src/history/projectHistory.test.ts b/packages/studio-server/src/history/projectHistory.test.ts
index a6163e11c1..a5258345f4 100644
--- a/packages/studio-server/src/history/projectHistory.test.ts
+++ b/packages/studio-server/src/history/projectHistory.test.ts
@@ -2113,3 +2113,16 @@ describe("claim: a writer that records after writing", () => {
]);
});
});
+
+describe("idle windows", () => {
+ it("sleeps a window with an idle limit past Node's timer range instead of waking every millisecond", async () => {
+ const { history } = await project({ "index.html": "A" });
+ const timer = vi.spyOn(globalThis, "setTimeout");
+ const window = await history.beginWindow(agent, "Long turn", { idleMs: 30 * 86_400_000 });
+ const delays = timer.mock.calls.map(([, delay]) => delay ?? 0);
+ timer.mockRestore();
+ expect(Math.max(...delays)).toBeLessThanOrEqual(2 ** 31 - 1);
+ expect(Math.max(...delays)).toBeGreaterThan(86_400_000);
+ await window.close();
+ });
+});
diff --git a/packages/studio-server/src/history/projectHistory.ts b/packages/studio-server/src/history/projectHistory.ts
index d8cbafab47..efccf1e4b3 100644
--- a/packages/studio-server/src/history/projectHistory.ts
+++ b/packages/studio-server/src/history/projectHistory.ts
@@ -257,6 +257,8 @@ const blocks = (removed: string, added: string) =>
added.startsWith(`${removed}/`) || removed.startsWith(`${added}/`);
/** A window takes a write within idleMs of its last one; past that it has ended, even before its timer commits it. */
+const MAX_TIMER_MS = 2 ** 31 - 1;
+
const takesWrite = (window: Group, at: number) =>
window.idleMs === undefined || at - (window.lastWriteAt ?? at) <= window.idleMs;
@@ -440,7 +442,7 @@ class Engine {
}
async firstOpen(): Promise<void> {
- const sweptAt = Date.now();
+ const sweptAt = this.now();
for (const file of listProjectFiles(this.dir)) {
const hash = await this.storeIfPresent(file.path);
if (this.whereFolder() !== "here") throw this.replaced();
@@ -477,7 +479,7 @@ class Engine {
async sweep(): Promise<void> {
// A folder moved or removed was not emptied, and another project at its path is none of this history's.
if (this.whereFolder() !== "here") return;
- const sweptAt = Date.now();
+ const sweptAt = this.now();
const changedAt = (file: { mtimeMs: number; ctimeMs: number }) =>
Math.min(sweptAt, Math.max(file.mtimeMs, file.ctimeMs));
const seen = listProjectFiles(this.dir);
@@ -820,7 +822,7 @@ class Engine {
await this.settle();
const window = { ...this.newGroup(who, label), idleMs };
this.windows.push(window);
- this.touch(window, Date.now());
+ this.touch(window, this.now());
const close = () => this.queue(() => this.sweepAndEnd(window));
return { id: window.id, startedAt: window.startedAt, close };
});
@@ -829,11 +831,20 @@ class Engine {
/** A window with no write for its idleMs ends, so a close that never comes cannot hold every later write. */
touch(window: Group, at: number): void {
window.lastWriteAt = Math.max(window.lastWriteAt ?? at, at);
+ this.endWhenIdle(window, window.idleMs);
+ }
+
+ endWhenIdle(window: Group, delay: number | undefined): void {
clearTimeout(window.idleTimer);
- if (window.idleMs === undefined || !Number.isFinite(window.idleMs)) return;
+ if (window.idleMs === undefined || !Number.isFinite(window.idleMs) || delay === undefined)
+ return;
window.idleTimer = setTimeout(
- () => this.background(() => this.sweepAndEnd(window)),
- window.idleMs,
+ () => {
+ const left = window.idleMs! - (this.now() - (window.lastWriteAt ?? this.now()));
+ if (left > 0) this.endWhenIdle(window, left);
+ else this.background(() => this.sweepAndEnd(window));
+ },
+ Math.min(delay, MAX_TIMER_MS),
);
window.idleTimer.unref?.();
}