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): fail every renderer command fast while a JavaScript dialog is open

Zhuowei Wang026be96920d1
diff --git a/docs/native-javascript-dialog-requirement.md b/docs/native-javascript-dialog-requirement.md
index c99aa39..1214512 100644
--- a/docs/native-javascript-dialog-requirement.md
+++ b/docs/native-javascript-dialog-requirement.md
@@ -26,6 +26,20 @@ No new binding is required. The existing CDP bridge must:
Permission prompts and device choosers must continue to transfer control to
the user.
+A dialog can outlive the `ego-browser nodejs` invocation that opened it. The
+SDK keeps dialog state per process, and while a dialog is open Chromium does
+not answer renderer commands, including `Page.enable`. The next invocation
+therefore cannot discover the dialog and every command it sends times out.
+Ego Lite 0.5.2.2 does not meet this requirement yet: in local runs the dialog
+was dismissed when the invocation exited, and sometimes the TaskSpace also
+moved to user control. In the field, the dialog stayed open and the next
+invocation timed out. When an invocation exits with a dialog open, the bridge
+must:
+
+- keep the dialog open and the TaskSpace Agent-owned;
+- report the open dialog to the next session that attaches to the Page, for
+ example by emitting `Page.javascriptDialogOpening` after `Page.enable`.
+
Acceptance: trigger each JavaScript dialog from a real Page click, verify that
the TaskSpace remains Agent-owned, accept a prompt with `promptText: "agent"`,
dismiss a confirm, accept an alert, and verify the returned values and opening
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-dialogs.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-dialogs.mjs
index 5f0e58b..bf37a94 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-dialogs.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-dialogs.mjs
@@ -159,6 +159,33 @@ export function pageJavaScriptDialogHandlingCase() {
"Page.javascriptDialogOpening",
(params) => params.type === "confirm"
);
+ // Chromium does not answer renderer commands while the confirm is open.
+ // Each must fail fast and name the dialog instead of running into the
+ // transport timeout.
+ for (const [label, operation] of [
+ ["snapshot", () => page.snapshot()],
+ ["screenshot", () => page.screenshot()],
+ ["raw Page.getFrameTree", () => page.cdp("Page.getFrameTree", {})],
+ ]) {
+ const startedAt = Date.now();
+ let dialogError;
+ try {
+ await operation();
+ } catch (error) {
+ dialogError = error;
+ }
+ assertEqual(
+ dialogError?.code,
+ "EGO_PAGE_DIALOG_OPENED",
+ label + " reports the open dialog"
+ );
+ assertIncludes(
+ dialogError.message,
+ "page.dismissDialog()",
+ label + " says how to handle the dialog"
+ );
+ assert(Date.now() - startedAt < 2_000, label + " fails fast");
+ }
assertEqual(await page.dismissDialog(), true, "dismissDialog closes a confirm");
await waitForDialogEvent(
"Page.javascriptDialogClosed",
diff --git a/package/ego-browser/src/browser-runtime.test.mjs b/package/ego-browser/src/browser-runtime.test.mjs
index caf6053..77bccdb 100644
--- a/package/ego-browser/src/browser-runtime.test.mjs
+++ b/package/ego-browser/src/browser-runtime.test.mjs
@@ -1561,6 +1561,207 @@ test("a JavaScript dialog interrupts the blocked Page input command", async () =
}
});
+function withDialogRuntime(fn, { hold = [] } = {}) {
+ const previous = globalThis.ego;
+ const sent = [];
+ const runtime = {
+ sendCDPMessage(payload) {
+ const request = JSON.parse(payload);
+ sent.push(request);
+ // Held methods behave like renderer commands stalled behind a dialog.
+ if (hold.includes(request.method)) return;
+ const result =
+ request.method === "Target.attachToTarget"
+ ? { sessionId: "session-page" }
+ : {};
+ queueMicrotask(() => {
+ runtime.onCDPMessage(JSON.stringify({ id: request.id, result }));
+ });
+ },
+ emit(sessionId, method, params) {
+ runtime.onCDPMessage(JSON.stringify({ sessionId, method, params }));
+ },
+ };
+ globalThis.ego = runtime;
+ invalidateSession();
+ return Promise.resolve()
+ .then(() => fn({ runtime, sent }))
+ .finally(() => {
+ invalidateSession();
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ });
+}
+
+const CONFIRM_DIALOG = {
+ type: "confirm",
+ message: "Submit? This cannot be undone.",
+ url: "https://example.test/form",
+};
+
+test("an open JavaScript dialog fails renderer commands fast and names the dialog", async () => {
+ await withDialogRuntime(async ({ runtime, sent }) => {
+ const attached = await browserCdp("Target.attachToTarget", {
+ targetId: "target-page",
+ flatten: true,
+ });
+ const sessionId = attached.result.sessionId;
+ runtime.emit(sessionId, "Page.javascriptDialogOpening", CONFIRM_DIALOG);
+ sent.length = 0;
+
+ for (const method of [
+ "Page.getFrameTree",
+ "Page.captureScreenshot",
+ "Page.getLayoutMetrics",
+ "Accessibility.getFullAXTree",
+ "DOM.getBoxModel",
+ ]) {
+ await assert.rejects(
+ () => browserCdp(method, {}, sessionId, 10_000),
+ (error) => {
+ assert.equal(error.code, "EGO_PAGE_DIALOG_OPENED");
+ assert.equal(error.method, method);
+ assert.deepEqual(error.dialog, CONFIRM_DIALOG);
+ assert.equal(
+ error.message,
+ `${method} cannot run while a JavaScript confirm dialog ` +
+ `("Submit? This cannot be undone.") is open; handle it with ` +
+ "page.acceptDialog() or page.dismissDialog() before continuing",
+ );
+ return true;
+ },
+ );
+ }
+ assert.deepEqual(sent, []);
+
+ // Browser-process methods still answer while the dialog is open.
+ await browserCdp("Target.getTargets", {});
+ await browserCdp(
+ "Page.setDownloadBehavior",
+ { behavior: "default" },
+ sessionId,
+ );
+ await browserCdp(
+ "Page.handleJavaScriptDialog",
+ { accept: false },
+ sessionId,
+ );
+ assert.deepEqual(
+ sent.map((request) => request.method),
+ [
+ "Target.getTargets",
+ "Page.setDownloadBehavior",
+ "Page.handleJavaScriptDialog",
+ ],
+ );
+
+ runtime.emit(sessionId, "Page.javascriptDialogClosed", { result: false });
+ await browserCdp("Page.getFrameTree", {}, sessionId);
+ });
+});
+
+test("a dialog rejects stalled in-flight commands across the Page's frame sessions", async () => {
+ await withDialogRuntime(
+ async ({ runtime, sent }) => {
+ const attached = await browserCdp("Target.attachToTarget", {
+ targetId: "target-page",
+ flatten: true,
+ });
+ const pageSession = attached.result.sessionId;
+ runtime.emit(pageSession, "Target.attachedToTarget", {
+ sessionId: "session-frame",
+ targetInfo: { targetId: "target-frame", type: "iframe" },
+ waitingForDebugger: false,
+ });
+
+ const pageTree = browserCdp("Page.getFrameTree", {}, pageSession, 10_000);
+ const frameTree = browserCdp(
+ "Page.getFrameTree",
+ {},
+ "session-frame",
+ 10_000,
+ );
+ let downloadSettled = false;
+ const download = browserCdp(
+ "Page.setDownloadBehavior",
+ { behavior: "default" },
+ pageSession,
+ 50,
+ ).finally(() => {
+ downloadSettled = true;
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+
+ // Chromium reports a dialog opened by any frame on the Page session.
+ runtime.emit(pageSession, "Page.javascriptDialogOpening", CONFIRM_DIALOG);
+
+ for (const [promise, sessionId] of [
+ [pageTree, pageSession],
+ [frameTree, "session-frame"],
+ ]) {
+ await assert.rejects(promise, (error) => {
+ assert.equal(error.code, "EGO_PAGE_DIALOG_OPENED");
+ assert.equal(error.sessionId, sessionId);
+ assert.match(
+ error.message,
+ /^a JavaScript confirm dialog \("Submit\? This cannot be undone\."\) opened while Page\.getFrameTree was running;/,
+ );
+ return true;
+ });
+ }
+ assert.equal(downloadSettled, false, "safe commands stay in flight");
+ await assert.rejects(download, CdpRequestTimeoutError);
+
+ // New commands on the frame session fail before they are sent.
+ sent.length = 0;
+ await assert.rejects(
+ () =>
+ browserCdp(
+ "Accessibility.getFullAXTree",
+ {},
+ "session-frame",
+ 10_000,
+ ),
+ (error) => error.code === "EGO_PAGE_DIALOG_OPENED",
+ );
+ assert.deepEqual(sent, []);
+ },
+ { hold: ["Page.getFrameTree", "Page.setDownloadBehavior"] },
+ );
+});
+
+test("a raw command stalled by a known dialog reports it instead of a bare timeout", async () => {
+ await withDialogRuntime(
+ async ({ runtime }) => {
+ const attached = await browserCdp("Target.attachToTarget", {
+ targetId: "target-page",
+ flatten: true,
+ });
+ const sessionId = attached.result.sessionId;
+ runtime.emit(sessionId, "Page.javascriptDialogOpening", CONFIRM_DIALOG);
+
+ // Network tracking sends Network.enable directly, outside browserCdp's
+ // pre-send check, so only its timeout can name the dialog.
+ await assert.rejects(
+ () => ensureNetworkTracking([sessionId], 20),
+ (error) => {
+ assert.equal(error.code, "EGO_PAGE_DIALOG_OPENED");
+ assert.equal(error.method, "Network.enable");
+ assert.match(error.message, /^Network\.enable cannot run while/);
+ return true;
+ },
+ );
+
+ runtime.emit(sessionId, "Page.javascriptDialogClosed", { result: true });
+ await assert.rejects(
+ () => ensureNetworkTracking([sessionId], 20),
+ CdpRequestTimeoutError,
+ );
+ },
+ { hold: ["Network.enable"] },
+ );
+});
+
test("page event drains exclude unscoped browser events", async () => {
const previous = globalThis.ego;
const runtime = {
diff --git a/package/ego-browser/src/browser-runtime.ts b/package/ego-browser/src/browser-runtime.ts
index 3c2dc09..fe5bedf 100644
--- a/package/ego-browser/src/browser-runtime.ts
+++ b/package/ego-browser/src/browser-runtime.ts
@@ -28,11 +28,15 @@ const OOPIF_AUTO_ATTACH_PARAMS = {
{ exclude: true },
],
};
-const DIALOG_BLOCKED_METHOD = (method) =>
- method.startsWith("Input.") ||
- method.startsWith("Runtime.") ||
- method === "DOM.setFileInputFiles" ||
- method === "Page.navigate";
+// A modal JavaScript dialog stalls every command the renderer has to answer,
+// including Page.getFrameTree, Page.captureScreenshot, DOM.*, Accessibility.*,
+// and even Page.enable. Only methods the browser process answers on its own
+// keep working, so allow those and fail every other command fast instead of
+// letting it run into the transport timeout.
+const DIALOG_SAFE_METHOD = (method) =>
+ BROWSER_LEVEL(method) ||
+ method === "Page.handleJavaScriptDialog" ||
+ method === "Page.setDownloadBehavior";
let nextMessageId = 1;
const pending = new Map();
const browserEvents = [];
@@ -118,9 +122,21 @@ export class PageDialogOpenedError extends Error {
method: string,
sessionId: string,
dialog: Record<string, unknown>,
+ { alreadyOpen = false }: { alreadyOpen?: boolean } = {},
) {
+ const kind =
+ typeof dialog.type === "string" && dialog.type
+ ? `JavaScript ${dialog.type} dialog`
+ : "JavaScript dialog";
+ const text =
+ typeof dialog.message === "string" && dialog.message
+ ? ` (${JSON.stringify(dialog.message)})`
+ : "";
+ const situation = alreadyOpen
+ ? `${method} cannot run while a ${kind}${text} is open`
+ : `a ${kind}${text} opened while ${method} was running`;
super(
- `a JavaScript dialog opened while ${method} was running; handle the dialog before continuing`,
+ `${situation}; handle it with page.acceptDialog() or page.dismissDialog() before continuing`,
);
this.name = "PageDialogOpenedError";
this.method = method;
@@ -452,7 +468,19 @@ function rawCdp(
return new Promise<any>((resolve, reject) => {
const timer = setTimeout(() => {
pending.delete(id);
- reject(new CdpRequestTimeoutError(method, timeoutMs, sessionId));
+ // Commands sent outside browserCdp() skip its dialog check. Name the
+ // dialog if one is what stalled this command.
+ const dialog =
+ sessionId && !DIALOG_SAFE_METHOD(method)
+ ? pendingDialog(sessionId)
+ : null;
+ reject(
+ dialog
+ ? new PageDialogOpenedError(method, sessionId, dialog, {
+ alreadyOpen: true,
+ })
+ : new CdpRequestTimeoutError(method, timeoutMs, sessionId),
+ );
}, timeoutMs);
pending.set(id, {
method,
@@ -493,9 +521,12 @@ export async function browserCdp(
if (!explicit && !BROWSER_LEVEL(method)) {
effective = await ensureSession();
}
- const dialog = effective ? pendingDialog(effective) : null;
- if (dialog && DIALOG_BLOCKED_METHOD(method)) {
- throw new PageDialogOpenedError(method, effective, dialog);
+ const dialog =
+ effective && !DIALOG_SAFE_METHOD(method) ? pendingDialog(effective) : null;
+ if (dialog) {
+ throw new PageDialogOpenedError(method, effective, dialog, {
+ alreadyOpen: true,
+ });
}
try {
const response = await rawCdp(method, params, effective, timeoutMs);
@@ -848,11 +879,19 @@ export function drainPageEvents(sessionId) {
return target ? target.events.splice(0, target.events.length) : [];
}
+/**
+ * Return the JavaScript dialog blocking the Page that owns this session. An
+ * OOPIF session reports its top-level Page's dialog: Chromium delivers every
+ * dialog event on the Page session, and a dialog opened by any frame stalls
+ * that frame's renderer.
+ */
export function pendingDialog(sessionId) {
const targetId = sessionId
? sessionTargets.get(sessionId)
: state.preferredTargetId || defaultTargetId;
- const dialog = targetId ? targetStates.get(targetId)?.pendingDialog : null;
+ const dialog = targetId
+ ? targetStates.get(pageRootTargetId(targetId))?.pendingDialog
+ : null;
return dialog ? { ...dialog } : null;
}
@@ -1456,14 +1495,23 @@ function handleMessage(message) {
}
if (data.method === "Page.javascriptDialogOpening") {
if (target) {
- target.pendingDialog = data.params || {};
- rejectCommandsBlockedByDialog(
- sessionId,
- target.pendingDialog as Record<string, unknown>,
- );
+ // A Page event proves the domain is enabled even if the Page.enable
+ // response is stalled behind this dialog and rejected below.
+ target.pageEventsEnabled = true;
+ const root = targetStates.get(pageRootTargetId(targetId));
+ if (root) {
+ root.pendingDialog = data.params || {};
+ rejectCommandsBlockedByDialog(
+ targetId,
+ root.pendingDialog as Record<string, unknown>,
+ );
+ }
}
} else if (data.method === "Page.javascriptDialogClosed") {
- if (target) target.pendingDialog = null;
+ const root = targetId
+ ? targetStates.get(pageRootTargetId(targetId))
+ : undefined;
+ if (root) root.pendingDialog = null;
} else if (data.method === "Page.fileChooserOpened") {
target?.fileChooserInterception?.resolve(data.params || {});
}
@@ -1483,16 +1531,24 @@ function handleMessage(message) {
}
function rejectCommandsBlockedByDialog(
- sessionId: string | undefined,
+ targetId: string,
dialog: Record<string, unknown>,
) {
- if (!sessionId) return;
+ // The dialog stalls whichever renderer opened it, and CDP does not say which
+ // frame session that is. Treat the whole Page tree as blocked.
+ const sessionIds = new Set(
+ pageTreeTargetIds(pageRootTargetId(targetId))
+ .map((id) => targetStates.get(id)?.sessionId)
+ .filter(Boolean),
+ );
for (const [id, entry] of pending) {
- if (entry.sessionId !== sessionId || !DIALOG_BLOCKED_METHOD(entry.method)) {
+ if (!sessionIds.has(entry.sessionId) || DIALOG_SAFE_METHOD(entry.method)) {
continue;
}
pending.delete(id);
- entry.reject(new PageDialogOpenedError(entry.method, sessionId, dialog));
+ entry.reject(
+ new PageDialogOpenedError(entry.method, entry.sessionId, dialog),
+ );
}
}
diff --git a/package/ego-browser/src/driver/observe.test.mjs b/package/ego-browser/src/driver/observe.test.mjs
index af5a7df..fa1d7bf 100644
--- a/package/ego-browser/src/driver/observe.test.mjs
+++ b/package/ego-browser/src/driver/observe.test.mjs
@@ -137,7 +137,7 @@ test("snapshotText forwards a subtree root to the native snapshot", async () =>
}
});
-test("captureScreenshot skips page metric JavaScript while a native dialog is pending", async () => {
+test("captureScreenshot fails fast while a native dialog is pending", async () => {
const writes = [];
const restore = setOverrides({
async writeFile(path, data) {
@@ -154,26 +154,30 @@ test("captureScreenshot skips page metric JavaScript while a native dialog is pe
});
sent.length = 0;
- await captureScreenshot("/tmp/ego-browser-dialog-shot.png");
-
+ // Chromium does not answer Page.captureScreenshot until the dialog
+ // closes, so the capture must not be attempted at all.
+ await assert.rejects(
+ () => captureScreenshot("/tmp/ego-browser-dialog-shot.png"),
+ (error) => {
+ assert.equal(error.code, "EGO_PAGE_DIALOG_OPENED");
+ assert.match(error.message, /page\.dismissDialog\(\)/);
+ return true;
+ },
+ );
assert.equal(
- sent.some((request) => request.method === "Runtime.evaluate"),
+ sent.some(
+ (request) =>
+ request.method === "Runtime.evaluate" ||
+ request.method === "Page.captureScreenshot",
+ ),
false,
);
- const screenshot = sent.find(
- (request) => request.method === "Page.captureScreenshot",
- );
- assert.deepEqual(screenshot.params, {
- format: "png",
- captureBeyondViewport: false,
- });
});
} finally {
restore();
}
- assert.equal(writes.length, 1);
- assert.equal(writes[0].path, "/tmp/ego-browser-dialog-shot.png");
+ assert.equal(writes.length, 0);
});
test("captureScreenshot clips the currently visible scrolled viewport", async () => {
diff --git a/package/ego-browser/src/driver/observe.ts b/package/ego-browser/src/driver/observe.ts
index 41556c7..f0389e8 100644
--- a/package/ego-browser/src/driver/observe.ts
+++ b/package/ego-browser/src/driver/observe.ts
@@ -10,7 +10,6 @@ import {
drainBrowserEvents,
ensureSession,
isBrowserRuntime,
- pendingDialog,
} from "../browser-runtime.js";
import { invokeEgo } from "../ego-errors.js";
import { resolveElementCenter } from "../element-resolver.js";
@@ -129,51 +128,49 @@ export async function captureScreenshotForSession(
params.clip = { ...options.clip };
}
} else {
- if (!pendingDialog(sessionId)) {
- const dprExpression = "window.devicePixelRatio";
- const dpr =
- Number(
- runtimeValue(
- await cdp(
- "Runtime.evaluate",
- {
- expression: dprExpression,
- returnByValue: true,
- },
- sessionId,
- ),
- dprExpression,
- ),
- ) || 1;
- const cssScale = 1 / dpr;
- if (options.clip) {
- params.clip = { scale: cssScale, ...options.clip };
- } else {
- const infoExpression =
- "({url:location.href,title:document.title,w:innerWidth,h:innerHeight,sx:scrollX,sy:scrollY,pw:document.documentElement.scrollWidth,ph:document.documentElement.scrollHeight})";
- const info = runtimeValue(
+ const dprExpression = "window.devicePixelRatio";
+ const dpr =
+ Number(
+ runtimeValue(
await cdp(
"Runtime.evaluate",
{
- expression: infoExpression,
+ expression: dprExpression,
returnByValue: true,
},
sessionId,
),
- infoExpression,
- );
- params.clip = {
- // CDP interprets clip coordinates in the page's document coordinate
- // space. A viewport screenshot therefore starts at the current scroll
- // offset, while a full-page screenshot still starts at the document
- // origin.
- x: full ? 0 : info.sx,
- y: full ? 0 : info.sy,
- width: full ? info.pw : info.w,
- height: full ? info.ph : info.h,
- scale: cssScale,
- };
- }
+ dprExpression,
+ ),
+ ) || 1;
+ const cssScale = 1 / dpr;
+ if (options.clip) {
+ params.clip = { scale: cssScale, ...options.clip };
+ } else {
+ const infoExpression =
+ "({url:location.href,title:document.title,w:innerWidth,h:innerHeight,sx:scrollX,sy:scrollY,pw:document.documentElement.scrollWidth,ph:document.documentElement.scrollHeight})";
+ const info = runtimeValue(
+ await cdp(
+ "Runtime.evaluate",
+ {
+ expression: infoExpression,
+ returnByValue: true,
+ },
+ sessionId,
+ ),
+ infoExpression,
+ );
+ params.clip = {
+ // CDP interprets clip coordinates in the page's document coordinate
+ // space. A viewport screenshot therefore starts at the current scroll
+ // offset, while a full-page screenshot still starts at the document
+ // origin.
+ x: full ? 0 : info.sx,
+ y: full ? 0 : info.sy,
+ width: full ? info.pw : info.w,
+ height: full ? info.ph : info.h,
+ scale: cssScale,
+ };
}
}
const result = await cdp("Page.captureScreenshot", params, sessionId);