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
fix(ego-browser): stop a pending navigation from evaluate and screenshot too
Zhuowei Wang28f5f7323b28
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjsindex e41a308..9d5d746 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs@@ -71,6 +71,7 @@ import { pageActionabilityCase } from "./page-actionability.mjs";import { pageEvaluateTimeoutCase } from "./page-evaluate-timeout.mjs";import {pagePendingNavigationCase,+ pagePendingNavigationEvaluateScreenshotCase,pagePendingNavigationFreshProcessCase,} from "./page-pending-navigation.mjs";import {@@ -244,6 +245,11 @@ export const e2eCases = [body: pagePendingNavigationFreshProcessCase,timeoutMs: 60_000,},+ {+ name: "Page pending navigation: evaluate and screenshot",+ body: pagePendingNavigationEvaluateScreenshotCase,+ 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.mjsindex 6bfbd24..6a24eb8 100644--- 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@@ -179,6 +179,114 @@ export function pagePendingNavigationCase() {`;}+// evaluate() and screenshot() reach the renderer through Runtime.evaluate+// rather than frame discovery; they end in the same bounded wait and stop.+export function pagePendingNavigationEvaluateScreenshotCase() {+ return `+ const transportMs = ${PENDING_NAVIGATION_RESPONSE_TIMEOUT_MS};+ process.env.EGO_BROWSER_RESPONSE_TIMEOUT_MS = String(transportMs);+ const task = await taskSpace(taskName);+ const page = await newPageAt(+ task,+ baseUrl + "/nav-target?pending-navigation-eval=" + Date.now()+ );+ const heldUrl = baseUrl + "/hold-page?ms=120000";+ const leavePending = (suffix) =>+ page+ .cdp("Page.navigate", { url: heldUrl + suffix }, { timeout: 500 })+ .catch(() => {});++ await leavePending("&eval=1");+ const evaluateStartedAt = Date.now();+ let evaluateError;+ try {+ await page.evaluate(() => document.title);+ } catch (error) {+ evaluateError = error;+ }+ const evaluateElapsed = Date.now() - evaluateStartedAt;+ assertEqual(+ evaluateError?.code,+ "EGO_PAGE_EVALUATION_TIMED_OUT",+ "evaluate during a pending navigation times out: " + evaluateError?.message+ );+ assertEqual(+ evaluateError?.stopped,+ true,+ "evaluate stops the pending navigation once its wait ran out"+ );+ assertEqual(evaluateError?.pageResponsive, true, "the Page answers again");+ assertIncludes(+ evaluateError?.message,+ "on Page " + page.label,+ "the evaluate error names the Page"+ );+ assertIncludes(+ evaluateError?.message,+ "shows " + baseUrl + "/nav-target",+ "the evaluate error says which document the Page shows now"+ );+ assert(+ evaluateElapsed < transportMs * 2 + 4_000,+ "evaluate gives up after one bounded wait: " + evaluateElapsed+ );+ const evaluateAgainStartedAt = Date.now();+ assertEqual(+ await page.evaluate(() => document.title),+ "ego-lite nav target",+ "the next evaluate answers on the previous document"+ );+ assert(+ Date.now() - evaluateAgainStartedAt < 5_000,+ "the next evaluate does not wait another full period: " ++ (Date.now() - evaluateAgainStartedAt)+ );++ await leavePending("&shot=1");+ const screenshotStartedAt = Date.now();+ let screenshotError;+ try {+ await page.screenshot();+ } catch (error) {+ screenshotError = error;+ }+ const screenshotElapsed = Date.now() - screenshotStartedAt;+ assertEqual(+ screenshotError?.code,+ "EGO_PAGE_UNRESPONSIVE",+ "screenshot during a pending navigation reports the unresponsive Page: " ++ screenshotError?.message+ );+ assertEqual(+ screenshotError?.stopped,+ true,+ "screenshot stops the pending navigation once its wait ran out"+ );+ assertIncludes(+ screenshotError?.message,+ "Page " + page.label,+ "the screenshot error names the Page"+ );+ assertIncludes(+ screenshotError?.message,+ "shows " + baseUrl + "/nav-target",+ "the screenshot error says which document the Page shows now"+ );+ assert(+ screenshotElapsed < transportMs * 2 + 4_000,+ "screenshot gives up after one bounded wait: " + screenshotElapsed+ );+ const screenshotAgainStartedAt = Date.now();+ await page.screenshot();+ assert(+ Date.now() - screenshotAgainStartedAt < 5_000,+ "the next screenshot does not wait another full period: " ++ (Date.now() - screenshotAgainStartedAt)+ );+ await page.close();+ `;+}+export function pagePendingNavigationFreshProcessCase() {return `const transportMs = ${PENDING_NAVIGATION_RESPONSE_TIMEOUT_MS};diff --git a/package/ego-browser/skill-body/SKILL.md b/package/ego-browser/skill-body/SKILL.mdindex f64ed54..f30630e 100644--- a/package/ego-browser/skill-body/SKILL.md+++ b/package/ego-browser/skill-body/SKILL.md@@ -225,7 +225,9 @@ timeout, so the Page stays usable on its previous document; retry with a longertimeout. Any other call on a Page whose navigation is pending (after a linkclick, for example) waits one bounded period, then fails with`EGO_PAGE_UNRESPONSIVE` and stops that navigation; the error says which-document the Page shows now and how to load the pending one.+document the Page shows now and how to load the pending one. `evaluate()`+reports the same outcome as `EGO_PAGE_EVALUATION_TIMED_OUT` with `stopped`+set.Work efficiently:diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjsindex d0264f2..7935f74 100644--- a/package/ego-browser/src/page-model.test.mjs+++ b/package/ego-browser/src/page-model.test.mjs@@ -7680,6 +7680,199 @@ test("snapshot names a probably hung renderer when stopping does not help", asyn});});+test("screenshot stops a pending navigation when the Page never answers its renderer command", async () => {+ await withFixture(async (fixture) => {+ const baseCdp = fixture.services.cdp;+ let held = true;+ const stops = [];+ const task = taskForRound(fixture, "round-a", {+ async screenshot(path, options, sessionId) {+ if (held) {+ throw new CdpRequestTimeoutError(+ "Runtime.evaluate",+ 15_000,+ sessionId,+ );+ }+ return "/tmp/after-stop.png";+ },+ async cdp(method, params, sessionId, timeoutMs) {+ if (method === "Page.stopLoading") {+ stops.push({ sessionId, timeoutMs });+ held = false;+ return {};+ }+ if (method === "Page.getFrameTree" && !held) {+ return {+ result: {+ frameTree: {+ frame: {+ id: "frame-1",+ loaderId: "loader-old",+ url: "https://example.test/previous",+ },+ },+ },+ };+ }+ return baseCdp(method, params, sessionId, timeoutMs);+ },+ });+ const page = await openTestPage(task, "https://example.test/previous");++ await assert.rejects(+ () => page.screenshot(),+ (error) => {+ assert.equal(error.code, "EGO_PAGE_UNRESPONSIVE");+ assert.equal(error.method, "Runtime.evaluate");+ assert.equal(error.waitedMs, 15_000);+ assert.equal(error.stopped, true);+ assert.equal(error.currentUrl, "https://example.test/previous");+ assert.match(+ error.message,+ /^Page p1 .*did not answer Runtime\.evaluate within 15000ms: a main-frame navigation had started but not committed\. It was stopped once that wait ran out/,+ );+ return true;+ },+ );+ assert.equal(stops.length, 1);+ assert.equal(typeof stops[0].sessionId, "string");+ assert.equal(await page.screenshot(), "/tmp/after-stop.png");+ });+});++test("a browser-level command timeout is not treated as an unresponsive Page", async () => {+ await withFixture(async (fixture) => {+ let stops = 0;+ const task = taskForRound(fixture, "round-a", {+ async screenshot(path, options, sessionId) {+ throw new CdpRequestTimeoutError("Target.getTargetInfo", 15_000);+ },+ async cdp(method, params, sessionId, timeoutMs) {+ if (method === "Page.stopLoading") stops += 1;+ return fixture.services.cdp(method, params, sessionId, timeoutMs);+ },+ });+ const page = await openTestPage(task, "https://example.test/browser");++ await assert.rejects(+ () => page.screenshot(),+ (error) => {+ assert.equal(error.code, "EGO_CDP_REQUEST_TIMEOUT");+ assert.equal(error.method, "Target.getTargetInfo");+ return true;+ },+ );+ assert.equal(stops, 0);+ });+});++test("evaluate stops a pending navigation when the Page never answers", async () => {+ await withFixture(async (fixture) => {+ const baseCdp = fixture.services.cdp;+ let held = false;+ let terminateCalls = 0;+ const stops = [];+ const task = taskForRound(fixture, "round-a", {+ async cdp(method, params, sessionId, timeoutMs) {+ if (+ method === "Runtime.evaluate" &&+ params.expression.includes("__egoPageEvaluate") &&+ params.expression.includes("pendingProbe")+ ) {+ held = true;+ }+ if (held && method === "Runtime.evaluate") {+ throw new CdpRequestTimeoutError(method, timeoutMs, sessionId);+ }+ if (held && method === "Runtime.terminateExecution") {+ terminateCalls += 1;+ throw new CdpRequestTimeoutError(method, timeoutMs, sessionId);+ }+ if (method === "Page.stopLoading") {+ stops.push({ sessionId, timeoutMs });+ held = false;+ return {};+ }+ if (method === "Page.getFrameTree" && stops.length > 0) {+ return {+ result: {+ frameTree: {+ frame: {+ id: "frame-1",+ loaderId: "loader-old",+ url: "https://example.test/previous",+ },+ },+ },+ };+ }+ return baseCdp(method, params, sessionId, timeoutMs);+ },+ });+ const page = await openTestPage(task, "https://example.test/previous");++ await assert.rejects(+ () => page.evaluate(() => "pendingProbe"),+ (error) => {+ assert.equal(error.code, "EGO_PAGE_EVALUATION_TIMED_OUT");+ assert.equal(error.stopped, true);+ assert.equal(error.currentUrl, "https://example.test/previous");+ assert.equal(error.pageResponsive, true);+ assert.equal(error.executionStopped, false);+ assert.equal(error.mayHaveLateEffects, true);+ assert.match(+ error.message,+ /^page\.evaluate on Page p1 timed out after \d+ms: a main-frame navigation had started but not committed, so the Page answered nothing\. It was stopped once that wait ran out, so the Page answers again and shows https:\/\/example\.test\/previous; the evaluation may still run late/,+ );+ assert.match(error.message, /page\.goto\(url, \{ timeout \}\)/);+ return true;+ },+ );+ assert.equal(terminateCalls, 1, "termination is still attempted first");+ assert.equal(stops.length, 1);+ });+});++test("evaluate names a probably hung renderer when stopping does not help", async () => {+ await withFixture(async (fixture) => {+ const baseCdp = fixture.services.cdp;+ let held = false;+ const task = taskForRound(fixture, "round-a", {+ async cdp(method, params, sessionId, timeoutMs) {+ if (+ method === "Runtime.evaluate" &&+ params.expression.includes("hungProbe")+ ) {+ held = true;+ }+ if (+ held &&+ (method === "Runtime.evaluate" ||+ method === "Runtime.terminateExecution" ||+ method === "Page.stopLoading")+ ) {+ throw new CdpRequestTimeoutError(method, timeoutMs, sessionId);+ }+ return baseCdp(method, params, sessionId, timeoutMs);+ },+ });+ const page = await openTestPage(task, "https://example.test/hung");++ await assert.rejects(+ () => page.evaluate(() => "hungProbe"),+ (error) => {+ assert.equal(error.code, "EGO_PAGE_EVALUATION_TIMED_OUT");+ assert.equal(error.stopped, false);+ assert.equal(error.pageResponsive, false);+ assert.match(error.message, /renderer is probably hung/);+ assert.match(error.message, /task\.newPage\(\)/);+ return true;+ },+ );+ });+});+test("snapshot describes a Page that stops answering after the first document check", async () => {await withFixture(async (fixture) => {let calls = 0;diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.tsindex 13f9fe0..b364ec9 100644--- a/package/ego-browser/src/page-model.ts+++ b/package/ego-browser/src/page-model.ts@@ -583,6 +583,13 @@ export class PageEvaluationTimeoutError extends Error {readonly executionStopped: boolean;readonly mayHaveLateEffects: boolean;readonly pageResponsive: boolean;+ /**+ * A main-frame navigation that had not committed kept the Page from+ * answering; it was stopped once the wait ran out and the Page answers+ * again, showing `currentUrl`.+ */+ stopped = false;+ currentUrl?: string;constructor(message: string,@@ -1953,7 +1960,7 @@ class Page {);}const page = await this.#resolve();- return this.#services.gate.withPage(page, async ({ sessionId }) => {+ return this.#withPage(page, async ({ sessionId }) => {await this.#activate(page.targetId);let root: number | undefined;let rootContext:@@ -2242,7 +2249,7 @@ class Page {async info(): Promise<Record<string, unknown>> {const page = await this.#resolve();- return this.#services.gate.withPage(page, async ({ sessionId }) => {+ return this.#withPage(page, async ({ sessionId }) => {const dialog = this.#services.pendingDialog(sessionId);if (dialog) return { dialog };return evaluateInSession(@@ -2360,6 +2367,7 @@ class Page {sessionId,"page.waitForFunction",timeoutMs,+ this.label,);}if (!isRetryablePageEvaluationError(error)) {@@ -2402,7 +2410,7 @@ class Page {assertUrl(url);const { payload, saveAs } = pageFetchPayload(url, options);const page = await this.#resolve();- return this.#services.gate.withPage(page, async ({ sessionId }) => {+ return this.#withPage(page, async ({ sessionId }) => {await this.#activate(page.targetId);const response = await evaluateInSession<PageFetchResult>(this.#services,@@ -2507,7 +2515,7 @@ class Page {assertAbsoluteFilePath(path, "page.screenshot path");}const page = await this.#resolve();- return this.#services.gate.withPage(page, async ({ sessionId }) => {+ return this.#withPage(page, async ({ sessionId }) => {await this.#activate(page.targetId);return this.#services.screenshot(path,@@ -2875,6 +2883,7 @@ class Page {sessionId,"page.evaluate",pageEvaluateTransportTimeoutMs(),+ this.label,);}if (typeof expression === "function") {@@ -3144,7 +3153,7 @@ class Page {page: PageTarget,operation: (sessionId: string) => Promise<T>,): Promise<T> {- return this.#services.gate.withPage(page, async ({ sessionId }) => {+ return this.#withPage(page, async ({ sessionId }) => {await this.#activate(page.targetId);return operation(sessionId);});@@ -3181,7 +3190,7 @@ class Page {throw new Error("file chooser waiter belongs to a different Page");}}- return this.#services.gate.withPage(+ return this.#withPage(page,async ({ sessionId }) => {await this.#activate(page.targetId);@@ -3409,6 +3418,47 @@ class Page {* unresponsive Page is always reported with its label and recovery steps,* whichever step of an operation first ran into it.*/+ /**+ * Run one public call on this Page. A renderer-bound command that the Page+ * never answered is the same condition frame discovery reports as an+ * unresponsive Page, so it is described the same way: the pending+ * navigation is stopped and the error names the Page and what it shows.+ */+ async #withPage<T>(+ page: PageTarget,+ operation: (context: PageExecutionContext) => T | Promise<T>,+ options: WithPageOptions = {},+ ): Promise<T> {+ let activeSessionId: string | undefined;+ try {+ return await this.#services.gate.withPage(+ page,+ (context) => {+ activeSessionId = context.sessionId;+ return operation(context);+ },+ options,+ );+ } catch (error) {+ if (+ !isCdpRequestTimeoutError(error) ||+ isPageUnresponsiveError(error) ||+ isBrowserLevelMethod(error.method)+ ) {+ throw error;+ }+ throw await this.#describeUnresponsivePage(+ new PageUnresponsiveError(+ error.method,+ error.timeoutMs,+ page.targetId,+ error.sessionId ?? activeSessionId,+ ),+ page,+ );+ }+ }+async #frameSessions(page: PageTarget,timeoutMs?: number,@@ -3477,37 +3527,10 @@ class Page {return described;}- /**- * Stop whatever main-frame navigation keeps this Page from answering and- * read its main frame once it does. "hung" means the Page still answers- * nothing: a hung renderer, which Page.stopLoading cannot help.- */async #stopPendingNavigation(sessionId: string,): Promise<{ url?: string } | "hung"> {- try {- await this.#services.cdp(- "Page.stopLoading",- {},- sessionId,- PAGE_UNRESPONSIVE_STOP_TIMEOUT_MS,- );- const response = await this.#services.cdp(- "Page.getFrameTree",- {},- sessionId,- PAGE_UNRESPONSIVE_STOP_TIMEOUT_MS,- );- const frame =- response?.result?.frameTree?.frame || response?.frameTree?.frame;- return {- ...(typeof frame?.url === "string" && frame.url.length > 0- ? { url: frame.url }- : {}),- };- } catch {- return "hung";- }+ return stopPendingNavigationInSession(this.#services, sessionId);}async #refMapForAction(@@ -3983,6 +4006,7 @@ async function recoverPageEvaluationTimeout(sessionId: string,apiName: string,timeoutMs: number,+ label?: string,): Promise<PageEvaluationTimeoutError> {if (await pageEvaluationHealthProbe(services, sessionId)) {return new PageEvaluationTimeoutError(@@ -4024,8 +4048,28 @@ async function recoverPageEvaluationTimeout();}+ // Nothing from the renderer: the usual cause is a main-frame navigation+ // that has not committed. The wait that ran out was this call's budget, so+ // stop that navigation as the other public calls do; the evaluation itself+ // was never confirmed stopped and may still run on the document in place.+ const recovered = await stopPendingNavigationInSession(services, sessionId);+ if (recovered !== "hung") {+ const error = new PageEvaluationTimeoutError(+ `${apiName}${label ? ` on Page ${label}` : ""} timed out after ${timeoutMs}ms: a main-frame navigation had started but not committed, so the Page answered nothing. It was stopped once that wait ran out, so the Page answers again${recovered.url ? ` and shows ${recovered.url}` : ""}; the evaluation may still run late on that document. Retry the call to continue on that document; to load the pending one, call page.goto(url, { timeout }) with a longer timeout, or continue on a new Page from task.newPage().`,+ {+ timeoutMs,+ executionStopped: false,+ mayHaveLateEffects: true,+ pageResponsive: true,+ },+ );+ error.stopped = true;+ error.currentUrl = recovered.url;+ return error;+ }+return new PageEvaluationTimeoutError(- `${apiName} timed out after ${timeoutMs}ms and the Page is still unresponsive. Execution could not be confirmed stopped; reload or close the Page before continuing.`,+ `${apiName}${label ? ` on Page ${label}` : ""} timed out after ${timeoutMs}ms and the Page is still unresponsive, even after Page.stopLoading, so its renderer is probably hung. Execution could not be confirmed stopped; continue on a new Page from task.newPage(), or close this Page and open it again.`,{timeoutMs,executionStopped: false,@@ -4035,6 +4079,44 @@ async function recoverPageEvaluationTimeout();}+/**+ * Stop whatever main-frame navigation keeps a Page from answering and read+ * its main frame once it does. "hung" means the Page still answers nothing: a+ * hung renderer, which Page.stopLoading cannot help.+ */+async function stopPendingNavigationInSession(+ services: PageModelServices,+ sessionId: string,+): Promise<{ url?: string } | "hung"> {+ try {+ await services.cdp(+ "Page.stopLoading",+ {},+ sessionId,+ PAGE_UNRESPONSIVE_STOP_TIMEOUT_MS,+ );+ const response = await services.cdp(+ "Page.getFrameTree",+ {},+ sessionId,+ PAGE_UNRESPONSIVE_STOP_TIMEOUT_MS,+ );+ const frame =+ response?.result?.frameTree?.frame || response?.frameTree?.frame;+ return {+ ...(typeof frame?.url === "string" && frame.url.length > 0+ ? { url: frame.url }+ : {}),+ };+ } catch {+ return "hung";+ }+}++function isBrowserLevelMethod(method: string): boolean {+ return method.startsWith("Target.") || method.startsWith("Browser.");+}+async function pageEvaluationHealthProbe(services: PageModelServices,sessionId: string,