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
feat(ego-browser): add navigation wait states
Aute2e2b98c2f694
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-load-states.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-load-states.mjsindex 8bb308b..d27d3fc 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-load-states.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-load-states.mjs@@ -2,11 +2,30 @@ export function pageLoadStatesCase() {return `const task = await taskSpace(taskName);const page = await task.openPage("about:blank", { as: "page-load-states" });- await page.cdp("Page.navigate", {- url: baseUrl + "/domcontentloaded-page?ms=1500",+ const referer = baseUrl + "/navigation-source";+ await page.goto(baseUrl + "/streamed-page?ms=1000", {+ referer,+ waitUntil: "commit",+ timeout: 1_000,});+ const afterCommit = await page.evaluate(() => ({+ marker: document.documentElement.dataset.committed,+ readyState: document.readyState,+ referer: document.referrer,+ }));+ assertEqual(afterCommit.marker, "true", "commit waits for the new document");+ assertEqual(+ afterCommit.readyState,+ "loading",+ "commit returns before the streamed document finishes loading"+ );+ assertEqual(afterCommit.referer, referer, "goto forwards the referer header");+ await page.waitForLoadState("load", { timeout: 2_000 });- await page.waitForLoadState("domcontentloaded", { timeout: 1_000 });+ await page.goto(baseUrl + "/domcontentloaded-page?ms=1500", {+ waitUntil: "domcontentloaded",+ timeout: 1_000,+ });const afterDomContentLoaded = await page.evaluate(() => ({marker: document.documentElement.dataset.domContentLoaded,readyState: document.readyState,diff --git a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs b/package/ego-browser/scripts/real-browser-e2e/fixture.mjsindex e83636a..516252c 100644--- a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs@@ -194,6 +194,17 @@ export async function startFixtureServer(taskName) {}, delayMs);return;}+ if (url.pathname === "/streamed-page") {+ const delayMs = Number(url.searchParams.get("ms") || 1000);+ res.writeHead(200, { "content-type": "text/html" });+ res.write(`<!doctype html><html><head><title>Streamed fixture</title></head>+ <body><h1 id="commit-marker">document committed</h1>+ <script>document.documentElement.dataset.committed = "true";</script>`);+ setTimeout(() => {+ res.end("</body></html>");+ }, delayMs);+ return;+ }if (url.pathname === "/domcontentloaded-page") {const delayMs = Number(url.searchParams.get("ms") || 1500);res.writeHead(200, { "content-type": "text/html" });diff --git a/package/ego-browser/src/driver/page-waits.ts b/package/ego-browser/src/driver/page-waits.tsindex 78d2494..d5a373a 100644--- a/package/ego-browser/src/driver/page-waits.ts+++ b/package/ego-browser/src/driver/page-waits.ts@@ -27,6 +27,18 @@ export type PageWaitForLoadStateOptions = {idleMs?: number;};+export type PageGotoWaitUntil =+ | "commit"+ | "domcontentloaded"+ | "load"+ | "networkidle";++export type PageNavigationOptions = {+ timeoutMs: number;+ waitUntil: PageGotoWaitUntil;+ referer?: string;+};+export type PageWaitForURLOptions = {timeout?: number;};@@ -168,6 +180,150 @@ export async function waitForURLInPage();}+/** Navigate one Page and wait for the selected state of this navigation. */+export async function navigateInPage(+ services: PageWaitServices,+ sessionId: string,+ url: string,+ options: PageNavigationOptions,+): Promise<void> {+ const { timeoutMs, waitUntil, referer } = options;+ const deadline = services.now() + timeoutMs;+ const ownsNetworkDomain =+ waitUntil === "networkidle" && !services.isNetworkDomainEnabled(sessionId);+ let enabledNetworkDomain = false;+ try {+ // Network tracking must start before Page.navigate or the initial document+ // requests can be missed by a network-idle wait.+ if (ownsNetworkDomain) {+ await services.cdp(+ "Network.enable",+ {},+ sessionId,+ navigationTimeRemaining(services, deadline, timeoutMs, waitUntil),+ );+ enabledNetworkDomain = true;+ }+ const response = await services.cdp(+ "Page.navigate",+ {+ url,+ ...(referer === undefined ? {} : { referrer: referer }),+ },+ sessionId,+ navigationTimeRemaining(services, deadline, timeoutMs, waitUntil),+ );+ const navigation = response?.result || response || {};+ if (navigation.errorText) {+ throw new Error(`page.goto failed: ${navigation.errorText}`);+ }+ if (navigation.isDownload === true) {+ throw new Error("page.goto failed: navigation started a download");+ }++ await waitForNavigationCommit(+ services,+ sessionId,+ navigation,+ deadline,+ timeoutMs,+ waitUntil,+ );+ if (waitUntil === "commit") return;++ await waitForLoadStateInPage(services, sessionId, waitUntil, {+ timeout: navigationTimeRemaining(+ services,+ deadline,+ timeoutMs,+ waitUntil,+ ),+ });+ } catch (error) {+ if (services.now() >= deadline || isLoadStateTimeout(error)) {+ throw navigationTimeout(timeoutMs, waitUntil);+ }+ throw error;+ } finally {+ if (enabledNetworkDomain) {+ await services.cdp("Network.disable", {}, sessionId).catch(() => {});+ }+ }+}++async function waitForNavigationCommit(+ services: PageWaitServices,+ sessionId: string,+ navigation: { frameId?: string; loaderId?: string },+ deadline: number,+ timeoutMs: number,+ waitUntil: PageGotoWaitUntil,+): Promise<void> {+ // CDP omits loaderId for a same-document navigation. Page.navigate has+ // already committed that URL change, and the existing document has already+ // passed its DOMContentLoaded and load boundaries.+ if (!navigation.loaderId) return;++ while (services.now() <= deadline) {+ const remaining = navigationTimeRemaining(+ services,+ deadline,+ timeoutMs,+ waitUntil,+ );+ try {+ const response = await services.cdp(+ "Page.getFrameTree",+ {},+ sessionId,+ Math.min(1_000, remaining),+ );+ const frame =+ response?.result?.frameTree?.frame || response?.frameTree?.frame;+ if (+ frame?.loaderId === navigation.loaderId &&+ (!navigation.frameId || frame?.id === navigation.frameId)+ ) {+ return;+ }+ } catch (error) {+ if (!isCdpTimeout(error, "Page.getFrameTree")) throw error;+ }+ const waitMs = deadline - services.now();+ if (waitMs <= 0) break;+ await services.sleep(Math.min(50, waitMs));+ }+ throw navigationTimeout(timeoutMs, waitUntil);+}++function navigationTimeRemaining(+ services: PageWaitServices,+ deadline: number,+ timeoutMs: number,+ waitUntil: PageGotoWaitUntil,+): number {+ const remaining = deadline - services.now();+ if (remaining <= 0) throw navigationTimeout(timeoutMs, waitUntil);+ return remaining;+}++function navigationTimeout(+ timeoutMs: number,+ waitUntil: PageGotoWaitUntil,+): Error {+ return new Error(+ `page.goto timed out after ${timeoutMs}ms waiting for ${waitUntil}`,+ );+}++function isLoadStateTimeout(error: unknown): boolean {+ return (+ error instanceof Error &&+ error.message.startsWith("page.waitForLoadState(") &&+ error.message.includes(" timed out")+ );+}+/** Wait for document load or network idle inside one Page session. */export async function waitForLoadStateInPage(services: PageWaitServices,@@ -224,11 +380,16 @@ async function waitForDocumentReadyState(Math.min(1_000, remaining),);} catch (error) {- // The final probe uses the remaining wait budget as its CDP timeout. If- // that probe consumes the budget, expose the stable Page-level timeout- // instead of leaking an implementation-detail Runtime.evaluate error.- if (isRuntimeEvaluateTimeout(error) && services.now() >= deadline) break;- throw error;+ // A document swap can briefly invalidate the execution context. Retry+ // those transitions and individual probe timeouts within the Page-level+ // wait budget instead of leaking a CDP implementation detail.+ if (+ !isRuntimeEvaluateTimeout(error) &&+ !isTransientNavigationContextError(error)+ ) {+ throw error;+ }+ if (services.now() >= deadline) break;}const value = response?.result?.value;if (state === "load" && value === "complete") return;@@ -249,6 +410,13 @@ function isRuntimeEvaluateTimeout(error: unknown): boolean {);}+function isCdpTimeout(error: unknown, method: string): boolean {+ return (+ error instanceof Error &&+ error.message.includes(`CDP request timed out: ${method}`)+ );+}+function isTransientNavigationContextError(error: unknown): boolean {if (!(error instanceof Error)) return false;return (diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjsindex a02c344..b2a56b1 100644--- a/package/ego-browser/src/page-model.test.mjs+++ b/package/ego-browser/src/page-model.test.mjs@@ -968,6 +968,118 @@ test("a page label restores in a new round and goto reuses its target", async ()});});+test("Page.goto accepts Playwright-style navigation options", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await task.openPage("https://example.test/first");+ fixture.setDocumentLifecycle({+ readyState: "interactive",+ domContentLoaded: true,+ });++ await page.goto("https://example.test/second", {+ referer: "https://example.test/source",+ timeout: 250,+ waitUntil: "domcontentloaded",+ });++ const navigation = fixture.calls.find(+ ([kind, method]) => kind === "cdp" && method === "Page.navigate",+ );+ assert.deepEqual(navigation.slice(2, 4), [+ {+ url: "https://example.test/second",+ referrer: "https://example.test/source",+ },+ "session:target-1",+ ]);+ });+});++test("Page.goto commit waits for this navigation without waiting for the DOM", async () => {+ await withFixture(async (fixture) => {+ const baseCdp = fixture.services.cdp;+ let nowMs = 5_000;+ let committed = false;+ let commitChecks = 0;+ const task = taskForRound(fixture, "round-a", {+ async cdp(method, params, sessionId, timeoutMs) {+ if (method === "Page.navigate") {+ await baseCdp(method, params, sessionId, timeoutMs);+ return {+ result: { frameId: "frame-1", loaderId: "loader-new" },+ };+ }+ if (method === "Page.getFrameTree") {+ commitChecks += 1;+ return {+ result: {+ frameTree: {+ frame: {+ id: "frame-1",+ loaderId: committed ? "loader-new" : "loader-old",+ },+ },+ },+ };+ }+ return baseCdp(method, params, sessionId, timeoutMs);+ },+ now: () => nowMs,+ async sleep(ms) {+ nowMs += ms;+ committed = true;+ },+ });+ const page = await task.openPage("https://example.test/first");+ fixture.setDocumentLifecycle({+ readyState: "loading",+ domContentLoaded: false,+ });+ const callsBeforeGoto = fixture.calls.length;++ await page.goto("https://example.test/second", {+ timeout: 250,+ waitUntil: "commit",+ });++ assert.equal(commitChecks, 2);+ assert.equal(+ fixture.calls+ .slice(callsBeforeGoto)+ .some(+ ([kind, method]) => kind === "cdp" && method === "Runtime.evaluate",+ ),+ false,+ "commit must not wait for DOM readiness",+ );+ });+});++test("Page.goto starts network tracking before a network-idle navigation", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await task.openPage("https://example.test/first");+ const callsBeforeGoto = fixture.calls.length;++ await page.goto("https://example.test/second", {+ timeout: 1_000,+ waitUntil: "networkidle",+ });++ const methods = fixture.calls+ .slice(callsBeforeGoto)+ .filter(([kind]) => kind === "cdp")+ .map(([, method]) => method);+ assert(+ methods.indexOf("Network.enable") < methods.indexOf("Page.navigate"),+ );+ assert(+ methods.lastIndexOf("Network.disable") > methods.indexOf("Page.navigate"),+ );+ });+});+test("openPage waits for the document created by this call, not an already-complete placeholder", async () => {await withFixture(async (fixture) => {const requestedUrl = "https://example.test/created-document";diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.tsindex b521bc4..04e9553 100644--- a/package/ego-browser/src/page-model.ts+++ b/package/ego-browser/src/page-model.ts@@ -54,9 +54,11 @@ import {type PageKeyboardTypeOptions,} from "./driver/page-keyboard.js";import {+ navigateInPage,waitForLoadStateInPage,waitForSelectorInPage,waitForURLInPage,+ type PageGotoWaitUntil,type PageWaitForLoadStateOptions,type PageWaitForSelectorOptions,type PageWaitForURLOptions,@@ -114,7 +116,9 @@ type AdoptPageOptions = {};type PageGotoOptions = {+ referer?: string;timeout?: number;+ waitUntil?: PageGotoWaitUntil;};type PageSnapshotOptions = SnapshotOptions;@@ -1233,20 +1237,16 @@ class Page {assertUrl(url);validatePublicApiOptions("Page.goto", options);const timeoutMs = options.timeout ?? 15_000;+ const waitUntil = options.waitUntil ?? "load";const page = await this.#resolve();const { receipt } = await this.#runActionBoundary(page,async (sessionId) => {- const navigation = await this.#services.cdp(- "Page.navigate",- { url },- sessionId,+ await navigateInPage(this.#services, sessionId, url, {+ referer: options.referer,timeoutMs,- );- if (navigation?.errorText) {- throw new Error(`page.goto failed: ${navigation.errorText}`);- }- await waitForReadyState(this.#services, sessionId, timeoutMs);+ waitUntil,+ });},);return receipt;@@ -2269,29 +2269,6 @@ function isBrowserPlaceholderUrl(url: string): boolean {);}-async function waitForReadyState(- services: PageModelServices,- sessionId: string,- timeoutMs: number,-): Promise<void> {- const deadline = services.now() + timeoutMs;- while (services.now() <= deadline) {- const remaining = Math.max(1, deadline - services.now());- const response = await services.cdp(- "Runtime.evaluate",- {- expression: "document.readyState",- returnByValue: true,- },- sessionId,- Math.min(1_000, remaining),- );- if (response?.result?.value === "complete") return;- await services.sleep(Math.min(100, remaining));- }- throw new Error(`page.goto timed out after ${timeoutMs}ms`);-}-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.test.mjs b/package/ego-browser/src/public-api-schema.test.mjsindex f503485..922358f 100644--- a/package/ego-browser/src/public-api-schema.test.mjs+++ b/package/ego-browser/src/public-api-schema.test.mjs@@ -42,6 +42,17 @@ test("schema-driven option validation rejects unknown and invalid fields", () =>force: true,timeout: 500,});+ for (const waitUntil of [+ "commit",+ "domcontentloaded",+ "load",+ "networkidle",+ ]) {+ validatePublicApiOptions("Page.goto", {+ referer: "https://example.test/source",+ waitUntil,+ });+ }assert.throws(() => validatePublicApiOptions("taskSpace", { profileId: "" }),@@ -55,6 +66,10 @@ test("schema-driven option validation rejects unknown and invalid fields", () =>() => validatePublicApiOptions("Page.goto", { timeout: 0 }),/timeout must be a positive number of milliseconds/,);+ assert.throws(+ () => validatePublicApiOptions("Page.goto", { waitUntil: "interactive" }),+ /waitUntil must be one of commit, domcontentloaded, load, networkidle/,+ );assert.throws(() => validatePublicApiOptions("Page.click", { button: "primary" }),/button must be one of left, middle, right/,@@ -69,6 +84,10 @@ test("the generated reference contains signatures and option descriptions", () =markdown,/`await task\.openPage\(url, \{ as\?, timeout\? \}\)`/,);+ assert.match(+ markdown,+ /`await page\.goto\(url, \{ referer\?, timeout\?, waitUntil\? \}\)`/,+ );assert.match(markdown, /`as` — Permanent Page label\.<br>`timeout`/);assert.match(markdown, /Open and durably label a new Page/);assert.match(diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.tsindex 3576084..18e0424 100644--- a/package/ego-browser/src/public-api-schema.ts+++ b/package/ego-browser/src/public-api-schema.ts@@ -192,9 +192,20 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [},{name: "Page.goto",- signature: "await page.goto(url, { timeout? })",+ signature: "await page.goto(url, { referer?, timeout?, waitUntil? })",summary: "Navigate this Page in place.",- options: { timeout },+ options: {+ referer: option(+ "nonEmptyString",+ "HTTP Referer header for the navigation.",+ ),+ timeout,+ waitUntil: option(+ "string",+ "Completion state; defaults to load. networkidle requires 500ms without network activity.",+ ["commit", "domcontentloaded", "load", "networkidle"],+ ),+ },},{name: "Page.snapshot",diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.mdindex e61d7cc..28ba350 100644--- a/skills/ego-browser/references/api.md+++ b/skills/ego-browser/references/api.md@@ -43,7 +43,7 @@ High-level Page actions return a receipt that may contain `popups` or a synchron| `page.spaceId` | — | Numeric identifier of the Page's task space. || `page.openedBy` | — | Conservative origin attribution for this Page. || `page.targetId` | — | Internal browser target identifier for advanced Target-domain CDP only. |-| `await page.goto(url, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Navigate this Page in place. |+| `await page.goto(url, { referer?, timeout?, waitUntil? })` | `referer` — HTTP Referer header for the navigation.<br>`timeout` — Maximum duration in milliseconds.<br>`waitUntil` (commit, domcontentloaded, load, networkidle) — Completion state; defaults to load. networkidle requires 500ms without network activity. | Navigate this Page in place. || `await page.snapshot({ scope?, includeActionMarks?, includeStableLocator? })` | `scope` (full_page, only_within_viewport) — Snapshot scope; defaults to only_within_viewport.<br>`includeActionMarks` — Include action marks.<br>`includeStableLocator` — Include stable locators. | Return a semantic snapshot of the current viewport with Page provenance. || `await page.screenshot({ path?, fullPage?, clip?, raw? })` | `path` — Output path; missing parent directories are created.<br>`fullPage` — Capture the full scrollable page.<br>`clip` — CSS-pixel clipping rectangle.<br>`raw` — Bypass device-pixel-ratio correction. | Capture this Page to a PNG file. || `await page.url()` | — | Read this Page's current URL. |