The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.
JavaScript agent-skillsai-agentautomationbrowserbrowser-automationclaude-codecodexhermes-agentskillsskills-sh
fix(ego-browser): retry transient rename errors when writing page ledgers
Zhuowei Wang98040737ff44
diff --git a/package/ego-browser/src/page-ledger.test.mjs b/package/ego-browser/src/page-ledger.test.mjsindex 7dc7c5c..6e086a5 100644--- a/package/ego-browser/src/page-ledger.test.mjs+++ b/package/ego-browser/src/page-ledger.test.mjs@@ -11,7 +11,11 @@ import {import { tmpdir } from "node:os";import { join } from "node:path";-import { PageLedgerStore, runtimeInstanceId } from "../dist/src/page-ledger.js";+import {+ PageLedgerStore,+ renameWithRetry,+ runtimeInstanceId,+} from "../dist/src/page-ledger.js";test("runtimeInstanceId is a pure browser-host identifier", () => {const first = runtimeInstanceId(42);@@ -343,6 +347,133 @@ test("writes use a complete atomic ledger document", async () => {});});+function sharingViolation(code = "EPERM") {+ const error = new Error(`${code}: operation not permitted, rename`);+ error.code = code;+ return error;+}++test("renameWithRetry retries transient Windows sharing violations with backoff", async () => {+ const calls = [];+ const delays = [];+ let failures = 3;+ await renameWithRetry("from", "to", {+ rename: async (from, to) => {+ calls.push([from, to]);+ if (failures-- > 0)+ throw sharingViolation(["EPERM", "EACCES", "EBUSY"][failures]);+ },+ sleep: async (ms) => {+ delays.push(ms);+ },+ });++ assert.equal(calls.length, 4);+ assert.deepEqual(calls[0], ["from", "to"]);+ assert.deepEqual(delays, [20, 40, 80]);+});++test("renameWithRetry does not retry non-transient errors", async () => {+ let calls = 0;+ await assert.rejects(+ renameWithRetry("from", "to", {+ rename: async () => {+ calls += 1;+ throw sharingViolation("ENOENT");+ },+ sleep: async () => {+ assert.fail("must not sleep");+ },+ }),+ { code: "ENOENT" },+ );+ assert.equal(calls, 1);+});++test("renameWithRetry gives up after the attempt budget", async () => {+ let calls = 0;+ const delays = [];+ await assert.rejects(+ renameWithRetry("from", "to", {+ rename: async () => {+ calls += 1;+ throw sharingViolation();+ },+ sleep: async (ms) => {+ delays.push(ms);+ },+ attempts: 4,+ }),+ { code: "EPERM" },+ );+ assert.equal(calls, 5);+ assert.deepEqual(delays, [20, 40, 80, 160]);+});++test("renameWithRetry caps the delay between attempts", async () => {+ let failures = 6;+ const delays = [];+ await renameWithRetry("from", "to", {+ rename: async () => {+ if (failures-- > 0) throw sharingViolation();+ },+ sleep: async (ms) => {+ delays.push(ms);+ },+ });+ assert.deepEqual(delays, [20, 40, 80, 160, 250, 250]);+});++test("a ledger write survives a transient EPERM on the final rename", async () => {+ await withTempLedger(async (rootDir) => {+ const { rename } = await import("node:fs/promises");+ let failures = 2;+ let renames = 0;+ const store = new PageLedgerStore({+ rootDir,+ rename: {+ rename: async (from, to) => {+ renames += 1;+ if (failures-- > 0) throw sharingViolation();+ await rename(from, to);+ },+ sleep: async () => {},+ },+ });+ await store.addPage(5, "target-a");+ const page = await store.addPage(5, "target-b");++ assert.equal(page.label, "p2");+ // Two writes: the first needed three attempts, the second one.+ assert.equal(renames, 4);+ const parsed = JSON.parse(+ await readFile(join(rootDir, "space-5.json"), "utf8"),+ );+ assert.deepEqual(Object.keys(parsed.pages), ["p1", "p2"]);+ assert.deepEqual(+ (await readdir(rootDir)).filter((name) => name.endsWith(".tmp")),+ [],+ );+ });+});++test("a persistent EPERM on the final rename still surfaces and leaves no temporary file", async () => {+ await withTempLedger(async (rootDir) => {+ const store = new PageLedgerStore({+ rootDir,+ rename: {+ rename: async () => {+ throw sharingViolation();+ },+ sleep: async () => {},+ attempts: 2,+ },+ });+ await assert.rejects(store.addPage(5, "target-a"), { code: "EPERM" });+ assert.deepEqual(await readdir(rootDir), []);+ });+});+test("old ledger metadata is accepted and removed on the next write", async () => {await withTempLedger(async (rootDir) => {const path = join(rootDir, "space-12.json");diff --git a/package/ego-browser/src/page-ledger.ts b/package/ego-browser/src/page-ledger.tsindex ff31cc5..9659479 100644--- a/package/ego-browser/src/page-ledger.ts+++ b/package/ego-browser/src/page-ledger.ts@@ -10,6 +10,7 @@ import {} from "node:fs/promises";import { homedir } from "node:os";import { join } from "node:path";+import { setTimeout as sleep } from "node:timers/promises";import {validatePageRefState,type PageRefState,@@ -44,10 +45,57 @@ type PageLedgerStoreOptions = {browserInstanceId?: string | (() => string | Promise<string>);staleAfterMs?: number;now?: () => number;+ /** Test seam for the final rename of an atomic ledger write. */+ rename?: RenameWithRetryOptions;};const DEFAULT_STALE_AFTER_MS = 30 * 24 * 60 * 60 * 1000;+/**+ * Windows reports a sharing violation as EPERM/EACCES/EBUSY when a rename+ * replaces a file that another handle (an antivirus scan, the search indexer,+ * a concurrent reader) still holds open. The condition clears within+ * milliseconds, so the replacement is retried briefly instead of aborting+ * the caller's script.+ */+const RETRYABLE_RENAME_CODES = new Set(["EPERM", "EACCES", "EBUSY"]);+const RENAME_RETRY_ATTEMPTS = 10;+const RENAME_RETRY_BASE_MS = 20;+const RENAME_RETRY_MAX_MS = 250;++type RenameWithRetryOptions = {+ rename?: (from: string, to: string) => Promise<void>;+ sleep?: (ms: number) => Promise<unknown>;+ attempts?: number;+};++/** Rename over an existing file, retrying transient sharing violations. */+export async function renameWithRetry(+ from: string,+ to: string,+ options: RenameWithRetryOptions = {},+): Promise<void> {+ const doRename = options.rename || rename;+ const wait = options.sleep || sleep;+ const attempts = options.attempts ?? RENAME_RETRY_ATTEMPTS;+ for (let attempt = 0; ; attempt++) {+ try {+ await doRename(from, to);+ return;+ } catch (error) {+ if (+ !RETRYABLE_RENAME_CODES.has((error as { code?: string })?.code ?? "") ||+ attempt >= attempts+ ) {+ throw error;+ }+ await wait(+ Math.min(RENAME_RETRY_BASE_MS * 2 ** attempt, RENAME_RETRY_MAX_MS),+ );+ }+ }+}+/** Stable across Agent rounds and Node-service restarts in one Ego Lite run. */export function runtimeInstanceId(parentPid = process.ppid): string {return `browser-host:${parentPid}`;@@ -76,6 +124,7 @@ export class PageLedgerStore {readonly #browserInstanceId?: string | (() => string | Promise<string>);readonly #staleAfterMs: number;readonly #now: () => number;+ readonly #renameOptions: RenameWithRetryOptions;#temporarySequence = 0;#resolvedBrowserInstanceId?: Promise<string | undefined>;#cleanup?: Promise<void>;@@ -91,6 +140,7 @@ export class PageLedgerStore {? DEFAULT_STALE_AFTER_MS: options.staleAfterMs;this.#now = options.now || Date.now;+ this.#renameOptions = options.rename || {};if (!Number.isFinite(this.#staleAfterMs) || this.#staleAfterMs < 0) {throw new TypeError("staleAfterMs must be a non-negative number");}@@ -460,7 +510,7 @@ export class PageLedgerStore {encoding: "utf8",mode: 0o600,});- await rename(temporary, path);+ await renameWithRetry(temporary, path, this.#renameOptions);} finally {await rm(temporary, { force: true }).catch(() => {});}