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 a snapshot whose capture straddles a document commit
Zhuowei Wangf7a12e3f1b4a
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjsindex 1905c86..e417043 100644--- a/package/ego-browser/src/page-model.test.mjs+++ b/package/ego-browser/src/page-model.test.mjs@@ -5899,9 +5899,10 @@ for (const mode of ["page", "same-process iframe", "OOPIF"]) {});}-test("a navigation during snapshot capture never publishes refs for a mixed document", async () => {+test("a navigation during snapshot capture is retried against the new document", async () => {await withFixture(async (fixture) => {let loaderId = "before";+ let captures = 0;const baseCdp = fixture.services.cdp;const task = taskForRound(fixture, "round-a", {async cdp(method, params, sessionId) {@@ -5910,7 +5911,53 @@ test("a navigation during snapshot capture never publishes refs for a mixed docureturn baseCdp(method, params, sessionId);},async snapshot() {+ captures += 1;+ // The commit lands while the first capture is in flight; the retry+ // sees the stable new document.loaderId = "after";+ return {+ content:+ captures === 1+ ? 'button "Old document" [ref=1]'+ : 'button "Save" [ref=1]',+ refs: [{ refId: 1, backendNodeId: 40 + captures }],+ };+ },+ });+ const page = await openTestPage(task, "https://example.test/first");+ const content = await page.snapshot();+ assert.equal(+ captures,+ 2,+ "the mixed capture is discarded and retried once",+ );+ assert.match(content, /Save.*\[ref=1\]/);+ assert.doesNotMatch(content, /Old document/);+ assert.equal(+ fixture.services.pageRefs.forTarget(page.targetId).get("1")+ ?.backendNodeId,+ 42,+ "only the stable capture publishes refs",+ );+ });+});++test("a page that keeps navigating during snapshot captures fails after bounded retries", async () => {+ await withFixture(async (fixture) => {+ let loaderId = 0;+ let captures = 0;+ const baseCdp = fixture.services.cdp;+ const task = taskForRound(fixture, "round-a", {+ async cdp(method, params, sessionId) {+ if (method === "Page.getFrameTree")+ return {+ frameTree: { frame: { id: "main", loaderId: `load-${loaderId}` } },+ };+ return baseCdp(method, params, sessionId);+ },+ async snapshot() {+ captures += 1;+ loaderId += 1;return {content: 'button "Save" [ref=1]',refs: [{ refId: 1, backendNodeId: 42 }],@@ -5918,15 +5965,19 @@ test("a navigation during snapshot capture never publishes refs for a mixed docu},});const page = await openTestPage(task, "https://example.test/first");- await assert.rejects(() => page.snapshot(), /Page changed during snapshot/);+ await assert.rejects(+ () => page.snapshot(),+ (error) => {+ assert.match(error.message, /Page changed during snapshot/);+ assert.equal(error.kind, "transient");+ return true;+ },+ );+ assert.equal(captures, 3, "one capture plus two retries");assert.equal(fixture.services.pageRefs.forTarget(page.targetId).get("1"),undefined,- );- assert.match(- await page.snapshot(),- /\[ref=1\]/,- "an explicit retry captures the stable new document",+ "a mixed capture never publishes refs",);});});diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.tsindex 5a3157e..875efd7 100644--- a/package/ego-browser/src/page-model.ts+++ b/package/ego-browser/src/page-model.ts@@ -635,6 +635,10 @@ const POPUP_POLL_SETTLE_MS = 50;// tracking (see ensureFrameSessions), so navigation keeps the settle that the// previous tab-list diff provided. Input actions do not need it.const NAVIGATION_FRAME_SETTLE_MS = 60;+// A snapshot whose capture straddles a document commit is retried against the+// new document. Two retries absorb the common "action, then snapshot" race+// without turning a page that keeps navigating into an unbounded loop.+const SNAPSHOT_DOCUMENT_CHANGE_RETRIES = 2;// A file chooser request can trail the input acknowledgement. When the page// reports that the action clicked a file input, wait for the chooser event// (it resolves the race early); when the page could not be asked, fall back@@ -1966,38 +1970,55 @@ class Page {}const { root: _root, ...snapshotOptions } = options;const snapshotScope = options.scope ?? "only_within_viewport";- const beforeDocuments = await this.#pageDocuments(page, sessionId);- const result = await this.#services.snapshot({- ...snapshotOptions,- ...(root === undefined ? {} : { root }),- scope: snapshotScope,- includeActionMarks: options.includeActionMarks ?? true,- includeStableLocator: options.includeStableLocator ?? true,- });- const iframeSessions =- Array.isArray(result?.refs) && result.refs.length > 0- ? await this.#frameSessions(page)- : new Map<string, string>();- await preparePageSnapshotResult(- this.#services,- sessionId,- iframeSessions,- result,- rootContext,- );- const documents = await this.#pageDocuments(page, sessionId);- for (const ref of result?.refs || []) {- const documentId = pageRefDocumentId(ref, documents);- if (- !documentId ||- documentId !== pageRefDocumentId(ref, beforeDocuments)- ) {+ const capture = async () => {+ const result = await this.#services.snapshot({+ ...snapshotOptions,+ ...(root === undefined ? {} : { root }),+ scope: snapshotScope,+ includeActionMarks: options.includeActionMarks ?? true,+ includeStableLocator: options.includeStableLocator ?? true,+ });+ const iframeSessions =+ Array.isArray(result?.refs) && result.refs.length > 0+ ? await this.#frameSessions(page)+ : new Map<string, string>();+ await preparePageSnapshotResult(+ this.#services,+ sessionId,+ iframeSessions,+ result,+ rootContext,+ );+ return result;+ };+ // An input action that triggers a navigation returns before the new+ // document commits, so the commit often lands inside the very next+ // snapshot. A capture that straddles a commit mixes two documents and is+ // discarded; the documents read after it are the baseline for the retry,+ // which captures the stable new document in the common case.+ let documents = await this.#pageDocuments(page, sessionId);+ let result: Awaited<ReturnType<typeof capture>>;+ for (let attempt = 0; ; attempt += 1) {+ const beforeDocuments = documents;+ result = await capture();+ documents = await this.#pageDocuments(page, sessionId);+ const changed = (result?.refs || []).some((ref) => {+ const documentId = pageRefDocumentId(ref, documents);+ return (+ !documentId ||+ documentId !== pageRefDocumentId(ref, beforeDocuments)+ );+ });+ if (!changed) break;+ if (attempt >= SNAPSHOT_DOCUMENT_CHANGE_RETRIES) {throw new ElementResolutionError("Page changed during snapshot; take a new snapshot","transient",);}- ref.documentId = documentId;+ }+ for (const ref of result?.refs || []) {+ ref.documentId = pageRefDocumentId(ref, documents);}await this.#loadRefs(page);this.#services.pageRefs.invalidateChangedDocuments(