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): preserve refs across page.evaluate calls
JackWang63d6848cb2b3
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-ref-identity.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-ref-identity.mjsindex 05ee30f..2b4679f 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-ref-identity.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-ref-identity.mjs@@ -44,7 +44,7 @@ export function pageRefPrepareRoundCase() {const task = await taskSpace(taskName);const page = await newPageAt(task, baseUrl + '/nav-target');await page.evaluate(() => {- document.body.innerHTML = '<button id="first" aria-label="First round action">First round action</button><button id="second" aria-label="Second round action">Second round action</button><input aria-label="Cell address"><output></output>';+ document.body.innerHTML = '<button id="first" aria-label="First round action">First round action</button><button id="second" aria-label="Second round action">Second round action</button><input aria-label="Cell address"><output></output><select aria-label="Sort homes"><option value="recommended">Recommended</option><option value="list_price_asc">Price (low to high)</option></select>';window.__refClicks = { first: 0, second: 0 };for (const id of ['first', 'second']) document.getElementById(id).onclick = () => window.__refClicks[id]++;document.querySelector('input').onkeydown = (event) => {@@ -65,7 +65,12 @@ export function pageRefPrepareRoundCase() {assert(published, 'the final snapshot publishes a ref for the second button');const input = initial.split('\n').find((line) => line.includes('Cell address')).match(/\[ref=(\d+)/);assert(input, 'the initial snapshot publishes the cell address input');- await writeFile(join(tempDir, 'page-ref-round.json'), JSON.stringify({ label: page.label, ref: '@' + published[1], inputRef: '@' + input[1] }));+ const sort = initial.split('\n').find((line) => line.includes('Sort homes')).match(/\[ref=(\d+)/);+ assert(sort, 'the initial snapshot publishes the sorting select');+ // Redfin reads available options after snapshot and consumes the ref in the next CLI invocation.+ const options = await page.evaluate(() => [...document.querySelector('select').options].map((option) => option.value));+ assert(options.includes('list_price_asc'), 'evaluate reads the available sort options');+ await writeFile(join(tempDir, 'page-ref-round.json'), JSON.stringify({ label: page.label, ref: '@' + published[1], inputRef: '@' + input[1], sortRef: '@' + sort[1] }));`;}@@ -76,6 +81,8 @@ export function pageRefResumeRoundCase() {const page = task.page(saved.label);try {await page.waitForTimeout(4_000);+ assertEqual((await page.selectOption(saved.sortRef, 'list_price_asc'))[0], 'list_price_asc', 'the first action after read-only evaluate reuses the original select ref');+ assertEqual(await page.evaluate(() => document.querySelector('select').value), 'list_price_asc', 'the original select receives the requested sort');await page.click(saved.ref);await page.fill(saved.inputRef, 'M2');await page.press(saved.inputRef, 'Enter');@@ -83,16 +90,21 @@ export function pageRefResumeRoundCase() {assertEqual(clicks.second, 1, 'the published subtree ref still clicks the second button in a new round');assertEqual(clicks.first, 0, 'restoring a ref never renumbers it to the first button');assertEqual(await page.evaluate(() => document.querySelector('output').textContent), 'M2', 'fill and press reuse the same input ref across rounds');- await assertRejects(() => page.click(saved.ref), 'Stale ref', 'evaluate still invalidates saved refs');+ await page.click(saved.ref);+ assertEqual(await page.evaluate(() => window.__refClicks.second), 2, 'read-only evaluate preserves the same ref within a round');await page.snapshot();- await page.click('loc=css:#first');+ await page.evaluate(() => document.getElementById('first').click());await assertRejectsAny(() => page.fill(saved.inputRef, 'wrong node', { timeout: 300 }), 'a replaced input cannot inherit its predecessor ref');assertEqual(await page.evaluate(() => document.querySelector('input').value), 'M2', 'the same-name replacement receives no input');+ await page.click(saved.ref);+ assertEqual(await page.evaluate(() => window.__refClicks.second), 3, 'evaluate replacing another node preserves the unchanged button ref');await page.snapshot();- await page.reload();- await assertRejects(() => page.click(saved.ref), 'Stale ref', 'navigation rejects refs from the previous document');+ const destination = baseUrl + '/nav-target?after-evaluate';+ await page.evaluate((url) => { location.href = url; }, destination);+ await page.waitForURL(destination);+ await assertRejects(() => page.click(saved.ref), 'Stale ref', 'evaluate navigation rejects refs from the previous document');} finally {await page.close();}diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjsindex acb3dfb..f7f8eb0 100644--- a/package/ego-browser/src/page-model.test.mjs+++ b/package/ego-browser/src/page-model.test.mjs@@ -2385,28 +2385,55 @@ test("a subtree snapshot inherits the root ref frame provenance", async () => {});});-test("Page evaluate makes prior snapshot refs stale until a new snapshot", async () => {- await withFixture(async (fixture) => {- const task = taskForRound(fixture, "round-a");- const page = await openTestPage(task, "https://example.test/iframe-host");- await page.snapshot({ scope: "full_page" });- await page.evaluate("document.body.replaceChildren()");- const snapshotsBefore = fixture.calls.filter(- ([kind]) => kind === "snapshot",- ).length;+for (const expression of ["document.title", () => document.title]) {+ test(`Page evaluate preserves snapshot refs for a read-only ${typeof expression}`, async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await openTestPage(task, "https://example.test/select");+ await page.snapshot({ scope: "full_page" });+ await page.evaluate(expression);- await assert.rejects(- () => page.click("@21"),- /Stale ref: @21; take a new snapshot/,+ assert.deepEqual(await page.selectOption("@21", "nl"), ["nl"]);+ assert.equal(+ fixture.calls.filter(([kind]) => kind === "snapshot").length,+ 1,+ "reading the Page must not require a new snapshot",+ );+ assert.equal(+ fixture.calls.find(([, method]) => method === "DOM.resolveNode")[2]+ .backendNodeId,+ 21,+ );+ });+ });+}++test("read-only evaluate preserves a published ref across Agent rounds", async () => {+ await withFixture(async (fixture) => {+ const page = await openTestPage(+ taskForRound(fixture, "round-a"),+ "https://example.test/select",);+ await page.snapshot();+ const inspected = taskForRound(fixture, "round-b", {+ pageRefs: new PageRefRegistry(),+ }).page(page.label);+ await inspected.evaluate("document.title");+ const restored = taskForRound(fixture, "round-c", {+ pageRefs: new PageRefRegistry(),+ }).page(page.label);++ assert.deepEqual(await restored.selectOption("@21", "nl"), ["nl"]);assert.equal(fixture.calls.filter(([kind]) => kind === "snapshot").length,- snapshotsBefore,- "a stale ref must not be silently remapped by an automatic snapshot",+ 1,+ "each round must reuse the original published mapping",+ );+ assert.equal(+ fixture.calls.find(([, method]) => method === "DOM.resolveNode")[2]+ .backendNodeId,+ 21,);-- await page.snapshot({ scope: "full_page" });- await page.click("@21");});});@@ -5251,14 +5278,14 @@ test("an unknown Page ref fails without guessing a mapping from a new snapshot",});});-test("ref invalidation survives a new Agent round", async () => {+test("raw CDP ref invalidation survives a new Agent round", async () => {await withFixture(async (fixture) => {const page = await openTestPage(taskForRound(fixture, "round-a"),"https://example.test/first",);await page.snapshot();- await page.evaluate("document.title");+ await page.cdp("Page.getFrameTree");const restored = taskForRound(fixture, "round-b", {pageRefs: new PageRefRegistry(),}).page(page.label);diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.tsindex 88292c4..90a30c3 100644--- a/package/ego-browser/src/page-model.ts+++ b/package/ego-browser/src/page-model.ts@@ -2476,38 +2476,34 @@ class Page {return this.#services.gate.withPage(page, async ({ sessionId }) => {if (activate) await this.#activate(page.targetId);try {- try {- return await evaluateInSession<T>(+ return await evaluateInSession<T>(+ this.#services,+ sessionId,+ expression,+ hasArgument,+ serializedArgument,+ PAGE_EVALUATE_TRANSPORT_TIMEOUT_MS,+ PAGE_EVALUATE_EXECUTION_TIMEOUT_MS,+ );+ } catch (error) {+ if (isEvaluationExecutionDeadlineError(error)) {+ throw evaluationExecutionDeadlineError(+ "page.evaluate",+ PAGE_EVALUATE_EXECUTION_TIMEOUT_MS,+ );+ }+ if (isRuntimeEvaluateTransportTimeout(error)) {+ throw await recoverPageEvaluationTimeout(this.#services,sessionId,- expression,- hasArgument,- serializedArgument,+ "page.evaluate",PAGE_EVALUATE_TRANSPORT_TIMEOUT_MS,- PAGE_EVALUATE_EXECUTION_TIMEOUT_MS,);- } catch (error) {- if (isEvaluationExecutionDeadlineError(error)) {- throw evaluationExecutionDeadlineError(- "page.evaluate",- PAGE_EVALUATE_EXECUTION_TIMEOUT_MS,- );- }- if (isRuntimeEvaluateTransportTimeout(error)) {- throw await recoverPageEvaluationTimeout(- this.#services,- sessionId,- "page.evaluate",- PAGE_EVALUATE_TRANSPORT_TIMEOUT_MS,- );- }- if (typeof expression === "function") {- throw enrichPageCallbackReferenceError(error, "page.evaluate");- }- throw error;}- } finally {- if (activate) await this.#invalidateRefs(page);+ if (typeof expression === "function") {+ throw enrichPageCallbackReferenceError(error, "page.evaluate");+ }+ throw error;}});}