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.

add page-scoped waits cdp and events

Aute508332f2023a
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 2cbaf0c..583d5ec 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
@@ -240,6 +240,36 @@ export function pageBasicOperationsCase() {
"function evaluate surfaces page exceptions"
);
+ const cdpTitle = await first.cdp(
+ "Runtime.evaluate",
+ { expression: "document.title", returnByValue: true },
+ { timeout: 2_000 }
+ );
+ assertEqual(cdpTitle.result.value, "ego-lite helper e2e", "page.cdp uses the addressed Page session");
+ const targetList = await task.cdp("Target.getTargets", {}, { timeout: 2_000 });
+ assert(Array.isArray(targetList.targetInfos), "task.cdp sends Target commands inside the task space");
+
+ await first.evaluate(() => {
+ setTimeout(() => {
+ const ready = document.createElement("button");
+ ready.id = "page-wait-ready";
+ ready.textContent = "Ready";
+ document.body.append(ready);
+ }, 75);
+ });
+ assertEqual(
+ await first.waitForSelector("#page-wait-ready", { timeout: 2_000, visible: true }),
+ true,
+ "page.waitForSelector uses milliseconds and the addressed Page"
+ );
+ await first.waitForLoadState("load", { timeout: 2_000 });
+ await first.waitForLoadState("networkidle", { timeout: 2_000, idleMs: 100 });
+
+ const firstEvents = await first.events();
+ const secondEvents = await second.events();
+ assert(Array.isArray(firstEvents), "page.events returns this Page's event buffer");
+ assert(Array.isArray(secondEvents), "a second Page has an independent event buffer");
+
await first.fill("#text-input", "page keyboard");
await first.evaluate(() => {
const input = document.querySelector("#text-input");
diff --git a/package/ego-browser/src/browser-runtime.test.mjs b/package/ego-browser/src/browser-runtime.test.mjs
index c9cb6ad..95d2996 100644
--- a/package/ego-browser/src/browser-runtime.test.mjs
+++ b/package/ego-browser/src/browser-runtime.test.mjs
@@ -1,7 +1,11 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { browserCdp, drainBrowserEvents } from "../dist/src/browser-runtime.js";
+import {
+ browserCdp,
+ drainBrowserEvents,
+ drainPageEvents,
+} from "../dist/src/browser-runtime.js";
// Gap A: ensureSession() calls the raw listTabs binding to attach a session.
// When the task is blocked it returns { error, error_code }; the result must
@@ -119,3 +123,50 @@ test("CDP events are drained only by the target session that received them", asy
}
}
});
+
+test("page event drains exclude unscoped browser events", async () => {
+ const previous = globalThis.ego;
+ const runtime = {
+ sendCDPMessage(payload) {
+ const request = JSON.parse(payload);
+ const result =
+ request.method === "Target.attachToTarget"
+ ? { sessionId: "session-page" }
+ : {};
+ queueMicrotask(() => {
+ runtime.onCDPMessage(JSON.stringify({ id: request.id, result }));
+ });
+ },
+ emit(event) {
+ runtime.onCDPMessage(JSON.stringify(event));
+ },
+ };
+ globalThis.ego = runtime;
+
+ try {
+ const attached = await browserCdp("Target.attachToTarget", {
+ targetId: "target-page",
+ flatten: true,
+ });
+ const sessionId = attached.result.sessionId;
+ runtime.emit({ method: "Target.targetCreated", params: { targetId: "x" } });
+ runtime.emit({
+ sessionId,
+ method: "Runtime.consoleAPICalled",
+ params: { value: "page" },
+ });
+
+ assert.deepEqual(
+ drainPageEvents(sessionId).map((event) => event.method),
+ ["Runtime.consoleAPICalled"],
+ );
+ assert.deepEqual(
+ drainBrowserEvents(sessionId).map((event) => event.method),
+ ["Target.targetCreated"],
+ "legacy drain still exposes unscoped browser events",
+ );
+ } finally {
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ }
+});
diff --git a/package/ego-browser/src/browser-runtime.ts b/package/ego-browser/src/browser-runtime.ts
index 5ec5f67..81350c2 100644
--- a/package/ego-browser/src/browser-runtime.ts
+++ b/package/ego-browser/src/browser-runtime.ts
@@ -287,6 +287,13 @@ export function drainBrowserEvents(sessionId = undefined) {
return out;
}
+/** Drain only events routed to one Page session. */
+export function drainPageEvents(sessionId) {
+ const targetId = sessionId ? sessionTargets.get(sessionId) : undefined;
+ const target = targetId ? targetStates.get(targetId) : undefined;
+ return target ? target.events.splice(0, target.events.length) : [];
+}
+
export function pendingDialog(sessionId) {
const targetId = sessionId
? sessionTargets.get(sessionId)
diff --git a/package/ego-browser/src/driver/page-waits.ts b/package/ego-browser/src/driver/page-waits.ts
new file mode 100644
index 0000000..231bf87
--- /dev/null
+++ b/package/ego-browser/src/driver/page-waits.ts
@@ -0,0 +1,204 @@
+import {
+ ElementResolutionError,
+ resolveElementObjectId,
+} from "../element-resolver.js";
+import { type RefMap } from "../ref-map.js";
+
+type PageWaitServices = {
+ cdp(
+ method: string,
+ params?: Record<string, unknown>,
+ sessionId?: string,
+ timeoutMs?: number,
+ ): Promise<any>;
+ drainEvents(sessionId: string): any[];
+ isNetworkDomainEnabled(sessionId: string): boolean;
+ now(): number;
+ sleep(ms: number): Promise<void>;
+};
+
+export type PageWaitForSelectorOptions = {
+ timeout?: number;
+ visible?: boolean;
+};
+
+export type PageWaitForLoadStateOptions = {
+ timeout?: number;
+ idleMs?: number;
+};
+
+const VISIBILITY_FUNCTION =
+ "function(){if(typeof this.checkVisibility==='function')return this.checkVisibility({checkOpacity:true,checkVisibilityCSS:true});const s=getComputedStyle(this);const r=this.getBoundingClientRect();return s.display!=='none'&&s.visibility!=='hidden'&&s.opacity!=='0'&&r.width>0&&r.height>0;}";
+
+/** Wait for a selector inside one explicit Page session. */
+export async function waitForSelectorInPage(
+ services: PageWaitServices,
+ sessionId: string,
+ refMap: RefMap,
+ selector: string,
+ options: PageWaitForSelectorOptions = {},
+): Promise<true> {
+ if (typeof selector !== "string" || selector.length === 0) {
+ throw new TypeError(
+ "page.waitForSelector selector must be a non-empty string",
+ );
+ }
+ const timeoutMs = options.timeout ?? 10_000;
+ assertPositiveMilliseconds(timeoutMs);
+ if (options.visible !== undefined && typeof options.visible !== "boolean") {
+ throw new TypeError("page.waitForSelector visible must be a boolean");
+ }
+
+ const deadline = services.now() + timeoutMs;
+ while (services.now() <= deadline) {
+ let resolved: { objectId: string; sessionId: string } | undefined;
+ try {
+ resolved = await resolveElementObjectId(
+ cdpAdapter(services),
+ sessionId,
+ refMap,
+ selector,
+ );
+ if (!options.visible) return true;
+ const response = await services.cdp(
+ "Runtime.callFunctionOn",
+ {
+ functionDeclaration: VISIBILITY_FUNCTION,
+ objectId: resolved.objectId,
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ resolved.sessionId,
+ );
+ if (response?.result?.value) return true;
+ } catch (error) {
+ if (
+ !(error instanceof ElementResolutionError) ||
+ error.kind !== "transient"
+ ) {
+ throw error;
+ }
+ } finally {
+ if (resolved?.objectId) {
+ await services
+ .cdp(
+ "Runtime.releaseObject",
+ { objectId: resolved.objectId },
+ resolved.sessionId,
+ )
+ .catch(() => {});
+ }
+ }
+ const remaining = deadline - services.now();
+ if (remaining <= 0) break;
+ await services.sleep(Math.min(100, remaining));
+ }
+ throw new Error(
+ `page.waitForSelector timed out after ${timeoutMs}ms: ${selector}`,
+ );
+}
+
+/** Wait for document load or network idle inside one Page session. */
+export async function waitForLoadStateInPage(
+ services: PageWaitServices,
+ sessionId: string,
+ state: "load" | "networkidle",
+ options: PageWaitForLoadStateOptions = {},
+): Promise<void> {
+ if (state !== "load" && state !== "networkidle") {
+ throw new TypeError(
+ 'page.waitForLoadState supports only "load" and "networkidle"',
+ );
+ }
+ const timeoutMs = options.timeout ?? 10_000;
+ assertPositiveMilliseconds(timeoutMs);
+ if (state === "load") {
+ await waitForDocumentLoad(services, sessionId, timeoutMs);
+ return;
+ }
+ const idleMs = options.idleMs ?? 500;
+ assertPositiveMilliseconds(idleMs, "idleMs");
+ await waitForNetworkIdle(services, sessionId, timeoutMs, idleMs);
+}
+
+async function waitForDocumentLoad(
+ services: PageWaitServices,
+ 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;
+ if (remaining <= 1) break;
+ await services.sleep(Math.min(100, remaining));
+ }
+ throw new Error(`page.waitForLoadState(load) timed out after ${timeoutMs}ms`);
+}
+
+async function waitForNetworkIdle(
+ services: PageWaitServices,
+ sessionId: string,
+ timeoutMs: number,
+ idleMs: number,
+): Promise<void> {
+ const ownsNetworkDomain = !services.isNetworkDomainEnabled(sessionId);
+ const deadline = services.now() + timeoutMs;
+ let lastActivityAt = services.now();
+ const inflight = new Set<string>();
+ await services.cdp("Network.enable", {}, sessionId);
+ try {
+ while (services.now() <= deadline) {
+ for (const event of services.drainEvents(sessionId)) {
+ const method = event?.method || "";
+ const requestId = event?.params?.requestId;
+ if (method === "Network.requestWillBeSent" && requestId) {
+ inflight.add(requestId);
+ lastActivityAt = services.now();
+ } else if (
+ (method === "Network.loadingFinished" ||
+ method === "Network.loadingFailed") &&
+ requestId
+ ) {
+ inflight.delete(requestId);
+ lastActivityAt = services.now();
+ } else if (method.startsWith("Network.")) {
+ lastActivityAt = services.now();
+ }
+ }
+ if (inflight.size === 0 && services.now() - lastActivityAt >= idleMs) {
+ return;
+ }
+ const remaining = deadline - services.now();
+ if (remaining <= 0) break;
+ await services.sleep(Math.min(50, remaining));
+ }
+ throw new Error(
+ `page.waitForLoadState(networkidle) timed out after ${timeoutMs}ms`,
+ );
+ } finally {
+ if (ownsNetworkDomain) {
+ await services.cdp("Network.disable", {}, sessionId).catch(() => {});
+ }
+ }
+}
+
+function cdpAdapter(services: PageWaitServices) {
+ return {
+ sendRaw(method, params, sessionId) {
+ return services.cdp(method, params, sessionId);
+ },
+ };
+}
+
+function assertPositiveMilliseconds(value: number, name = "timeout"): void {
+ if (!Number.isFinite(value) || value <= 0) {
+ throw new TypeError(`${name} must be a positive number of milliseconds`);
+ }
+}
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index b2b0879..66ffe94 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -27,6 +27,9 @@ function createFixture(rootDir) {
let popupOnNextClick = null;
let timeoutNextMouseDispatch = false;
let rejectNextClickPoint = false;
+ let nowMs = 1_000;
+ const pageEvents = new Map();
+ const networkSessions = new Set();
function openPendingPopup() {
if (!popupOnNextClick) return;
@@ -136,6 +139,9 @@ function createFixture(rootDir) {
return { result: { type: "string", value: "complete" } };
}
if (method === "Runtime.callFunctionOn") {
+ if (params.functionDeclaration.includes("checkVisibility")) {
+ return { result: { type: "boolean", value: true } };
+ }
if (params.functionDeclaration.includes("window.scrollBy")) {
return {
result: {
@@ -211,6 +217,17 @@ function createFixture(rootDir) {
if (method === "Input.insertText") return {};
if (method === "Input.dispatchKeyEvent") return {};
if (method === "DOM.setFileInputFiles") return {};
+ if (method === "Network.enable") {
+ networkSessions.add(sessionId);
+ return {};
+ }
+ if (method === "Network.disable") {
+ networkSessions.delete(sessionId);
+ return {};
+ }
+ if (method === "Browser.getVersion") {
+ return { product: "Ego Lite/Test" };
+ }
if (method === "Input.dispatchMouseEvent") {
if (timeoutNextMouseDispatch) {
timeoutNextMouseDispatch = false;
@@ -251,6 +268,14 @@ function createFixture(rootDir) {
pendingDialog() {
return null;
},
+ drainEvents(sessionId) {
+ const events = pageEvents.get(sessionId) || [];
+ pageEvents.set(sessionId, []);
+ return events;
+ },
+ isNetworkDomainEnabled(sessionId) {
+ return networkSessions.has(sessionId);
+ },
ensureSession: ensureTargetSession,
invalidateSession(targetId) {
calls.push(["invalidateSession", targetId]);
@@ -258,8 +283,10 @@ function createFixture(rootDir) {
setPreferredTarget(targetId) {
calls.push(["setPreferredTarget", targetId]);
},
- now: () => Date.now(),
- sleep: async () => {},
+ now: () => nowMs,
+ sleep: async (ms) => {
+ nowMs += ms;
+ },
};
return {
activeTarget: () => activeTarget,
@@ -277,6 +304,12 @@ function createFixture(rootDir) {
rejectNextClickPoint() {
rejectNextClickPoint = true;
},
+ emitPageEvent(targetId, method, params = {}) {
+ const sessionId = `session:${targetId}`;
+ const events = pageEvents.get(sessionId) || [];
+ events.push({ sessionId, method, params });
+ pageEvents.set(sessionId, events);
+ },
};
}
@@ -788,6 +821,117 @@ test("Page keyboard dispatch and file input resolve inside the addressed page",
});
});
+test("Page and TaskSpace CDP commands preserve their intended scope", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const first = await task.newPage("https://example.test/first");
+ await task.newPage("https://example.test/second");
+
+ const pageResult = await first.cdp(
+ "Runtime.evaluate",
+ { expression: "document.title" },
+ { timeout: 1_234 },
+ );
+ const taskResult = await task.cdp(
+ "Browser.getVersion",
+ {},
+ { timeout: 987 },
+ );
+
+ assert.equal(pageResult.result.value, "https://example.test/first");
+ assert.equal(taskResult.product, "Ego Lite/Test");
+ assert(
+ fixture.calls.some(
+ ([kind, method, , sessionId, timeout]) =>
+ kind === "cdp" &&
+ method === "Runtime.evaluate" &&
+ sessionId === "session:target-1" &&
+ timeout === 1_234,
+ ),
+ "page.cdp must use the Page session and millisecond timeout",
+ );
+ assert(
+ fixture.calls.some(
+ ([kind, method, , sessionId, timeout]) =>
+ kind === "cdp" &&
+ method === "Browser.getVersion" &&
+ sessionId === undefined &&
+ timeout === 987,
+ ),
+ "task.cdp must use the selected space without a Page session",
+ );
+ });
+});
+
+test("Page waits and events remain isolated to the addressed target", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const first = await task.newPage("https://example.test/first");
+ const second = await task.newPage("https://example.test/second");
+
+ assert.equal(
+ await first.waitForSelector("#ready", { timeout: 250, visible: true }),
+ true,
+ );
+ await first.waitForLoadState("load", { timeout: 250 });
+ fixture.emitPageEvent(first.targetId, "Network.requestWillBeSent", {
+ requestId: "request-first",
+ });
+ fixture.emitPageEvent(first.targetId, "Network.loadingFinished", {
+ requestId: "request-first",
+ });
+ await first.waitForLoadState("networkidle", {
+ timeout: 500,
+ idleMs: 100,
+ });
+
+ fixture.emitPageEvent(first.targetId, "Runtime.consoleAPICalled", {
+ value: "first",
+ });
+ fixture.emitPageEvent(second.targetId, "Runtime.consoleAPICalled", {
+ value: "second",
+ });
+ assert.deepEqual(
+ (await second.events()).map((event) => event.params.value),
+ ["second"],
+ );
+ assert.deepEqual(
+ (await first.events()).map((event) => event.params.value),
+ ["first"],
+ );
+
+ assert(
+ fixture.calls.some(
+ ([kind, method, , sessionId]) =>
+ kind === "cdp" &&
+ method === "Network.enable" &&
+ sessionId === "session:target-1",
+ ),
+ "network idle must enable events on the addressed Page session",
+ );
+ });
+});
+
+test("Page wait methods reject invalid states and millisecond timeouts", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await task.newPage("https://example.test/first");
+
+ await assert.rejects(
+ () => page.waitForLoadState("domcontentloaded"),
+ /supports only "load" and "networkidle"/,
+ );
+ await assert.rejects(
+ () => page.waitForSelector("#ready", { timeout: 0 }),
+ /positive number of milliseconds/,
+ );
+ await assert.rejects(
+ () => task.cdp("Page.navigate"),
+ /only supports Target\. and Browser\. commands/,
+ );
+ });
+});
+
test("Page actions resolve snapshot refs inside the addressed page", 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 8c22e33..406f853 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -1,8 +1,10 @@
import {
browserCdp,
browserEgo,
+ drainPageEvents,
ensureSession,
invalidateSession,
+ isNetworkDomainEnabled,
pendingDialog,
setPreferredTarget,
} from "./browser-runtime.js";
@@ -35,6 +37,12 @@ import {
setInputFilesInPage,
} from "./driver/page-input.js";
import { pressKeyInPage, typeTextInPage } from "./driver/keyboard.js";
+import {
+ waitForLoadStateInPage,
+ waitForSelectorInPage,
+ type PageWaitForLoadStateOptions,
+ type PageWaitForSelectorOptions,
+} from "./driver/page-waits.js";
import { assertNoEgoError } from "./ego-errors.js";
import {
withPage as defaultWithPage,
@@ -70,6 +78,10 @@ type PageGotoOptions = {
timeout?: number;
};
+type CdpOptions = {
+ timeout?: number;
+};
+
export type PageFetchOptions = {
timeout?: number;
method?: string;
@@ -167,6 +179,8 @@ type PageModelServices = {
sessionId: string,
): Promise<string>;
pendingDialog(sessionId: string): Record<string, unknown> | null;
+ drainEvents(sessionId: string): any[];
+ isNetworkDomainEnabled(sessionId: string): boolean;
ensureSession(targetId: string): Promise<string>;
invalidateSession(targetId: string): void;
setPreferredTarget(targetId: string): void;
@@ -362,6 +376,8 @@ const baseDefaultServices: Omit<PageModelServices, "ledger" | "pageBudget"> = {
snapshot: snapshotRaw,
screenshot: captureScreenshotForSession,
pendingDialog,
+ drainEvents: drainPageEvents,
+ isNetworkDomainEnabled,
ensureSession,
invalidateSession,
setPreferredTarget,
@@ -423,6 +439,23 @@ export class TaskSpace {
});
}
+ /** Send a Target or Browser domain command within this selected space. */
+ async cdp(
+ method: string,
+ params: Record<string, unknown> = {},
+ options: CdpOptions = {},
+ ): Promise<any> {
+ assertCdpCall(method, params, options);
+ if (!method.startsWith("Target.") && !method.startsWith("Browser.")) {
+ throw new TypeError(
+ "task.cdp only supports Target. and Browser. commands",
+ );
+ }
+ return this.#services.gate.withSpace(this.id, () =>
+ this.#services.cdp(method, params, undefined, options.timeout),
+ );
+ }
+
/**
* Bring an untracked browser tab under the durable Page lifecycle.
* Untracked handles intentionally cannot operate on the tab before adoption.
@@ -730,6 +763,74 @@ export class Page {
});
}
+ /** Send one CDP command through this Page's target session. */
+ async cdp(
+ method: string,
+ params: Record<string, unknown> = {},
+ options: CdpOptions = {},
+ ): Promise<any> {
+ assertCdpCall(method, params, options);
+ const page = await this.#resolve();
+ return this.#services.gate.withPage(page, async ({ sessionId }) => {
+ await this.#activate(page.targetId);
+ try {
+ return await this.#services.cdp(
+ method,
+ params,
+ sessionId,
+ options.timeout,
+ );
+ } finally {
+ // Raw CDP can navigate or mutate the document, so existing refs are no
+ // longer safe even when the command looked observational.
+ this.#services.pageRefs.clear(page.targetId);
+ }
+ });
+ }
+
+ async waitForSelector(
+ selector: string,
+ options: PageWaitForSelectorOptions = {},
+ ): Promise<true> {
+ if (options.timeout !== undefined) assertTimeout(options.timeout);
+ const page = await this.#resolve();
+ return this.#services.gate.withPage(page, async ({ sessionId }) => {
+ await this.#activate(page.targetId);
+ const refMap = await this.#refMapForAction(page, selector);
+ return waitForSelectorInPage(
+ this.#services,
+ sessionId,
+ refMap,
+ selector,
+ options,
+ );
+ });
+ }
+
+ async waitForLoadState(
+ state: "load" | "networkidle",
+ options: PageWaitForLoadStateOptions = {},
+ ): Promise<void> {
+ if (options.timeout !== undefined) assertTimeout(options.timeout);
+ const page = await this.#resolve();
+ return this.#services.gate.withPage(page, async ({ sessionId }) => {
+ await this.#activate(page.targetId);
+ try {
+ await waitForLoadStateInPage(this.#services, sessionId, state, options);
+ } finally {
+ this.#services.pageRefs.clear(page.targetId);
+ }
+ });
+ }
+
+ /** Drain only CDP events routed to this Page session. */
+ async events(): Promise<any[]> {
+ const page = await this.#resolve();
+ return this.#services.gate.withPage(page, ({ sessionId }) =>
+ this.#services.drainEvents(sessionId),
+ );
+ }
+
async screenshot(
path?: string,
options: CaptureScreenshotOptions = {},
@@ -1288,6 +1389,23 @@ function assertTimeout(timeout: number | undefined): void {
}
}
+function assertCdpCall(
+ method: string,
+ params: Record<string, unknown>,
+ options: CdpOptions,
+): void {
+ if (typeof method !== "string" || method.length === 0) {
+ throw new TypeError("cdp method must be a non-empty string");
+ }
+ if (!params || typeof params !== "object" || Array.isArray(params)) {
+ throw new TypeError("cdp params must be an object");
+ }
+ if (!options || typeof options !== "object" || Array.isArray(options)) {
+ throw new TypeError("cdp options must be an object");
+ }
+ if (options.timeout !== undefined) assertTimeout(options.timeout);
+}
+
function pageInventory(
task: TaskSpace,
services: PageModelServices,