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): harden runtime identity and locator validation

Autea25f488a516b
diff --git a/package/ego-browser/src/element-resolver.ts b/package/ego-browser/src/element-resolver.ts
index a9947e2..d4f0073 100644
--- a/package/ego-browser/src/element-resolver.ts
+++ b/package/ego-browser/src/element-resolver.ts
@@ -297,27 +297,28 @@ async function validateRoleLocatorBackendNodes(
): Promise<Set<number>> {
const valid = new Set<number>();
if (entries.length === 0) return valid;
- const contexts = pageContexts(sessionId, iframeSessions);
- let trees;
- try {
- trees = await Promise.all(
- contexts.map((context) =>
- send(
- cdp,
- "Accessibility.getFullAXTree",
- context.frameId ? { frameId: context.frameId } : {},
- context.sessionId,
- ),
- ),
- );
- } catch {
- return valid;
- }
+ const available = (
+ await Promise.all(
+ pageContexts(sessionId, iframeSessions).map(async (context) => {
+ try {
+ const tree = await send(
+ cdp,
+ "Accessibility.getFullAXTree",
+ context.frameId ? { frameId: context.frameId } : {},
+ context.sessionId,
+ );
+ return { context, tree };
+ } catch {
+ // A detached frame must not discard locators from healthy contexts.
+ return undefined;
+ }
+ }),
+ )
+ ).filter((item) => item !== undefined);
for (const entry of entries) {
- const matchesIn = (contextIndex: number) => {
- const context = contexts[contextIndex];
- return (trees[contextIndex]?.nodes || [])
+ const rawMatches = available.flatMap(({ context, tree }) =>
+ (tree?.nodes || [])
.filter(
(node) =>
!node.ignored &&
@@ -329,24 +330,18 @@ async function validateRoleLocatorBackendNodes(
backendNodeId: node.backendDOMNodeId,
frameId: context.frameId,
sessionId: context.sessionId,
- }));
- };
- const rawMain = matchesIn(0);
- const frameMatches = contexts
- .slice(1)
- .flatMap((_, offset) => matchesIn(offset + 1));
+ })),
+ );
const framedNodeKeys = new Set(
- frameMatches
+ rawMatches
.filter((match) => match.frameId)
.map((match) => `${match.sessionId}\u0000${match.backendNodeId}`),
);
- const matches = [
- ...rawMain.filter(
- (match) =>
- !framedNodeKeys.has(`${match.sessionId}\u0000${match.backendNodeId}`),
- ),
- ...frameMatches,
- ];
+ const matches = rawMatches.filter(
+ (match) =>
+ match.frameId ||
+ !framedNodeKeys.has(`${match.sessionId}\u0000${match.backendNodeId}`),
+ );
if (
matches.length === 1 &&
matches[0].backendNodeId === entry.candidate.backendNodeId &&
@@ -372,33 +367,40 @@ async function validateDomLocatorBackendNodes(
const valid = new Set<number>();
if (entries.length === 0) return valid;
- let contexts: PageRuntimeContext[];
- let countsByContext: number[][];
- try {
- contexts = await runtimePageContexts(cdp, sessionId, iframeSessions);
- countsByContext = await Promise.all(
- contexts.map(async (context) => {
- const result = await evaluateInContext(
- cdp,
- context,
- buildBatchLocatorCountJs(entries.map((entry) => entry.locator)),
- true,
- );
- const counts = result.result?.value;
- if (
- result.exceptionDetails ||
- !Array.isArray(counts) ||
- counts.length !== entries.length ||
- counts.some((count) => !Number.isInteger(count) || count < -1)
- ) {
- throw new Error("invalid batched locator count result");
+ const candidateContexts = await availableRuntimePageContexts(
+ cdp,
+ sessionId,
+ iframeSessions,
+ );
+ const countedContexts = (
+ await Promise.all(
+ candidateContexts.map(async (context) => {
+ try {
+ const result = await evaluateInContext(
+ cdp,
+ context,
+ buildBatchLocatorCountJs(entries.map((entry) => entry.locator)),
+ true,
+ );
+ const counts = result.result?.value;
+ if (
+ result.exceptionDetails ||
+ !Array.isArray(counts) ||
+ counts.length !== entries.length ||
+ counts.some((count) => !Number.isInteger(count) || count < -1)
+ ) {
+ return undefined;
+ }
+ return { context, counts };
+ } catch {
+ // Count failures are scoped to the frame that disappeared.
+ return undefined;
}
- return counts;
}),
- );
- } catch {
- return valid;
- }
+ )
+ ).filter((item) => item !== undefined);
+ const contexts = countedContexts.map(({ context }) => context);
+ const countsByContext = countedContexts.map(({ counts }) => counts);
const contextForEntry = entries.map((_, entryIndex) => {
let total = 0;
@@ -755,33 +757,53 @@ async function runtimePageContexts(
): Promise<PageRuntimeContext[]> {
const contexts = pageContexts(sessionId, iframeSessions);
return Promise.all(
- contexts.map(async (context) => {
- if (!context.frameId) return context;
- try {
- const result = await send(
- cdp,
- "Page.createIsolatedWorld",
- {
- frameId: context.frameId,
- worldName: "ego-browser-locator",
- grantUniveralAccess: true,
- },
- context.sessionId,
- );
- if (!Number.isInteger(result?.executionContextId)) {
- throw new Error("Page.createIsolatedWorld returned no context id");
- }
- return { ...context, contextId: result.executionContextId };
- } catch (error) {
- throw new ElementResolutionError(
- `Frame ${context.frameId} is not ready: ${error?.message || String(error)}`,
- "transient",
- );
- }
- }),
+ contexts.map((context) => runtimePageContext(cdp, context)),
+ );
+}
+
+async function availableRuntimePageContexts(
+ cdp,
+ sessionId,
+ iframeSessions,
+): Promise<PageRuntimeContext[]> {
+ const settled = await Promise.allSettled(
+ pageContexts(sessionId, iframeSessions).map((context) =>
+ runtimePageContext(cdp, context),
+ ),
+ );
+ return settled.flatMap((result) =>
+ result.status === "fulfilled" ? [result.value] : [],
);
}
+async function runtimePageContext(
+ cdp,
+ context: PageRuntimeContext,
+): Promise<PageRuntimeContext> {
+ if (!context.frameId) return context;
+ try {
+ const result = await send(
+ cdp,
+ "Page.createIsolatedWorld",
+ {
+ frameId: context.frameId,
+ worldName: "ego-browser-locator",
+ grantUniveralAccess: true,
+ },
+ context.sessionId,
+ );
+ if (!Number.isInteger(result?.executionContextId)) {
+ throw new Error("Page.createIsolatedWorld returned no context id");
+ }
+ return { ...context, contextId: result.executionContextId };
+ } catch (error) {
+ throw new ElementResolutionError(
+ `Frame ${context.frameId} is not ready: ${error?.message || String(error)}`,
+ "transient",
+ );
+ }
+}
+
function evaluateInContext(
cdp,
context: PageRuntimeContext,
diff --git a/package/ego-browser/src/native-gate.ts b/package/ego-browser/src/native-gate.ts
index 3bf9ba6..a943483 100644
--- a/package/ego-browser/src/native-gate.ts
+++ b/package/ego-browser/src/native-gate.ts
@@ -64,6 +64,9 @@ export class NativeOperationGate {
),
);
}
+ // Re-entry deliberately bypasses the FIFO because the outer operation
+ // owns the lease. Nested callers must await same-space work in order;
+ // Promise.all here would issue concurrent native requests by design.
return Promise.resolve().then(() => operation({ spaceId }));
}
diff --git a/package/ego-browser/src/page-ledger.test.mjs b/package/ego-browser/src/page-ledger.test.mjs
index 808765a..dddf848 100644
--- a/package/ego-browser/src/page-ledger.test.mjs
+++ b/package/ego-browser/src/page-ledger.test.mjs
@@ -6,12 +6,12 @@ import { join } from "node:path";
import { PageLedgerStore, runtimeInstanceId } from "../dist/src/page-ledger.js";
-test("runtimeInstanceId is stable for the current Ego Lite browser host", async () => {
- const first = await runtimeInstanceId();
- const second = await runtimeInstanceId();
+test("runtimeInstanceId is a pure browser-host identifier", () => {
+ const first = runtimeInstanceId(42);
+ const second = runtimeInstanceId(42);
assert.equal(second, first);
- assert.match(first, new RegExp(`^browser-host:${process.ppid}:[^:]+`));
+ assert.equal(first, "browser-host:42");
});
async function withTempLedger(fn) {
@@ -74,6 +74,41 @@ test("a reused space id starts conservatively in a new browser instance", async
});
});
+test("a ledger from before instance ids is preserved and backfilled", async () => {
+ await withTempLedger(async (rootDir) => {
+ const path = join(rootDir, "space-7.json");
+ await writeFile(
+ path,
+ JSON.stringify({
+ spaceId: 7,
+ nextLabel: 2,
+ usedLabels: ["p1"],
+ releasedLabels: [],
+ initialized: true,
+ userControlPending: false,
+ unmanagedTargets: {},
+ pages: {
+ p1: { targetId: "target-live", openedBy: "agent" },
+ },
+ }),
+ );
+
+ const store = new PageLedgerStore({
+ rootDir,
+ browserInstanceId: "browser-current",
+ });
+ assert.deepEqual(await store.getPage(7, "p1"), {
+ label: "p1",
+ targetId: "target-live",
+ openedBy: "agent",
+ });
+ assert.equal(
+ JSON.parse(await readFile(path, "utf8")).browserInstanceId,
+ "browser-current",
+ );
+ });
+});
+
test("expired ledgers from other browser instances are removed", async () => {
await withTempLedger(async (rootDir) => {
const stalePath = join(rootDir, "space-99.json");
diff --git a/package/ego-browser/src/page-ledger.ts b/package/ego-browser/src/page-ledger.ts
index c513fcc..48afce2 100644
--- a/package/ego-browser/src/page-ledger.ts
+++ b/package/ego-browser/src/page-ledger.ts
@@ -1,5 +1,4 @@
import { randomUUID } from "node:crypto";
-import { execFile } from "node:child_process";
import {
mkdir,
readFile,
@@ -43,41 +42,10 @@ type PageLedgerStoreOptions = {
};
const DEFAULT_STALE_AFTER_MS = 30 * 24 * 60 * 60 * 1000;
-let runtimeInstanceIdPromise: Promise<string> | undefined;
/** Stable across Agent rounds and Node-service restarts in one Ego Lite run. */
-export function runtimeInstanceId(): Promise<string> {
- runtimeInstanceIdPromise ||= browserHostInstanceId();
- return runtimeInstanceIdPromise;
-}
-
-async function browserHostInstanceId(): Promise<string> {
- const parentPid = process.ppid;
- const startedAt = await processStartToken(parentPid);
- return `browser-host:${parentPid}:${startedAt || "unknown"}`;
-}
-
-async function processStartToken(pid: number): Promise<string | undefined> {
- if (process.platform === "win32") return undefined;
- return new Promise((resolve) => {
- execFile(
- "ps",
- ["-o", "lstart=", "-p", String(pid)],
- {
- encoding: "utf8",
- env: { ...process.env, LC_ALL: "C" },
- timeout: 1_000,
- },
- (error, stdout) => {
- if (error) {
- resolve(undefined);
- return;
- }
- const token = stdout.trim().replace(/\s+/g, "_");
- resolve(token || undefined);
- },
- );
- });
+export function runtimeInstanceId(parentPid = process.ppid): string {
+ return `browser-host:${parentPid}`;
}
type AddPageOptions = {
@@ -375,13 +343,25 @@ export class PageLedgerStore {
} catch (error) {
throw new Error(`invalid page ledger ${path}: ${error.message}`);
}
+ const storedBrowserInstanceId = ledgerBrowserInstanceId(parsed);
if (
browserInstanceId !== undefined &&
- ledgerBrowserInstanceId(parsed) !== browserInstanceId
+ storedBrowserInstanceId !== undefined &&
+ storedBrowserInstanceId !== browserInstanceId
) {
return emptyLedger(spaceId, browserInstanceId);
}
- return validateLedger(parsed, spaceId, path);
+ const ledger = validateLedger(parsed, spaceId, path);
+ if (
+ browserInstanceId !== undefined &&
+ storedBrowserInstanceId === undefined
+ ) {
+ // Preserve ledgers created before instance ids existed. This one-time
+ // backfill avoids discarding live Page labels during an SDK upgrade.
+ ledger.browserInstanceId = browserInstanceId;
+ await this.#writeAtomic(spaceId, ledger);
+ }
+ return ledger;
}
async #currentBrowserInstanceId(): Promise<string | undefined> {
diff --git a/package/ego-browser/src/snapshot-result.test.mjs b/package/ego-browser/src/snapshot-result.test.mjs
index 4e66d1b..51d14d8 100644
--- a/package/ego-browser/src/snapshot-result.test.mjs
+++ b/package/ego-browser/src/snapshot-result.test.mjs
@@ -75,6 +75,112 @@ test("snapshot locator validation batches DOM queries and object cleanup", async
);
});
+test("DOM locator validation keeps healthy contexts when one count fails", async () => {
+ const cdp = {
+ async sendRaw(method, params, sessionId) {
+ if (sessionId === "session:detached") {
+ throw new Error("frame detached");
+ }
+ if (method === "Runtime.evaluate" && params.returnByValue) {
+ return { result: { value: [1] } };
+ }
+ if (method === "Runtime.evaluate") {
+ return { result: { objectId: "locator-batch" } };
+ }
+ if (method === "Runtime.getProperties") {
+ return {
+ result: [{ name: "0", value: { objectId: "node:10" } }],
+ };
+ }
+ if (method === "DOM.describeNode") {
+ return { node: { backendNodeId: 10 } };
+ }
+ if (method === "Runtime.releaseObjectGroup") return {};
+ throw new Error(`unexpected CDP method: ${method}`);
+ },
+ };
+
+ assert.equal(
+ await validateSnapshotLocator(
+ cdp,
+ "session:page",
+ new Map([["frame-detached", "session:detached"]]),
+ { backendNodeId: 10, loc: "css:#save" },
+ ),
+ true,
+ );
+});
+
+test("DOM locator validation keeps the Page when an iframe world disappears", async () => {
+ const cdp = {
+ async sendRaw(method, params) {
+ if (method === "Page.createIsolatedWorld") {
+ throw new Error("frame detached");
+ }
+ if (method === "Runtime.evaluate" && params.returnByValue) {
+ return { result: { value: [1] } };
+ }
+ if (method === "Runtime.evaluate") {
+ return { result: { objectId: "locator-batch" } };
+ }
+ if (method === "Runtime.getProperties") {
+ return {
+ result: [{ name: "0", value: { objectId: "node:10" } }],
+ };
+ }
+ if (method === "DOM.describeNode") {
+ return { node: { backendNodeId: 10 } };
+ }
+ if (method === "Runtime.releaseObjectGroup") return {};
+ throw new Error(`unexpected CDP method: ${method}`);
+ },
+ };
+
+ assert.equal(
+ await validateSnapshotLocator(
+ cdp,
+ "session:page",
+ new Map([["frame-detached", "session:page"]]),
+ { backendNodeId: 10, loc: "css:#save" },
+ ),
+ true,
+ );
+});
+
+test("role locator validation keeps healthy trees when one frame detaches", async () => {
+ const cdp = {
+ async sendRaw(method, _params, sessionId) {
+ assert.equal(method, "Accessibility.getFullAXTree");
+ if (sessionId === "session:detached") {
+ throw new Error("frame detached");
+ }
+ return {
+ nodes: [
+ {
+ backendDOMNodeId: 10,
+ ignored: false,
+ role: { value: "button" },
+ name: { value: "Save" },
+ },
+ ],
+ };
+ },
+ };
+
+ assert.equal(
+ await validateSnapshotLocator(
+ cdp,
+ "session:page",
+ new Map([["frame-detached", "session:detached"]]),
+ {
+ backendNodeId: 10,
+ loc: 'role:button[name="Save"]',
+ },
+ ),
+ true,
+ );
+});
+
test("invalid native snapshot locators are hidden without removing their refs", async () => {
const result = {
content: [