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 context diagnostics

Aute971d264ec15f
diff --git a/package/ego-browser/src/page-context-guard.ts b/package/ego-browser/src/page-context-guard.ts
index c0081d0..00e6b1f 100644
--- a/package/ego-browser/src/page-context-guard.ts
+++ b/package/ego-browser/src/page-context-guard.ts
@@ -1,18 +1,35 @@
-const PAGE_CONTEXT_HINT =
- "Page JavaScript must run inside page.evaluate(); document is not available in the Node.js script.";
+const PAGE_ONLY_GLOBALS = [
+ "document",
+ "innerHeight",
+ "innerWidth",
+ "localStorage",
+ "location",
+ "scrollX",
+ "scrollY",
+ "sessionStorage",
+ "window",
+] as const;
+const PAGE_ONLY_GLOBAL_NAMES = new Set<string>(PAGE_ONLY_GLOBALS);
+
+function pageContextHint(globalName: string): string {
+ return (
+ `The heredoc runs in Node.js, not in the Page. ${globalName} is a Page global. ` +
+ "Put browser-side code inside page.evaluate(), for example page.evaluate(() => ...); " +
+ "keep Node.js work outside it."
+ );
+}
/** Add one actionable hint to the common Node-versus-Page context mistake. */
export function addPageContextHint(error: unknown): unknown {
- if (
- !(error instanceof ReferenceError) ||
- !/^document is not defined\.?$/i.test(error.message.trim())
- ) {
- return error;
- }
+ if (!(error instanceof ReferenceError)) return error;
+ const match = /^([A-Za-z_$][\w$]*) is not defined\.?$/i.exec(
+ error.message.trim(),
+ );
+ if (!match || !PAGE_ONLY_GLOBAL_NAMES.has(match[1])) return error;
if (error.message.includes("page.evaluate()")) return error;
const originalMessage = error.message;
- error.message = `${originalMessage}. ${PAGE_CONTEXT_HINT}`;
+ error.message = `${originalMessage}. ${pageContextHint(match[1])}`;
if (typeof error.stack === "string") {
const lines = error.stack.split("\n");
lines[0] = `${error.name}: ${error.message}`;
@@ -26,12 +43,19 @@ export function addPageContextHint(error: unknown): unknown {
* though it, rather than ego-browser's CLI wrapper, executes the heredoc.
*/
export function installPageContextGuard(target: Record<string, unknown>): void {
- if (Object.getOwnPropertyDescriptor(target, "document")) return;
- Object.defineProperty(target, "document", {
- configurable: true,
- enumerable: false,
- get() {
- throw new ReferenceError(`document is not defined. ${PAGE_CONTEXT_HINT}`);
- },
- });
+ for (const globalName of PAGE_ONLY_GLOBALS) {
+ // Defining `window` would change normal Node.js checks such as
+ // `typeof window`, so only the CLI wrapper enriches that error.
+ if (globalName === "window") continue;
+ if (Object.getOwnPropertyDescriptor(target, globalName)) continue;
+ Object.defineProperty(target, globalName, {
+ configurable: true,
+ enumerable: false,
+ get() {
+ throw new ReferenceError(
+ `${globalName} is not defined. ${pageContextHint(globalName)}`,
+ );
+ },
+ });
+ }
}
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 840956b..7c9844e 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -138,8 +138,12 @@ function createFixture(rootDir) {
if (params.expression.includes("__egoWaitForFunction")) {
return {
result: {
- type: "boolean",
- value: waitFunctionResults.shift() ?? false,
+ type: "object",
+ value: {
+ matched: waitFunctionResults.shift() ?? false,
+ url: tab.url,
+ title: tab.title,
+ },
},
};
}
@@ -973,7 +977,18 @@ test("Page.waitForFunction validates input and reports its timeout", async () =>
timeout: 60,
polling: 25,
}),
- /page\.waitForFunction timed out after 60ms/,
+ (error) => {
+ assert.match(
+ error.message,
+ /page\.waitForFunction timed out after 60ms/,
+ );
+ assert.match(error.message, /page p1/);
+ assert.match(
+ error.message,
+ /last URL was "https:\/\/example\.test\/first"/,
+ );
+ return true;
+ },
);
await assert.rejects(
() => page.waitForFunction(42),
@@ -998,6 +1013,30 @@ test("Page.waitForFunction validates input and reports its timeout", async () =>
});
});
+test("Page.waitForFunction timeout points to an unhandled popup", async () => {
+ await withFixture(async (fixture) => {
+ resetPageNotices();
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/source");
+ fixture.openPopupOnNextClick("https://example.test/popup");
+ await page.click("#open-popup");
+
+ await assert.rejects(
+ () =>
+ page.waitForFunction(() => false, undefined, {
+ timeout: 60,
+ polling: 25,
+ }),
+ (error) => {
+ assert.match(error.message, /popup p2 opened from p1/i);
+ assert.match(error.message, /task\.page\("p2"\)/);
+ assert.match(error.message, /before retrying the preceding action/i);
+ return true;
+ },
+ );
+ });
+});
+
test("Page.evaluate explains that its callback cannot capture Node variables", 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 0519d01..7dff0a9 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -1447,6 +1447,8 @@ class Page {
return this.#services.gate.withPage(page, async ({ sessionId }) => {
await this.#activate(page.targetId);
const deadline = this.#services.now() + timeoutMs;
+ let lastUrl = "";
+ let lastTitle = "";
try {
while (this.#services.now() <= deadline) {
const remaining = Math.max(1, deadline - this.#services.now());
@@ -1461,7 +1463,12 @@ class Page {
sessionId,
Math.min(1_000, remaining),
);
- if (runtimeValue(response, source) === true) return true as const;
+ const state = runtimeValue(response, source);
+ if (isWaitForFunctionState(state)) {
+ lastUrl = state.url;
+ lastTitle = state.title;
+ if (state.matched) return true as const;
+ }
} catch (error) {
if (!isRetryablePageEvaluationError(error)) {
throw enrichPageCallbackReferenceError(
@@ -1481,7 +1488,13 @@ class Page {
// guaranteed to identify the same elements.
this.#services.pageRefs.clear(page.targetId);
}
- throw new Error(`page.waitForFunction timed out after ${timeoutMs}ms`);
+ throw waitForFunctionTimeoutError(
+ this.spaceId,
+ this.label,
+ timeoutMs,
+ lastUrl,
+ lastTitle,
+ );
});
}
@@ -2349,11 +2362,44 @@ function waitForFunctionExpression(
serializedArgument: unknown,
): string {
if (typeof expression === "string") {
- return `(async function __egoWaitForFunction() { return Boolean(await (${expression})); })()`;
+ return `(async function __egoWaitForFunction() { return { matched: Boolean(await (${expression})), url: location.href, title: document.title }; })()`;
}
const source = expression.toString();
const argument = hasArgument ? JSON.stringify(serializedArgument) : "";
- return `(async function __egoWaitForFunction() { return Boolean(await (${source})(${argument})); })()`;
+ return `(async function __egoWaitForFunction() { return { matched: Boolean(await (${source})(${argument})), url: location.href, title: document.title }; })()`;
+}
+
+function isWaitForFunctionState(
+ value: unknown,
+): value is { matched: boolean; url: string; title: string } {
+ if (!value || typeof value !== "object") return false;
+ const state = value as Record<string, unknown>;
+ return (
+ typeof state.matched === "boolean" &&
+ typeof state.url === "string" &&
+ typeof state.title === "string"
+ );
+}
+
+function waitForFunctionTimeoutError(
+ spaceId: number,
+ pageLabel: string,
+ timeoutMs: number,
+ lastUrl: string,
+ lastTitle: string,
+): Error {
+ const title = lastTitle
+ ? `; last title was ${JSON.stringify(lastTitle)}`
+ : "";
+ const popup = peekUnhandledPageNotices().find(
+ (notice) => notice.spaceId === spaceId && notice.openerLabel === pageLabel,
+ );
+ const popupHint = popup
+ ? ` Popup ${popup.label} opened from ${pageLabel} at ${JSON.stringify(popup.url)}; inspect task.page(${JSON.stringify(popup.label)}) before retrying the preceding action.`
+ : "";
+ return new Error(
+ `page.waitForFunction timed out after ${timeoutMs}ms on page ${pageLabel}; last URL was ${JSON.stringify(lastUrl)}${title}.${popupHint}`,
+ );
}
function isRetryablePageEvaluationError(error: unknown): boolean {
diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.ts
index 130c11f..1399e14 100644
--- a/package/ego-browser/src/public-api-schema.ts
+++ b/package/ego-browser/src/public-api-schema.ts
@@ -511,7 +511,8 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
{
name: "Page.mouse.wheel",
signature: "await page.mouse.wheel(deltaX, deltaY)",
- summary: "Send a wheel event at the current Page position.",
+ summary:
+ "Send a wheel event at the current Page position; move or click over the intended scroll container first in each process.",
},
{
name: "Page.keyboard.down",
diff --git a/package/ego-browser/src/run-output-sink.test.mjs b/package/ego-browser/src/run-output-sink.test.mjs
index ea240bc..4ba42cc 100644
--- a/package/ego-browser/src/run-output-sink.test.mjs
+++ b/package/ego-browser/src/run-output-sink.test.mjs
@@ -266,13 +266,27 @@ test("an ordinary uncaught error still flushes the output logged before it", asy
assert.equal(result.stdout, "partial result\n");
});
-test("a top-level document ReferenceError explains the Page execution boundary", async () => {
- const result = await runScript(`console.log(document.body);`);
-
- assert.ok(result.error, "expected runMain to reject");
- assert.match(result.error.message, /document is not defined/i);
- assert.match(result.error.message, /page\.evaluate\(\)/i);
-});
+for (const [globalName, expression] of [
+ ["document", "document.body"],
+ ["window", "window.scrollY"],
+ ["location", "location.href"],
+ ["scrollY", "scrollY"],
+]) {
+ test(`a top-level ${globalName} ReferenceError explains the Node and Page execution boundary`, async () => {
+ const result = await runScript(`console.log(${expression});`);
+
+ assert.ok(result.error, "expected runMain to reject");
+ assert.match(
+ result.error.message,
+ new RegExp(`${globalName} is not defined`, "i"),
+ );
+ assert.match(
+ result.error.message,
+ /heredoc runs in Node\.js, not in the Page/i,
+ );
+ assert.match(result.error.message, /page\.evaluate\(\)/i);
+ });
+}
test("a syntax error points to the invalid user-script line", async () => {
const result = await runScript(`
diff --git a/package/ego-browser/src/sdk-lifecycle.test.mjs b/package/ego-browser/src/sdk-lifecycle.test.mjs
index f49098c..3a7fd87 100644
--- a/package/ego-browser/src/sdk-lifecycle.test.mjs
+++ b/package/ego-browser/src/sdk-lifecycle.test.mjs
@@ -50,17 +50,25 @@ test("disposeEgoSdk releases native callbacks and rejects pending CDP work", ()
assert.match(result.stderr, /sdk lifecycle ok/);
});
-test("the embedded SDK explains that document belongs inside Page.evaluate", () => {
+test("the embedded SDK explains that browser globals belong inside Page.evaluate", () => {
const sdkUrl = new URL("../dist/src/index.js", import.meta.url).href;
const script = `
globalThis.ego = {};
await import(${JSON.stringify(sdkUrl)});
- try {
- document.body;
- throw new Error("document guard did not run");
- } catch (error) {
- if (!/document is not defined/i.test(error.message)) throw error;
- if (!/page\\.evaluate\\(\\)/i.test(error.message)) throw error;
+ const checks = [
+ ["document", () => document.body],
+ ["location", () => location.href],
+ ["scrollY", () => scrollY],
+ ];
+ for (const [name, read] of checks) {
+ try {
+ read();
+ throw new Error(name + " guard did not run");
+ } catch (error) {
+ if (!error.message.includes(name + " is not defined")) throw error;
+ if (!/heredoc runs in Node\.js, not in the Page/i.test(error.message)) throw error;
+ if (!/page\\.evaluate\\(\\)/i.test(error.message)) throw error;
+ }
}
`;
const result = spawnSync(
diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.md
index bb8c35b..ff25710 100644
--- a/skills/ego-browser/SKILL.md
+++ b/skills/ego-browser/SKILL.md
@@ -24,9 +24,10 @@ console.log(await page.snapshot());
EOF
```
-The heredoc runs in Node.js with the browser APIs preloaded. Use them directly;
-run page JavaScript inside `page.evaluate()`. Do not import Playwright or launch
-another browser.
+The heredoc always runs in Node.js, not in the web Page. Browser helpers and
+Node.js APIs belong in the heredoc; Page globals such as `window`, `document`,
+`location`, and DOM APIs do not. Put browser-side JavaScript inside
+`page.evaluate()`. Do not import Playwright or launch another browser.
The Node.js runtime uses ESM. When a script needs local files, load built-ins
with dynamic imports such as `await import("node:fs/promises")`.
@@ -111,9 +112,10 @@ them. Supported Page API:
- Page code and protocols: `evaluate(fnOrString, argument)`,
`fetch(url, options)`, `cdp(method, params, options)`
-`page.evaluate()` callbacks run inside the Page, so they cannot read variables
-from the surrounding Node.js script. Define browser-side helpers inside the
-callback or pass one JSON-serializable value as its second argument.
+This boundary is strict. `page.evaluate()` callbacks run only inside the Page;
+they cannot read variables or Node.js modules from the surrounding heredoc.
+Define browser-side helpers inside the callback or pass one JSON-serializable
+value as its second argument.
### Semantic pages: snapshot and selectors
@@ -190,6 +192,8 @@ console.log({ screenshot: path });
Inspect the screenshot with an image-viewing tool. Coordinates use CSS pixels;
keyboard names and `+`-separated chords follow Playwright syntax. Use
`ControlOrMeta` for portable shortcuts and verify the resulting page state.
+`mouse.wheel()` sends the event at the current mouse position. In each heredoc,
+move or click over the intended scrollable area before using it.
`keyboard.paste()` sends the native paste shortcut and then restores the user's
clipboard. Pass `{ text, html }` when a rich editor needs structured clipboard
@@ -202,8 +206,10 @@ await page.keyboard.paste({
});
```
-For rich-text editors and editable grids, validate a small edit and its result
-before repeating it at scale.
+For rich-text editors and editable grids, validate a small edit before repeating
+it at scale. Canvas-backed editors may not expose visible content through DOM
+text or selectors; verify those results with a screenshot or an
+application-specific visible state.
### Page JavaScript and CDP
diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.md
index 68fd1b5..c6e22bd 100644
--- a/skills/ego-browser/references/api.md
+++ b/skills/ego-browser/references/api.md
@@ -76,13 +76,13 @@ For an explicit popup wait, arm it before the action: `const popupPromise = page
## Page.mouse
-| API | Options | Purpose |
-| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- |
-| `await page.mouse.click(x, y, { button?, clickCount?, delay? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Number of clicks.<br>`delay` — Input delay in milliseconds. | Click CSS-pixel coordinates with native CDP input. |
-| `await page.mouse.move(x, y, { steps? })` | `steps` — Number of movement steps. | Move the mouse to CSS-pixel coordinates. |
-| `await page.mouse.down({ button?, clickCount? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Click count reported to the page. | Press a mouse button at the current Page position. |
-| `await page.mouse.up({ button?, clickCount? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Click count reported to the page. | Release a mouse button at the current Page position. |
-| `await page.mouse.wheel(deltaX, deltaY)` | — | Send a wheel event at the current Page position. |
+| API | Options | Purpose |
+| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
+| `await page.mouse.click(x, y, { button?, clickCount?, delay? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Number of clicks.<br>`delay` — Input delay in milliseconds. | Click CSS-pixel coordinates with native CDP input. |
+| `await page.mouse.move(x, y, { steps? })` | `steps` — Number of movement steps. | Move the mouse to CSS-pixel coordinates. |
+| `await page.mouse.down({ button?, clickCount? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Click count reported to the page. | Press a mouse button at the current Page position. |
+| `await page.mouse.up({ button?, clickCount? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Click count reported to the page. | Release a mouse button at the current Page position. |
+| `await page.mouse.wheel(deltaX, deltaY)` | — | Send a wheel event at the current Page position; move or click over the intended scroll container first in each process. |
## Page.keyboard