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): address runtime review findings

Aute5181432c79ab
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
index deffb32..55ecf4b 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
@@ -943,7 +943,6 @@ export function pageComplexEvaluateCase() {
})),
documentState: {
visibility: document.visibilityState,
- hasFocus: document.hasFocus(),
articleCount: root.querySelectorAll("article").length,
htmlLength: root.outerHTML.length,
},
@@ -964,7 +963,6 @@ export function pageComplexEvaluateCase() {
assertEqual(result.event.marker, complexInput.marker, "custom event receives the complex marker");
assertEqual(result.event.checksum, expectedChecksum, "custom event receives computed data");
assertEqual(result.documentState.visibility, "visible", "evaluate runs in the active document");
- assertEqual(result.documentState.hasFocus, true, "evaluate runs in the focused document");
assertEqual(result.documentState.articleCount, 96, "complex script writes every DOM record");
assert(result.documentState.htmlLength > 10000, "complex script produces a substantial DOM result");
diff --git a/package/ego-browser/src/clipboard.ts b/package/ego-browser/src/clipboard.ts
index 9cea70f..ee1a8c7 100644
--- a/package/ego-browser/src/clipboard.ts
+++ b/package/ego-browser/src/clipboard.ts
@@ -288,6 +288,27 @@ ObjC.import("AppKit");
ObjC.import("Foundation");
const pasteboard = $.NSPasteboard.generalPasteboard;
+const transactionLock = $.NSDistributedLock.alloc.initWithPath(
+ $(ObjC.unwrap($.NSTemporaryDirectory()) + "ego-browser-clipboard.lock")
+);
+
+function acquireTransactionLock() {
+ const deadline = Date.now() + 5000;
+ while (!transactionLock.tryLock) {
+ const lockDate = transactionLock.lockDate;
+ const lockAge = lockDate
+ ? Date.now() - Number(lockDate.timeIntervalSince1970) * 1000
+ : 0;
+ if (lockAge > 30000) {
+ transactionLock.breakLock;
+ continue;
+ }
+ if (Date.now() >= deadline) {
+ throw new Error("another ego-browser process is using the clipboard");
+ }
+ $.NSThread.sleepForTimeInterval(0.02);
+ }
+}
function emit(message) {
const line = $(JSON.stringify(message) + "\n").dataUsingEncoding($.NSUTF8StringEncoding);
@@ -331,6 +352,7 @@ const serialized = ObjC.unwrap(
);
const parsed = JSON.parse(serialized);
const content = typeof parsed === "string" ? { text: parsed } : parsed;
+acquireTransactionLock();
const saved = snapshotPasteboard();
try {
@@ -347,6 +369,7 @@ try {
} catch (error) {
try { restorePasteboard(saved); } catch (_) {}
emit({ state: "error", message: String(error.message || error) });
+ transactionLock.unlock;
throw error;
}
@@ -357,14 +380,18 @@ const restoreSignal = $.NSFileHandle.alloc.initWithFileDescriptorCloseOnDealloc(
restoreSignal.readDataOfLength(1);
try {
- if (Number(pasteboard.changeCount) !== temporaryChangeCount) {
- emit({ state: "changed" });
- } else {
- restorePasteboard(saved);
- emit({ state: "restored" });
+ try {
+ if (Number(pasteboard.changeCount) !== temporaryChangeCount) {
+ emit({ state: "changed" });
+ } else {
+ restorePasteboard(saved);
+ emit({ state: "restored" });
+ }
+ } catch (error) {
+ emit({ state: "error", message: String(error.message || error) });
+ throw error;
}
-} catch (error) {
- emit({ state: "error", message: String(error.message || error) });
- throw error;
+} finally {
+ transactionLock.unlock;
}
`;
diff --git a/package/ego-browser/src/driver/page-waits.test.mjs b/package/ego-browser/src/driver/page-waits.test.mjs
new file mode 100644
index 0000000..8db14da
--- /dev/null
+++ b/package/ego-browser/src/driver/page-waits.test.mjs
@@ -0,0 +1,46 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { waitForURLInPage } from "../../dist/src/driver/page-waits.js";
+
+test("waitForURLInPage recovers from a transient execution-context change", async () => {
+ let now = 0;
+ let attempt = 0;
+ const calls = [];
+ const services = {
+ async cdp(method, params, sessionId, timeoutMs) {
+ calls.push([method, params, sessionId, timeoutMs]);
+ attempt += 1;
+ if (attempt === 1) {
+ throw new Error("Execution context was destroyed");
+ }
+ return {
+ result: {
+ value:
+ attempt === 2
+ ? "https://example.test/loading"
+ : "https://example.test/ready",
+ },
+ };
+ },
+ now: () => now,
+ async sleep(ms) {
+ now += ms;
+ },
+ };
+
+ await waitForURLInPage(services, "session:page", /\/ready$/g, {
+ timeout: 500,
+ });
+
+ assert.equal(attempt, 3);
+ assert(
+ calls.every(
+ ([method, , sessionId, timeoutMs]) =>
+ method === "Runtime.evaluate" &&
+ sessionId === "session:page" &&
+ timeoutMs > 0 &&
+ timeoutMs <= 500,
+ ),
+ );
+});
diff --git a/package/ego-browser/src/ego-errors.test.mjs b/package/ego-browser/src/ego-errors.test.mjs
index 48c569e..fbab985 100644
--- a/package/ego-browser/src/ego-errors.test.mjs
+++ b/package/ego-browser/src/ego-errors.test.mjs
@@ -6,9 +6,39 @@ import {
invokeEgo,
isEgoErrorCode,
isEgoUserControlError,
+ probeAgentControl,
resolveEgoError,
} from "../dist/src/ego-errors.js";
+test("probeAgentControl treats both native user-control shapes as waiting", async () => {
+ assert.equal(
+ await probeAgentControl(async () => ({
+ error: "manual_takeover",
+ error_code: "EGO_TASK_SPACE_USER_IN_CONTROL",
+ })),
+ false,
+ );
+ assert.equal(
+ await probeAgentControl(async () => {
+ throw Object.assign(new Error("manual_takeover"), {
+ error_code: "EGO_TASK_SPACE_USER_IN_CONTROL",
+ });
+ }),
+ false,
+ );
+});
+
+test("probeAgentControl propagates non-user-control native errors", async () => {
+ await assert.rejects(
+ () =>
+ probeAgentControl(async () => ({
+ error: "renderer failed",
+ error_code: "EGO_SNAPSHOT_FAILED",
+ })),
+ /renderer failed/,
+ );
+});
+
test("invokeEgo recognizes a permission reason from a resolved native error", async () => {
await assert.rejects(
() =>
diff --git a/package/ego-browser/src/ego-errors.ts b/package/ego-browser/src/ego-errors.ts
index c0edc41..4764183 100644
--- a/package/ego-browser/src/ego-errors.ts
+++ b/package/ego-browser/src/ego-errors.ts
@@ -170,6 +170,39 @@ export function isEgoUserControlError(err: unknown): boolean {
return egoErrorCode(err) === "EGO_TASK_SPACE_USER_IN_CONTROL";
}
+/**
+ * Probe control without turning the expected user-control response into a hard
+ * stop. Ego bindings can report failures either by rejecting or by resolving an
+ * `{ error, error_code }` object, so both paths must be inspected here.
+ */
+export async function probeAgentControl(
+ invokeSnapshot: () => unknown | Promise<unknown>,
+): Promise<boolean> {
+ let result: unknown;
+ try {
+ result = await invokeSnapshot();
+ } catch (error) {
+ if (isEgoUserControlError(error)) return false;
+ throw error;
+ }
+ if (isResolvedEgoError(result)) {
+ if (isEgoUserControlError(result)) return false;
+ throw buildEgoError(result);
+ }
+ return true;
+}
+
+function isResolvedEgoError(
+ value: unknown,
+): value is { error: unknown; error_code?: unknown } {
+ return (
+ value !== null &&
+ typeof value === "object" &&
+ "error" in value &&
+ (value as { error?: unknown }).error != null
+ );
+}
+
/**
* Codes that halt the whole agent task rather than mark a routable obstacle: a task
* space the user has taken back, or one that is inactive / not assigned to this agent.
diff --git a/package/ego-browser/src/element-resolver.ts b/package/ego-browser/src/element-resolver.ts
index 4ef5b7d..a9947e2 100644
--- a/package/ego-browser/src/element-resolver.ts
+++ b/package/ego-browser/src/element-resolver.ts
@@ -8,6 +8,15 @@ type PageRuntimeContext = {
contextId?: number;
};
+export type LocatorBackendCandidate = {
+ index: number;
+ locator: string;
+ backendNodeId: number;
+ frameId?: string;
+};
+
+let snapshotLocatorBatchSequence = 0;
+
export class ElementResolutionError extends Error {
kind: "transient" | "permanent";
constructor(message: string, kind: "transient" | "permanent") {
@@ -241,6 +250,273 @@ export async function resolveElementObjectId(
);
}
+/**
+ * Validate many native snapshot locators together. DOM locator counts are
+ * queried once per execution context, matching nodes are described in
+ * parallel, and one object group releases every temporary handle.
+ */
+export async function validateLocatorBackendNodes(
+ cdp,
+ sessionId: string,
+ iframeSessions: Map<string, string>,
+ candidates: LocatorBackendCandidate[],
+): Promise<Set<number>> {
+ const parsed = candidates
+ .map((candidate) => ({
+ candidate,
+ locator: parseLocator(candidate.locator),
+ }))
+ .filter((entry) => entry.locator);
+ const roleCandidates = parsed.filter(
+ (entry) => entry.locator.kind === "role",
+ );
+ const domCandidates = parsed.filter((entry) => entry.locator.kind !== "role");
+
+ const [roleMatches, domMatches] = await Promise.all([
+ validateRoleLocatorBackendNodes(
+ cdp,
+ sessionId,
+ iframeSessions,
+ roleCandidates,
+ ),
+ validateDomLocatorBackendNodes(
+ cdp,
+ sessionId,
+ iframeSessions,
+ domCandidates,
+ ),
+ ]);
+ return new Set([...roleMatches, ...domMatches]);
+}
+
+async function validateRoleLocatorBackendNodes(
+ cdp,
+ sessionId,
+ iframeSessions,
+ entries,
+): 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;
+ }
+
+ for (const entry of entries) {
+ const matchesIn = (contextIndex: number) => {
+ const context = contexts[contextIndex];
+ return (trees[contextIndex]?.nodes || [])
+ .filter(
+ (node) =>
+ !node.ignored &&
+ normalizeRole(extractAxString(node.role)) === entry.locator.role &&
+ extractAxString(node.name) === entry.locator.name &&
+ Number.isInteger(node.backendDOMNodeId),
+ )
+ .map((node) => ({
+ 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
+ .filter((match) => match.frameId)
+ .map((match) => `${match.sessionId}\u0000${match.backendNodeId}`),
+ );
+ const matches = [
+ ...rawMain.filter(
+ (match) =>
+ !framedNodeKeys.has(`${match.sessionId}\u0000${match.backendNodeId}`),
+ ),
+ ...frameMatches,
+ ];
+ if (
+ matches.length === 1 &&
+ matches[0].backendNodeId === entry.candidate.backendNodeId &&
+ locatorContextMatchesCandidate(
+ matches[0],
+ entry.candidate,
+ sessionId,
+ iframeSessions,
+ )
+ ) {
+ valid.add(entry.candidate.index);
+ }
+ }
+ return valid;
+}
+
+async function validateDomLocatorBackendNodes(
+ cdp,
+ sessionId,
+ iframeSessions,
+ entries,
+): Promise<Set<number>> {
+ 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");
+ }
+ return counts;
+ }),
+ );
+ } catch {
+ return valid;
+ }
+
+ const contextForEntry = entries.map((_, entryIndex) => {
+ let total = 0;
+ let matchedContext = -1;
+ for (let contextIndex = 0; contextIndex < contexts.length; contextIndex++) {
+ const count = countsByContext[contextIndex][entryIndex];
+ if (count < 0) return -1;
+ total += count;
+ if (count === 1) matchedContext = contextIndex;
+ }
+ return total === 1 ? matchedContext : -1;
+ });
+ const objectGroup = `ego-browser-snapshot-locators-${++snapshotLocatorBatchSequence}`;
+ const usedSessions = new Set<string>();
+
+ try {
+ const resolved = (
+ await Promise.all(
+ contexts.map(async (context, contextIndex) => {
+ const localEntries = entries
+ .map((entry, entryIndex) => ({ entry, entryIndex }))
+ .filter(
+ ({ entryIndex }) => contextForEntry[entryIndex] === contextIndex,
+ );
+ if (localEntries.length === 0) return [];
+ usedSessions.add(context.sessionId);
+ try {
+ const evaluated = await evaluateInContext(
+ cdp,
+ context,
+ buildBatchLocatorObjectsJs(
+ localEntries.map(({ entry }) => entry.locator),
+ ),
+ false,
+ objectGroup,
+ );
+ const batchObjectId = evaluated.result?.objectId;
+ if (!batchObjectId || evaluated.exceptionDetails) return [];
+ const properties = await send(
+ cdp,
+ "Runtime.getProperties",
+ { objectId: batchObjectId, ownProperties: true },
+ context.sessionId,
+ );
+ return localEntries.flatMap(({ entry }, localIndex) => {
+ const property = (properties.result || []).find(
+ (candidate) => candidate.name === String(localIndex),
+ );
+ const objectId = property?.value?.objectId;
+ return objectId ? [{ entry, context, objectId }] : [];
+ });
+ } catch {
+ return [];
+ }
+ }),
+ )
+ ).flat();
+
+ await Promise.all(
+ resolved.map(async ({ entry, context, objectId }) => {
+ try {
+ const described = await send(
+ cdp,
+ "DOM.describeNode",
+ { objectId, depth: 0 },
+ context.sessionId,
+ );
+ if (
+ described?.node?.backendNodeId === entry.candidate.backendNodeId &&
+ locatorContextMatchesCandidate(
+ context,
+ entry.candidate,
+ sessionId,
+ iframeSessions,
+ )
+ ) {
+ valid.add(entry.candidate.index);
+ }
+ } catch {
+ // A stale node is unsafe to advertise as a stable locator.
+ }
+ }),
+ );
+ } finally {
+ await Promise.all(
+ [...usedSessions].map((candidateSessionId) =>
+ send(
+ cdp,
+ "Runtime.releaseObjectGroup",
+ { objectGroup },
+ candidateSessionId,
+ ).catch(() => {}),
+ ),
+ );
+ }
+ return valid;
+}
+
+function locatorContextMatchesCandidate(
+ context,
+ candidate,
+ pageSessionId,
+ iframeSessions,
+): boolean {
+ if (!candidate.frameId) return true;
+ const expectedSessionId = resolveFrameSession(
+ candidate.frameId,
+ pageSessionId,
+ iframeSessions,
+ );
+ const expectedFrameId =
+ expectedSessionId === pageSessionId ? candidate.frameId : undefined;
+ return (
+ context.sessionId === expectedSessionId &&
+ context.frameId === expectedFrameId
+ );
+}
+
async function resolveRawSelectorObjectId(
cdp,
contexts,
@@ -1330,6 +1606,31 @@ function buildLocatorCountJs(locator) {
return `(() => ${hrefElementsJs(locator.href)}.length)()`;
}
+function buildBatchLocatorCountJs(locators) {
+ const queries = locators
+ .map(
+ (locator) =>
+ `() => Array.from(${buildLocatorElementsJs(locator)} || []).length`,
+ )
+ .join(",\n");
+ return `(() => {
+ const queries = [${queries}];
+ return queries.map((query) => {
+ try {
+ return query();
+ } catch {
+ return -1;
+ }
+ });
+ })()`;
+}
+
+function buildBatchLocatorObjectsJs(locators) {
+ return `(() => [${locators
+ .map((locator) => buildLocatorFindJs(locator))
+ .join(",\n")}])()`;
+}
+
function buildLocatorElementsJs(locator) {
if (locator.kind === "css") {
return buildCssQueryAllJs(locator.selector);
diff --git a/package/ego-browser/src/format.test.mjs b/package/ego-browser/src/format.test.mjs
new file mode 100644
index 0000000..a38a023
--- /dev/null
+++ b/package/ego-browser/src/format.test.mjs
@@ -0,0 +1,30 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { formatCliLogValue } from "../dist/src/format.js";
+
+test("formatCliLogValue preserves useful Error details", () => {
+ const output = formatCliLogValue(new Error("page action failed"));
+
+ assert.match(output, /Error: page action failed/);
+ assert.match(output, /format\.test\.mjs/);
+});
+
+test("formatCliLogValue handles circular objects without throwing", () => {
+ const value = { name: "root" };
+ value.self = value;
+
+ assert.match(formatCliLogValue(value), /Circular/);
+});
+
+test("formatCliLogValue shows Map, Set, and function values", () => {
+ assert.match(
+ formatCliLogValue(new Map([["status", 200]])),
+ /Map\(1\).*status.*200/,
+ );
+ assert.match(formatCliLogValue(new Set(["ready"])), /Set\(1\).*ready/);
+ assert.match(
+ formatCliLogValue(function runTask() {}),
+ /runTask/,
+ );
+});
diff --git a/package/ego-browser/src/format.ts b/package/ego-browser/src/format.ts
index abcd09e..e70662f 100644
--- a/package/ego-browser/src/format.ts
+++ b/package/ego-browser/src/format.ts
@@ -1,12 +1,12 @@
+import { inspect } from "node:util";
+
export function formatCliLogValue(value: unknown) {
if (typeof value === "string") {
return value;
}
- if (typeof value === "bigint") {
- return `${value}n`;
- }
- if (value === undefined) {
- return "undefined";
- }
- return JSON.stringify(value);
+ return inspect(value, {
+ depth: 6,
+ breakLength: Infinity,
+ compact: true,
+ });
}
diff --git a/package/ego-browser/src/help-runtime.test.mjs b/package/ego-browser/src/help-runtime.test.mjs
new file mode 100644
index 0000000..cfd9066
--- /dev/null
+++ b/package/ego-browser/src/help-runtime.test.mjs
@@ -0,0 +1,21 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { formatHelp, help } from "../dist/src/help-runtime.js";
+
+test("help resolves public aliases from the API schema", () => {
+ const pageClick = help({}, "page.click");
+
+ assert.equal(pageClick.name, "Page.click");
+ assert.match(pageClick.signature, /await page\.click/);
+ assert.match(pageClick.description, /timeout/);
+ assert.match(formatHelp(pageClick), /Page\.click[\s\S]*await page\.click/);
+});
+
+test("help keeps legacy and unknown names out of the public surface", () => {
+ assert.equal(
+ help({ oldHelper() {} }, "oldHelper"),
+ 'Legacy helper hidden from default help: oldHelper. Use help("legacy", "oldHelper").',
+ );
+ assert.equal(help({}, "missingHelper"), "Unknown helper: missingHelper");
+});
diff --git a/package/ego-browser/src/helpers.test.mjs b/package/ego-browser/src/helpers.test.mjs
index 1f5df5e..6aa5dce 100644
--- a/package/ego-browser/src/helpers.test.mjs
+++ b/package/ego-browser/src/helpers.test.mjs
@@ -1096,6 +1096,33 @@ test("waitForAgentControl retries while snapshot reports user control", async ()
assert.equal(calls, 3);
});
+test("waitForAgentControl retries when snapshot resolves a user-control error", async () => {
+ const restore = helperExports.__testing.setOverrides({
+ sleep: () => Promise.resolve(),
+ });
+ let calls = 0;
+ try {
+ await withEgo(
+ taskSpaceEgo(async () => {
+ calls += 1;
+ if (calls < 3) {
+ return {
+ error: "manual_takeover",
+ error_code: "EGO_TASK_SPACE_USER_IN_CONTROL",
+ };
+ }
+ return { content: "" };
+ }),
+ async () => {
+ await waitForAgentControl("t", { interval: 0, timeout: 5 });
+ },
+ );
+ } finally {
+ restore();
+ }
+ assert.equal(calls, 3);
+});
+
test("waitForAgentControl propagates non-user-control snapshot errors", async () => {
await withEgo(
taskSpaceEgo(async () => {
diff --git a/package/ego-browser/src/helpers.ts b/package/ego-browser/src/helpers.ts
index 1ad14c8..e800b55 100644
--- a/package/ego-browser/src/helpers.ts
+++ b/package/ego-browser/src/helpers.ts
@@ -3,7 +3,7 @@ import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { setOverrides, state } from "./state.js";
-import { invokeEgo, isEgoUserControlError } from "./ego-errors.js";
+import { invokeEgo, probeAgentControl } from "./ego-errors.js";
import { help as helpRuntime, formatHelp } from "./help-runtime.js";
import { validatePublicApiOptions } from "./public-api-schema.js";
import { createStaleEgoBrowserGuard } from "./skill-migration.js";
@@ -432,16 +432,10 @@ export async function takeOverTaskSpace(nameOrId?: string | number) {
* (task not found, internal errors) propagate so the caller fails fast instead
* of busy-looping until timeout.
*/
-async function probeAgentControl() {
+async function probeCurrentAgentControl() {
const ego = globalThis.ego;
if (!ego || typeof ego.snapshot !== "function") return false;
- try {
- await ego.snapshot({ maxResultLength: 1 });
- return true;
- } catch (err) {
- if (isEgoUserControlError(err)) return false;
- throw err;
- }
+ return probeAgentControl(() => ego.snapshot({ maxResultLength: 1 }));
}
/**
@@ -471,7 +465,7 @@ export async function waitForAgentControl(
const timeout = typeof options.timeout === "number" ? options.timeout : 600;
const deadline = Date.now() + timeout * 1000;
while (true) {
- if (await probeAgentControl()) return;
+ if (await probeCurrentAgentControl()) return;
if (Date.now() >= deadline) {
throw new Error(`waitForAgentControl timed out after ${timeout}s`);
}
diff --git a/package/ego-browser/src/native-gate.test.mjs b/package/ego-browser/src/native-gate.test.mjs
index 23c5e6d..d8970d3 100644
--- a/package/ego-browser/src/native-gate.test.mjs
+++ b/package/ego-browser/src/native-gate.test.mjs
@@ -127,3 +127,45 @@ test("NativeOperationGate resolves an explicit page session inside the space loc
});
assert.deepEqual(log, ["select:7", "attach:target-a", "run:session-a"]);
});
+
+test("NativeOperationGate reuses same-space ownership for nested operations", async () => {
+ const log = [];
+ const gate = new NativeOperationGate({
+ async selectSpace(spaceId) {
+ log.push(`select:${spaceId}`);
+ },
+ async ensureSession(targetId) {
+ log.push(`attach:${targetId}`);
+ return `session:${targetId}`;
+ },
+ });
+
+ const result = await gate.withSpace(7, () =>
+ gate.withPage({ spaceId: 7, targetId: "target-a" }, ({ sessionId }) => {
+ log.push(`run:${sessionId}`);
+ return "nested";
+ }),
+ );
+
+ assert.equal(result, "nested");
+ assert.deepEqual(log, [
+ "select:7",
+ "attach:target-a",
+ "run:session:target-a",
+ ]);
+});
+
+test("NativeOperationGate rejects nested selection of another space", async () => {
+ const gate = new NativeOperationGate({
+ async selectSpace() {},
+ async ensureSession() {
+ throw new Error("not used");
+ },
+ });
+
+ await assert.rejects(
+ () => gate.withSpace(7, () => gate.withSpace(8, async () => undefined)),
+ /cannot select space 8 while space 7 is active/,
+ );
+ assert.equal(await gate.withSpace(9, async () => "recovered"), "recovered");
+});
diff --git a/package/ego-browser/src/native-gate.ts b/package/ego-browser/src/native-gate.ts
index a5539e5..3bf9ba6 100644
--- a/package/ego-browser/src/native-gate.ts
+++ b/package/ego-browser/src/native-gate.ts
@@ -1,3 +1,5 @@
+import { AsyncLocalStorage } from "node:async_hooks";
+
import { browserEgo, ensureSession } from "./browser-runtime.js";
import { invokeEgo } from "./ego-errors.js";
@@ -20,6 +22,10 @@ type PageTarget = {
targetId: string;
};
+type GateOwnership = SpaceScope & {
+ active: boolean;
+};
+
/**
* Serializes native operations that rely on Ego Lite's process-wide selected
* task space. The queue covers the entire async operation, so another caller
@@ -27,6 +33,7 @@ type PageTarget = {
*/
export class NativeOperationGate {
readonly #services: NativeGateServices;
+ readonly #ownership = new AsyncLocalStorage<GateOwnership>();
#tail: Promise<void> = Promise.resolve();
constructor(services: NativeGateServices) {
@@ -48,13 +55,36 @@ export class NativeOperationGate {
throw new TypeError("withSpace requires an operation function");
}
+ const ownership = this.#ownership.getStore();
+ if (ownership?.active) {
+ if (ownership.spaceId !== spaceId) {
+ return Promise.reject(
+ new Error(
+ `cannot select space ${spaceId} while space ${ownership.spaceId} is active`,
+ ),
+ );
+ }
+ return Promise.resolve().then(() => operation({ spaceId }));
+ }
+
const run = async () => {
await this.#services.selectSpace(spaceId);
- return operation({ spaceId });
+ const acquired: GateOwnership = { spaceId, active: true };
+ return this.#ownership.run(acquired, async () => {
+ try {
+ return await operation({ spaceId });
+ } finally {
+ // AsyncLocalStorage also flows into detached child tasks. Mark this
+ // lease inactive when its awaited operation ends so late work queues
+ // normally instead of bypassing a released gate.
+ acquired.active = false;
+ }
+ });
};
const result = this.#tail.then(run);
- // A failed operation must reject its own caller without poisoning the FIFO
- // queue for every operation submitted after it.
+ // The queue is intentionally unbounded and covers long waits: changing the
+ // selected space during any in-flight native operation would misroute it.
+ // A failure rejects its caller without poisoning later FIFO entries.
this.#tail = result.then(
() => undefined,
() => undefined,
diff --git a/package/ego-browser/src/output-sink.test.mjs b/package/ego-browser/src/output-sink.test.mjs
index 39447cf..c83db0b 100644
--- a/package/ego-browser/src/output-sink.test.mjs
+++ b/package/ego-browser/src/output-sink.test.mjs
@@ -1,9 +1,14 @@
import test from "node:test";
import assert from "node:assert/strict";
+import { EventEmitter } from "node:events";
+import { mkdtemp, open, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import {
bufferOutput,
flushSink,
+ installLifecycleFlush,
markHardStop,
resetSink,
} from "../dist/src/output-sink.js";
@@ -12,6 +17,33 @@ import {
recordUnhandledPage,
} from "../dist/src/page-discovery.js";
+test("lifecycle flush writes synchronously when stdout exposes an fd", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "ego-output-sink-test-"));
+ const path = join(directory, "stdout.txt");
+ const file = await open(path, "w");
+ const lifecycle = new EventEmitter();
+ try {
+ resetSink();
+ bufferOutput("tail output\n");
+ installLifecycleFlush(
+ {
+ fd: file.fd,
+ write() {
+ throw new Error("asynchronous write should not be used");
+ },
+ },
+ lifecycle,
+ );
+
+ lifecycle.emit("exit");
+ await file.sync();
+ assert.equal(await readFile(path, "utf8"), "tail output\n");
+ } finally {
+ await file.close();
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
function fakeStream() {
const chunks = [];
return {
diff --git a/package/ego-browser/src/output-sink.ts b/package/ego-browser/src/output-sink.ts
index babc245..8cd84e8 100644
--- a/package/ego-browser/src/output-sink.ts
+++ b/package/ego-browser/src/output-sink.ts
@@ -1,3 +1,5 @@
+import { writeSync } from "node:fs";
+
import { formatCliLogValue } from "./format.js";
import {
consumeUnhandledPageNotices,
@@ -12,7 +14,10 @@ import {
* round-local; reset functions exist only for in-process tests.
*/
-type WritableLike = { write(chunk: string): unknown };
+type WritableLike = { write(chunk: string): unknown; fd?: number };
+type LifecycleLike = {
+ on(event: "beforeExit" | "exit", listener: () => void): unknown;
+};
export type RoundConsole = Pick<Console, "log" | "info" | "warn" | "error">;
@@ -115,9 +120,21 @@ function oneLine(value: string): string {
* stays silent and lets the propagating Error surface the message). The stream still
* accepts writes in both events, so the same `stream` serves both. Registered once.
*/
-export function installLifecycleFlush(stream: WritableLike): void {
+export function installLifecycleFlush(
+ stream: WritableLike,
+ lifecycle: LifecycleLike = process,
+): void {
if (lifecycleHooked) return;
lifecycleHooked = true;
- process.on("beforeExit", () => flushSink(stream, false));
- process.on("exit", () => flushSink(stream, true));
+ const writer = Number.isInteger(stream.fd)
+ ? {
+ write(chunk: string) {
+ // `exit` cannot wait for a piped Writable to drain. A synchronous fd
+ // write preserves the final buffered lines on both lifecycle paths.
+ writeSync(stream.fd!, chunk);
+ },
+ }
+ : stream;
+ lifecycle.on("beforeExit", () => flushSink(writer, false));
+ lifecycle.on("exit", () => flushSink(writer, true));
}
diff --git a/package/ego-browser/src/page-discovery.test.mjs b/package/ego-browser/src/page-discovery.test.mjs
new file mode 100644
index 0000000..ec162cc
--- /dev/null
+++ b/package/ego-browser/src/page-discovery.test.mjs
@@ -0,0 +1,61 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ consumeUnhandledPageNotices,
+ markPageObserved,
+ peekUnhandledPageNotices,
+ recordUnhandledPage,
+ resetPageNotices,
+ subscribeUnhandledPageNotices,
+} from "../dist/src/page-discovery.js";
+
+test("page discovery merges updates and notifies subscribers", () => {
+ resetPageNotices();
+ const delivered = [];
+ const unsubscribe = subscribeUnhandledPageNotices((notice) =>
+ delivered.push(notice),
+ );
+
+ recordUnhandledPage({
+ spaceId: 7,
+ targetId: "popup",
+ label: "p2",
+ openerLabel: "p1",
+ url: "about:blank",
+ });
+ recordUnhandledPage({
+ spaceId: 7,
+ targetId: "popup",
+ label: "p2",
+ url: "https://example.test/popup",
+ });
+ unsubscribe();
+
+ assert.equal(delivered.length, 2);
+ assert.deepEqual(peekUnhandledPageNotices(), [
+ {
+ spaceId: 7,
+ targetId: "popup",
+ label: "p2",
+ openerLabel: "p1",
+ url: "https://example.test/popup",
+ },
+ ]);
+});
+
+test("observed and consumed page notices do not reappear", () => {
+ resetPageNotices();
+ recordUnhandledPage({ spaceId: 7, targetId: "a", label: "p2" });
+ recordUnhandledPage({ spaceId: 7, targetId: "b", label: "p3" });
+
+ markPageObserved(7, "a");
+ assert.deepEqual(
+ consumeUnhandledPageNotices().map((notice) => notice.targetId),
+ ["b"],
+ );
+ assert.deepEqual(consumeUnhandledPageNotices(), []);
+
+ recordUnhandledPage({ spaceId: 7, targetId: "a", label: "p2" });
+ assert.deepEqual(peekUnhandledPageNotices(), []);
+});
diff --git a/package/ego-browser/src/page-ledger.test.mjs b/package/ego-browser/src/page-ledger.test.mjs
index b87a660..808765a 100644
--- a/package/ego-browser/src/page-ledger.test.mjs
+++ b/package/ego-browser/src/page-ledger.test.mjs
@@ -1,10 +1,18 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { PageLedgerStore } from "../dist/src/page-ledger.js";
+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();
+
+ assert.equal(second, first);
+ assert.match(first, new RegExp(`^browser-host:${process.ppid}:[^:]+`));
+});
async function withTempLedger(fn) {
const rootDir = await mkdtemp(join(tmpdir(), "ego-page-ledger-test-"));
@@ -37,6 +45,68 @@ test("page labels survive a new process and are never reused", async () => {
});
});
+test("a reused space id starts conservatively in a new browser instance", async () => {
+ await withTempLedger(async (rootDir) => {
+ const firstBrowser = new PageLedgerStore({
+ rootDir,
+ browserInstanceId: "browser-a",
+ });
+ await firstBrowser.addPage(7, "target-from-browser-a");
+
+ const secondBrowser = new PageLedgerStore({
+ rootDir,
+ browserInstanceId: "browser-b",
+ });
+ const fresh = await secondBrowser.read(7);
+ assert.equal(fresh.initialized, false);
+ assert.deepEqual(fresh.pages, {});
+
+ const baseline = await secondBrowser.reconcile(7, ["target-existing"], {
+ autoAdoptNew: true,
+ });
+ assert.deepEqual(baseline.pages, {});
+ assert.equal(baseline.unmanagedTargets["target-existing"], "unknown");
+
+ const persisted = JSON.parse(
+ await readFile(join(rootDir, "space-7.json"), "utf8"),
+ );
+ assert.equal(persisted.browserInstanceId, "browser-b");
+ });
+});
+
+test("expired ledgers from other browser instances are removed", async () => {
+ await withTempLedger(async (rootDir) => {
+ const stalePath = join(rootDir, "space-99.json");
+ await writeFile(
+ stalePath,
+ JSON.stringify({
+ browserInstanceId: "browser-a",
+ spaceId: 99,
+ nextLabel: 1,
+ usedLabels: [],
+ releasedLabels: [],
+ initialized: true,
+ userControlPending: false,
+ unmanagedTargets: {},
+ pages: {},
+ }),
+ );
+ await utimes(stalePath, new Date(0), new Date(0));
+
+ const secondBrowser = new PageLedgerStore({
+ rootDir,
+ browserInstanceId: "browser-b",
+ staleAfterMs: 1_000,
+ now: () => 10_000,
+ });
+ await secondBrowser.read(7);
+
+ await assert.rejects(() => readFile(stalePath, "utf8"), {
+ code: "ENOENT",
+ });
+ });
+});
+
test("custom labels share the permanent used-label namespace", async () => {
await withTempLedger(async (rootDir) => {
const store = new PageLedgerStore({ rootDir });
diff --git a/package/ego-browser/src/page-ledger.ts b/package/ego-browser/src/page-ledger.ts
index 06473a4..c513fcc 100644
--- a/package/ego-browser/src/page-ledger.ts
+++ b/package/ego-browser/src/page-ledger.ts
@@ -1,5 +1,14 @@
import { randomUUID } from "node:crypto";
-import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import { execFile } from "node:child_process";
+import {
+ mkdir,
+ readFile,
+ readdir,
+ rename,
+ rm,
+ stat,
+ writeFile,
+} from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
@@ -15,6 +24,7 @@ export type ManagedPage = PageLedgerEntry & {
};
export type PageLedger = {
+ browserInstanceId?: string;
spaceId: number;
nextLabel: number;
usedLabels: string[];
@@ -27,8 +37,49 @@ export type PageLedger = {
type PageLedgerStoreOptions = {
rootDir?: string;
+ browserInstanceId?: string | (() => string | Promise<string>);
+ staleAfterMs?: number;
+ now?: () => number;
};
+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);
+ },
+ );
+ });
+}
+
type AddPageOptions = {
as?: string;
openedBy?: PageOrigin;
@@ -47,13 +98,27 @@ type ReconcileOptions = {
export class PageLedgerStore {
readonly rootDir: string;
readonly #writeToken = randomUUID();
+ readonly #browserInstanceId?: string | (() => string | Promise<string>);
+ readonly #staleAfterMs: number;
+ readonly #now: () => number;
#temporarySequence = 0;
+ #resolvedBrowserInstanceId?: Promise<string | undefined>;
+ #cleanup?: Promise<void>;
constructor(options: PageLedgerStoreOptions = {}) {
this.rootDir =
options.rootDir ||
process.env.EGO_BROWSER_STATE_DIR ||
join(homedir(), ".ego-browser", "state");
+ this.#browserInstanceId = options.browserInstanceId;
+ this.#staleAfterMs =
+ options.staleAfterMs === undefined
+ ? DEFAULT_STALE_AFTER_MS
+ : options.staleAfterMs;
+ this.#now = options.now || Date.now;
+ if (!Number.isFinite(this.#staleAfterMs) || this.#staleAfterMs < 0) {
+ throw new TypeError("staleAfterMs must be a non-negative number");
+ }
}
async read(spaceId: number): Promise<PageLedger> {
@@ -292,12 +357,16 @@ export class PageLedgerStore {
}
async #readCurrent(spaceId: number): Promise<PageLedger> {
+ const browserInstanceId = await this.#currentBrowserInstanceId();
+ await this.#cleanupExpiredLedgers(browserInstanceId);
const path = this.#path(spaceId);
let raw: string;
try {
raw = await readFile(path, "utf8");
} catch (error) {
- if (error?.code === "ENOENT") return emptyLedger(spaceId);
+ if (error?.code === "ENOENT") {
+ return emptyLedger(spaceId, browserInstanceId);
+ }
throw error;
}
let parsed: unknown;
@@ -306,9 +375,73 @@ export class PageLedgerStore {
} catch (error) {
throw new Error(`invalid page ledger ${path}: ${error.message}`);
}
+ if (
+ browserInstanceId !== undefined &&
+ ledgerBrowserInstanceId(parsed) !== browserInstanceId
+ ) {
+ return emptyLedger(spaceId, browserInstanceId);
+ }
return validateLedger(parsed, spaceId, path);
}
+ async #currentBrowserInstanceId(): Promise<string | undefined> {
+ this.#resolvedBrowserInstanceId ||= Promise.resolve(
+ typeof this.#browserInstanceId === "function"
+ ? this.#browserInstanceId()
+ : this.#browserInstanceId,
+ ).then((value) => {
+ if (value === undefined) return undefined;
+ if (typeof value !== "string" || value.length === 0) {
+ throw new TypeError("browserInstanceId must be a non-empty string");
+ }
+ return value;
+ });
+ return this.#resolvedBrowserInstanceId;
+ }
+
+ async #cleanupExpiredLedgers(
+ browserInstanceId: string | undefined,
+ ): Promise<void> {
+ if (browserInstanceId === undefined) return;
+ this.#cleanup ||= this.#removeExpiredLedgers(browserInstanceId);
+ await this.#cleanup;
+ }
+
+ async #removeExpiredLedgers(browserInstanceId: string): Promise<void> {
+ let names: string[];
+ try {
+ names = await readdir(this.rootDir);
+ } catch (error) {
+ if (error?.code === "ENOENT") return;
+ throw error;
+ }
+ await Promise.all(
+ names
+ .filter((name) => /^space-\d+\.json$/.test(name))
+ .map(async (name) => {
+ const path = join(this.rootDir, name);
+ const metadata = await stat(path).catch(() => undefined);
+ if (
+ !metadata ||
+ this.#now() - metadata.mtimeMs < this.#staleAfterMs
+ ) {
+ return;
+ }
+ let storedInstanceId: string | undefined;
+ try {
+ storedInstanceId = ledgerBrowserInstanceId(
+ JSON.parse(await readFile(path, "utf8")),
+ );
+ } catch {
+ // An expired unreadable ledger cannot belong to the active browser.
+ }
+ if (storedInstanceId !== browserInstanceId) {
+ await rm(path, { force: true });
+ }
+ }),
+ );
+ }
+
async #writeAtomic(spaceId: number, ledger: PageLedger): Promise<void> {
await mkdir(this.rootDir, { recursive: true, mode: 0o700 });
const path = this.#path(spaceId);
@@ -329,8 +462,9 @@ export class PageLedgerStore {
}
}
-function emptyLedger(spaceId: number): PageLedger {
+function emptyLedger(spaceId: number, browserInstanceId?: string): PageLedger {
return {
+ ...(browserInstanceId ? { browserInstanceId } : {}),
spaceId,
nextLabel: 1,
usedLabels: [],
@@ -342,6 +476,17 @@ function emptyLedger(spaceId: number): PageLedger {
};
}
+function ledgerBrowserInstanceId(value: unknown): string | undefined {
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ return undefined;
+ }
+ const browserInstanceId = (value as { browserInstanceId?: unknown })
+ .browserInstanceId;
+ return typeof browserInstanceId === "string" && browserInstanceId.length > 0
+ ? browserInstanceId
+ : undefined;
+}
+
function nextAutomaticLabel(ledger: PageLedger, used: Set<string>): string {
let sequence = ledger.nextLabel;
let label = `p${sequence}`;
@@ -373,6 +518,9 @@ function validateLedger(
(legacyHandoffBaseline !== undefined && legacyHandoffBaseline !== null);
const unmanagedTargets = stored.unmanagedTargets ?? {};
if (
+ (stored.browserInstanceId !== undefined &&
+ (typeof stored.browserInstanceId !== "string" ||
+ stored.browserInstanceId.length === 0)) ||
stored.spaceId !== expectedSpaceId ||
!Number.isInteger(stored.nextLabel) ||
stored.nextLabel < 1 ||
@@ -434,6 +582,9 @@ function validateLedger(
]),
);
return {
+ ...(stored.browserInstanceId
+ ? { browserInstanceId: stored.browserInstanceId }
+ : {}),
spaceId: stored.spaceId,
nextLabel: stored.nextLabel,
usedLabels: [...stored.usedLabels],
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 7c9844e..926e49e 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -125,6 +125,67 @@ function createFixture(rootDir) {
if (method === "Runtime.evaluate") {
const targetId = targetForSession(sessionId);
const tab = tabs.get(targetId);
+ if (params.expression.includes("__egoPageEvaluate")) {
+ if (params.expression.includes("missingClosureForE2E")) {
+ return {
+ result: {
+ type: "object",
+ subtype: "error",
+ description:
+ "ReferenceError: missingClosureForE2E is not defined",
+ },
+ exceptionDetails: {
+ text: "Uncaught",
+ lineNumber: 0,
+ columnNumber: 0,
+ },
+ };
+ }
+ const match = /JSON\.parse\(("(?:\\.|[^"\\])*")\)/.exec(
+ params.expression,
+ );
+ const argument = match ? JSON.parse(JSON.parse(match[1])) : undefined;
+ if (params.expression.includes("window.fetch")) {
+ if (fetchFailure) {
+ const message = fetchFailure;
+ fetchFailure = null;
+ return {
+ result: {
+ type: "object",
+ value: { fetchError: message },
+ },
+ };
+ }
+ const binary = argument?.responseType === "base64";
+ return {
+ result: {
+ type: "object",
+ value: {
+ ok: false,
+ status: 418,
+ statusText: "I'm a Teapot",
+ url: "https://example.test/api/teapot",
+ headers: {
+ "content-type": "text/plain",
+ "x-fixture": "page-fetch",
+ },
+ ...(binary
+ ? {
+ bodyBase64:
+ Buffer.from("\x89PNG\r\n\x1a\n").toString("base64"),
+ }
+ : { body: "short and stout" }),
+ },
+ },
+ };
+ }
+ return {
+ result: {
+ type: "object",
+ value: argument ?? null,
+ },
+ };
+ }
if (params.expression.includes("__egoActionableMatches")) {
return params.returnByValue === false
? {
@@ -952,7 +1013,7 @@ test("Page.waitForFunction polls one Page with one JSON argument", async () => {
sessionId === "session:target-1",
);
assert.equal(probes.length, 3);
- assert.match(probes[0][2].expression, /"selector":"#ready"/);
+ assert.match(probes[0][2].expression, /selector.*#ready/);
assert(
fixture.calls.some(
([kind, method, params]) =>
@@ -1464,13 +1525,21 @@ test("metadata reads stay target-scoped while evaluate and screenshot activate t
assert(
pageCalls.every(([, , , sessionId]) => sessionId === "session:target-1"),
);
- const callFunction = pageCalls.find(
- ([kind, method]) => kind === "cdp" && method === "Runtime.callFunctionOn",
+ const pageEvaluation = pageCalls.find(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Runtime.evaluate" &&
+ params.expression.includes("__egoPageEvaluate"),
+ );
+ assert.match(pageEvaluation[2].expression, /value.*=> value/);
+ assert.match(pageEvaluation[2].expression, /source/);
+ assert.equal(
+ pageCalls.some(
+ ([kind, method]) =>
+ kind === "cdp" && method === "Runtime.callFunctionOn",
+ ),
+ false,
);
- assert.deepEqual(callFunction[2].arguments, [
- { value: { source: "first" } },
- ]);
- assert.match(callFunction[2].functionDeclaration, /value.*=> value/);
});
});
@@ -1496,6 +1565,32 @@ test("Page evaluate rejects ambiguous or non-serializable arguments", async () =
});
});
+test("Page evaluate follows JSON omission rules in one CDP request", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/evaluate");
+ fixture.calls.length = 0;
+
+ const result = await page.evaluate((value) => value, {
+ kept: 1,
+ omitted: undefined,
+ list: [undefined, "ready"],
+ });
+
+ assert.deepEqual(result, { kept: 1, list: [null, "ready"] });
+ const evaluationCalls = fixture.calls.filter(
+ ([kind, method]) =>
+ kind === "cdp" &&
+ (method === "Runtime.evaluate" ||
+ method === "Runtime.callFunctionOn" ||
+ method === "Runtime.releaseObject"),
+ );
+ assert.equal(evaluationCalls.length, 1);
+ assert.equal(evaluationCalls[0][1], "Runtime.evaluate");
+ assert.match(evaluationCalls[0][2].expression, /__egoPageEvaluate/);
+ });
+});
+
test("Page evaluate preserves a large nested JSON argument", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
@@ -1554,23 +1649,23 @@ test("Page fetch activates its target and returns a structured non-2xx response"
const fetchCall = fixture.calls.find(
([kind, method, params]) =>
kind === "cdp" &&
- method === "Runtime.callFunctionOn" &&
- params.functionDeclaration.includes("window.fetch"),
- );
- assert.deepEqual(fetchCall[2].arguments, [
- {
- value: {
- url: "/api/teapot",
- options: {
- method: "POST",
- headers: { "x-request": "page-fetch" },
- body: "payload",
- },
- timeoutMs: 250,
- responseType: "text",
- },
+ method === "Runtime.evaluate" &&
+ params.expression.includes("__egoPageEvaluate") &&
+ params.expression.includes("window.fetch"),
+ );
+ const argumentMatch = /JSON\.parse\(("(?:\\.|[^"\\])*")\)/.exec(
+ fetchCall[2].expression,
+ );
+ assert.deepEqual(JSON.parse(JSON.parse(argumentMatch[1])), {
+ url: "/api/teapot",
+ options: {
+ method: "POST",
+ headers: { "x-request": "page-fetch" },
+ body: "payload",
},
- ]);
+ timeoutMs: 250,
+ responseType: "text",
+ });
assert.equal(fetchCall[3], "session:target-1");
assert.equal(fetchCall[4], 1_250);
});
@@ -2988,6 +3083,22 @@ test("Page.waitForEvent arms before a click and resolves the opened popup", asyn
});
});
+test("Page.waitForEvent replays a popup reported by the preceding action", async () => {
+ await withFixture(async (fixture) => {
+ resetPageNotices();
+ const task = taskForRound(fixture, "round-a");
+ const source = await openTestPage(task, "https://example.test/source");
+ fixture.openPopupOnNextClick("https://example.test/popup");
+
+ const receipt = await source.click("#open-popup");
+ const popup = await source.waitForEvent("popup", { timeout: 1_000 });
+
+ assert.equal(popup.label, receipt.popups[0].label);
+ assert.equal(await popup.url(), "https://example.test/popup");
+ assert.deepEqual(consumeUnhandledPageNotices(), []);
+ });
+});
+
test("Page.waitForEvent rejects unsupported events and times out cleanly", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.ts
index 7dff0a9..5f1578f 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -69,7 +69,7 @@ import {
type PageWaitForURLOptions,
} from "./driver/page-waits.js";
import { ElementResolutionError } from "./element-resolver.js";
-import { invokeEgo, isEgoUserControlError } from "./ego-errors.js";
+import { invokeEgo, probeAgentControl } from "./ego-errors.js";
import {
withPage as defaultWithPage,
withSpace as defaultWithSpace,
@@ -77,6 +77,7 @@ import {
} from "./native-gate.js";
import {
PageLedgerStore,
+ runtimeInstanceId,
type ManagedPage,
type PageLedger,
type PageOrigin,
@@ -557,15 +558,11 @@ const baseDefaultServices: Omit<PageModelServices, "ledger" | "pageBudget"> = {
return result?.tabs || result?.targetInfos || [];
},
async probeAgentControl() {
- try {
- // Use the native probe directly. snapshotRaw turns user control into a
- // hard-stop output signal, while waiting for that state is intentional.
- await browserEgo().snapshot({ maxResultLength: 1 });
- return true;
- } catch (error) {
- if (isEgoUserControlError(error)) return false;
- throw error;
- }
+ // Do not route this through invokeEgo: observing user control is the
+ // expected waiting state, not a hard-stop signal.
+ return probeAgentControl(() =>
+ browserEgo().snapshot({ maxResultLength: 1 }),
+ );
},
async handOffTaskSpace() {
const ego = browserEgo();
@@ -636,7 +633,9 @@ export function createTaskSpaceHandle(
// Ego Lite imports the SDK before it evaluates the submitted script. Resolve
// environment-backed settings lazily so SDK callers can configure a round
// before their first taskSpace() call.
- defaultLedger ||= new PageLedgerStore();
+ defaultLedger ||= new PageLedgerStore({
+ browserInstanceId: runtimeInstanceId,
+ });
const services = {
...baseDefaultServices,
ledger: defaultLedger,
@@ -1360,10 +1359,13 @@ class Page {
),
);
}, timeoutMs);
+ for (const notice of peekUnhandledPageNotices()) onNotice(notice);
// Resolve the source after arming the listener. A stale Page should fail
// the waiter, but no popup may be lost while that validation is pending.
- void this.#resolve().catch((error) => finish(() => reject(error)));
+ if (!settled) {
+ void this.#resolve().catch((error) => finish(() => reject(error)));
+ }
});
}
@@ -2287,40 +2289,23 @@ async function evaluateInSession<T>(
}
const source = expression.toString();
- const owner = await services.cdp(
+ const response = await services.cdp(
"Runtime.evaluate",
{
- expression: "globalThis",
- returnByValue: false,
+ expression: `(async function __egoPageEvaluate() {
+ return await ${pageFunctionCallExpression(
+ source,
+ hasArgument,
+ serializedArgument,
+ )};
+ })()`,
+ returnByValue: true,
+ awaitPromise: true,
},
sessionId,
timeoutMs,
);
- const objectId = owner?.result?.objectId;
- if (typeof objectId !== "string" || objectId.length === 0) {
- throw new Error("page.evaluate could not resolve the page global object");
- }
- try {
- const response = await services.cdp(
- "Runtime.callFunctionOn",
- {
- objectId,
- functionDeclaration: hasArgument
- ? `function(argument) { return (${source})(argument); }`
- : `function() { return (${source})(); }`,
- arguments: hasArgument ? [{ value: serializedArgument }] : [],
- returnByValue: true,
- awaitPromise: true,
- },
- sessionId,
- timeoutMs,
- );
- return runtimeValue(response, source) as T;
- } finally {
- await services
- .cdp("Runtime.releaseObject", { objectId }, sessionId)
- .catch(() => {});
- }
+ return runtimeValue(response, source) as T;
}
function validateEvaluateInput(
@@ -2365,8 +2350,21 @@ function waitForFunctionExpression(
return `(async function __egoWaitForFunction() { return { matched: Boolean(await (${expression})), url: location.href, title: document.title }; })()`;
}
const source = expression.toString();
- const argument = hasArgument ? JSON.stringify(serializedArgument) : "";
- return `(async function __egoWaitForFunction() { return { matched: Boolean(await (${source})(${argument})), url: location.href, title: document.title }; })()`;
+ return `(async function __egoWaitForFunction() { return { matched: Boolean(await ${pageFunctionCallExpression(
+ source,
+ hasArgument,
+ serializedArgument,
+ )}), url: location.href, title: document.title }; })()`;
+}
+
+function pageFunctionCallExpression(
+ source: string,
+ hasArgument: boolean,
+ serializedArgument: unknown,
+): string {
+ if (!hasArgument) return `(${source})()`;
+ const json = JSON.stringify(serializedArgument);
+ return `(${source})(JSON.parse(${JSON.stringify(json)}))`;
}
function isWaitForFunctionState(
@@ -2434,9 +2432,6 @@ function serializeJsonValue(value: unknown, message: string): unknown {
try {
const json = JSON.stringify(value, (_key, item) => {
if (
- typeof item === "undefined" ||
- typeof item === "function" ||
- typeof item === "symbol" ||
typeof item === "bigint" ||
(typeof item === "number" && !Number.isFinite(item))
) {
diff --git a/package/ego-browser/src/run-output-sink.test.mjs b/package/ego-browser/src/run-output-sink.test.mjs
index 4ba42cc..bd5f72e 100644
--- a/package/ego-browser/src/run-output-sink.test.mjs
+++ b/package/ego-browser/src/run-output-sink.test.mjs
@@ -100,7 +100,7 @@ test("round console methods share the buffered output channel", async () => {
assert.equal(result.exitCode, 0);
assert.equal(
result.stdout,
- 'plain {"value":1}\ninfo\n[warn] careful\n[error] broken\nlegacy\n',
+ "plain { value: 1 }\ninfo\n[warn] careful\n[error] broken\nlegacy\n",
);
});
diff --git a/package/ego-browser/src/snapshot-result.test.mjs b/package/ego-browser/src/snapshot-result.test.mjs
index ac9f9d2..4e66d1b 100644
--- a/package/ego-browser/src/snapshot-result.test.mjs
+++ b/package/ego-browser/src/snapshot-result.test.mjs
@@ -3,10 +3,78 @@ import assert from "node:assert/strict";
import {
enrichSnapshotRefFrames,
+ preparePageSnapshotResult,
sanitizeSnapshotLocators,
validateSnapshotLocator,
} from "../dist/src/snapshot-result.js";
+test("snapshot locator validation batches DOM queries and object cleanup", async () => {
+ const calls = [];
+ const services = {
+ async cdp(method, params, sessionId) {
+ calls.push([method, params, sessionId]);
+ if (method === "Runtime.evaluate" && params.returnByValue) {
+ return { result: { value: [1, 1] } };
+ }
+ if (method === "Runtime.evaluate") {
+ return { result: { objectId: "locator-batch" } };
+ }
+ if (method === "Runtime.getProperties") {
+ return {
+ result: [
+ { name: "0", value: { objectId: "node:10" } },
+ { name: "1", value: { objectId: "node:11" } },
+ ],
+ };
+ }
+ if (method === "DOM.describeNode") {
+ return {
+ node: {
+ backendNodeId: Number(params.objectId.slice("node:".length)),
+ },
+ };
+ }
+ if (method === "Runtime.releaseObjectGroup") return {};
+ throw new Error(`unexpected CDP method: ${method}`);
+ },
+ };
+ const result = {
+ content: [
+ "button A [ref=10, loc=css:#a]",
+ "button B [ref=11, loc=css:#b]",
+ ].join("\n"),
+ refs: [
+ { backendNodeId: 10, loc: "css:#a" },
+ { backendNodeId: 11, loc: "css:#b" },
+ ],
+ };
+
+ await preparePageSnapshotResult(services, "session:page", new Map(), result);
+
+ assert.equal(result.refs[0].loc, "css:#a");
+ assert.equal(result.refs[1].loc, "css:#b");
+ assert.equal(
+ calls.filter(([method]) => method === "Runtime.evaluate").length,
+ 2,
+ );
+ assert.equal(
+ calls.filter(([method]) => method === "Runtime.getProperties").length,
+ 1,
+ );
+ assert.equal(
+ calls.filter(([method]) => method === "DOM.describeNode").length,
+ 2,
+ );
+ assert.equal(
+ calls.filter(([method]) => method === "Runtime.releaseObjectGroup").length,
+ 1,
+ );
+ assert.equal(
+ calls.some(([method]) => method === "Runtime.releaseObject"),
+ false,
+ );
+});
+
test("invalid native snapshot locators are hidden without removing their refs", async () => {
const result = {
content: [
@@ -57,13 +125,16 @@ test("stable locator validation requires one match for the original backend node
);
const response = responses.get(key);
if (params.returnByValue) {
- return { result: { value: response.count } };
+ return { result: { value: [response.count] } };
}
return {
- result:
- response.count === 1
- ? { objectId: `node:${response.resolvedBackendNodeId}` }
- : {},
+ result: { objectId: `batch:${response.resolvedBackendNodeId}` },
+ };
+ }
+ if (method === "Runtime.getProperties") {
+ const backendNodeId = params.objectId.slice("batch:".length);
+ return {
+ result: [{ name: "0", value: { objectId: `node:${backendNodeId}` } }],
};
}
if (method === "DOM.describeNode") {
@@ -73,6 +144,7 @@ test("stable locator validation requires one match for the original backend node
},
};
}
+ if (method === "Runtime.releaseObjectGroup") return {};
return {};
},
};
diff --git a/package/ego-browser/src/snapshot-result.ts b/package/ego-browser/src/snapshot-result.ts
index 02a30af..a6ee308 100644
--- a/package/ego-browser/src/snapshot-result.ts
+++ b/package/ego-browser/src/snapshot-result.ts
@@ -1,5 +1,4 @@
-import { resolveElementObjectId } from "./element-resolver.js";
-import { RefMap } from "./ref-map.js";
+import { validateLocatorBackendNodes } from "./element-resolver.js";
type SnapshotRef = {
backendNodeId?: number;
@@ -83,48 +82,15 @@ export async function validateSnapshotLocator(
iframeSessions: Map<string, string>,
ref: SnapshotRef,
): Promise<boolean> {
- if (
- !Number.isInteger(ref.backendNodeId) ||
- typeof ref.loc !== "string" ||
- ref.loc.length === 0 ||
- ref.loc === "unstable" ||
- ref.loc === "ambiguous"
- ) {
- return false;
- }
-
- let resolved:
- | { objectId: string; sessionId: string; frameId?: string }
- | undefined;
- try {
- resolved = await resolveElementObjectId(
- cdp,
- pageSessionId,
- new RefMap(),
- ref.loc.startsWith("loc=") ? ref.loc : `loc=${ref.loc}`,
- iframeSessions,
- { strict: true, strictGlobal: true },
- );
- const described = await cdp.sendRaw(
- "DOM.describeNode",
- { objectId: resolved.objectId, depth: 0 },
- resolved.sessionId,
- );
- return described?.node?.backendNodeId === ref.backendNodeId;
- } catch {
- // Invalid, missing, and ambiguous native locators are all unsafe to expose.
- return false;
- } finally {
- if (resolved?.objectId) {
- await cdp
- .sendRaw(
- "Runtime.releaseObject",
- { objectId: resolved.objectId },
- resolved.sessionId,
- )
- .catch(() => {});
- }
- }
+ const candidates = snapshotLocatorCandidates([ref]);
+ if (candidates.length === 0) return false;
+ const valid = await validateLocatorBackendNodes(
+ cdp,
+ pageSessionId,
+ iframeSessions,
+ candidates,
+ );
+ return valid.has(0);
}
/** Replace invalid native stable locators while retaining their short-lived refs. */
@@ -174,7 +140,35 @@ export async function preparePageSnapshotResult(
sendRaw: (method, params = {}, sessionId) =>
services.cdp(method, params, sessionId),
};
- return sanitizeSnapshotLocators(result, (ref) =>
- validateSnapshotLocator(adapter, pageSessionId, iframeSessions, ref),
+ const refs = result?.refs || [];
+ const validIndexes = await validateLocatorBackendNodes(
+ adapter,
+ pageSessionId,
+ iframeSessions,
+ snapshotLocatorCandidates(refs),
);
+ const validRefs = new Set(refs.filter((_, index) => validIndexes.has(index)));
+ return sanitizeSnapshotLocators(result, async (ref) => validRefs.has(ref));
+}
+
+function snapshotLocatorCandidates(refs: SnapshotRef[]) {
+ return refs.flatMap((ref, index) => {
+ if (
+ !Number.isInteger(ref.backendNodeId) ||
+ typeof ref.loc !== "string" ||
+ ref.loc.length === 0 ||
+ ref.loc === "unstable" ||
+ ref.loc === "ambiguous"
+ ) {
+ return [];
+ }
+ return [
+ {
+ index,
+ locator: ref.loc.startsWith("loc=") ? ref.loc : `loc=${ref.loc}`,
+ backendNodeId: ref.backendNodeId!,
+ ...(ref.frameId ? { frameId: ref.frameId } : {}),
+ },
+ ];
+ });
}
diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.md
index ff25710..b9189ce 100644
--- a/skills/ego-browser/SKILL.md
+++ b/skills/ego-browser/SKILL.md
@@ -195,9 +195,10 @@ keyboard names and `+`-separated chords follow Playwright syntax. Use
`mouse.wheel()` sends the event at the current mouse position. In each heredoc,
move or click over the intended scrollable area before using it.
-`keyboard.paste()` sends the native paste shortcut and then restores the user's
-clipboard. Pass `{ text, html }` when a rich editor needs structured clipboard
-content; `text` is the plain-text fallback.
+On macOS, `keyboard.paste()` sends the native paste shortcut and then restores
+the user's clipboard. Pass `{ text, html }` when a rich editor needs structured
+clipboard content; `text` is the plain-text fallback. On other platforms, use
+`keyboard.insertText()` for plain text.
```js
await page.keyboard.paste({