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
add page-scoped refs and offscreen actions
Aute2fc8eb0a712c
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjsindex 0d3683d..156bd53 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs@@ -2,11 +2,15 @@ export function pageLabelCreateCase() {return `const task = await taskSpace(taskName);await openOrReuseTab(baseUrl + "/?inventory=unknown", { wait: true, timeout: 10 });- const page = await task.newPage(baseUrl + "/secondary?managed=p1");+ const page = await task.newPage(baseUrl + "/?managed=p1");assertEqual(page.label, "p1", "first managed page receives p1");assertEqual(page.spaceId, task.id, "page carries its task-space id");assertEqual(typeof page.targetId, "string", "new page exposes its target id");- assertIncludes(await page.snapshot(), "Secondary tab", "p1 snapshot addresses the created page");+ const snapshot = await page.snapshot();+ assertIncludes(snapshot, "Helper e2e fixture", "p1 snapshot addresses the created page");+ const refLine = snapshot.split("\\n").find((line) => line.includes("Increment counter"));+ const refMatch = refLine && refLine.match(/\\[ref=([0-9]+)/);+ assert(refMatch, "snapshot exposes a ref for the cross-round action");const inventory = await task.listPages();const managed = inventory.find((item) => item.label === page.label);assertEqual(managed.page.targetId, page.targetId, "listPages returns the managed Page handle");@@ -17,7 +21,7 @@ export function pageLabelCreateCase() {);await writeFile(join(tempDir, "managed-page.json"),- JSON.stringify({ label: page.label, targetId: page.targetId })+ JSON.stringify({ label: page.label, targetId: page.targetId, ref: "@" + refMatch[1] }));`;}@@ -27,6 +31,12 @@ export function pageLabelRestoreCase() {const saved = JSON.parse(await readFile(join(tempDir, "managed-page.json"), "utf8"));const task = await taskSpace(taskName);const page = task.page(saved.label);+ await page.click(saved.ref);+ assertEqual(+ await page.evaluate("window.__fixtureState.clicks"),+ 1,+ "a ref printed in the previous process resolves in the restored Page"+ );const before = await listTabs();await page.goto(baseUrl + "/nav-target?managed=restored");const after = await listTabs();@@ -269,6 +279,25 @@ export function pageActionsAndPopupCase() {assertEqual(await source.fill("#text-input", "page-filled").then(() => source.evaluate("document.querySelector('#text-input').value")), "page-filled", "page.fill writes into the addressed page");assertEqual((await currentTab()).targetId, source.targetId, "page.fill activates and keeps its page current");+ await source.evaluate(() => {+ const spacer = document.createElement("div");+ spacer.style.height = "2200px";+ const button = document.createElement("button");+ button.id = "page-offscreen-button";+ button.textContent = "Offscreen trusted action";+ button.addEventListener("click", (event) => {+ window.__pageOffscreenClickTrusted = event.isTrusted;+ });+ document.body.append(spacer, button);+ });+ await source.click("#page-offscreen-button");+ const offscreenResult = await source.evaluate(() => ({+ trusted: window.__pageOffscreenClickTrusted,+ scrollY,+ }));+ assertEqual(offscreenResult.trusted, true, "offscreen Page click remains a trusted browser event");+ assert(offscreenResult.scrollY > 0, "Page click scrolls an offscreen element into view");+await source.evaluate((popupUrl) => {const link = document.createElement("a");link.id = "page-popup-link";diff --git a/package/ego-browser/src/driver/page-actions.ts b/package/ego-browser/src/driver/page-actions.tsindex 487d888..fdb9df3 100644--- a/package/ego-browser/src/driver/page-actions.ts+++ b/package/ego-browser/src/driver/page-actions.ts@@ -1,6 +1,6 @@import { runtimeValue } from "../cdp-eval.js";import { resolveElementObjectId } from "../element-resolver.js";-import { parseRef, RefMap } from "../ref-map.js";+import { RefMap } from "../ref-map.js";type PageActionServices = {cdp(@@ -27,15 +27,11 @@ export type PageFillOptions = {const INPUT_EVENT_DELAY_MS = 25;const INPUT_DISPATCH_TIMEOUT_MS = 1_000;-/**- * Click an element through one explicit target session. Page refs are rejected- * until the Page model owns a target-scoped ref registry; accepting the legacy- * process-global map here could silently click the same numeric ref on another- * tab.- */+/** Click an element through one explicit target session and Page ref map. */export async function clickInPage(services: PageActionServices,sessionId: string,+ refMap: RefMap,selector: string,options: PageClickOptions = {},): Promise<void> {@@ -51,7 +47,7 @@ export async function clickInPage(const target = await resolveElementObjectId(cdpAdapter(services),sessionId,- new RefMap(),+ refMap,selector,);try {@@ -139,6 +135,7 @@ export async function clickInPage(export async function fillInPage(services: PageActionServices,sessionId: string,+ refMap: RefMap,selector: string,value: string,options: PageFillOptions = {},@@ -155,7 +152,7 @@ export async function fillInPage(const resolved = await resolveElementObjectId(cdpAdapter(services),sessionId,- new RefMap(),+ refMap,selector,);try {@@ -222,9 +219,30 @@ async function resolveElementPoint() {throw new TypeError("page.click position requires finite x and y offsets");}- const expression = position- ? "function(position){const rect=this.getBoundingClientRect(); return {x:rect.x+position.x,y:rect.y+position.y};}"- : "function(){const rect=this.getBoundingClientRect(); return {x:rect.x+rect.width/2,y:rect.y+rect.height/2};}";+ const pointExpression = position+ ? "({x:rect.x+position.x,y:rect.y+position.y})"+ : "({x:rect.x+rect.width/2,y:rect.y+rect.height/2})";+ const expression = `function(${position ? "position" : ""}) {+ let rect = this.getBoundingClientRect();+ let point = ${pointExpression};+ const outsideViewport =+ rect.width <= 0 || rect.height <= 0 ||+ point.x < 0 || point.y < 0 ||+ point.x >= window.innerWidth || point.y >= window.innerHeight;+ if (outsideViewport) {+ this.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });+ rect = this.getBoundingClientRect();+ point = ${pointExpression};+ }+ if (+ rect.width <= 0 || rect.height <= 0 ||+ point.x < 0 || point.y < 0 ||+ point.x >= window.innerWidth || point.y >= window.innerHeight+ ) {+ return { error: "element is not visible in the viewport" };+ }+ return point;+ }`;const response = await services.cdp("Runtime.callFunctionOn",{@@ -237,6 +255,9 @@ async function resolveElementPoint(sessionId,);const point = runtimeValue(response, expression);+ if (typeof point?.error === "string") {+ throw new Error(`page.click failed: ${point.error}`);+ }if (!Number.isFinite(point?.x) || !Number.isFinite(point?.y)) {throw new Error("page.click could not resolve the element position");}@@ -343,11 +364,6 @@ function assertPageSelector(selector: unknown): asserts selector is string {if (typeof selector !== "string" || selector.trim().length === 0) {throw new TypeError("Page actions require a non-empty selector string");}- if (parseRef(selector)) {- throw new Error(- "page-scoped ref support is not available yet; use CSS, xpath=, or loc= for this Page action",- );- }}function cdpAdapter(services: PageActionServices) {diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjsindex afbb9d4..5ca21e5 100644--- a/package/ego-browser/src/page-model.test.mjs+++ b/package/ego-browser/src/page-model.test.mjs@@ -7,6 +7,7 @@ import { join } from "node:path";import { NativeOperationGate } from "../dist/src/native-gate.js";import { PageLedgerStore } from "../dist/src/page-ledger.js";import { createTaskSpaceHandle } from "../dist/src/page-model.js";+import { PageRefRegistry } from "../dist/src/page-ref-registry.js";async function withFixture(fn) {const rootDir = await mkdtemp(join(tmpdir(), "ego-page-model-test-"));@@ -25,6 +26,7 @@ function createFixture(rootDir) {let activeTarget = null;let popupOnNextClick = null;let timeoutNextMouseDispatch = false;+ let rejectNextClickPoint = false;function openPendingPopup() {if (!popupOnNextClick) return;@@ -51,6 +53,7 @@ function createFixture(rootDir) {});const services = {gate,+ pageRefs: new PageRefRegistry(),async createTab(url) {assert.equal(selectedSpace, 7);const targetId = `target-${nextTarget++}`;@@ -120,6 +123,15 @@ function createFixture(rootDir) {}if (method === "Runtime.callFunctionOn") {if (params.functionDeclaration.includes("getBoundingClientRect")) {+ if (rejectNextClickPoint) {+ rejectNextClickPoint = false;+ return {+ result: {+ type: "object",+ value: { error: "element is not visible in the viewport" },+ },+ };+ }return {result: { type: "object", value: { x: 40, y: 60 } },};@@ -143,6 +155,15 @@ function createFixture(rootDir) {},};}+ if (method === "DOM.resolveNode") {+ const targetId = sessionId.slice("session:".length);+ return {+ object: {+ type: "object",+ objectId: `element:${targetId}:${params.backendNodeId}`,+ },+ };+ }if (method === "Runtime.releaseObject") return {};if (method === "Input.insertText") return {};if (method === "Input.dispatchMouseEvent") {@@ -166,7 +187,17 @@ function createFixture(rootDir) {},async snapshot() {const tab = tabs.get(activeTarget);- return { content: `snapshot:${tab?.url}`, refs: [] };+ calls.push(["snapshot", activeTarget]);+ return {+ content: `snapshot:${tab?.url}`,+ refs: [+ {+ backendNodeId: 21,+ role: "button",+ name: "Run action",+ },+ ],+ };},async screenshot(path, options, sessionId) {calls.push(["screenshot", path, options, sessionId]);@@ -198,6 +229,9 @@ function createFixture(rootDir) {timeoutNextMouseDispatch() {timeoutNextMouseDispatch = true;},+ rejectNextClickPoint() {+ rejectNextClickPoint = true;+ },};}@@ -437,18 +471,111 @@ test("Page fill uses its target session and reports no popup when none opened",});});-test("Page actions reject global refs until the page-scoped ref registry exists", async () => {+test("Page actions resolve snapshot refs inside the addressed page", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const first = await task.newPage("https://example.test/first");+ const second = await task.newPage("https://example.test/second");++ await first.snapshot();+ await second.snapshot();+ await first.click("@21");+ await second.fill("@21", "page-scoped");++ const firstResolveCall = fixture.calls.find(+ ([kind, method, params, sessionId]) =>+ kind === "cdp" &&+ method === "DOM.resolveNode" &&+ params.backendNodeId === 21 &&+ sessionId === "session:target-1",+ );+ const secondResolveCall = fixture.calls.find(+ ([kind, method, params, sessionId]) =>+ kind === "cdp" &&+ method === "DOM.resolveNode" &&+ params.backendNodeId === 21 &&+ sessionId === "session:target-2",+ );+ assert(firstResolveCall, "click must resolve through the first Page session");+ assert(secondResolveCall, "fill must resolve through the second Page session");+ assert.equal(fixture.activeTarget(), second.targetId);+ });+});++test("a new round refreshes the addressed Page before resolving a ref", async () => {+ await withFixture(async (fixture) => {+ const firstRound = taskForRound(fixture, "round-a");+ const created = await firstRound.newPage("https://example.test/first");+ await created.snapshot();+ const snapshotsBefore = fixture.calls.filter(+ ([kind]) => kind === "snapshot",+ ).length;++ const secondRound = taskForRound(fixture, "round-b", {+ pageRefs: new PageRefRegistry(),+ });+ await secondRound.page(created.label).click("@21");++ assert.equal(+ fixture.calls.filter(([kind]) => kind === "snapshot").length,+ snapshotsBefore + 1,+ "an empty per-round ref map must refresh the same Page",+ );+ assert.deepEqual(+ fixture.calls.filter(([kind]) => kind === "snapshot").at(-1),+ ["snapshot", created.targetId],+ );+ });+});++test("an unknown Page ref fails after one target-scoped refresh", async () => {await withFixture(async (fixture) => {const task = taskForRound(fixture, "round-a");const page = await task.newPage("https://example.test/first");await assert.rejects(- () => page.click("@21"),- /page-scoped ref support is not available yet/,+ () => page.click("@99"),+ /Unknown ref: 99/,+ );+ assert.deepEqual(+ fixture.calls.filter(([kind]) => kind === "snapshot"),+ [["snapshot", page.targetId]],+ );+ });+});++test("Page click scrolls the element into view before computing its point", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await task.newPage("https://example.test/first");++ await page.click("#offscreen");++ const pointCall = fixture.calls.find(+ ([kind, method, params]) =>+ kind === "cdp" &&+ method === "Runtime.callFunctionOn" &&+ params.functionDeclaration.includes("getBoundingClientRect"),);+ assert.match(pointCall[2].functionDeclaration, /scrollIntoView/);+ });+});++test("Page click does not dispatch input when scrolling cannot make the element visible", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await task.newPage("https://example.test/first");+ fixture.rejectNextClickPoint();+await assert.rejects(- () => page.fill("@21", "wrong"),- /page-scoped ref support is not available yet/,+ () => page.click("#hidden"),+ /element is not visible in the viewport/,+ );+ assert.equal(+ fixture.calls.some(+ ([kind, method]) => kind === "cdp" && method === "Input.dispatchMouseEvent",+ ),+ false,);});});diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.tsindex 957b08c..24d15e1 100644--- a/package/ego-browser/src/page-model.ts+++ b/package/ego-browser/src/page-model.ts@@ -30,6 +30,8 @@ import {type PageLedger,type PageOrigin,} from "./page-ledger.js";+import { PageRefRegistry } from "./page-ref-registry.js";+import { parseRef, type RefMap } from "./ref-map.js";import { state } from "./state.js";type TaskSpaceDescriptor = {@@ -95,6 +97,7 @@ type RuntimeTab = {type PageModelServices = {ledger: LedgerPort;+ pageRefs: PageRefRegistry;gate: OperationGate;createTab(url: string): Promise<string>;listTabs(): Promise<RuntimeTab[]>;@@ -147,6 +150,7 @@ export class PageBudgetError extends Error {}let defaultLedger: PageLedgerStore | undefined;+const defaultPageRefs = new PageRefRegistry();const unmanagedPageConstructorToken = Symbol("UnmanagedPage");const defaultGate: OperationGate = {@@ -156,6 +160,7 @@ const defaultGate: OperationGate = {const baseDefaultServices: Omit<PageModelServices, "ledger" | "pageBudget"> = {gate: defaultGate,+ pageRefs: defaultPageRefs,async createTab(url) {const result = assertNoEgoError(await browserEgo().createTab(url),@@ -441,17 +446,21 @@ export class Page {assertTimeout(timeoutMs);const page = await this.#resolve();return this.#services.gate.withPage(page, async ({ sessionId }) => {- const navigation = await this.#services.cdp(- "Page.navigate",- { url },- sessionId,- timeoutMs,- );- if (navigation?.errorText) {- throw new Error(`page.goto failed: ${navigation.errorText}`);+ try {+ const navigation = await this.#services.cdp(+ "Page.navigate",+ { url },+ sessionId,+ timeoutMs,+ );+ if (navigation?.errorText) {+ throw new Error(`page.goto failed: ${navigation.errorText}`);+ }+ await waitForReadyState(this.#services, sessionId, timeoutMs);+ return navigation;+ } finally {+ this.#services.pageRefs.clear(page.targetId);}- await waitForReadyState(this.#services, sessionId, timeoutMs);- return navigation;});}@@ -465,6 +474,7 @@ export class Page {includeStableLocator: true,...options,});+ this.#services.pageRefs.replace(page.targetId, result?.refs || []);return result?.content || "";});}@@ -517,8 +527,8 @@ export class Page {selector: string,options: PageClickOptions = {},): Promise<PageActionReceipt> {- return this.#runAction((sessionId) =>- clickInPage(this.#services, sessionId, selector, options),+ return this.#runAction(selector, (sessionId, refMap) =>+ clickInPage(this.#services, sessionId, refMap, selector, options),);}@@ -527,8 +537,8 @@ export class Page {value: string,options: PageFillOptions = {},): Promise<PageActionReceipt> {- return this.#runAction((sessionId) =>- fillInPage(this.#services, sessionId, selector, value, options),+ return this.#runAction(selector, (sessionId, refMap) =>+ fillInPage(this.#services, sessionId, refMap, selector, value, options),);}@@ -539,6 +549,7 @@ export class Page {const live = tabs.some((tab) => tab.targetId === page.targetId);if (!live) {await this.#services.ledger.closePage(this.spaceId, this.label);+ this.#services.pageRefs.clear(page.targetId);this.#closed = true;throw new Error(`page ${this.label} was closed`);}@@ -552,6 +563,7 @@ export class Page {throw new Error(`failed to close page ${this.label}`);}this.#services.invalidateSession(page.targetId);+ this.#services.pageRefs.clear(page.targetId);await this.#services.ledger.closePage(this.spaceId, this.label);this.#closed = true;});@@ -579,57 +591,84 @@ export class Page {const page = await this.#resolve();return this.#services.gate.withPage(page, async ({ sessionId }) => {if (activate) await this.#activate(page.targetId);- return evaluateInSession<T>(- this.#services,- sessionId,- expression,- hasArgument,- serializedArgument,- );+ try {+ return await evaluateInSession<T>(+ this.#services,+ sessionId,+ expression,+ hasArgument,+ serializedArgument,+ );+ } finally {+ if (activate) this.#services.pageRefs.clear(page.targetId);+ }});}async #runAction(- operation: (sessionId: string) => Promise<void>,+ selector: string,+ operation: (sessionId: string, refMap: RefMap) => Promise<void>,): Promise<PageActionReceipt> {const page = await this.#resolve();return this.#services.gate.withPage(page, async ({ sessionId }) => {await this.#activate(page.targetId);- const before = new Set(- (await this.#services.listTabs()).map((tab) => tab.targetId),- );- let actionError: unknown;try {- await operation(sessionId);- } catch (error) {- actionError = error;- }+ const refMap = await this.#refMapForAction(page, selector);+ const before = new Set(+ (await this.#services.listTabs()).map((tab) => tab.targetId),+ );+ let actionError: unknown;+ try {+ await operation(sessionId, refMap);+ } catch (error) {+ actionError = error;+ }- // A popup is normally created synchronously by the input event. A short- // settle covers native tab-list propagation without turning this into a- // navigation wait or silently changing the page's active state.- await this.#services.sleep(50);- let popupError: unknown;- const popups: Array<{ label: string; targetId: string }> = [];- try {- const after = await this.#services.listTabs();- for (const tab of after) {- if (before.has(tab.targetId)) continue;- const managed = await this.#services.ledger.addPage(- this.spaceId,- tab.targetId,- { openedBy: "agent" },- );- popups.push({ label: managed.label, targetId: managed.targetId });+ // A popup is normally created synchronously by the input event. A short+ // settle covers native tab-list propagation without turning this into a+ // navigation wait or silently changing the page's active state.+ await this.#services.sleep(50);+ let popupError: unknown;+ const popups: Array<{ label: string; targetId: string }> = [];+ try {+ const after = await this.#services.listTabs();+ for (const tab of after) {+ if (before.has(tab.targetId)) continue;+ const managed = await this.#services.ledger.addPage(+ this.spaceId,+ tab.targetId,+ { openedBy: "agent" },+ );+ popups.push({ label: managed.label, targetId: managed.targetId });+ }+ } catch (error) {+ popupError = error;}- } catch (error) {- popupError = error;++ if (actionError) throw actionError;+ if (popupError) throw popupError;+ return popups.length > 0 ? { popups } : {};+ } finally {+ this.#services.pageRefs.clear(page.targetId);}+ });+ }- if (actionError) throw actionError;- if (popupError) throw popupError;- return popups.length > 0 ? { popups } : {};+ async #refMapForAction(+ page: PageTarget,+ selector: string,+ ): Promise<RefMap> {+ let refs = this.#services.pageRefs.forTarget(page.targetId);+ const refId = parseRef(selector);+ if (!refId || refs.get(refId)) return refs;++ const result = await this.#services.snapshot({+ scope: "full_page",+ includeActionMarks: true,+ includeStableLocator: true,});+ refs = this.#services.pageRefs.replace(page.targetId, result?.refs || []);+ return refs;}async #activate(targetId: string): Promise<void> {diff --git a/package/ego-browser/src/page-ref-registry.ts b/package/ego-browser/src/page-ref-registry.tsnew file mode 100644index 0000000..66c195f--- /dev/null+++ b/package/ego-browser/src/page-ref-registry.ts@@ -0,0 +1,59 @@+import { RefMap } from "./ref-map.js";++type SnapshotRef = {+ backendNodeId?: number;+ role?: string;+ name?: string;+};++/**+ * Keeps native snapshot refs isolated by browser target. The printed ref stays+ * compact (`@21`), while the Page carrying the target id supplies its scope.+ */+export class PageRefRegistry {+ readonly #targets = new Map<string, RefMap>();++ forTarget(targetId: string): RefMap {+ assertTargetId(targetId);+ let refs = this.#targets.get(targetId);+ if (!refs) {+ refs = new RefMap();+ this.#targets.set(targetId, refs);+ }+ return refs;+ }++ replace(targetId: string, snapshotRefs: SnapshotRef[] = []): RefMap {+ assertTargetId(targetId);+ const refs = new RefMap();+ for (const ref of snapshotRefs) {+ if (+ !ref ||+ typeof ref !== "object" ||+ ref.backendNodeId === undefined ||+ ref.backendNodeId === null+ ) {+ continue;+ }+ refs.add(+ String(ref.backendNodeId),+ ref.backendNodeId,+ ref.role,+ ref.name,+ );+ }+ this.#targets.set(targetId, refs);+ return refs;+ }++ clear(targetId: string): void {+ assertTargetId(targetId);+ this.#targets.delete(targetId);+ }+}++function assertTargetId(targetId: string): void {+ if (typeof targetId !== "string" || targetId.length === 0) {+ throw new TypeError("PageRefRegistry requires a non-empty targetId");+ }+}