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): align role locator match sets
0x0fc4a8c7ae6e5
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjsindex 8968f93..06941fb 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs@@ -59,6 +59,21 @@ export function helperSurfaceCase() {assertEqual(await page.locator("#text-input").inputValue(), "from placeholder", "getByPlaceholder targets the input");assertEqual(await page.getByAltText("Ego fixture logo").count(), 1, "getByAltText finds the image");assertEqual(await page.getByTitle("Counter button").count(), 1, "getByTitle finds titled elements");+ // Role-locator match-set consistency (the Redfin "Locator miss" regression).+ // The listbox holds two visible "House" options plus one display:none dupe.+ // A DOM role scan counts all three (no visibility filtering); the AX tree+ // ignores the hidden one. count()/nth()/click() must all agree on the same+ // AX set, otherwise "read count, act on the last index" targets past the end.+ const houseOptions = page.getByRole("option", { name: "House" });+ const houseCount = await houseOptions.count();+ assertEqual(houseCount, 2, "count() reports only AX-actionable options (display:none dupe excluded)");+ assertEqual(await houseOptions.nth(houseCount - 1).innerText(), "House", "nth reads from the same AX match set count() used");+ await houseOptions.nth(houseCount - 1).click();+ assertEqual(+ await houseOptions.nth(houseCount - 1).getAttribute("aria-selected"),+ "true",+ "the option count() calls last is exactly the one nth()/click() targets"+ );assertEqual(await page.locator("text=Download sample").count(), 1, "text= locator compatibility works"); // agent-style-ok: compatibility checkconst extracted = await page.locator(".card").first().evaluateAll((cards) =>cards.map((card) => ({diff --git a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs b/package/ego-browser/scripts/real-browser-e2e/fixture.mjsindex f1becb9..424a34b 100644--- a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs@@ -402,6 +402,12 @@ function pageHtml(kind) {<button class="duplicate-action" type="button">Duplicate action</button><a id="nav-link" href="/nav-target" style="margin-left:8px">Go to nav target</a><a id="download-link" href="/download/sample.txt" download style="margin-left:8px">Download sample</a>+ <div id="home-type-listbox" role="listbox" aria-label="Home type" style="display:inline-flex;gap:6px;margin-left:8px">+ <button id="house-option-primary" type="button" role="option" aria-selected="false">House</button>+ <button id="house-option-secondary" type="button" role="option" aria-selected="false">House</button>+ <!-- Hidden responsive-variant dupe: visible to a naive DOM role scan, ignored by the AX tree. -->+ <button id="house-option-hidden" type="button" role="option" aria-selected="false" style="display:none">House</button>+ </div></div><div class="card-row">@@ -561,6 +567,14 @@ function pageHtml(kind) {window.__fixtureState.lastDoubleClickDetail = event.detail;});+ for (const option of document.querySelectorAll("#home-type-listbox [role=option]")) {+ option.addEventListener("click", () => {+ for (const peer of document.querySelectorAll("#home-type-listbox [role=option]")) {+ peer.setAttribute("aria-selected", String(peer === option));+ }+ });+ }+/* ---- hover zone ---- */for (const type of ["mousemove", "mouseover"]) {document.querySelector("#hover-zone").addEventListener(type, () => {diff --git a/package/ego-browser/src/driver/locator.test.mjs b/package/ego-browser/src/driver/locator.test.mjsindex 6fee94b..e0679e9 100644--- a/package/ego-browser/src/driver/locator.test.mjs+++ b/package/ego-browser/src/driver/locator.test.mjs@@ -150,17 +150,27 @@ test("filter locators support hasText, hasNotText, has, and hasNot", async () =>}});-test("role locators support regex accessible names in collection queries", async () => {+test("role locators use AX regex accessible names in collection queries", async () => {const selector = `loc=role:button[name=${JSON.stringify({regex: "checkout",flags: "i",})}]`;+ const calls = [];const restore = setOverrides({cdpOverride(method, params) {- assert.equal(method, "Runtime.evaluate");- assert.match(params.expression, /new RegExp\("checkout", "i"\)/);- assert.match(params.expression, /accessibleName\(el\)/);- return { result: { value: 1 } };+ calls.push({ method, params });+ if (method === "Accessibility.getFullAXTree") {+ return {+ nodes: [+ {+ role: { value: "button" },+ name: { value: "Proceed to Checkout" },+ backendDOMNodeId: 101,+ },+ ],+ };+ }+ throw new Error(`Unexpected CDP method: ${method}`);},});try {@@ -168,6 +178,86 @@ test("role locators support regex accessible names in collection queries", async} finally {restore();}+ assert.deepEqual(+ calls.map((call) => call.method),+ ["Accessibility.getFullAXTree"],+ );+});++test("role collections use the same AX match set as nth element operations", async () => {+ const selector = 'loc=role:option[name="House"]';+ const second = `internal:nth=1;${selector}`;+ const calls = [];+ const restore = setOverrides({+ cdpOverride(method, params) {+ calls.push({ method, params });+ if (method === "Accessibility.getFullAXTree") {+ return {+ nodes: [+ {+ role: { value: "option" },+ name: { value: "House" },+ backendDOMNodeId: 100,+ },+ {+ role: { value: "option" },+ name: { value: "House" },+ backendDOMNodeId: 200,+ },+ ],+ };+ }+ if (method === "DOM.resolveNode") {+ return { object: { objectId: `node-${params.backendNodeId}` } };+ }+ if (method === "Runtime.callFunctionOn") {+ if (params.functionDeclaration.includes("innerText target")) {+ assert.equal(params.objectId, "node-200");+ return { result: { value: "House 2" } };+ }+ assert.deepEqual(+ [+ params.objectId,+ ...params.arguments+ .filter((argument) => argument.objectId)+ .map((argument) => argument.objectId),+ ],+ ["node-100", "node-200"],+ );+ const functionSource = params.arguments.find(+ (argument) =>+ typeof argument.value === "string" &&+ argument.value.includes("elements"),+ )?.value;+ if (functionSource?.includes("allInnerTexts targets")) {+ return { result: { value: ["House 1", "House 2"] } };+ }+ return { result: { value: ["HOUSE 1", "HOUSE 2"] } };+ }+ if (method === "Runtime.releaseObject") {+ return {};+ }+ throw new Error(`Unexpected CDP method: ${method}`);+ },+ });+ try {+ assert.equal(await count(selector), 2);+ assert.equal(await count(second), 1);+ assert.equal(await innerText(second), "House 2");+ assert.deepEqual(await allInnerTexts(selector), ["House 1", "House 2"]);+ assert.deepEqual(+ await evaluateAll(selector, (elements) =>+ elements.map((element) => element.textContent.toUpperCase()),+ ),+ ["HOUSE 1", "HOUSE 2"],+ );+ } finally {+ restore();+ }+ assert.equal(+ calls.some((call) => call.method === "Runtime.evaluate"),+ false,+ );});test("raw Playwright has-text selectors filter native CSS candidates", async () => {diff --git a/package/ego-browser/src/driver/locator.ts b/package/ego-browser/src/driver/locator.tsindex 5dc86c9..0b7cbc6 100644--- a/package/ego-browser/src/driver/locator.ts+++ b/package/ego-browser/src/driver/locator.ts@@ -1,5 +1,8 @@import { cdp, runtimeValue } from "../cdp-eval.js";-import { ElementResolutionError } from "../element-resolver.js";+import {+ ElementResolutionError,+ queryRoleLocatorBackendNodeIds,+} from "../element-resolver.js";import { queryAllExpression as buildQueryAllExpression } from "../locator-query.js";import { parseRef } from "../ref-map.js";import { releaseHandle, resolveAndCall, resolveHandle } from "./element-ops.js";@@ -218,6 +221,10 @@ export async function count(selector) {await releaseHandle(handle.objectId, handle.sessionId);return 1;}+ const backendNodeIds = await queryRoleBackendNodeIds(selector);+ if (backendNodeIds !== null) {+ return backendNodeIds.length;+ }return readQueryAll(selector, "return elements.length;");}@@ -286,6 +293,10 @@ export async function evaluateAll(selector, pageFunction, arg = undefined) {[functionSource, arg],);}+ const backendNodeIds = await queryRoleBackendNodeIds(selector);+ if (backendNodeIds !== null) {+ return evaluateRoleBackendNodes(backendNodeIds, functionSource, arg, true);+ }return evaluateQueryAll(selector, functionSource, arg);}@@ -311,6 +322,15 @@ async function readOptionalElement(}async function readQueryAll(selector, body) {+ const backendNodeIds = await queryRoleBackendNodeIds(selector);+ if (backendNodeIds !== null) {+ return evaluateRoleBackendNodes(+ backendNodeIds,+ `function(elements){${body}}`,+ undefined,+ false,+ );+ }const expression = `(() => {const elements = ${buildQueryAllExpression(selector)};${body}@@ -323,6 +343,73 @@ async function readQueryAll(selector, body) {return runtimeValue(result, expression);}+async function evaluateRoleBackendNodes(+ backendNodeIds,+ functionSource,+ arg,+ awaitPromise,+) {+ if (backendNodeIds.length === 0) {+ const expression = `(() => {+ const pageFunction = (0, eval)(${JSON.stringify(`(${functionSource})`)});+ return pageFunction([], ${serializedArg(arg)});+ })()`;+ const result = await cdp("Runtime.evaluate", {+ expression,+ returnByValue: true,+ awaitPromise,+ });+ return runtimeValue(result, expression);+ }++ const handles = [];+ try {+ for (const backendNodeId of backendNodeIds) {+ const result = await cdp("DOM.resolveNode", {+ backendNodeId,+ objectGroup: "ego-browser-role-collection",+ });+ const objectId = result.object?.objectId;+ if (!objectId) {+ throw new ElementResolutionError(+ `No objectId for AX backend node ${backendNodeId}`,+ "permanent",+ );+ }+ handles.push({ objectId });+ }++ const [first, ...rest] = handles;+ const functionDeclaration = `function(...args) {+ const functionSource = args.at(-2);+ const arg = args.at(-1);+ const elements = [this, ...args.slice(0, -2)];+ const pageFunction = (0, eval)("(" + functionSource + ")");+ return pageFunction(elements, arg);+ }`;+ const result = await cdp("Runtime.callFunctionOn", {+ functionDeclaration,+ objectId: first.objectId,+ arguments: [+ ...rest.map(({ objectId }) => ({ objectId })),+ { value: functionSource },+ { value: arg },+ ],+ returnByValue: true,+ awaitPromise,+ });+ return runtimeValue(result, functionDeclaration);+ } finally {+ for (const { objectId } of handles) {+ await releaseHandle(objectId, undefined);+ }+ }+}++function queryRoleBackendNodeIds(selector) {+ return queryRoleLocatorBackendNodeIds({ sendRaw: cdp }, undefined, selector);+}+async function evaluateQueryAll(selector, functionSource, arg) {const expression = `(() => {const elements = ${buildQueryAllExpression(selector)};diff --git a/package/ego-browser/src/element-resolver.ts b/package/ego-browser/src/element-resolver.tsindex 6a259b8..87af29b 100644--- a/package/ego-browser/src/element-resolver.ts+++ b/package/ego-browser/src/element-resolver.ts@@ -10,6 +10,34 @@ export class ElementResolutionError extends Error {}}+/**+ * Return the ordered AX backend-node match set for a root role locator.+ * Non-role selectors return null so callers can use their normal DOM path.+ */+export async function queryRoleLocatorBackendNodeIds(+ cdp,+ sessionId,+ selectorOrRef,+): Promise<number[] | null> {+ const locator = parseLocator(selectorOrRef);+ if (locator?.kind !== "role") {+ return null;+ }+ const backendNodeIds = await findBackendNodeIdsByRoleName(+ cdp,+ sessionId,+ locator.role,+ locator.name,+ );+ const nth = locator.nth as number | "last" | undefined;+ if (nth === undefined) {+ return backendNodeIds;+ }+ const nthIndex = nth === "last" ? backendNodeIds.length - 1 : nth;+ const backendNodeId = backendNodeIds[nthIndex];+ return backendNodeId === undefined ? [] : [backendNodeId];+}+function exceptionText(result: any) {const d = result?.exceptionDetails;return d?.exception?.description || d?.text || "evaluation error";@@ -369,6 +397,33 @@ async function findBackendNodeIdByRoleName(frameId = undefined,iframeSessions = new Map(),) {+ const matches = await findBackendNodeIdsByRoleName(+ cdp,+ sessionId,+ role,+ name,+ frameId,+ iframeSessions,+ );+ const nthIndex = nth === "last" ? matches.length - 1 : (nth ?? 0);+ const match = matches[nthIndex];+ if (match !== undefined) {+ return match;+ }+ throw new ElementResolutionError(+ `Could not locate element with role=${role} name=${name}`,+ "transient",+ );+}++async function findBackendNodeIdsByRoleName(+ cdp,+ sessionId,+ role,+ name,+ frameId = undefined,+ iframeSessions = new Map(),+): Promise<number[]> {const [params, effectiveSessionId] = resolveAxSession(frameId,sessionId,@@ -394,42 +449,25 @@ async function findBackendNodeIdByRoleName() {continue;}- matches.push(node);- }- const nthIndex = nth === "last" ? matches.length - 1 : (nth ?? 0);- const match = matches[nthIndex];- if (match) {- if (- match.backendDOMNodeId === undefined ||- match.backendDOMNodeId === null- ) {+ const backendNodeId = node.backendDOMNodeId;+ if (backendNodeId === undefined || backendNodeId === null) {throw new ElementResolutionError(`AX node has no backendDOMNodeId for role=${role} name=${name}`,"permanent",);}- return match.backendDOMNodeId;+ matches.push(backendNodeId);}- throw new ElementResolutionError(- `Could not locate element with role=${role} name=${name}`,- "transient",- );+ return matches;}async function findUniqueBackendNodeIdByRoleName(cdp, sessionId, role, name) {- const result = await send(cdp, "Accessibility.getFullAXTree", {}, sessionId);- const matches = [];- for (const node of result.nodes || []) {- if (node.ignored) {- continue;- }- if (- extractAxString(node.role) === role &&- (name === undefined || axNameMatches(extractAxString(node.name), name))- ) {- matches.push(node);- }- }+ const matches = await findBackendNodeIdsByRoleName(+ cdp,+ sessionId,+ role,+ name,+ );if (matches.length === 0) {throw new ElementResolutionError(`Locator role:${role}[name=${JSON.stringify(name)}] matched 0 elements`,@@ -442,14 +480,7 @@ async function findUniqueBackendNodeIdByRoleName(cdp, sessionId, role, name) {"permanent",);}- const backendNodeId = matches[0].backendDOMNodeId;- if (backendNodeId === undefined || backendNodeId === null) {- throw new ElementResolutionError(- `AX node has no backendDOMNodeId for role=${role} name=${name}`,- "permanent",- );- }- return backendNodeId;+ return matches[0];}function resolveAxSession(frameId, sessionId, iframeSessions) {