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): enable Ego automation hooks on every Page session

Zhuowei Wangcaf6b21fc069
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 06fa5d1..6a321c6 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
@@ -48,6 +48,7 @@ import {
} from "./page-download.mjs";
import { pageOopifActionCase, pageOopifRestoreCase } from "./page-oopif.mjs";
import { pageLoadStatesCase } from "./page-load-states.mjs";
+import { pageAutomationHooksCase } from "./page-automation-hooks.mjs";
import {
pageAudioWorkletCase,
pageDedicatedWorkerCase,
@@ -187,6 +188,7 @@ export const e2eCases = [
{ name: "Page OOPIF actions", body: pageOopifActionCase },
{ name: "Page OOPIF restore and close", body: pageOopifRestoreCase },
{ name: "Page load states", body: pageLoadStatesCase },
+ { name: "Page automation hooks", body: pageAutomationHooksCase },
{ name: "Page dedicated Worker startup", body: pageDedicatedWorkerCase },
{ name: "Page AudioWorklet startup", body: pageAudioWorkletCase },
{ name: "Page SharedWorker startup", body: pageSharedWorkerCase },
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-automation-hooks.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-automation-hooks.mjs
new file mode 100644
index 0000000..0da76d7
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-automation-hooks.mjs
@@ -0,0 +1,41 @@
+export function pageAutomationHooksCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const page = await newPageAt(task, baseUrl + "/?page-api=automation-hooks");
+ assertEqual(
+ (await page.cdp("egoAutomated.ping")).result,
+ "pong",
+ "the browser exposes the Ego automation domain on Page sessions"
+ );
+ await page.cdp("Runtime.enable");
+ await page.events();
+ const logMarker = (marker) =>
+ page.evaluate((marker) => console.log(marker), marker);
+ const hasConsoleMarker = (events, marker) =>
+ events.some(
+ (event) =>
+ event.method === "Runtime.consoleAPICalled" &&
+ event.params?.args?.some((argument) => argument.value === marker)
+ );
+
+ // Pages detect CDP through side effects of console serialization, so
+ // Agent sessions do not receive console messages by default.
+ const hiddenMarker = "ego-automation-hooks-hidden";
+ await logMarker(hiddenMarker);
+ await page.waitForTimeout(100);
+ assert(
+ !hasConsoleMarker(await page.events(), hiddenMarker),
+ "console messages do not reach an Agent session with Runtime enabled"
+ );
+
+ await page.cdp("egoAutomated.disable");
+ const visibleMarker = "ego-automation-hooks-visible";
+ await logMarker(visibleMarker);
+ await page.waitForTimeout(100);
+ assert(
+ hasConsoleMarker(await page.events(), visibleMarker),
+ "egoAutomated.disable restores console messages for debugging"
+ );
+ await page.close();
+ `;
+}
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-load-states.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-load-states.mjs
index 0941d84..bb2f2cc 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-load-states.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-load-states.mjs
@@ -187,6 +187,9 @@ export function pageLoadStatesCase() {
);
await faviconPage.close();
+ // The markers below are console messages, which Ego automation hooks
+ // keep from reaching the session.
+ await page.cdp("egoAutomated.disable");
await page.cdp("Runtime.enable");
const networkEventMarker = "ego-networkidle-event-preserved";
await page.evaluate(({ url, marker }) => {
@@ -236,6 +239,7 @@ export function pageLoadStatesCase() {
waitUntil: "domcontentloaded",
timeout: 2_000,
});
+ await busyPage.cdp("egoAutomated.disable");
await busyPage.cdp("Runtime.enable");
await quietPage.cdp("Runtime.enable");
await busyPage.events();
diff --git a/package/ego-browser/skill-body/SKILL.md b/package/ego-browser/skill-body/SKILL.md
index 2a0f519..8f54650 100644
--- a/package/ego-browser/skill-body/SKILL.md
+++ b/package/ego-browser/skill-body/SKILL.md
@@ -410,6 +410,11 @@ the destination matters.
For uncommon protocol-event workflows, `await page.events()` returns and clears
the buffered event array; it is not an EventEmitter.
+Page sessions hide page console messages from CDP so sites cannot detect the
+automation. To read `Runtime.consoleAPICalled` while debugging, first call
+`await page.cdp("egoAutomated.disable")`, then `page.cdp("Runtime.enable")`.
+Sites can detect CDP again while it is off.
+
A synchronous JavaScript dialog may appear as `receipt.dialog` or in
`page.info()`. Handle it before continuing:
diff --git a/package/ego-browser/src/browser-runtime.test.mjs b/package/ego-browser/src/browser-runtime.test.mjs
index 59e9531..72f6bdc 100644
--- a/package/ego-browser/src/browser-runtime.test.mjs
+++ b/package/ego-browser/src/browser-runtime.test.mjs
@@ -1027,6 +1027,20 @@ test("auto-attached OOPIFs are instrumented and resumed without waiting for Netw
childNetworkIndex < childResumeIndex,
"Network.enable is sent before the child resumes",
);
+ const childAutomationIndex = sent.findIndex(
+ (request) =>
+ request.method === "egoAutomated.enable" &&
+ request.sessionId === "session:frame-child",
+ );
+ assert.ok(
+ childAutomationIndex >= 0 && childAutomationIndex < childNetworkIndex,
+ "automation hooks are the first command on the child session",
+ );
+ assert.equal(
+ sent.filter((request) => request.method === "egoAutomated.enable").length,
+ 2,
+ "the page and the OOPIF session each enable automation hooks once",
+ );
assert.equal(
delayedChildNetworkEnable,
undefined,
@@ -1055,6 +1069,73 @@ test("auto-attached OOPIFs are instrumented and resumed without waiting for Netw
}
});
+test("automation hooks are enabled once per session and tolerate older browsers", async () => {
+ const previous = globalThis.ego;
+ const sent = [];
+ let attachCount = 0;
+ const runtime = {
+ sendCDPMessage(payload) {
+ const request = JSON.parse(payload);
+ sent.push(request);
+ queueMicrotask(() => {
+ if (request.method === "egoAutomated.enable") {
+ // Browsers without the Ego automation domain reject the command.
+ runtime.onCDPMessage(
+ JSON.stringify({
+ id: request.id,
+ error: {
+ code: -32601,
+ message: "'egoAutomated.enable' wasn't found",
+ },
+ }),
+ );
+ return;
+ }
+ const result =
+ request.method === "Target.attachToTarget"
+ ? {
+ sessionId: `session:${request.params.targetId}:${++attachCount}`,
+ }
+ : {};
+ runtime.onCDPMessage(JSON.stringify({ id: request.id, result }));
+ });
+ },
+ };
+ globalThis.ego = runtime;
+ const automationSessions = () =>
+ sent
+ .filter((request) => request.method === "egoAutomated.enable")
+ .map((request) => request.sessionId);
+
+ try {
+ const sessionId = await ensureSession("page-main");
+ await ensureSession("page-main");
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.deepEqual(automationSessions(), [sessionId]);
+ assert.equal(
+ sent.findIndex((request) => request.sessionId === sessionId),
+ sent.findIndex((request) => request.method === "egoAutomated.enable"),
+ "automation hooks are the first command on the session",
+ );
+
+ // Scripts that attach their own session, such as js(expr, targetId),
+ // get the hooks before their first command too.
+ const attached = await browserCdp("Target.attachToTarget", {
+ targetId: "frame-child",
+ flatten: true,
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.deepEqual(automationSessions(), [
+ sessionId,
+ attached.result.sessionId,
+ ]);
+ } finally {
+ invalidateSession();
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ }
+});
+
for (const targetType of ["worker", "worklet", "shared_worker"]) {
test(`${targetType} targets are auto-attached, resumed, then detached`, async () => {
const previous = globalThis.ego;
diff --git a/package/ego-browser/src/browser-runtime.ts b/package/ego-browser/src/browser-runtime.ts
index 0502b09..858fde0 100644
--- a/package/ego-browser/src/browser-runtime.ts
+++ b/package/ego-browser/src/browser-runtime.ts
@@ -175,6 +175,7 @@ function targetState(targetId) {
sessionAt: 0,
sessionInflight: null,
events: [],
+ egoAutomationEnabled: false,
pageEventsEnabled: false,
networkDomainEnabled: false,
networkEnableInflight: null,
@@ -212,6 +213,7 @@ function registerSession(targetId, sessionId) {
}
target.sessionId = sessionId;
target.sessionAt = Date.now();
+ target.egoAutomationEnabled = false;
target.pageEventsEnabled = false;
target.networkDomainEnabled = false;
target.networkEnableInflight = null;
@@ -316,6 +318,7 @@ function clearTargetSession(targetId, { remove = false } = {}) {
target.sessionAt = 0;
target.sessionInflight = null;
target.events.length = 0;
+ target.egoAutomationEnabled = false;
target.pageEventsEnabled = false;
target.networkDomainEnabled = false;
target.networkEnableInflight = null;
@@ -552,6 +555,7 @@ function recordCommandState(method, params, sessionId, response) {
const attachedSessionId = response.result?.sessionId || response.sessionId;
if (params?.targetId && attachedSessionId) {
registerSession(params.targetId, attachedSessionId);
+ enableEgoAutomation(attachedSessionId);
}
return;
}
@@ -636,6 +640,7 @@ export async function ensureSession(
}
registerSession(targetId, sessionId);
}
+ enableEgoAutomation(target.sessionId);
await Promise.all([
enablePageEvents(target.sessionId, timeoutMs),
enableNetworkTrackingForSession(target.sessionId, false, timeoutMs),
@@ -1072,6 +1077,28 @@ export function prepareFileChooser(
return interception;
}
+/**
+ * Turn on Ego Lite's automation hooks for one renderer session. They keep the
+ * session's Runtime domain from reporting console messages and capturing call
+ * stacks, both of which pages can observe to detect CDP automation. The
+ * browser keeps the flag across renderer swaps, so it is sent once per session
+ * and before anything else, without waiting: older browsers reject the unknown
+ * domain, and a renderer stalled by a dialog must not block attachment.
+ */
+function enableEgoAutomation(sessionId: string): void {
+ const targetId = sessionId ? sessionTargets.get(sessionId) : undefined;
+ const target = targetId ? targetStates.get(targetId) : undefined;
+ if (
+ !target ||
+ target.sessionId !== sessionId ||
+ target.egoAutomationEnabled
+ ) {
+ return;
+ }
+ target.egoAutomationEnabled = true;
+ void rawCdp("egoAutomated.enable", {}, sessionId).catch(() => {});
+}
+
async function enablePageEvents(sessionId, timeoutMs = RESPONSE_TIMEOUT_MS) {
const targetId = sessionId ? sessionTargets.get(sessionId) : undefined;
const target = targetId ? targetStates.get(targetId) : undefined;
@@ -1232,6 +1259,8 @@ function initializeAutoAttachedTarget(
// Invoke every initializer before awaiting any result. Chromium can pause an
// OOPIF at attachment, so waiting for Network.enable before sending resume
// would deadlock if the protocol response depends on renderer progress.
+ // Automation hooks go first so they cover the frame's first script.
+ enableEgoAutomation(sessionId);
const pageEvents = enablePageEvents(sessionId);
const networkEvents = enableNetworkTrackingForSession(sessionId);
const nestedFrames = enableOopifAutoAttach(sessionId);
diff --git a/package/ego-browser/src/driver/nav.test.mjs b/package/ego-browser/src/driver/nav.test.mjs
index 12552c5..e0b2a5c 100644
--- a/package/ego-browser/src/driver/nav.test.mjs
+++ b/package/ego-browser/src/driver/nav.test.mjs
@@ -231,6 +231,7 @@ test("browser runtime continuously enables Page and Network events", async () =>
sent.map((request) => request.method),
[
"Target.attachToTarget",
+ "egoAutomated.enable",
"Page.enable",
"Network.enable",
"Target.setAutoAttach",
@@ -239,7 +240,8 @@ test("browser runtime continuously enables Page and Network events", async () =>
);
assert.equal(sent[1].sessionId, "session-1");
assert.equal(sent[2].sessionId, "session-1");
- assert.deepEqual(sent[3].params, {
+ assert.equal(sent[3].sessionId, "session-1");
+ assert.deepEqual(sent[4].params, {
autoAttach: true,
waitForDebuggerOnStart: true,
flatten: true,