Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix: keep failed routine progress writes pending for flush
Afloat395260f7dc81
diff --git a/server/routine-progress-save.test.ts b/server/routine-progress-save.test.tsnew file mode 100644index 0000000000..4292727aee--- /dev/null+++ b/server/routine-progress-save.test.ts@@ -0,0 +1,62 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, expect, it, vi } from "vitest";++import { RunProgressSave } from "./routine-progress-save.ts";++let directory: string;+beforeEach(() => {+ directory = mkdtempSync(join(tmpdir(), "omb-progress-save-"));+ vi.useFakeTimers();+});+afterEach(() => {+ vi.restoreAllMocks();+ vi.useRealTimers();+ rmSync(directory, { recursive: true, force: true });+});++it("retries a failed timed save when shutdown flushes pending progress", () => {+ vi.spyOn(console, "error").mockImplementation(() => {});+ const write = vi.fn().mockImplementationOnce(() => { throw new Error("disk unavailable"); });+ const progress = new RunProgressSave(() => join(directory, "routines.json"), write, 100);+ progress.soon();+ vi.advanceTimersByTime(100);+ expect(write).toHaveBeenCalledTimes(1);+ progress.flush();+ expect(write).toHaveBeenCalledTimes(2);+ progress.flush();+ expect(write).toHaveBeenCalledTimes(2);+});++it("keeps a failed flush pending for a later stop or backup", () => {+ const write = vi.fn().mockImplementationOnce(() => { throw new Error("disk unavailable"); });+ const progress = new RunProgressSave(() => join(directory, "routines.json"), write, 100);+ progress.soon();+ expect(() => progress.flush()).toThrow("disk unavailable");+ progress.flush();+ expect(write).toHaveBeenCalledTimes(2);+ vi.advanceTimersByTime(100);+ expect(write).toHaveBeenCalledTimes(2);+});++it("a successful whole-file save clears progress pending after a failed write", () => {+ vi.spyOn(console, "error").mockImplementation(() => {});+ const write = vi.fn(() => { throw new Error("disk unavailable"); });+ const progress = new RunProgressSave(() => join(directory, "routines.json"), write, 100);+ progress.soon();+ vi.advanceTimersByTime(100);+ progress.written();+ expect(() => progress.flush()).not.toThrow();+ expect(write).toHaveBeenCalledTimes(1);+});++it("a removed progress directory is not recreated by a later flush", () => {+ const write = vi.fn();+ const progress = new RunProgressSave(() => join(directory, "routines.json"), write, 100);+ progress.soon();+ rmSync(directory, { recursive: true });+ vi.advanceTimersByTime(100);+ progress.flush();+ expect(write).not.toHaveBeenCalled();+});diff --git a/server/routine-progress-save.ts b/server/routine-progress-save.tsindex 7cbe37b63e..93e51c5856 100644--- a/server/routine-progress-save.ts+++ b/server/routine-progress-save.ts@@ -10,6 +10,7 @@ export const RUN_PROGRESS_WINDOW_MS = 5_000;export class RunProgressSave {private timer: ReturnType<typeof setTimeout> | undefined;+ private pending = false;private immediate = false;private readonly file: () => string;private readonly write: () => void;@@ -23,27 +24,32 @@ export class RunProgressSave {/** Saves within the window; a later change in the same window rides along and never pushes the save back. */soon(): void {+ this.pending = true;if (this.immediate) return this.writeLogged();if (this.timer) return;this.timer = setTimeout(() => {this.timer = undefined;// A folder removed meanwhile (a test's, a wiped data folder) stays removed: progress never recreates it.if (existsSync(dirname(this.file()))) this.writeLogged();+ else this.written();}, this.windowMs);this.timer.unref?.();}/** A whole-file save just ran, so nothing is waiting any more. */written(): void {+ this.pending = false;clearTimeout(this.timer);this.timer = undefined;}/** Writes what is waiting now, if anything is. */flush(): void {- if (!this.timer) return;- this.written();+ if (!this.pending) return;+ clearTimeout(this.timer);+ this.timer = undefined;this.write();+ this.written();}/** From shutdown on, progress is saved as it happens, as no later window may come. */@@ -54,6 +60,7 @@ export class RunProgressSave {private writeLogged(): void {try {this.write();+ this.written();} catch (error) {// The progress stays in memory and the next save of the file writes it.console.error("routines: could not save run progress; the next save retries it", error);diff --git a/server/routines.ts b/server/routines.tsindex d20e885dff..35ca6d32bc 100644--- a/server/routines.ts+++ b/server/routines.ts@@ -1540,7 +1540,7 @@ export class RoutineManager {/** Lands at the end of the running save batch (server/save-batch.ts); what a caller rolls back on failure uses save. */private saveLater() { saveSoon(this, () => this.save()); }private save() {- this.progress.written(); if (this.unreadable) return;+ if (this.unreadable) { this.progress.written(); return; }// Evict only terminal receipts: an active one owns cancellation, timeout and event routing.let excess = this.runs.length - MAX_RUNS;for (let index = 0; index < this.runs.length && excess > 0;) {@@ -1563,5 +1563,6 @@ export class RoutineManager {...(this.ownerNotices.length ? { ownerNotices: this.ownerNotices } : {}),...(this.holds.length ? { holds: this.holds } : {}),} satisfies RoutineFile));+ this.progress.written();}}diff --git a/server/server-writes.test.ts b/server/server-writes.test.tsindex 1040bc3152..4bb775a278 100644--- a/server/server-writes.test.ts+++ b/server/server-writes.test.ts@@ -186,4 +186,25 @@ describe("routines.json saves", () => {deliver({ type: "item.completed", itemType: "assistant_text", text: "Nearly there." });expect(onDisk().output).toBe("Nearly there.");});++ it("retry failed progress writes before stopping for a backup or shutdown", async () => {+ const { manager, routine, onDisk, deliver } = setup();+ manager.runNow(routine.id);+ await manager.tick();+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ const error = vi.spyOn(console, "error").mockImplementation(() => {});+ try {+ deliver({ type: "item.completed", itemType: "assistant_text", text: "Keep this completed step." });+ vi.mocked(fs.renameSync).mockImplementationOnce(() => { throw Object.assign(new Error("disk full"), { code: "ENOSPC" }); });+ vi.advanceTimersByTime(RUN_PROGRESS_WINDOW_MS);+ expect(error).toHaveBeenCalled();+ expect(onDisk().output).toBeUndefined();+ manager.stop();+ expect(onDisk().output).toBe("Keep this completed step.");+ expect(vi.getTimerCount()).toBe(0);+ } finally {+ error.mockRestore();+ manager.close();+ }+ });});