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): bound session setup waits and name an unresponsive Page

Zhuowei Wangb88175ddc471
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
index fba5230..48e3efe 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
@@ -68,6 +68,10 @@ import {
import { pageApiAlignmentCase } from "./page-api-alignment.mjs";
import { pageActionabilityCase } from "./page-actionability.mjs";
import { pageEvaluateTimeoutCase } from "./page-evaluate-timeout.mjs";
+import {
+ pagePendingNavigationCase,
+ pagePendingNavigationFreshProcessCase,
+} from "./page-pending-navigation.mjs";
import {
pageDelayedPopupResumeCase,
pageDelayedPopupScheduleCase,
@@ -225,6 +229,16 @@ export const e2eCases = [
body: pageEvaluateTimeoutCase,
timeoutMs: 60_000,
},
+ {
+ name: "Page pending navigation: same process",
+ body: pagePendingNavigationCase,
+ timeoutMs: 60_000,
+ },
+ {
+ name: "Page pending navigation: fresh process",
+ body: pagePendingNavigationFreshProcessCase,
+ timeoutMs: 60_000,
+ },
{
name: "Page delayed popup: schedule",
body: pageDelayedPopupScheduleCase,
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-pending-navigation.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-pending-navigation.mjs
new file mode 100644
index 0000000..f32ceed
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-pending-navigation.mjs
@@ -0,0 +1,146 @@
+// A main-frame navigation that has started but not committed suspends every
+// renderer-bound CDP command until the new document commits or the navigation
+// stops. These cases pin the harness behavior on such a Page: public calls
+// stay inside one bounded wait, the error names the Page and what to do, and
+// Page.stopLoading recovers it.
+export function pagePendingNavigationCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const page = await newPageAt(
+ task,
+ baseUrl + "/nav-target?pending-navigation=" + Date.now()
+ );
+ const heldUrl = baseUrl + "/hold-page?ms=120000";
+
+ const gotoStartedAt = Date.now();
+ let gotoError;
+ try {
+ await page.goto(heldUrl, { timeout: 1_500 });
+ } catch (error) {
+ gotoError = error;
+ }
+ assertEqual(
+ gotoError?.code,
+ "EGO_NAVIGATION_TIMEOUT",
+ "goto to a held response times out: " + gotoError?.message
+ );
+ assert(
+ Date.now() - gotoStartedAt < 4_000,
+ "goto returns close to its own timeout: " + (Date.now() - gotoStartedAt)
+ );
+
+ const snapshotStartedAt = Date.now();
+ let snapshotError;
+ try {
+ await page.snapshot();
+ } catch (error) {
+ snapshotError = error;
+ }
+ const snapshotElapsed = Date.now() - snapshotStartedAt;
+ assertEqual(
+ snapshotError?.code,
+ "EGO_PAGE_UNRESPONSIVE",
+ "snapshot during a pending navigation reports the unresponsive Page: " +
+ snapshotError?.message
+ );
+ assertIncludes(
+ snapshotError?.message,
+ "Page " + page.label,
+ "the error names the Page"
+ );
+ assertIncludes(
+ snapshotError?.message,
+ "(" + baseUrl + "/",
+ "the error names the Page URL"
+ );
+ assertIncludes(
+ snapshotError?.message,
+ 'page.cdp("Page.stopLoading")',
+ "the error tells the agent how to recover"
+ );
+ assert(
+ snapshotElapsed < 20_000,
+ "snapshot gives up after one bounded wait, not one per setup command: " +
+ snapshotElapsed
+ );
+
+ const secondGotoStartedAt = Date.now();
+ let secondGotoError;
+ try {
+ await page.goto(heldUrl + "&second=1", { timeout: 2_000 });
+ } catch (error) {
+ secondGotoError = error;
+ }
+ assertEqual(
+ secondGotoError?.code,
+ "EGO_NAVIGATION_TIMEOUT",
+ "goto on an unresponsive Page still times out: " + secondGotoError?.message
+ );
+ assert(
+ Date.now() - secondGotoStartedAt < 4_500,
+ "goto on an unresponsive Page counts session setup against its timeout: " +
+ (Date.now() - secondGotoStartedAt)
+ );
+
+ await page.cdp("Page.stopLoading");
+ const recoveredStartedAt = Date.now();
+ const recovered = await page.snapshot();
+ assert(
+ Date.now() - recoveredStartedAt < 5_000,
+ "snapshot answers promptly once the pending navigation stops: " +
+ (Date.now() - recoveredStartedAt)
+ );
+ assertIncludes(
+ recovered,
+ "Navigation target",
+ "the Page still shows the last committed document"
+ );
+
+ // Leave a pending navigation behind for the fresh-process case.
+ try {
+ await page.goto(heldUrl + "&fresh=1", { timeout: 1_000 });
+ } catch {}
+ await writeFile(
+ join(tempDir, "pending-navigation-state.json"),
+ JSON.stringify({ label: page.label })
+ );
+ `;
+}
+
+export function pagePendingNavigationFreshProcessCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const saved = JSON.parse(
+ await readFile(join(tempDir, "pending-navigation-state.json"), "utf8")
+ );
+ const page = task.page(saved.label);
+
+ const startedAt = Date.now();
+ let error;
+ try {
+ await page.snapshot();
+ } catch (caught) {
+ error = caught;
+ }
+ const elapsed = Date.now() - startedAt;
+ assertEqual(
+ error?.code,
+ "EGO_PAGE_UNRESPONSIVE",
+ "the first call of a new process reports the unresponsive Page: " +
+ error?.message
+ );
+ assert(
+ elapsed < 20_000,
+ "a new process does not wait a full transport timeout per setup command: " +
+ elapsed
+ );
+
+ await page.cdp("Page.stopLoading");
+ assertIncludes(
+ await page.snapshot(),
+ "Navigation target",
+ "the Page recovers in the new process as well"
+ );
+ await page.close();
+ `;
+}
diff --git a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
index 28f2d6f..e67a3ed 100644
--- a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
@@ -477,6 +477,20 @@ export async function startFixtureServer(taskName) {
}, delayMs);
return;
}
+ if (url.pathname === "/hold-page") {
+ // Hold the whole response so a main-frame navigation to this URL stays
+ // started but not committed until the client stops it or gives up.
+ const holdMs = Number(url.searchParams.get("ms") || 60_000);
+ const timer = setTimeout(() => {
+ res.writeHead(200, { "content-type": "text/html" });
+ res.end(
+ "<!doctype html><html><head><title>held page</title></head>" +
+ '<body><h1 id="held-marker">held document loaded</h1></body></html>',
+ );
+ }, holdMs);
+ req.on("close", () => clearTimeout(timer));
+ return;
+ }
if (url.pathname === "/streamed-page") {
const delayMs = Number(url.searchParams.get("ms") || 1000);
res.writeHead(200, { "content-type": "text/html" });
diff --git a/package/ego-browser/skill-body/SKILL.md b/package/ego-browser/skill-body/SKILL.md
index ed69291..f353903 100644
--- a/package/ego-browser/skill-body/SKILL.md
+++ b/package/ego-browser/skill-body/SKILL.md
@@ -220,6 +220,14 @@ ego-browser provides the following Page API:
or Node.js modules from the surrounding script. Define browser-side helpers
inside the callback or pass one JSON-serializable value as its second argument.
+`goto()` and `reload()` count session setup against their `timeout`. While a
+main-frame navigation has started but not committed, or when a renderer hangs,
+the Page answers no renderer command; `snapshot()` and ref actions on it fail
+with `EGO_PAGE_UNRESPONSIVE` after one bounded wait, naming the Page and its
+last committed URL. Retry once the navigation commits, call `goto()` again with
+a longer `timeout`, stop the pending navigation with
+`page.cdp("Page.stopLoading")`, or continue on a new Page.
+
Work efficiently:
- Each time you observe, collect only the cheapest page state sufficient to
diff --git a/package/ego-browser/src/browser-runtime.test.mjs b/package/ego-browser/src/browser-runtime.test.mjs
index 3e58358..0f7387e 100644
--- a/package/ego-browser/src/browser-runtime.test.mjs
+++ b/package/ego-browser/src/browser-runtime.test.mjs
@@ -2235,3 +2235,146 @@ test("file chooser interception suppresses the native picker and returns its inp
else globalThis.ego = previous;
}
});
+
+function pageEnableHoldingRuntime(methods) {
+ const held = new Map();
+ const runtime = {
+ sendCDPMessage(payload) {
+ const request = JSON.parse(payload);
+ methods.push([request.method, request.sessionId]);
+ const result =
+ request.method === "Target.attachToTarget"
+ ? { sessionId: `session:${request.params.targetId}` }
+ : {};
+ const respond = () => {
+ runtime.onCDPMessage(JSON.stringify({ id: request.id, result }));
+ };
+ if (held.has(request.method)) {
+ held.get(request.method).push(respond);
+ return;
+ }
+ queueMicrotask(respond);
+ },
+ hold(method) {
+ held.set(method, []);
+ },
+ release(method) {
+ for (const respond of held.get(method) || []) respond();
+ held.delete(method);
+ },
+ };
+ return runtime;
+}
+
+test("ensureSession bounds its wait for an unanswered Page.enable and shares the request", async () => {
+ const previous = globalThis.ego;
+ const methods = [];
+ const runtime = pageEnableHoldingRuntime(methods);
+ runtime.hold("Page.enable");
+ globalThis.ego = runtime;
+ const pageEnables = () =>
+ methods.filter(([method]) => method === "Page.enable").length;
+
+ try {
+ let startedAt = performance.now();
+ assert.equal(await ensureSession("page-main", 50), "session:page-main");
+ assert(
+ performance.now() - startedAt < 200,
+ "an unanswered Page.enable must not hold the session wait beyond its budget",
+ );
+ assert.equal(pageEnables(), 1);
+
+ startedAt = performance.now();
+ assert.equal(await ensureSession("page-main", 50), "session:page-main");
+ assert(
+ performance.now() - startedAt < 200,
+ "a cached session must not wait a full budget again",
+ );
+ assert.equal(
+ pageEnables(),
+ 1,
+ "the second caller reuses the still-pending Page.enable request",
+ );
+
+ runtime.release("Page.enable");
+ await new Promise((resolve) => setImmediate(resolve));
+ await ensureSession("page-main", 50);
+ assert.equal(
+ pageEnables(),
+ 1,
+ "a late Page.enable answer records the enabled state for later callers",
+ );
+ } finally {
+ runtime.release("Page.enable");
+ invalidateSession();
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ }
+});
+
+test("ensureSession caps the setup wait below the transport timeout", async () => {
+ const previous = globalThis.ego;
+ const methods = [];
+ const runtime = pageEnableHoldingRuntime(methods);
+ runtime.hold("Page.enable");
+ runtime.hold("Network.enable");
+ globalThis.ego = runtime;
+
+ try {
+ const startedAt = performance.now();
+ assert.equal(await ensureSession("page-main"), "session:page-main");
+ const elapsed = performance.now() - startedAt;
+ assert(
+ elapsed >= 1_500 && elapsed < 3_500,
+ `the default session wait is capped near two seconds, got ${elapsed}ms`,
+ );
+ } finally {
+ runtime.release("Page.enable");
+ runtime.release("Network.enable");
+ invalidateSession();
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ }
+});
+
+test("ensureFrameSessions reports an unanswered frame tree as an unresponsive Page", async () => {
+ const previous = globalThis.ego;
+ const methods = [];
+ const runtime = pageEnableHoldingRuntime(methods);
+ runtime.hold("Page.getFrameTree");
+ globalThis.ego = runtime;
+
+ try {
+ const startedAt = performance.now();
+ await assert.rejects(
+ () => ensureFrameSessions("page-main", 100),
+ (error) => {
+ assert.equal(error.code, "EGO_PAGE_UNRESPONSIVE");
+ assert.equal(error.name, "PageUnresponsiveError");
+ assert(
+ error instanceof CdpRequestTimeoutError,
+ "budget-driven retry loops still recognize it as a request timeout",
+ );
+ assert.equal(error.method, "Page.getFrameTree");
+ assert.equal(error.targetId, "page-main");
+ assert(error.waitedMs >= 90, `waited ${error.waitedMs}ms`);
+ assert.match(error.message, /did not answer Page\.getFrameTree/);
+ assert.match(error.message, /navigation has not committed/);
+ return true;
+ },
+ );
+ assert(
+ performance.now() - startedAt < 400,
+ "the unresponsive Page is reported inside the caller's budget",
+ );
+ assert.equal(
+ methods.filter(([method]) => method === "Page.getFrameTree").length,
+ 1,
+ );
+ } finally {
+ runtime.release("Page.getFrameTree");
+ invalidateSession();
+ 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 0c8a62f..6f0b56c 100644
--- a/package/ego-browser/src/browser-runtime.ts
+++ b/package/ego-browser/src/browser-runtime.ts
@@ -6,6 +6,11 @@ import {
} from "./ego-errors.js";
const RESPONSE_TIMEOUT_MS = 15000;
+// Page.enable, Network.enable, and Target.setAutoAttach answer within
+// milliseconds on a responsive Page. A Page whose main-frame navigation has
+// started but not committed, or whose renderer hangs, answers none of them
+// until it recovers, so one caller never waits longer than this for setup.
+const SESSION_SETUP_WAIT_MS = 2000;
const SESSION_TTL_MS = 2000;
// Upper bound for buffered CDP events. The runtime can be long-lived (installEgoSdk
// inside the browser); without a cap, undrained events grow without bound.
@@ -55,7 +60,8 @@ type EgoCdpCallbackRuntime = {
let callbackRuntime: EgoCdpCallbackRuntime | undefined;
export class CdpRequestTimeoutError extends Error {
- readonly code = "EGO_CDP_REQUEST_TIMEOUT";
+ readonly code: "EGO_CDP_REQUEST_TIMEOUT" | "EGO_PAGE_UNRESPONSIVE" =
+ "EGO_CDP_REQUEST_TIMEOUT";
readonly method: string;
readonly timeoutMs: number;
readonly sessionId?: string;
@@ -69,6 +75,42 @@ export class CdpRequestTimeoutError extends Error {
}
}
+/**
+ * The Page's renderer did not answer a command it has to answer itself.
+ * Chromium suspends every renderer-bound command while a main-frame navigation
+ * has started but not committed; a hung renderer behaves the same way. It is
+ * still a request timeout, so budget-driven retry loops that treat a timeout
+ * at their deadline as their own timeout keep doing so.
+ */
+export class PageUnresponsiveError extends CdpRequestTimeoutError {
+ override readonly code = "EGO_PAGE_UNRESPONSIVE";
+ readonly waitedMs: number;
+ readonly targetId?: string;
+
+ constructor(
+ method: string,
+ waitedMs: number,
+ targetId?: string,
+ sessionId?: string,
+ ) {
+ super(method, waitedMs, sessionId);
+ this.name = "PageUnresponsiveError";
+ this.message = `Page did not answer ${method} within ${waitedMs}ms; its main-frame navigation has not committed or its renderer is unresponsive`;
+ this.waitedMs = waitedMs;
+ this.targetId = targetId;
+ }
+}
+
+export function isPageUnresponsiveError(
+ error: unknown,
+): error is PageUnresponsiveError {
+ return (
+ error instanceof PageUnresponsiveError ||
+ (error instanceof Error &&
+ (error as { code?: unknown }).code === "EGO_PAGE_UNRESPONSIVE")
+ );
+}
+
export function isCdpRequestTimeoutError(
error: unknown,
): error is CdpRequestTimeoutError {
@@ -177,6 +219,7 @@ function targetState(targetId) {
events: [],
egoAutomationEnabled: false,
pageEventsEnabled: false,
+ pageEnableInflight: null,
networkDomainEnabled: false,
networkEnableInflight: null,
autoAttachEnabled: false,
@@ -215,6 +258,7 @@ function registerSession(targetId, sessionId) {
target.sessionAt = Date.now();
target.egoAutomationEnabled = false;
target.pageEventsEnabled = false;
+ target.pageEnableInflight = null;
target.networkDomainEnabled = false;
target.networkEnableInflight = null;
target.autoAttachEnabled = false;
@@ -320,6 +364,7 @@ function clearTargetSession(targetId, { remove = false } = {}) {
target.events.length = 0;
target.egoAutomationEnabled = false;
target.pageEventsEnabled = false;
+ target.pageEnableInflight = null;
target.networkDomainEnabled = false;
target.networkEnableInflight = null;
target.autoAttachEnabled = false;
@@ -593,11 +638,15 @@ export async function ensureSession(
const cachedTargetId =
requestedTargetId || state.preferredTargetId || defaultTargetId;
const cached = cachedTargetId ? targetStates.get(cachedTargetId) : undefined;
+ // Session setup is best-effort and shared: an unanswered request keeps
+ // running for later callers, while this caller's wait stays short so that
+ // the command it actually came for gets the rest of its budget.
+ const setupWaitMs = Math.min(Math.max(1, timeoutMs), SESSION_SETUP_WAIT_MS);
if (cached?.sessionId && Date.now() - cached.sessionAt < SESSION_TTL_MS) {
await Promise.all([
- enablePageEvents(cached.sessionId, timeoutMs),
- enableNetworkTrackingForSession(cached.sessionId, false, timeoutMs),
- enableOopifAutoAttach(cached.sessionId, timeoutMs),
+ enablePageEvents(cached.sessionId, setupWaitMs),
+ enableNetworkTrackingForSession(cached.sessionId, false, setupWaitMs),
+ enableOopifAutoAttach(cached.sessionId, setupWaitMs),
]);
cached.sessionAt = Date.now();
return cached.sessionId;
@@ -642,9 +691,9 @@ export async function ensureSession(
}
enableEgoAutomation(target.sessionId);
await Promise.all([
- enablePageEvents(target.sessionId, timeoutMs),
- enableNetworkTrackingForSession(target.sessionId, false, timeoutMs),
- enableOopifAutoAttach(target.sessionId, timeoutMs),
+ enablePageEvents(target.sessionId, setupWaitMs),
+ enableNetworkTrackingForSession(target.sessionId, false, setupWaitMs),
+ enableOopifAutoAttach(target.sessionId, setupWaitMs),
]);
target.sessionAt = Date.now();
return target.sessionId;
@@ -668,13 +717,34 @@ export async function ensureFrameSessions(
if (typeof pageTargetId !== "string" || pageTargetId.length === 0) {
throw new TypeError("ensureFrameSessions requires a non-empty targetId");
}
- const deadline = state.now() + Math.max(1, timeoutMs);
+ const startedAt = state.now();
+ const deadline = startedAt + Math.max(1, timeoutMs);
const remaining = () => Math.max(1, deadline - state.now());
const pageSessionId = await ensureSession(pageTargetId, remaining());
- const [response, frameTreeResponse] = await Promise.all([
- browserCdp("Target.getTargets", {}, undefined, remaining()),
- browserCdp("Page.getFrameTree", {}, pageSessionId, remaining()),
- ]);
+ let response;
+ let frameTreeResponse;
+ try {
+ [response, frameTreeResponse] = await Promise.all([
+ browserCdp("Target.getTargets", {}, undefined, remaining()),
+ browserCdp("Page.getFrameTree", {}, pageSessionId, remaining()),
+ ]);
+ } catch (error) {
+ // The browser process answers Target.getTargets on its own, so a frame
+ // tree timeout means the Page's renderer did not answer within the budget
+ // this call had left: name that instead of the last command sent.
+ if (
+ isCdpRequestTimeoutError(error) &&
+ error.method === "Page.getFrameTree"
+ ) {
+ throw new PageUnresponsiveError(
+ "Page.getFrameTree",
+ state.now() - startedAt,
+ pageTargetId,
+ pageSessionId,
+ );
+ }
+ throw error;
+ }
const targetInfos =
response?.result?.targetInfos || response?.targetInfos || [];
const frameTree =
@@ -1112,15 +1182,25 @@ function enableEgoAutomation(sessionId: string): void {
async function enablePageEvents(sessionId, timeoutMs = RESPONSE_TIMEOUT_MS) {
const targetId = sessionId ? sessionTargets.get(sessionId) : undefined;
const target = targetId ? targetStates.get(targetId) : undefined;
- if (!target || target.pageEventsEnabled) {
+ if (!target || target.sessionId !== sessionId || target.pageEventsEnabled) {
return;
}
try {
- await rawCdp("Page.enable", {}, sessionId, timeoutMs);
- target.pageEventsEnabled = true;
+ await sharedSetupCommand(
+ target,
+ "pageEnableInflight",
+ "Page.enable",
+ {},
+ sessionId,
+ timeoutMs,
+ () => {
+ target.pageEventsEnabled = true;
+ },
+ );
} catch {
// Dialog tracking is best-effort. Do not make all helpers fail on targets
- // that reject Page.enable, such as unusual internal pages.
+ // that reject Page.enable, such as unusual internal pages, or that cannot
+ // answer yet because a navigation has not committed.
}
}
@@ -1141,42 +1221,25 @@ async function enableNetworkTrackingForSession(
}
if (target.networkDomainEnabled) return;
- let inflight = target.networkEnableInflight;
- const reusedInflight = Boolean(inflight);
- if (!inflight) {
- inflight = rawCdp("Network.enable", {}, sessionId, timeoutMs).then(() => {
- // Events and an OOPIF request migration can race ahead of this response.
- // Network.disable and session replacement already clear stale state, so
- // enabling must preserve everything observed for the current session.
- if (target.sessionId === sessionId && !target.networkDomainEnabled) {
- target.lastNetworkActivityAt = state.now();
- target.networkDomainEnabled = true;
- }
- });
- target.networkEnableInflight = inflight;
- void inflight.then(
- () => {
- if (target.networkEnableInflight === inflight) {
- target.networkEnableInflight = null;
- }
- },
+ try {
+ await sharedSetupCommand(
+ target,
+ "networkEnableInflight",
+ "Network.enable",
+ {},
+ sessionId,
+ timeoutMs,
() => {
- if (target.networkEnableInflight === inflight) {
- target.networkEnableInflight = null;
+ // Events and an OOPIF request migration can race ahead of this
+ // response. Network.disable and session replacement already clear
+ // stale state, so enabling must preserve everything observed for the
+ // current session.
+ if (!target.networkDomainEnabled) {
+ target.lastNetworkActivityAt = state.now();
+ target.networkDomainEnabled = true;
}
},
);
- }
-
- try {
- await (reusedInflight
- ? waitForSharedCdpRequest(
- inflight,
- "Network.enable",
- sessionId,
- timeoutMs,
- )
- : inflight);
} catch (error) {
if (required) throw error;
}
@@ -1196,47 +1259,59 @@ async function enableOopifAutoAttach(
if (!target || target.sessionId !== sessionId || target.autoAttachEnabled) {
return;
}
-
- let inflight = target.autoAttachInflight;
- const reusedInflight = Boolean(inflight);
- if (!inflight) {
- inflight = rawCdp(
+ try {
+ await sharedSetupCommand(
+ target,
+ "autoAttachInflight",
"Target.setAutoAttach",
OOPIF_AUTO_ATTACH_PARAMS,
sessionId,
timeoutMs,
- ).then(() => {
- if (target.sessionId === sessionId) target.autoAttachEnabled = true;
- });
- target.autoAttachInflight = inflight;
- void inflight.then(
() => {
- if (target.autoAttachInflight === inflight) {
- target.autoAttachInflight = null;
- }
- },
- () => {
- if (target.autoAttachInflight === inflight) {
- target.autoAttachInflight = null;
- }
+ target.autoAttachEnabled = true;
},
);
- }
- try {
- await (reusedInflight
- ? waitForSharedCdpRequest(
- inflight,
- "Target.setAutoAttach",
- sessionId,
- timeoutMs,
- )
- : inflight);
} catch {
// Page APIs still work on bridges without auto-attach. Frame discovery can
// attach explicitly later, but exact network-idle tracking needs support.
}
}
+type SetupInflightKey =
+ | "pageEnableInflight"
+ | "networkEnableInflight"
+ | "autoAttachInflight";
+
+/**
+ * Send one session-setup command at most once at a time per session, and
+ * bound this caller's wait without cancelling the request. The request keeps
+ * the full transport timeout, so a Page that answers late (after its pending
+ * navigation commits) still records the enabled state for later callers
+ * instead of each caller sending the command again and waiting again.
+ */
+function sharedSetupCommand(
+ target,
+ key: SetupInflightKey,
+ method: string,
+ params: Record<string, unknown>,
+ sessionId: string,
+ timeoutMs: number,
+ onSuccess: () => void,
+): Promise<void> {
+ let inflight: Promise<void> | null = target[key];
+ if (!inflight) {
+ inflight = rawCdp(method, params, sessionId).then(() => {
+ if (target.sessionId === sessionId) onSuccess();
+ });
+ target[key] = inflight;
+ const clear = () => {
+ if (target[key] === inflight) target[key] = null;
+ };
+ void inflight.then(clear, clear);
+ }
+ return waitForSharedCdpRequest(inflight, method, sessionId, timeoutMs);
+}
+
/** Bound one caller's wait without cancelling the shared CDP request. */
function waitForSharedCdpRequest(
request: Promise<void>,
@@ -1247,7 +1322,17 @@ function waitForSharedCdpRequest(
const callerTimeoutMs = Math.max(1, timeoutMs);
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
- reject(new CdpRequestTimeoutError(method, callerTimeoutMs, sessionId));
+ // Mirror rawCdp's timeout: name a dialog if one is what stalled it.
+ const dialog = DIALOG_SAFE_METHOD(method)
+ ? null
+ : pendingDialog(sessionId);
+ reject(
+ dialog
+ ? new PageDialogOpenedError(method, sessionId, dialog, {
+ alreadyOpen: true,
+ })
+ : new CdpRequestTimeoutError(method, callerTimeoutMs, sessionId),
+ );
}, callerTimeoutMs);
request.then(
() => {
diff --git a/package/ego-browser/src/driver/page-actions.ts b/package/ego-browser/src/driver/page-actions.ts
index 0937d72..f49d72f 100644
--- a/package/ego-browser/src/driver/page-actions.ts
+++ b/package/ego-browser/src/driver/page-actions.ts
@@ -377,13 +377,7 @@ export async function clickInPage(
}
}
} finally {
- await services
- .cdp(
- "Runtime.releaseObject",
- { objectId: target.objectId },
- target.sessionId,
- )
- .catch(() => {});
+ await releaseObject(services, target.sessionId, target.objectId);
}
}
@@ -1948,7 +1942,11 @@ async function releaseObject(
sessionId: string,
objectId: string,
): Promise<void> {
- await services
+ // Best-effort and not awaited: the action already finished with the handle.
+ // When the action started a navigation, the Page answers nothing until the
+ // new document commits, and waiting here would add a transport timeout to
+ // every click on a link.
+ void services
.cdp("Runtime.releaseObject", { objectId }, sessionId)
.catch(() => {});
}
diff --git a/package/ego-browser/src/driver/page-waits.ts b/package/ego-browser/src/driver/page-waits.ts
index 96c5aef..605fc1d 100644
--- a/package/ego-browser/src/driver/page-waits.ts
+++ b/package/ego-browser/src/driver/page-waits.ts
@@ -66,6 +66,11 @@ export type PageNavigationOptions = {
timeoutMs: number;
waitUntil: PageGotoWaitUntil;
referer?: string;
+ /**
+ * Absolute deadline when the public call started before this function,
+ * so session setup counts against the caller's timeout.
+ */
+ deadline?: number;
};
export type PageWaitForURLOptions = {
@@ -428,7 +433,7 @@ export async function navigateInPage(
options: PageNavigationOptions,
): Promise<void> {
const { timeoutMs, waitUntil, referer } = options;
- const deadline = services.now() + timeoutMs;
+ const deadline = options.deadline ?? services.now() + timeoutMs;
let committed = false;
let navigation: {
frameId?: string;
@@ -510,7 +515,7 @@ export async function reloadInPage(
options: Omit<PageNavigationOptions, "referer">,
): Promise<void> {
const { timeoutMs, waitUntil } = options;
- const deadline = services.now() + timeoutMs;
+ const deadline = options.deadline ?? services.now() + timeoutMs;
try {
const previousFrame = await mainFrame(
services,
diff --git a/package/ego-browser/src/native-gate.test.mjs b/package/ego-browser/src/native-gate.test.mjs
index d8970d3..8e4c2f4 100644
--- a/package/ego-browser/src/native-gate.test.mjs
+++ b/package/ego-browser/src/native-gate.test.mjs
@@ -169,3 +169,21 @@ test("NativeOperationGate rejects nested selection of another space", async () =
);
assert.equal(await gate.withSpace(9, async () => "recovered"), "recovered");
});
+
+test("NativeOperationGate forwards the withPage session budget to ensureSession", async () => {
+ const budgets = [];
+ const gate = new NativeOperationGate({
+ async selectSpace() {},
+ async ensureSession(targetId, timeoutMs) {
+ budgets.push(timeoutMs);
+ return `session:${targetId}`;
+ },
+ });
+
+ await gate.withPage({ spaceId: 7, targetId: "target-a" }, () => "a");
+ await gate.withPage({ spaceId: 7, targetId: "target-a" }, () => "b", {
+ sessionTimeoutMs: 1_234,
+ });
+
+ assert.deepEqual(budgets, [undefined, 1_234]);
+});
diff --git a/package/ego-browser/src/native-gate.ts b/package/ego-browser/src/native-gate.ts
index a943483..fdcbdd9 100644
--- a/package/ego-browser/src/native-gate.ts
+++ b/package/ego-browser/src/native-gate.ts
@@ -14,7 +14,12 @@ export type PageExecutionContext = SpaceScope & {
type NativeGateServices = {
selectSpace(spaceId: number): unknown | Promise<unknown>;
- ensureSession(targetId: string): Promise<string>;
+ ensureSession(targetId: string, timeoutMs?: number): Promise<string>;
+};
+
+export type WithPageOptions = {
+ /** Budget for attaching and preparing the Page session. */
+ sessionTimeoutMs?: number;
};
type PageTarget = {
@@ -98,6 +103,7 @@ export class NativeOperationGate {
withPage<T>(
page: PageTarget,
operation: (context: PageExecutionContext) => T | Promise<T>,
+ options: WithPageOptions = {},
): Promise<T> {
if (!page || typeof page !== "object") {
throw new TypeError("withPage requires a page target");
@@ -111,7 +117,10 @@ export class NativeOperationGate {
}
return this.withSpace(page.spaceId, async () => {
- const sessionId = await this.#services.ensureSession(page.targetId);
+ const sessionId = await this.#services.ensureSession(
+ page.targetId,
+ options.sessionTimeoutMs,
+ );
return operation({
spaceId: page.spaceId,
targetId: page.targetId,
@@ -148,6 +157,7 @@ export function withSpace<T>(
export function withPage<T>(
page: PageTarget,
operation: (context: PageExecutionContext) => T | Promise<T>,
+ options: WithPageOptions = {},
): Promise<T> {
- return defaultGate.withPage(page, operation);
+ return defaultGate.withPage(page, operation, options);
}
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 54e850a..ebaa7fe 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -12,7 +12,10 @@ import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { NativeOperationGate } from "../dist/src/native-gate.js";
-import { CdpRequestTimeoutError } from "../dist/src/browser-runtime.js";
+import {
+ CdpRequestTimeoutError,
+ PageUnresponsiveError,
+} from "../dist/src/browser-runtime.js";
import { PageLedgerStore } from "../dist/src/page-ledger.js";
import {
captureTaskSpaceUserBoundary,
@@ -6983,3 +6986,32 @@ test("a click that reaches a file input waits for the trailing chooser event", a
);
});
});
+
+test("snapshot names the Page and the next step when the Page does not answer", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a", {
+ async ensureFrameSessions() {
+ throw new PageUnresponsiveError("Page.getFrameTree", 1_500, "target-1");
+ },
+ });
+ const page = await openTestPage(task, "https://example.test/pending");
+
+ await assert.rejects(
+ () => page.snapshot(),
+ (error) => {
+ assert.equal(error.code, "EGO_PAGE_UNRESPONSIVE");
+ assert.equal(error.method, "Page.getFrameTree");
+ assert.equal(error.waitedMs, 1_500);
+ assert.equal(error.targetId, "target-1");
+ assert.match(
+ error.message,
+ /^Page p1 .*did not answer Page\.getFrameTree within 1500ms\./,
+ );
+ assert.match(error.message, /navigation has started but not committed/);
+ assert.match(error.message, /page\.cdp\("Page\.stopLoading"\)/);
+ assert.match(error.message, /task\.newPage\(\)/);
+ return true;
+ },
+ );
+ });
+});
diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.ts
index ffc235b..6cf9626 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -10,6 +10,8 @@ import {
ensureFrameSessions,
invalidateSession,
isCdpRequestTimeoutError,
+ isPageUnresponsiveError,
+ PageUnresponsiveError,
isBrowserRuntime,
isPageDialogOpenedError,
isSessionLostError,
@@ -89,6 +91,7 @@ import {
withPage as defaultWithPage,
withSpace as defaultWithSpace,
type PageExecutionContext,
+ type WithPageOptions,
} from "./native-gate.js";
import {
PageLedgerStore,
@@ -436,6 +439,7 @@ type OperationGate = {
withPage<T>(
page: PageTarget,
operation: (context: PageExecutionContext) => T | Promise<T>,
+ options?: WithPageOptions,
): Promise<T>;
};
@@ -526,7 +530,7 @@ type PageModelServices = {
lastActivityAt: number;
pendingRequests?: string[];
};
- ensureSession(targetId: string): Promise<string>;
+ ensureSession(targetId: string, timeoutMs?: number): Promise<string>;
ensureFrameSessions(
targetId: string,
timeoutMs?: number,
@@ -616,6 +620,7 @@ const MISSING_TARGET_PROBE_TIMEOUT_MS = 1_000;
// One page round trip after an action orders a popup's Target.targetCreated
// event ahead of the response, so no settle delay is needed.
const POPUP_SYNC_TIMEOUT_MS = 1_000;
+const PAGE_UNRESPONSIVE_URL_TIMEOUT_MS = 1_000;
// The native tab list can lag the CDP target event by a few milliseconds.
const POPUP_TAB_LIST_RETRIES = 10;
const POPUP_TAB_LIST_RETRY_MS = 20;
@@ -1818,6 +1823,7 @@ class Page {
const timeoutMs = options.timeout ?? 15_000;
const waitUntil = options.waitUntil ?? "load";
const page = await this.#resolve();
+ const deadline = this.#services.now() + timeoutMs;
const { receipt } = await this.#runActionBoundary(
page,
async (sessionId) => {
@@ -1825,9 +1831,10 @@ class Page {
referer: options.referer,
timeoutMs,
waitUntil,
+ deadline,
});
},
- { inputAction: false },
+ { inputAction: false, sessionTimeoutMs: timeoutMs },
);
return receipt;
}
@@ -1837,15 +1844,17 @@ class Page {
const timeoutMs = options.timeout ?? 15_000;
const waitUntil = options.waitUntil ?? "load";
const page = await this.#resolve();
+ const deadline = this.#services.now() + timeoutMs;
const { receipt } = await this.#runActionBoundary(
page,
async (sessionId) => {
await reloadInPage(this.#services, sessionId, {
timeoutMs,
waitUntil,
+ deadline,
});
},
- { inputAction: false },
+ { inputAction: false, sessionTimeoutMs: timeoutMs },
);
return receipt;
}
@@ -3044,7 +3053,12 @@ class Page {
// Navigation already waits on page lifecycle; only input actions need
// the ordering round trip to see a popup created by the input itself.
inputAction = true,
- }: { guardFileChooser?: boolean; inputAction?: boolean } = {},
+ sessionTimeoutMs,
+ }: {
+ guardFileChooser?: boolean;
+ inputAction?: boolean;
+ sessionTimeoutMs?: number;
+ } = {},
): Promise<{ value: T; receipt: PageActionReceipt }> {
const explicitDownload = this.#pendingDownload;
const armedDownload = explicitDownload
@@ -3062,80 +3076,84 @@ class Page {
throw new Error("file chooser waiter belongs to a different Page");
}
}
- return this.#services.gate.withPage(page, async ({ sessionId }) => {
- await this.#activate(page.targetId);
- await armedDownload?.interception.ready(sessionId);
- const fileChooserGuard =
- guardFileChooser && !explicitFileChooser
- ? this.#services.prepareFileChooser(sessionId, {
- timeoutMs: 1_000,
- cancel: true,
- })
- : undefined;
- const popupWatch = await this.#watchPopups(inputAction);
- try {
- await fileChooserGuard?.ready;
- const fileInputProbe = fileChooserGuard
- ? await this.#installFileInputProbe(sessionId)
- : false;
- let actionError: unknown;
- let value: T | undefined;
+ return this.#services.gate.withPage(
+ page,
+ async ({ sessionId }) => {
+ await this.#activate(page.targetId);
+ await armedDownload?.interception.ready(sessionId);
+ const fileChooserGuard =
+ guardFileChooser && !explicitFileChooser
+ ? this.#services.prepareFileChooser(sessionId, {
+ timeoutMs: 1_000,
+ cancel: true,
+ })
+ : undefined;
+ const popupWatch = await this.#watchPopups(inputAction);
try {
- value = await operation(sessionId);
- } catch (error) {
- actionError = error;
- }
+ await fileChooserGuard?.ready;
+ const fileInputProbe = fileChooserGuard
+ ? await this.#installFileInputProbe(sessionId)
+ : false;
+ let actionError: unknown;
+ let value: T | undefined;
+ try {
+ value = await operation(sessionId);
+ } catch (error) {
+ actionError = error;
+ }
- if (isPageDialogOpenedError(actionError)) {
- const dialog =
- this.#services.pendingDialog(sessionId) || actionError.dialog;
- return {
- value: undefined as T,
- receipt: { dialog },
- };
- }
+ if (isPageDialogOpenedError(actionError)) {
+ const dialog =
+ this.#services.pendingDialog(sessionId) || actionError.dialog;
+ return {
+ value: undefined as T,
+ receipt: { dialog },
+ };
+ }
- if (!inputAction) {
- await this.#services.sleep(NAVIGATION_FRAME_SETTLE_MS);
- }
- let popupError: unknown;
- let popups: PopupReceiptEntry[] = [];
- try {
- popups = await popupWatch.collect(sessionId);
- } catch (error) {
- popupError = error;
- }
+ if (!inputAction) {
+ await this.#services.sleep(NAVIGATION_FRAME_SETTLE_MS);
+ }
+ let popupError: unknown;
+ let popups: PopupReceiptEntry[] = [];
+ try {
+ popups = await popupWatch.collect(sessionId);
+ } catch (error) {
+ popupError = error;
+ }
- if (fileChooserGuard && !fileChooserGuard.peek()) {
- const clickedFileInput = fileInputProbe
- ? await this.#readFileInputProbe(sessionId)
- : null;
- if (clickedFileInput !== false) {
- await Promise.race([
- fileChooserGuard.event.catch(() => {}),
- this.#services.sleep(
- clickedFileInput
- ? FILE_CHOOSER_OPEN_WAIT_MS
- : FILE_CHOOSER_SETTLE_MS,
- ),
- ]);
+ if (fileChooserGuard && !fileChooserGuard.peek()) {
+ const clickedFileInput = fileInputProbe
+ ? await this.#readFileInputProbe(sessionId)
+ : null;
+ if (clickedFileInput !== false) {
+ await Promise.race([
+ fileChooserGuard.event.catch(() => {}),
+ this.#services.sleep(
+ clickedFileInput
+ ? FILE_CHOOSER_OPEN_WAIT_MS
+ : FILE_CHOOSER_SETTLE_MS,
+ ),
+ ]);
+ }
+ }
+ if (fileChooserGuard?.peek()) {
+ throw unhandledFileChooserError();
}
- }
- if (fileChooserGuard?.peek()) {
- throw unhandledFileChooserError();
- }
- if (actionError) throw actionError;
- if (popupError) throw popupError;
- return {
- value: value as T,
- receipt: popups.length > 0 ? { popups } : {},
- };
- } finally {
- popupWatch.dispose();
- await fileChooserGuard?.dispose();
- }
- });
+ if (actionError) throw actionError;
+ if (popupError) throw popupError;
+ return {
+ value: value as T,
+ receipt: popups.length > 0 ? { popups } : {},
+ };
+ } finally {
+ popupWatch.dispose();
+ await fileChooserGuard?.dispose();
+ }
+ },
+ { sessionTimeoutMs },
+ );
}
/**
@@ -3281,6 +3299,44 @@ class Page {
return popups;
}
+ /**
+ * Replace the runtime's generic "did not answer" error with one that names
+ * this Page and tells the agent what can be done about it. Thrown from here
+ * so the stack shows the public call instead of a transport timer.
+ */
+ async #describeUnresponsivePage(
+ error: PageUnresponsiveError,
+ page: PageTarget,
+ ): Promise<PageUnresponsiveError> {
+ let url: string | undefined;
+ try {
+ // The browser process answers Target.* on its own, so this cannot stall.
+ // Its URL may already show the pending navigation, so do not call it
+ // the committed one.
+ const response = await this.#services.cdp(
+ "Target.getTargetInfo",
+ { targetId: page.targetId },
+ undefined,
+ PAGE_UNRESPONSIVE_URL_TIMEOUT_MS,
+ );
+ const info = response?.result?.targetInfo || response?.targetInfo;
+ if (typeof info?.url === "string" && info.url.length > 0) url = info.url;
+ } catch {
+ // The URL is a courtesy; the error stands without it.
+ }
+ const described = new PageUnresponsiveError(
+ error.method,
+ error.waitedMs,
+ page.targetId,
+ error.sessionId,
+ );
+ described.message =
+ `Page ${this.label}${url ? ` (${url})` : ""} did not answer ${error.method} within ${error.waitedMs}ms. ` +
+ "Chromium suspends every renderer command while a main-frame navigation has started but not committed, and a hung renderer behaves the same way. " +
+ 'Retry once the pending navigation commits, call page.goto(url, { timeout }) with a longer timeout, stop the pending navigation with page.cdp("Page.stopLoading"), or continue on a new Page from task.newPage().';
+ return described;
+ }
+
async #refMapForAction(
page: PageTarget,
sessionId: string,
@@ -3320,9 +3376,13 @@ class Page {
page: PageTarget,
sessionId: string,
): Promise<Map<string, string>> {
- const iframeSessions = await this.#services.ensureFrameSessions(
- page.targetId,
- );
+ let iframeSessions: Map<string, string>;
+ try {
+ iframeSessions = await this.#services.ensureFrameSessions(page.targetId);
+ } catch (error) {
+ if (!isPageUnresponsiveError(error)) throw error;
+ throw await this.#describeUnresponsivePage(error, page);
+ }
const readTree = async (session: string) => {
const response = await this.#services.cdp(
"Page.getFrameTree",