Skip to content

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.

fix(ego-browser): improve page operation diagnostics

Aute46576ae378c1
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.mjs
index da8a575..deffb32 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
@@ -1036,6 +1036,13 @@ export function pageFetchCase() {
"page.fetch enforces a millisecond timeout"
);
+ const crossOriginUrl = baseUrl.replace("127.0.0.1", "localhost") + "/api/request-info";
+ await assertRejects(
+ () => source.fetch(crossOriginUrl, { timeout: 2_000 }),
+ "page.fetch uses window.fetch and obeys browser CORS",
+ "page.fetch explains browser CORS failures"
+ );
+
await source.close();
await comparison.close();
`;
diff --git a/package/ego-browser/src/element-resolver.test.mjs b/package/ego-browser/src/element-resolver.test.mjs
index 43df462..ac48af7 100644
--- a/package/ego-browser/src/element-resolver.test.mjs
+++ b/package/ego-browser/src/element-resolver.test.mjs
@@ -144,6 +144,69 @@ test("CSS locators search nested open shadow roots", async () => {
assert.deepEqual(point, { x: 12, y: 34, sessionId: undefined });
});
+test("invalid numeric CSS ids suggest a valid attribute selector", async () => {
+ const cdp = new FakeCDP(async (method) => {
+ if (method === "Runtime.evaluate") {
+ return {
+ exceptionDetails: {
+ exception: {
+ description:
+ "SyntaxError: Failed to execute 'querySelectorAll' on 'Document'",
+ },
+ },
+ };
+ }
+ return {};
+ });
+
+ await assert.rejects(
+ () =>
+ resolveElementObjectId(
+ cdp,
+ "session:page",
+ new RefMap(),
+ "#73503e10-2be7-42d1-a053-c77402da1f80",
+ new Map(),
+ { strict: true },
+ ),
+ (error) => {
+ assert.ok(error instanceof ElementResolutionError);
+ assert.equal(error.kind, "permanent");
+ assert.match(
+ error.message,
+ /\[id="73503e10-2be7-42d1-a053-c77402da1f80"\]/,
+ );
+ return true;
+ },
+ );
+});
+
+test("malformed role locators fail before raw CSS evaluation", async () => {
+ const cdp = new FakeCDP(async () => {
+ throw new Error("malformed role locator must not reach CDP");
+ });
+
+ await assert.rejects(
+ () =>
+ resolveElementObjectId(
+ cdp,
+ "session:page",
+ new RefMap(),
+ 'loc=role:button[name^="View flight details"]',
+ new Map(),
+ { strict: true },
+ ),
+ (error) => {
+ assert.ok(error instanceof ElementResolutionError);
+ assert.equal(error.kind, "permanent");
+ assert.match(error.message, /loc=role:<role>\[name="<exact name>"\]/);
+ assert.match(error.message, /text=\.\.\./);
+ return true;
+ },
+ );
+ assert.deepEqual(cdp.calls, []);
+});
+
test("text locators normalize whitespace and search nested open shadow roots", 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.ts
index 191945b..4ef5b7d 100644
--- a/package/ego-browser/src/element-resolver.ts
+++ b/package/ego-browser/src/element-resolver.ts
@@ -86,7 +86,7 @@ export async function resolveElementCenter(
return { ...boxModelCenter(result.model), sessionId: effectiveSessionId };
}
- const locator = parseLocator(selectorOrRef);
+ const locator = parseLocatorOrThrow(selectorOrRef);
if (locator) {
return resolveLocatorCenter(cdp, sessionId, locator, iframeSessions);
}
@@ -195,7 +195,7 @@ export async function resolveElementObjectId(
};
}
- const locator = parseLocator(selectorOrRef);
+ const locator = parseLocatorOrThrow(selectorOrRef);
if (locator) {
return resolveLocatorObjectId(
cdp,
@@ -413,12 +413,26 @@ async function rawSelectorCountError(cdp, contexts, selector, count) {
}
function invalidSelectorError(raw, result) {
+ const hint = numericCssIdHint(raw);
return new ElementResolutionError(
- `Invalid selector: ${raw}: ${exceptionText(result)}`,
+ `Invalid selector: ${raw}${hint ? `. ${hint}` : ""}: ${exceptionText(result)}`,
"permanent",
);
}
+function numericCssIdHint(raw) {
+ const value = String(raw || "").trim();
+ const prefix = value.startsWith("loc=css:")
+ ? "loc=css:"
+ : value.startsWith("css:")
+ ? "css:"
+ : "";
+ const match = /^#([0-9][A-Za-z0-9_-]*)$/.exec(value.slice(prefix.length));
+ if (!match) return undefined;
+ const selector = `[id=${JSON.stringify(match[1])}]`;
+ return `CSS ids beginning with a digit must be escaped; use ${prefix}${selector}`;
+}
+
function resolveFrameSession(frameId, sessionId, iframeSessions) {
if (!frameId) {
return sessionId;
@@ -1563,6 +1577,24 @@ function parseLocator(input) {
return null;
}
+function parseLocatorOrThrow(input) {
+ const locator = parseLocator(input);
+ if (locator) return locator;
+
+ const value = String(input || "").trim();
+ if (
+ value.startsWith("loc=") ||
+ value.startsWith("role:") ||
+ value.startsWith("text=")
+ ) {
+ throw new ElementResolutionError(
+ `Invalid locator: ${value}. Expected loc=role:<role>[name="<exact name>"], loc=css:<selector>, loc=href:<substring>, or text=... for text matching`,
+ "permanent",
+ );
+ }
+ return null;
+}
+
function parseLocatorName(raw) {
const trimmed = raw.trim();
if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 322fbba..840956b 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -57,6 +57,7 @@ function createFixture(rootDir) {
let timeoutNextLifecycleEvaluate = false;
let timeoutNextUrlEvaluate = false;
let waitFunctionResults = [];
+ let fetchFailure = null;
let nowMs = 1_000;
const pageEvents = new Map();
const networkSessions = new Set();
@@ -334,6 +335,16 @@ function createFixture(rootDir) {
};
}
if (params.functionDeclaration.includes("window.fetch")) {
+ if (fetchFailure) {
+ const message = fetchFailure;
+ fetchFailure = null;
+ return {
+ result: {
+ type: "object",
+ value: { fetchError: message },
+ },
+ };
+ }
const binary =
params.arguments?.[0]?.value?.responseType === "base64";
return {
@@ -668,6 +679,9 @@ function createFixture(rootDir) {
setWaitFunctionResults(results) {
waitFunctionResults = [...results];
},
+ failNextFetch(message) {
+ fetchFailure = message;
+ },
setSession(targetId, sessionId) {
sessionOverrides.set(targetId, sessionId);
},
@@ -977,6 +991,10 @@ test("Page.waitForFunction validates input and reports its timeout", async () =>
() => page.waitForFunction(() => true, undefined, { polling: 0 }),
/polling must be a positive number of milliseconds/,
);
+ await assert.rejects(
+ () => page.waitForFunction(() => false, { timeout: 60 }),
+ /options are the third argument.*pass undefined.*Expected: await page\.waitForFunction\(fnOrString, argument\?, \{ timeout\?, polling\? \}\)/,
+ );
});
});
@@ -1541,6 +1559,26 @@ test("Page fetch validates its JSON options and millisecond timeout", async () =
});
});
+test("Page fetch reports browser CORS failures without an evaluation wrapper", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/fetch");
+ fixture.failNextFetch(
+ 'page.fetch uses window.fetch and obeys browser CORS. Request "https://cdn.example.test/image.png" from "https://example.test" failed: TypeError: Failed to fetch',
+ );
+
+ await assert.rejects(
+ () => page.fetch("https://cdn.example.test/image.png"),
+ (error) => {
+ assert.match(error.message, /page\.fetch uses window\.fetch/);
+ assert.match(error.message, /obeys browser CORS/);
+ assert.doesNotMatch(error.message, /JavaScript evaluation failed/);
+ return true;
+ },
+ );
+ });
+});
+
test("Page fetch saves a binary response without converting it to text", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.ts
index 192a482..0519d01 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -93,7 +93,10 @@ import {
subscribeUnhandledPageNotices,
type UnhandledPageNotice,
} from "./page-discovery.js";
-import { validatePublicApiOptions } from "./public-api-schema.js";
+import {
+ publicApiEntry,
+ validatePublicApiOptions,
+} from "./public-api-schema.js";
import { parseRef, type RefMap } from "./ref-map.js";
import { state } from "./state.js";
@@ -198,7 +201,9 @@ type PageFetchPayload = {
responseType: "text" | "base64";
};
-type PageFetchResult = PageFetchResponse & { bodyBase64?: string };
+type PageFetchResult =
+ | (PageFetchResponse & { bodyBase64?: string })
+ | { fetchError: string };
type PageTarget = {
spaceId: number;
@@ -1409,6 +1414,17 @@ class Page {
argument?: unknown,
options: PageWaitForFunctionOptions = {},
): Promise<true> {
+ if (
+ arguments.length === 2 &&
+ typeof expression === "function" &&
+ expression.length === 0 &&
+ looksLikeWaitForFunctionOptions(argument)
+ ) {
+ const signature = publicApiEntry("Page.waitForFunction")?.signature;
+ throw new TypeError(
+ `page.waitForFunction options are the third argument; pass undefined when omitting the callback argument. Expected: ${signature}`,
+ );
+ }
validatePublicApiOptions("Page.waitForFunction", options);
// Passing `undefined` is how callers omit the optional argument while
// supplying the third options parameter, matching Playwright's shape.
@@ -1471,8 +1487,8 @@ class Page {
/**
* Run window.fetch inside this Page and return a CDP-serializable response.
- * Unlike a Node fetch, relative URLs, cookies, CORS, and service workers all
- * use the addressed document's browser context.
+ * Relative URLs, cookies, and service workers use the addressed document's
+ * browser context. Browser CORS still applies.
*/
async fetch(
url: string,
@@ -1491,6 +1507,9 @@ class Page {
payload,
payload.timeoutMs + 1_000,
);
+ if ("fetchError" in response) {
+ throw new Error(response.fetchError);
+ }
if (!saveAs) return response;
if (typeof response.bodyBase64 !== "string") {
throw new Error("page.fetch received no binary response body");
@@ -2411,7 +2430,7 @@ async function fetchInPage({
options,
timeoutMs,
responseType,
-}: PageFetchPayload): Promise<PageFetchResponse> {
+}: PageFetchPayload): Promise<PageFetchResult> {
const controller = new AbortController();
const timer = window.setTimeout(() => controller.abort(), timeoutMs);
try {
@@ -2441,14 +2460,37 @@ async function fetchInPage({
return { ...metadata, bodyBase64: btoa(binary) } as PageFetchResult;
} catch (error) {
if (controller.signal.aborted) {
- throw new Error(`page.fetch timed out after ${timeoutMs}ms`);
+ return { fetchError: `page.fetch timed out after ${timeoutMs}ms` };
+ }
+ let requestUrl = url;
+ try {
+ requestUrl = new URL(url, window.location.href).href;
+ } catch {
+ // Keep the caller's URL when it cannot be resolved in the Page.
}
- throw error;
+ const detail =
+ error instanceof Error
+ ? `${error.name}: ${error.message}`
+ : String(error);
+ return {
+ fetchError:
+ `page.fetch uses window.fetch and obeys browser CORS. ` +
+ `Request ${JSON.stringify(requestUrl)} from ${JSON.stringify(window.location.origin)} failed: ${detail}`,
+ };
} finally {
window.clearTimeout(timer);
}
}
+function looksLikeWaitForFunctionOptions(value: unknown): boolean {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
+ const keys = Object.keys(value);
+ return (
+ keys.length > 0 &&
+ keys.every((key) => key === "timeout" || key === "polling")
+ );
+}
+
function assertUrl(url: string): void {
if (typeof url !== "string" || url.length === 0) {
throw new TypeError("page URL must be a non-empty string");
diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.ts
index 51af73e..130c11f 100644
--- a/package/ego-browser/src/public-api-schema.ts
+++ b/package/ego-browser/src/public-api-schema.ts
@@ -295,7 +295,8 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
{
name: "Page.fetch",
signature: "await page.fetch(url, options?)",
- summary: "Run window.fetch in this Page and return a structured response.",
+ summary:
+ "Run window.fetch in this Page, obey browser CORS, and return a structured response.",
options: {
timeout,
saveAs: option(
diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.md
index f90bf6d..bb8c35b 100644
--- a/skills/ego-browser/SKILL.md
+++ b/skills/ego-browser/SKILL.md
@@ -117,19 +117,38 @@ callback or pass one JSON-serializable value as its second argument.
### Semantic pages: snapshot and selectors
-For an ordinary DOM page, use an observe → act → observe loop.
+Prefer snapshots and semantic selectors for ordinary DOM pages. Use screenshots
+and coordinates only when useful DOM semantics are unavailable.
+
+Before choosing an unfamiliar target, take a snapshot. When the next step
+depends on an action's result, keep the action, an expected-state wait, and the
+next snapshot in the same heredoc. Print the snapshot last so the next round
+can act on it directly. If no decision depends on intermediate states, batch
+deterministic actions and observe only after the last verified result.
+The final snapshot is the next round's starting view of the changed page;
+without it, that round usually has to spend a separate browser call observing
+before it can choose the next target.
+
+Wait for the expected result: use `waitForURL()` for navigation,
+`waitForSelector()` for element state, or `waitForFunction()` for application
+state. Avoid fixed delays when an observable condition exists. A snapshot
+captures the current moment; it does not wait for the page to become stable.
`page.snapshot()` captures the current viewport. For content outside it, use
`page.snapshot({ scope: "full_page" })`.
```js
+// Round 1: inspect and choose targets from this output.
const page = task.page("p1");
console.log(await page.snapshot());
+```
+```js
+// Next round: act using the previous output, verify, then prepare the next round.
+const page = task.page("p1");
await page.fill("@21", "[email protected]");
await page.click("loc=role:button[name='Sign in']");
-await page.selectOption("#country", "nl");
-await page.waitForSelector("loc=css:#account-home");
-await page.click("text=Save changes");
+await page.waitForSelector("loc=css:#account-home", { state: "visible" });
+console.log(await page.snapshot());
```
Element actions accept:
@@ -202,9 +221,11 @@ const rows = await page.evaluate(
);
```
-Use `page.cdp()` for Page, Runtime, DOM, Network, Input, and similar commands
-missing from the Page API; use `task.cdp()` for Target and Browser commands.
-Raw CDP invalidates refs. Do not persist `page.targetId` across rounds.
+Use documented Page methods first. If a wrapper is missing or does not work
+reliably on the current page, use `page.cdp()` as a lower-level path for
+diagnosis or control. It accepts Page, Runtime, DOM, Network, Input, and similar
+commands; use `task.cdp()` for Target and Browser commands. Raw CDP invalidates
+refs. Do not persist `page.targetId` across rounds.
## Action results, popups, and dialogs
@@ -230,8 +251,8 @@ await page.cdp("Page.handleJavaScriptDialog", { accept: true });
// Use accept: false to dismiss it.
```
-Use state-based waits to verify the application result; a receipt only describes
-the dispatched action and immediate popup or dialog observations.
+A receipt describes only the dispatched action and immediate popup or dialog
+observations; it does not verify the resulting application state.
## Files and requests
@@ -250,8 +271,8 @@ const chooser = await chooserPromise;
await chooser.setFiles("/absolute/path/report.pdf");
```
-Use `page.fetch()` for requests that need the Page's relative URL, cookies,
-CORS, or service worker. It returns
+`page.fetch()` runs `window.fetch()` in the Page: relative URLs, cookies, and
+service workers use that Page, and browser CORS still applies. It returns
`{ ok, status, statusText, url, headers, body }`:
```js
diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.md
index 96bd60d..68fd1b5 100644
--- a/skills/ego-browser/references/api.md
+++ b/skills/ego-browser/references/api.md
@@ -57,7 +57,7 @@ For an explicit popup wait, arm it before the action: `const popupPromise = page
| `await page.info()` | — | Read URL, title, viewport, scroll, and dialog state. |
| `await page.evaluate(fnOrString, argument?)` | — | Run JavaScript in this Page; callbacks receive JSON data but cannot capture Node.js variables. |
| `await page.waitForFunction(fnOrString, argument?, { timeout?, polling? })` | `timeout` — Maximum duration in milliseconds.<br>`polling` — Polling interval in milliseconds; defaults to 100. | Wait until a Page function or expression returns a truthy value. |
-| `await page.fetch(url, options?)` | `timeout` — Maximum duration in milliseconds.<br>`saveAs` — Write the response body to this path without text conversion.<br>`method` — HTTP method.<br>`headers` — Request headers.<br>`body` — Request body.<br>`cache` (default, no-store, reload, no-cache, force-cache, only-if-cached) — Fetch cache mode.<br>`credentials` (omit, same-origin, include) — Fetch credentials mode.<br>`integrity` — Subresource integrity value.<br>`keepalive` — Allow the request to outlive the page.<br>`mode` (cors, no-cors, same-origin) — Fetch request mode.<br>`redirect` (follow, error, manual) — Redirect handling mode.<br>`referrer` — Request referrer.<br>`referrerPolicy` — Request referrer policy. | Run window.fetch in this Page and return a structured response. |
+| `await page.fetch(url, options?)` | `timeout` — Maximum duration in milliseconds.<br>`saveAs` — Write the response body to this path without text conversion.<br>`method` — HTTP method.<br>`headers` — Request headers.<br>`body` — Request body.<br>`cache` (default, no-store, reload, no-cache, force-cache, only-if-cached) — Fetch cache mode.<br>`credentials` (omit, same-origin, include) — Fetch credentials mode.<br>`integrity` — Subresource integrity value.<br>`keepalive` — Allow the request to outlive the page.<br>`mode` (cors, no-cors, same-origin) — Fetch request mode.<br>`redirect` (follow, error, manual) — Redirect handling mode.<br>`referrer` — Request referrer.<br>`referrerPolicy` — Request referrer policy. | Run window.fetch in this Page, obey browser CORS, and return a structured response. |
| `await page.cdp(method, params?, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Send a CDP command through this Page's target session. |
| `await page.waitForSelector(selector, { timeout?, state? })` | `timeout` — Maximum duration in milliseconds.<br>`state` (attached, detached, visible, hidden) — Required element state. | Wait for an element state in this Page. |
| `await page.waitForLoadState(state, { timeout?, idleMs? })` | `timeout` — Maximum duration in milliseconds.<br>`idleMs` — Required network-idle window in milliseconds. | Wait for DOM content, load, or network-idle state. |