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): enforce raw locator strictness
0x06153889ebca1
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/playwright-locators.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/playwright-locators.mjsindex 9941f7d..81a641b 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/playwright-locators.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/playwright-locators.mjs@@ -33,8 +33,28 @@ export const playwrightLocatorCases = ["PWB-06 non-unique locator remains strict");assertEqual(await locator.count(), 2, "PWB-06 count exposes both matches");- await locator.first().click({ timeout: 1000 });- assert(await locator.first().isVisible(), "PWB-06 first resolves a confirmed legitimate duplicate");++ const rawCss = page.locator(".duplicate-action");+ await assertRejects(+ () => rawCss.click({ timeout: 1000 }),+ "matched 2 elements",+ "PWB-06 raw CSS action remains strict"+ );++ const rawXpath = page.locator('xpath=//button[contains(@class, "duplicate-action")]');+ await assertRejects(+ () => rawXpath.innerText(),+ "matched 2 elements",+ "PWB-06 raw XPath read remains strict"+ );++ await rawCss.first().click({ timeout: 1000 });+ assert(await rawCss.first().isVisible(), "PWB-06 first resolves a confirmed legitimate duplicate");+ assertEqual(+ await rawXpath.nth(1).innerText(),+ "Duplicate action",+ "PWB-06 nth resolves a confirmed legitimate XPath duplicate"+ );`),},];diff --git a/package/ego-browser/src/element-resolver.test.mjs b/package/ego-browser/src/element-resolver.test.mjsindex 42d68e0..7cd7802 100644--- a/package/ego-browser/src/element-resolver.test.mjs+++ b/package/ego-browser/src/element-resolver.test.mjs@@ -3,6 +3,7 @@ import assert from "node:assert/strict";import {resolveElementCenter,+ resolveElementObjectId,ElementResolutionError,} from "../dist/src/element-resolver.js";import { RefMap } from "../dist/src/ref-map.js";@@ -168,6 +169,79 @@ test("css locator matched multiple elements is permanent", async () => {);});+test("raw CSS selector matched multiple elements is permanent", async () => {+ const cdp = new FakeCDP(async (method, params) => {+ if (method === "Runtime.evaluate") {+ assert.match(params.expression, /querySelectorAll\("\.duplicate"\)/);+ assert.match(params.expression, /elements\.length > 1/);+ return {+ exceptionDetails: {+ exception: {+ description: "Error: Locator .duplicate matched 2 elements",+ },+ },+ };+ }+ return {};+ });+ await assert.rejects(+ () => resolveElementCenter(cdp, undefined, new RefMap(), ".duplicate"),+ (error) => {+ assert.ok(error instanceof ElementResolutionError);+ assert.equal(error.kind, "permanent");+ assert.match(error.message, /matched 2 elements/);+ return true;+ },+ );+});++test("raw XPath selector matched multiple elements is permanent for reads", async () => {+ const cdp = new FakeCDP(async (method, params) => {+ if (method === "Runtime.evaluate") {+ assert.match(+ params.expression,+ /XPathResult\.ORDERED_NODE_SNAPSHOT_TYPE/,+ );+ assert.match(params.expression, /elements\.length > 1/);+ return {+ exceptionDetails: {+ exception: {+ description: "Error: Locator xpath=\/\/button matched 2 elements",+ },+ },+ };+ }+ return {};+ });+ await assert.rejects(+ () =>+ resolveElementObjectId(cdp, undefined, new RefMap(), "xpath=//button"),+ (error) => {+ assert.ok(error instanceof ElementResolutionError);+ assert.equal(error.kind, "permanent");+ assert.match(error.message, /matched 2 elements/);+ return true;+ },+ );+});++test("raw CSS selector matched zero elements remains transient", async () => {+ const cdp = new FakeCDP(async (method) => {+ if (method === "Runtime.evaluate") {+ return { result: { value: null } };+ }+ return {};+ });+ await assert.rejects(+ () => resolveElementCenter(cdp, undefined, new RefMap(), ".missing"),+ (error) => {+ assert.ok(error instanceof ElementResolutionError);+ assert.equal(error.kind, "transient");+ return true;+ },+ );+});+test("raw Playwright has-text selector resolves through filtered CSS candidates", async () => {const cdp = new FakeCDP(async (method, params) => {if (method === "Runtime.evaluate") {diff --git a/package/ego-browser/src/element-resolver.ts b/package/ego-browser/src/element-resolver.tsindex 87af29b..f140a06 100644--- a/package/ego-browser/src/element-resolver.ts+++ b/package/ego-browser/src/element-resolver.ts@@ -49,6 +49,17 @@ function matchCountKind(message: string): "transient" | "permanent" {return n > 1 ? "permanent" : "transient";}+function selectorResolutionError(selector, result) {+ const message = exceptionText(result);+ if (/\bmatched \d+ elements\b/.test(message)) {+ return new ElementResolutionError(message, matchCountKind(message));+ }+ return new ElementResolutionError(+ `Invalid selector: ${selector}: ${message}`,+ "permanent",+ );+}+export async function resolveElementCenter(cdp,sessionId,@@ -123,10 +134,7 @@ export async function resolveElementCenter(sessionId,);if (result.exceptionDetails) {- throw new ElementResolutionError(- `Invalid selector: ${selectorOrRef}: ${exceptionText(result)}`,- "permanent",- );+ throw selectorResolutionError(selectorOrRef, result);}const value = result.result?.value;if (typeof value?.x !== "number" || typeof value?.y !== "number") {@@ -217,10 +225,7 @@ export async function resolveElementObjectId(sessionId,);if (result.exceptionDetails) {- throw new ElementResolutionError(- `Invalid selector: ${selectorOrRef}: ${exceptionText(result)}`,- "permanent",- );+ throw selectorResolutionError(selectorOrRef, result);}const objectId = result.result?.objectId;if (!objectId) {@@ -498,10 +503,12 @@ function resolveAxSession(frameId, sessionId, iframeSessions) {}function buildFindElementJs(selector) {- if (String(selector).startsWith("xpath=")) {- return `document.evaluate(${JSON.stringify(String(selector).slice(6))}, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue`;- }- return `(() => ${queryAllExpression(selector)}[0] || null)()`;+ const matchError = JSON.stringify(`Locator ${String(selector)} matched `);+ return `(() => {+ const elements = ${queryAllExpression(selector)};+ if (elements.length > 1) throw new Error(${matchError} + elements.length + ' elements');+ return elements[0] || null;+ })()`;}function buildLocatorFindJs(locator) {diff --git a/package/ego-browser/src/helpers.ts b/package/ego-browser/src/helpers.tsindex e9a8b9a..0fefa5c 100644--- a/package/ego-browser/src/helpers.ts+++ b/package/ego-browser/src/helpers.ts@@ -803,7 +803,7 @@ function createSiteFacade() {const FACADE_HELP: Record<string, string> = {page: 'page: Playwright-style page facade. page.url() asynchronously returns the current URL; always call await page.url() before using the string. Use page.goto(url), page.locator(selector), page.getByText(text), page.getByLabel(text), page.getByPlaceholder(text), page.getByTestId(testId), page.setDefaultTimeout(ms), page.waitForEvent("download"), page.waitForLoadState(state, options), page.waitForURL(url, options), page.waitForRequest(urlOrPredicate, options), page.waitForResponse(urlOrPredicate, options), page.evaluate(expression), page.screenshot(options), page.keyboard.press(key), page.keyboard.type(text), and page.mouse.click(x, y). waitForURL predicates receive URL objects and waitUntil defaults to load.',locator:- "page.locator(selector): returns an auto-waiting locator facade with locator(), getByRole(), getByText(), filter(), first(), nth(index), last(), click(), fill(value), clear(), press(key), check(), selectOption(value), textContent(), innerText(), innerHTML(), isVisible(), isEnabled(), getAttribute(name), screenshot(), count(), evaluate(fn, arg), evaluateAll(fn, arg), and waitFor(options). Unqualified raw CSS and raw xpath= selectors are not strict and act on the first match by default; prefer getBy*, loc=..., or chained/filtered locators when ambiguity must fail loudly. Narrow multiple matches; use first()/nth() only for confirmed legitimate duplicates.",+ "page.locator(selector): returns a strict, auto-waiting locator facade with locator(), getByRole(), getByText(), filter(), first(), nth(index), last(), click(), fill(value), clear(), press(key), check(), selectOption(value), textContent(), innerText(), innerHTML(), isVisible(), isEnabled(), getAttribute(name), screenshot(), count(), evaluate(fn, arg), evaluateAll(fn, arg), and waitFor(options). Narrow multiple matches; use first()/nth() only for confirmed legitimate duplicates.",browser:"browser: tab facade. Use browser.listTabs(), browser.currentTab(), browser.switchTab(target), browser.openOrReuseTab(url, options), and browser.closeTab(target). Treat targetId as short-lived: obtain and validate it in the current script; switchTab/closeTab refresh the tab list before acting.",taskSpaces:diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.mdindex 00e5a2d..4e6db23 100644--- a/skills/ego-browser/SKILL.md+++ b/skills/ego-browser/SKILL.md@@ -139,7 +139,7 @@ EOF- A `page.waitForURL(...)` predicate receives a `URL` object. Use `url.href`, `url.pathname`, or `url.searchParams`, never `url.includes(...)`. It waits for `load` by default; use `waitUntil: 'commit'` only when intentionally proceeding before load.- `page.waitForURL`, `page.waitForLoadState`, `page.waitForSelector`, locator `waitFor`, and `page.waitForFunction` return a falsy value on timeout. Check the result or immediately verify the required state; do not continue on an unverified assumption.- Start `page.waitForRequest(...)`, `page.waitForResponse(...)`, or another event wait before the triggering action. Network predicates are synchronous and receive Playwright-style request/response facades.-- Single-element actions and required reads auto-wait. Unqualified raw CSS and raw `xpath=` locators are not strict and act on the first match by default; prefer `getBy*`, `loc=...`, or chained/filtered locators when ambiguity must fail loudly, especially for destructive actions. For zero matches, confirm load, active tab, and modal/overlay state before correcting the locator. For multiple matches, inspect `count()` / `allInnerTexts()`, narrow semantically or with `filter(...)`, and use `first()` / `nth()` only after confirming duplicates are legitimate.+- Single-element actions and required reads are strict and auto-wait. For zero matches, confirm load, active tab, and modal/overlay state before correcting the locator. For multiple matches, inspect `count()` / `allInnerTexts()`, narrow semantically or with `filter(...)`, and use `first()` / `nth()` only after confirming duplicates are legitimate.- Prefer `getByRole`, `getByLabel`, `getByText`, `getByPlaceholder`, `getByTestId`, chained locators, and stable `loc=...` values. Use coordinates only for genuinely visual or canvas-like surfaces.- For lists, extract item objects with `evaluateAll`, `allInnerTexts`, or semantic locators before choosing. Do not choose primarily from a sliced snapshot, a broad free-text regex, or coordinates.- Verify every state-changing action before the Bash command exits. Throw when the required URL, dialog, selected value, item, or data is absent. Do not swallow errors from required actions; reserve `.catch(() => {})` for optional cleanup or non-blocking probes.