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.

feat(ego-browser): align page automation behavior

Autead239e3da896
diff --git a/docs/native-bindings-api.md b/docs/native-bindings-api.md
index 2e00e70..21e65db 100644
--- a/docs/native-bindings-api.md
+++ b/docs/native-bindings-api.md
@@ -315,6 +315,9 @@ Callers should use `error_code` to identify the control boundary, then use the
reason key to choose guidance. Unknown reason keys must fall back to generic
user-control guidance.
+Page-authored JavaScript dialogs must not use this user-control path; see
+[Native JavaScript dialog requirement](native-javascript-dialog-requirement.md).
+
## Snapshot
### `await ego.snapshot(options?)`
diff --git a/docs/native-javascript-dialog-requirement.md b/docs/native-javascript-dialog-requirement.md
new file mode 100644
index 0000000..86d30eb
--- /dev/null
+++ b/docs/native-javascript-dialog-requirement.md
@@ -0,0 +1,24 @@
+# Native JavaScript dialog requirement
+
+Page-authored `alert`, `confirm`, `prompt`, and `beforeunload` dialogs must stay
+under Agent control. They must not change TaskSpace ownership or report
+`EGO_TASK_SPACE_USER_IN_CONTROL` with
+`fallback_site_dialog_required_notice`.
+
+No new binding is required. The existing CDP bridge must:
+
+- forward `Page.javascriptDialogOpening` and
+ `Page.javascriptDialogClosed` on the Page session;
+- accept `Page.handleJavaScriptDialog` on that session while the dialog is
+ open, even when the triggering command is still pending;
+- preserve the dialog type, message, URL, prompt default, and supplied
+ `promptText`.
+
+Permission prompts and device choosers must continue to transfer control to
+the user.
+
+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
+and closing events. Separately verify that location, camera, and device prompts
+still transfer control to the user.
diff --git a/package/ego-browser/README.md b/package/ego-browser/README.md
index 370690d..aac30a9 100644
--- a/package/ego-browser/README.md
+++ b/package/ego-browser/README.md
@@ -19,7 +19,7 @@ The build emits a single ESM file `dist/out/index.js`. The ego-browser browser d
```bash
ego-browser nodejs <<'EOF'
const task = await taskSpace('demo')
-const page = await task.newPage()
+const page = task.page('p1')
await page.goto('https://example.com')
console.log(await page.snapshot())
EOF
@@ -92,11 +92,19 @@ existing scripts.
- The browser runtime owns tabs, task spaces, CDP transport, snapshots, and event delivery. This package keeps only agent-facing ergonomics.
- Snapshot helpers use the browser runtime contract: `ego.snapshot({ scope, includeActionMarks, includeStableLocator })`.
- Page selectors search the top document first. Input actions search frames
- when the top document has no actionable match, then require one actionable
- frame match.
-- Pointer actions require a real hit target. DOM-backed actions such as
- `selectOption()` require a rendered, enabled control but may operate on an
- opacity-zero native control used by a custom widget.
+ when the top document has no match usable for that action, then require one
+ usable frame match.
+- The selector parser supports the documented Ego forms plus a narrow
+ Playwright-compatible subset: `css=`, terminal `:has-text()`, `:text-is()`,
+ `>> nth=N` after CSS/text/href selectors (`N >= 0` or `-1`), and role
+ `name*=` matching.
+- Clicks require an enabled element and a real hit target. Hover and drag keep
+ the hit-target requirement but may address disabled elements. DOM-backed
+ actions such as `selectOption()` require a rendered, enabled control but may
+ operate on an opacity-zero native control used by a custom widget. Like
+ Playwright, `selectOption()` can programmatically choose a disabled option.
+- Network-idle waits use continuous per-Page and OOPIF request state; they do
+ not consume the CDP events returned by `page.events()` or include other Pages.
- `fill()` verifies that editing took effect, not that application formatting
preserved the requested string byte-for-byte. Business postconditions remain
explicit Page reads or waits.
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 0efeb38..21e2412 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
@@ -11,7 +11,7 @@ import { pageKeyboardInterfaceCase } from "./page-keyboard.mjs";
import { pageClickHitTargetCase } from "./page-click-hit-target.mjs";
import { pageDragAndDrawCase } from "./page-drag-and-draw.mjs";
import {
- pageJavaScriptDialogHandoffCase,
+ pageJavaScriptDialogHandlingCase,
pageJavaScriptDialogRecoveryCase,
} from "./page-dialogs.mjs";
import { pageMediaPlaybackCase } from "./page-media-playback.mjs";
@@ -19,9 +19,13 @@ import { pageScrolledScreenshotCase } from "./page-screenshot.mjs";
import { pageSnapshotLocatorCase } from "./page-snapshot-locators.mjs";
import { pageShadowDomCase } from "./page-shadow-dom.mjs";
import { pageTextLocatorCase } from "./page-text-locators.mjs";
+import { pageSelectorCompatibilityCase } from "./page-selector-compatibility.mjs";
import { pagePopupWaiterCase } from "./page-popup-waiter.mjs";
import { pageOopifActionCase, pageOopifRestoreCase } from "./page-oopif.mjs";
import { pageLoadStatesCase } from "./page-load-states.mjs";
+import { pageApiAlignmentCase } from "./page-api-alignment.mjs";
+import { pageActionabilityCase } from "./page-actionability.mjs";
+import { pageEvaluateTimeoutCase } from "./page-evaluate-timeout.mjs";
import {
pageDelayedPopupResumeCase,
pageDelayedPopupScheduleCase,
@@ -86,12 +90,14 @@ export const e2eCases = [
{ name: "Page click hit target", body: pageClickHitTargetCase },
{ name: "Page drag and canvas drawing", body: pageDragAndDrawCase },
{
- name: "Page JavaScript dialog handoff",
- body: pageJavaScriptDialogHandoffCase,
+ name: "Page JavaScript dialog handling",
+ body: pageJavaScriptDialogHandlingCase,
expectedTermination: true,
markerName: "dialog-hard-stop.json",
expectedOutput: "The page has displayed a dialog that requires review.",
- acceptedCompletionOutput: '"dialogReceipt":true',
+ acceptedCompletionOutput: '"dialogHandled":true',
+ pendingOnExpectedTermination:
+ "installed Ego Lite still hands page-authored JavaScript dialogs to the user",
},
{
name: "Page JavaScript dialog recovery",
@@ -102,10 +108,21 @@ export const e2eCases = [
{ name: "Page snapshot locator quality", body: pageSnapshotLocatorCase },
{ name: "Page open Shadow DOM locators", body: pageShadowDomCase },
{ name: "Page text locators", body: pageTextLocatorCase },
+ {
+ name: "Page Playwright selector compatibility",
+ body: pageSelectorCompatibilityCase,
+ },
{ name: "Page popup waiter and URL diagnostic", body: pagePopupWaiterCase },
{ name: "Page OOPIF actions", body: pageOopifActionCase },
{ name: "Page OOPIF restore and close", body: pageOopifRestoreCase },
{ name: "Page load states", body: pageLoadStatesCase },
+ { name: "Page API alignment", body: pageApiAlignmentCase },
+ { name: "Page actionability", body: pageActionabilityCase },
+ {
+ name: "Page evaluate timeout recovery",
+ body: pageEvaluateTimeoutCase,
+ timeoutMs: 60_000,
+ },
{
name: "Page delayed popup: schedule",
body: pageDelayedPopupScheduleCase,
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-actionability.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-actionability.mjs
new file mode 100644
index 0000000..cfecc43
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-actionability.mjs
@@ -0,0 +1,329 @@
+export function pageActionabilityCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const page = await newPageAt(task, baseUrl + "/?page-actionability=" + Date.now());
+
+ await page.evaluate(() => {
+ document.body.innerHTML = \
+ '<style>' +
+ ' .action-row { display: flex; gap: 12px; margin: 12px; min-height: 40px; }' +
+ ' .drag-box { width: 80px; height: 40px; background: #ddd; }' +
+ '</style>' +
+ '<div class="action-row">' +
+ ' <button id="nested-disabled" disabled><span>Nested disabled action</span></button>' +
+ ' <button id="native-disabled" disabled aria-disabled="false">Native disabled</button>' +
+ '</div>' +
+ '<div id="aria-container" aria-disabled="true" class="action-row">' +
+ ' <button id="aria-blocked">ARIA blocked</button>' +
+ ' <button id="aria-override" aria-disabled="false">ARIA override</button>' +
+ ' <input id="aria-fill-blocked">' +
+ '</div>' +
+ '<div class="action-row">' +
+ ' <button id="aria-owner" aria-disabled="true"><span aria-disabled="false">ARIA owner action</span></button>' +
+ ' <div id="unsupported-aria" aria-disabled="true">Unsupported ARIA action</div>' +
+ '</div>' +
+ '<fieldset id="disabled-fieldset" disabled>' +
+ ' <legend><button id="legend-action">Legend action</button></legend>' +
+ ' <input id="fieldset-input">' +
+ '</fieldset>' +
+ '<div class="action-row">' +
+ ' <button class="duplicate-action" disabled>Disabled duplicate</button>' +
+ ' <button class="duplicate-action" id="enabled-duplicate">Enabled duplicate</button>' +
+ ' <input class="duplicate-fill" disabled>' +
+ ' <input class="duplicate-fill" id="enabled-fill">' +
+ '</div>' +
+ '<div class="action-row">' +
+ ' <button id="disabled-hover" disabled>Hover disabled</button>' +
+ ' <div id="disabled-drag-source" class="drag-box" role="button" aria-disabled="true">Drag source</div>' +
+ ' <div id="disabled-drag-target" class="drag-box" role="button" aria-disabled="true">Drag target</div>' +
+ '</div>' +
+ '<div id="force-wrapper" class="action-row" style="position:relative;width:180px">' +
+ ' <button id="force-target" style="width:180px;height:40px">Force target</button>' +
+ ' <div id="force-overlay" style="position:absolute;inset:0;background:rgba(0,0,0,.1)"></div>' +
+ '</div>' +
+ '<div class="action-row">' +
+ ' <select id="disabled-select" disabled><option value="value">Value</option></select>' +
+ ' <select id="option-states">' +
+ ' <option value="normal">Normal</option>' +
+ ' <option value="disabled" disabled>Disabled option</option>' +
+ ' <option value="aria-disabled" aria-disabled="true">ARIA disabled option</option>' +
+ ' <optgroup label="Disabled group" disabled><option value="grouped">Grouped option</option></optgroup>' +
+ ' </select>' +
+ '</div>';
+
+ window.__actionability = {
+ nestedClicks: 0,
+ ariaBlockedClicks: 0,
+ ariaOverrideClicks: 0,
+ ariaOwnerClicks: 0,
+ unsupportedAriaClicks: 0,
+ duplicateClicks: 0,
+ fieldsetInputBeforeEnabled: 0,
+ ariaInputBeforeEnabled: 0,
+ hoverEvents: 0,
+ hoverTrusted: false,
+ dragDown: 0,
+ dragUp: 0,
+ dragTrusted: false,
+ forceTargetClicks: 0,
+ forceOverlayClicks: 0,
+ fieldsetEnabled: false,
+ ariaEnabled: false,
+ };
+ const state = window.__actionability;
+ document.querySelector("#nested-disabled").addEventListener("click", () => state.nestedClicks++);
+ document.querySelector("#aria-blocked").addEventListener("click", () => state.ariaBlockedClicks++);
+ document.querySelector("#aria-override").addEventListener("click", () => state.ariaOverrideClicks++);
+ document.querySelector("#aria-owner").addEventListener("click", () => state.ariaOwnerClicks++);
+ document.querySelector("#unsupported-aria").addEventListener("click", () => state.unsupportedAriaClicks++);
+ document.querySelector("#enabled-duplicate").addEventListener("click", () => state.duplicateClicks++);
+ document.querySelector("#fieldset-input").addEventListener("input", () => {
+ if (!state.fieldsetEnabled) state.fieldsetInputBeforeEnabled++;
+ });
+ document.querySelector("#aria-fill-blocked").addEventListener("input", () => {
+ if (!state.ariaEnabled) state.ariaInputBeforeEnabled++;
+ });
+ document.querySelector("#disabled-hover").addEventListener("mouseover", (event) => {
+ state.hoverEvents++;
+ state.hoverTrusted ||= event.isTrusted;
+ });
+ document.querySelector("#disabled-drag-source").addEventListener("mousedown", (event) => {
+ state.dragDown++;
+ state.dragTrusted ||= event.isTrusted;
+ });
+ document.querySelector("#disabled-drag-target").addEventListener("mouseup", (event) => {
+ state.dragUp++;
+ state.dragTrusted ||= event.isTrusted;
+ });
+ document.querySelector("#force-target").addEventListener("click", () => {
+ state.forceTargetClicks++;
+ });
+ document.querySelector("#force-overlay").addEventListener("click", () => {
+ state.forceOverlayClicks++;
+ });
+
+ const shadowHost = document.createElement("div");
+ shadowHost.id = "shadow-action-host";
+ shadowHost.setAttribute("aria-disabled", "true");
+ shadowHost.attachShadow({ mode: "open" }).innerHTML =
+ '<div class="action-row">' +
+ ' <button id="shadow-blocked">Shadow blocked</button>' +
+ ' <button id="shadow-override" aria-disabled="false">Shadow override</button>' +
+ ' <input id="shadow-fill-blocked">' +
+ '</div>';
+ document.body.append(shadowHost);
+ state.shadowBlockedClicks = 0;
+ state.shadowOverrideClicks = 0;
+ shadowHost.shadowRoot.querySelector("#shadow-blocked").addEventListener("click", () => {
+ state.shadowBlockedClicks++;
+ });
+ shadowHost.shadowRoot.querySelector("#shadow-override").addEventListener("click", () => {
+ state.shadowOverrideClicks++;
+ });
+ });
+
+ await assertRejectsAny(
+ () => page.click('text="Nested disabled action"', { timeout: 150 }),
+ "click rejects a disabled control reached through its child"
+ );
+ assertEqual(
+ await page.evaluate("window.__actionability.nestedClicks"),
+ 0,
+ "a disabled nested control receives no click"
+ );
+
+ const snapshot = await page.snapshot({ scope: "full_page" });
+ const nestedLines = snapshot.split("\\n");
+ const nestedTextIndex = nestedLines.findIndex((line) =>
+ line.includes("Nested disabled action")
+ );
+ const nestedRef =
+ nestedTextIndex >= 0 &&
+ nestedLines
+ .slice(0, nestedTextIndex + 1)
+ .reverse()
+ .map((line) => line.match(/\\[ref=([0-9]+)/))
+ .find(Boolean);
+ assert(nestedRef, "snapshot exposes the disabled button ref");
+ await assertRejectsAny(
+ () => page.click("@" + nestedRef[1], { timeout: 150 }),
+ "the final action check also protects the ref path"
+ );
+
+ await page.evaluate(() => {
+ setTimeout(() => {
+ document.querySelector("#nested-disabled").disabled = false;
+ }, 100);
+ });
+ await page.click('text="Nested disabled action"', { timeout: 1_000 });
+ assertEqual(
+ await page.evaluate("window.__actionability.nestedClicks"),
+ 1,
+ "click retries until the nested control becomes enabled"
+ );
+
+ await assertRejectsAny(
+ () => page.click("#native-disabled", { force: true, timeout: 150 }),
+ "force does not override native disabled state or aria-disabled=false"
+ );
+ await assertRejectsAny(
+ () => page.click("#aria-blocked", { timeout: 150 }),
+ "aria-disabled is inherited from an ordinary ancestor"
+ );
+ await page.click("#aria-override");
+ assertEqual(
+ await page.evaluate("window.__actionability.ariaOverrideClicks"),
+ 1,
+ "a nearer aria-disabled=false stops inherited ARIA disabled state"
+ );
+ await assertRejectsAny(
+ () => page.click('text="ARIA owner action"', { timeout: 150 }),
+ "aria-disabled=false on button content does not override the button"
+ );
+ assertEqual(
+ await page.evaluate("window.__actionability.ariaOwnerClicks"),
+ 0,
+ "the ARIA-disabled action owner receives no click"
+ );
+ await page.click("#unsupported-aria");
+ assertEqual(
+ await page.evaluate("window.__actionability.unsupportedAriaClicks"),
+ 1,
+ "aria-disabled does not disable an element without a supporting role"
+ );
+
+ await assertRejectsAny(
+ () => page.click("#shadow-blocked", { timeout: 150 }),
+ "aria-disabled crosses an open shadow root"
+ );
+ await page.click("#shadow-override");
+ assertEqual(
+ await page.evaluate("window.__actionability.shadowOverrideClicks"),
+ 1,
+ "aria-disabled=false overrides a shadow host"
+ );
+ await assertRejectsAny(
+ () => page.fill("#shadow-fill-blocked", "must not appear", { timeout: 150 }),
+ "fill uses the same shadow-aware enabled state"
+ );
+ assertEqual(
+ await page.evaluate("document.querySelector('#shadow-action-host').shadowRoot.querySelector('#shadow-fill-blocked').value"),
+ "",
+ "blocked shadow fill dispatches no input"
+ );
+
+ await page.click("#legend-action");
+ await assertRejectsAny(
+ () => page.fill("#fieldset-input", "early", { timeout: 150 }),
+ "a disabled fieldset blocks controls outside its first legend"
+ );
+ assertEqual(
+ await page.evaluate("document.querySelector('#fieldset-input').value"),
+ "",
+ "fieldset-disabled fill leaves the input unchanged"
+ );
+ await page.evaluate(() => {
+ setTimeout(() => {
+ window.__actionability.fieldsetEnabled = true;
+ document.querySelector("#disabled-fieldset").disabled = false;
+ }, 100);
+ });
+ await page.fill("#fieldset-input", "ready", { timeout: 1_000 });
+ assertEqual(
+ await page.evaluate("document.querySelector('#fieldset-input').value"),
+ "ready",
+ "fill retries until the fieldset becomes enabled"
+ );
+ assertEqual(
+ await page.evaluate("window.__actionability.fieldsetInputBeforeEnabled"),
+ 0,
+ "fill emits no input before the fieldset becomes enabled"
+ );
+
+ await assertRejectsAny(
+ () => page.fill("#aria-fill-blocked", "early", { timeout: 150 }),
+ "fill inherits aria-disabled from an ordinary ancestor"
+ );
+ assertEqual(
+ await page.evaluate("document.querySelector('#aria-fill-blocked').value"),
+ "",
+ "ARIA-disabled fill leaves the input unchanged"
+ );
+ await page.evaluate(() => {
+ setTimeout(() => {
+ window.__actionability.ariaEnabled = true;
+ document.querySelector("#aria-fill-blocked").setAttribute("aria-disabled", "false");
+ }, 100);
+ });
+ await page.fill("#aria-fill-blocked", "ready", { timeout: 1_000 });
+ assertEqual(
+ await page.evaluate("window.__actionability.ariaInputBeforeEnabled"),
+ 0,
+ "fill emits no input before ARIA state becomes enabled"
+ );
+
+ await page.click(".duplicate-action");
+ assertEqual(
+ await page.evaluate("window.__actionability.duplicateClicks"),
+ 1,
+ "click chooses the only enabled duplicate"
+ );
+ await page.fill(".duplicate-fill", "usable");
+ assertEqual(
+ await page.evaluate("document.querySelector('#enabled-fill').value"),
+ "usable",
+ "fill chooses the only enabled duplicate"
+ );
+ await assertRejects(
+ () => page.hover(".duplicate-action", { timeout: 150 }),
+ "matched 2",
+ "hover treats disabled and enabled duplicates as equally usable"
+ );
+
+ await page.hover("#disabled-hover");
+ const hoverState = await page.evaluate(() => ({
+ count: window.__actionability.hoverEvents,
+ trusted: window.__actionability.hoverTrusted,
+ }));
+ assert(hoverState.count > 0, "hover reaches a disabled element");
+ assertEqual(hoverState.trusted, true, "disabled hover still uses trusted input");
+
+ await page.dragAndDrop("#disabled-drag-source", "#disabled-drag-target");
+ const dragState = await page.evaluate(() => ({
+ down: window.__actionability.dragDown,
+ up: window.__actionability.dragUp,
+ trusted: window.__actionability.dragTrusted,
+ }));
+ assert(dragState.down > 0, "drag starts on an aria-disabled source");
+ assert(dragState.up > 0, "drag ends on an aria-disabled target");
+ assertEqual(dragState.trusted, true, "disabled drag still uses trusted input");
+
+ await page.click("#force-target", { force: true });
+ const forceState = await page.evaluate(() => ({
+ target: window.__actionability.forceTargetClicks,
+ overlay: window.__actionability.forceOverlayClicks,
+ }));
+ assertEqual(forceState.target, 0, "force does not synthesize a target click");
+ assertEqual(forceState.overlay, 1, "force bypasses only pointer interception");
+
+ await assertRejectsAny(
+ () => page.selectOption("#disabled-select", "value", { timeout: 150 }),
+ "selectOption requires the select itself to be enabled"
+ );
+ assertEqual(
+ JSON.stringify(await page.selectOption("#option-states", "disabled")),
+ JSON.stringify(["disabled"]),
+ "selectOption follows Playwright and can select a disabled option"
+ );
+ assertEqual(
+ JSON.stringify(await page.selectOption("#option-states", "aria-disabled")),
+ JSON.stringify(["aria-disabled"]),
+ "option ARIA state does not disable an enabled select"
+ );
+ assertEqual(
+ JSON.stringify(await page.selectOption("#option-states", "grouped")),
+ JSON.stringify(["grouped"]),
+ "selectOption can programmatically select an option in a disabled optgroup"
+ );
+ `;
+}
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-api-alignment.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-api-alignment.mjs
new file mode 100644
index 0000000..52d6ff0
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-api-alignment.mjs
@@ -0,0 +1,292 @@
+export function pageApiAlignmentCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const page = await newPageAt(task, baseUrl + "/?page-api-alignment=" + Date.now());
+ const originalTargetId = page.targetId;
+ const originalLabel = page.label;
+
+ await page.waitForLoadState();
+ assertEqual(
+ await page.evaluate("document.readyState"),
+ "complete",
+ "waitForLoadState defaults to the load state"
+ );
+
+ assertEqual(
+ JSON.stringify(await page.selectOption("#dropdown", "Beta")),
+ JSON.stringify(["beta"]),
+ "a selectOption string matches an option label"
+ );
+ assertEqual(
+ JSON.stringify(await page.selectOption("#dropdown", { value: "gamma" })),
+ JSON.stringify(["gamma"]),
+ "selectOption matches an option value descriptor"
+ );
+ assertEqual(
+ JSON.stringify(await page.selectOption("#dropdown", { label: "Alpha" })),
+ JSON.stringify(["alpha"]),
+ "selectOption matches an option label descriptor"
+ );
+ assertEqual(
+ JSON.stringify(await page.selectOption("#dropdown", { index: 1 })),
+ JSON.stringify(["beta"]),
+ "selectOption matches an option index descriptor"
+ );
+
+ await page.evaluate(() => {
+ const single = document.createElement("select");
+ single.id = "single-candidates";
+ single.innerHTML =
+ '<option value="first">Earlier</option><option value="second">Later</option>';
+ document.body.append(single);
+
+ const multiple = document.createElement("select");
+ multiple.id = "multiple-options";
+ multiple.multiple = true;
+ multiple.innerHTML =
+ '<option value="one">One</option>' +
+ '<option value="two">Two</option>' +
+ '<option value="undefined">Undefined</option>' +
+ '<option value="">None</option>';
+ document.body.append(multiple);
+
+ const disabled = document.createElement("option");
+ disabled.value = "blocked";
+ disabled.label = "Blocked";
+ disabled.textContent = "Blocked";
+ disabled.disabled = true;
+ document.querySelector("#dropdown").append(disabled);
+
+ const ariaDisabled = document.createElement("option");
+ ariaDisabled.value = "aria-blocked";
+ ariaDisabled.label = "ARIA blocked";
+ ariaDisabled.textContent = "ARIA blocked";
+ ariaDisabled.setAttribute("aria-disabled", "true");
+ document.querySelector("#dropdown").append(ariaDisabled);
+
+ const disabledGroup = document.createElement("optgroup");
+ disabledGroup.label = "Disabled group";
+ disabledGroup.disabled = true;
+ disabledGroup.innerHTML = '<option value="grouped">Grouped</option>';
+ document.querySelector("#dropdown").append(disabledGroup);
+
+ const fieldset = document.createElement("fieldset");
+ fieldset.disabled = true;
+ fieldset.innerHTML =
+ '<select id="fieldset-select"><option value="inside">Inside</option></select>';
+ document.body.append(fieldset);
+
+ const ariaSelect = document.createElement("select");
+ ariaSelect.id = "aria-disabled-select";
+ ariaSelect.innerHTML = '<option value="inside">Inside</option>';
+ const ariaDisabledContainer = document.createElement("div");
+ ariaDisabledContainer.id = "aria-disabled-container";
+ ariaDisabledContainer.setAttribute("aria-disabled", "true");
+ ariaDisabledContainer.append(ariaSelect);
+ document.body.append(ariaDisabledContainer);
+ });
+
+ assertEqual(
+ JSON.stringify(
+ await page.selectOption("#single-candidates", [
+ { label: "Later" },
+ { label: "Earlier" },
+ ])
+ ),
+ JSON.stringify(["first"]),
+ "a single select chooses the first DOM option matching any candidate"
+ );
+ assertEqual(
+ JSON.stringify(
+ await page.selectOption("#multiple-options", [
+ { value: "one" },
+ { label: "Two", index: 1 },
+ ])
+ ),
+ JSON.stringify(["one", "two"]),
+ "a multiple select matches all properties in each descriptor"
+ );
+ assertEqual(
+ JSON.stringify(await page.selectOption("#multiple-options", "")),
+ JSON.stringify([""]),
+ "selectOption accepts an empty string option value"
+ );
+ await page.evaluate(() => {
+ setTimeout(() => {
+ const delayed = document.createElement("option");
+ delayed.value = "delta";
+ delayed.label = "Delta";
+ delayed.textContent = "Delta";
+ document.querySelector("#dropdown").append(delayed);
+ }, 100);
+ });
+ assertEqual(
+ JSON.stringify(
+ await page.selectOption("#dropdown", { label: "Delta" }, { timeout: 2_000 })
+ ),
+ JSON.stringify(["delta"]),
+ "selectOption waits for an option that appears during its timeout"
+ );
+ await assertRejects(
+ () => page.selectOption("#dropdown", { label: "Missing" }, { timeout: 150 }),
+ "available options:",
+ "a missing option error lists the real available labels and values"
+ );
+ assertEqual(
+ JSON.stringify(await page.selectOption("#dropdown", { label: "Blocked" })),
+ JSON.stringify(["blocked"]),
+ "a disabled option remains programmatically selectable"
+ );
+ assertEqual(
+ JSON.stringify(await page.selectOption("#dropdown", { label: "ARIA blocked" })),
+ JSON.stringify(["aria-blocked"]),
+ "option ARIA state does not disable an enabled select"
+ );
+ assertEqual(
+ JSON.stringify(await page.selectOption("#dropdown", { label: "Grouped" })),
+ JSON.stringify(["grouped"]),
+ "an option in a disabled optgroup remains programmatically selectable"
+ );
+ await assertRejects(
+ () => page.selectOption("#fieldset-select", "inside", { timeout: 150 }),
+ "none can receive input",
+ "a select inside a disabled fieldset is not changed"
+ );
+ await assertRejects(
+ () => page.selectOption("#aria-disabled-select", "inside", { timeout: 150 }),
+ "element is disabled",
+ "an aria-disabled select is not changed"
+ );
+ await page.evaluate(() => {
+ setTimeout(() => {
+ document.querySelector("#fieldset-select").closest("fieldset").disabled = false;
+ }, 100);
+ });
+ assertEqual(
+ JSON.stringify(
+ await page.selectOption("#fieldset-select", "inside", { timeout: 2_000 })
+ ),
+ JSON.stringify(["inside"]),
+ "selectOption waits for a disabled fieldset to become enabled"
+ );
+ await page.evaluate(() => {
+ setTimeout(() => {
+ document
+ .querySelector("#aria-disabled-container")
+ .setAttribute("aria-disabled", "false");
+ }, 100);
+ });
+ assertEqual(
+ JSON.stringify(
+ await page.selectOption("#aria-disabled-select", "inside", {
+ timeout: 2_000,
+ })
+ ),
+ JSON.stringify(["inside"]),
+ "selectOption waits for an aria-disabled select to become enabled"
+ );
+ assertEqual(
+ JSON.stringify(await page.selectOption("#multiple-options", null)),
+ JSON.stringify([]),
+ "selectOption null clears a multiple selection even when a value is undefined"
+ );
+ assertEqual(
+ await page.evaluate(
+ "document.querySelector('#multiple-options').selectedOptions.length"
+ ),
+ 0,
+ "clearing a selection updates the real DOM"
+ );
+ await page.selectOption("#multiple-options", ["one", "two"]);
+ assertEqual(
+ JSON.stringify(await page.selectOption("#multiple-options", [])),
+ JSON.stringify([]),
+ "selectOption [] clears a multiple selection"
+ );
+
+ await page.evaluate(() => {
+ window.__reloadSentinel = "must disappear";
+ });
+ await page.reload({ timeout: 3_000, waitUntil: "domcontentloaded" });
+ await page.waitForLoadState();
+ assertEqual(page.targetId, originalTargetId, "reload keeps the same browser target");
+ assertEqual(page.label, originalLabel, "reload keeps the same durable Page label");
+ assertEqual(
+ await page.evaluate("window.__reloadSentinel"),
+ null,
+ "reload creates a fresh document instead of navigating by URL reuse"
+ );
+
+ await page.goto(baseUrl + "/domcontentloaded-page?ms=400", {
+ waitUntil: "domcontentloaded",
+ timeout: 2_000,
+ });
+ assertEqual(
+ await page.evaluate("document.readyState"),
+ "interactive",
+ "the reload fixture is still loading after DOMContentLoaded"
+ );
+ await page.reload({ timeout: 2_000 });
+ assertEqual(
+ await page.evaluate("document.readyState"),
+ "complete",
+ "reload defaults to waiting for load"
+ );
+
+ await page.goto(baseUrl + "/streamed-page?ms=750", {
+ waitUntil: "load",
+ timeout: 2_000,
+ });
+ await page.reload({ waitUntil: "commit", timeout: 1_000 });
+ assertEqual(
+ await page.evaluate("document.readyState"),
+ "loading",
+ "reload can return at the new-document commit boundary"
+ );
+ const defaultLoadStartedAt = Date.now();
+ await page.waitForLoadState(undefined, { timeout: 2_000 });
+ assertEqual(
+ await page.evaluate("document.readyState"),
+ "complete",
+ "waitForLoadState without a state waits for the load boundary"
+ );
+ assert(
+ Date.now() - defaultLoadStartedAt >= 500,
+ "the default load wait does not return while the streamed response is open"
+ );
+
+ await page.evaluate(() => {
+ setTimeout(() => {
+ document.documentElement.dataset.waitForFunctionReady = "true";
+ }, 400);
+ });
+ const waitForFunctionStartedAt = Date.now();
+ assertEqual(
+ await page.waitForFunction(
+ () => document.documentElement.dataset.waitForFunctionReady === "true",
+ undefined,
+ { timeout: 2_000 }
+ ),
+ true,
+ "waitForFunction uses the Playwright-compatible argument and options positions"
+ );
+ assert(
+ Date.now() - waitForFunctionStartedAt >= 250,
+ "waitForFunction waits for a predicate that becomes true later"
+ );
+ assertEqual(
+ await page.evaluate(
+ "document.documentElement.dataset.waitForFunctionReady"
+ ),
+ "true",
+ "waitForFunction returns only after the predicate is true in the Page"
+ );
+ await assertRejects(
+ () => page.keyboard.press("Left"),
+ 'Use "ArrowLeft"',
+ "keyboard errors suggest the Playwright arrow-key name"
+ );
+
+ await page.close();
+ `;
+}
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 5c02b27..48511c6 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
@@ -1,39 +1,203 @@
-export function pageJavaScriptDialogHandoffCase() {
+export function pageJavaScriptDialogHandlingCase() {
return `
const task = await taskSpace(taskName);
const page = await newPageAt(task, baseUrl + "/?page-dialogs=" + Date.now());
await page.evaluate(() => {
- const button = document.createElement("button");
- button.id = "dialog-alert";
- button.textContent = "Alert";
const result = document.createElement("output");
result.id = "dialog-result";
result.textContent = "idle";
- button.addEventListener("click", () => {
+
+ const noDialogButton = document.createElement("button");
+ noDialogButton.id = "no-dialog-action";
+ noDialogButton.textContent = "Run without dialog";
+ noDialogButton.addEventListener("click", () => {
+ result.dataset.noDialogClicks = String(
+ Number(result.dataset.noDialogClicks || "0") + 1
+ );
+ });
+
+ const promptButton = document.createElement("button");
+ promptButton.id = "dialog-prompt";
+ promptButton.textContent = "Prompt";
+ promptButton.addEventListener("click", () => {
+ const value = prompt("Name from real E2E", "guest");
+ result.textContent = "prompt:" + String(value);
+ result.dataset.prompt = String(value);
+ });
+
+ const confirmButton = document.createElement("button");
+ confirmButton.id = "dialog-confirm";
+ confirmButton.textContent = "Confirm";
+ confirmButton.addEventListener("click", () => {
+ result.dataset.confirm = String(confirm("Continue real E2E?"));
+ });
+
+ const alertButton = document.createElement("button");
+ alertButton.id = "dialog-alert";
+ alertButton.textContent = "Alert";
+ alertButton.addEventListener("click", () => {
alert("Alert from real E2E");
- result.textContent = "alert:continued";
- result.dataset.value = "alert:continued";
+ result.dataset.alert = "closed";
});
- document.body.prepend(button, result);
+
+ document.body.prepend(
+ noDialogButton,
+ promptButton,
+ confirmButton,
+ alertButton,
+ result
+ );
});
+ const snapshot = await page.snapshot();
+ const snapshotLines = snapshot.split("\\n");
+ const noDialogTextIndex = snapshotLines.findIndex((line) =>
+ line.includes("Run without dialog")
+ );
+ const noDialogMatch =
+ noDialogTextIndex >= 0 &&
+ snapshotLines
+ .slice(0, noDialogTextIndex)
+ .reverse()
+ .map((line) => line.match(/\\[ref=([0-9]+)/))
+ .find(Boolean);
+ assert(noDialogMatch, "snapshot exposes a ref before the no-dialog checks");
+ assertEqual(await page.acceptDialog(), false, "acceptDialog reports no open dialog");
+ assertEqual(await page.dismissDialog(), false, "dismissDialog reports no open dialog");
+ await page.click("@" + noDialogMatch[1]);
+ assertEqual(
+ await page.evaluate("document.querySelector('#dialog-result').dataset.noDialogClicks"),
+ "1",
+ "a no-dialog check preserves existing snapshot refs"
+ );
+
+ const dialogPageUrl = await page.url();
+ const waitForDialogEvent = async (method, predicate = () => true) => {
+ const deadline = Date.now() + 2_000;
+ while (Date.now() < deadline) {
+ const match = (await page.events()).find(
+ (event) => event.method === method && predicate(event.params || {})
+ );
+ if (match) return match;
+ await page.waitForTimeout(25);
+ }
+ throw new Error("timed out waiting for " + method);
+ };
+
await writeFile(
join(tempDir, "dialog-hard-stop.json"),
JSON.stringify({ label: page.label, targetId: page.targetId })
);
- // Ego Lite may hand control to the user, which terminates this script. If
- // it keeps Agent control, the Page layer must return the dialog instead of
- // waiting for the blocked input command to time out.
- const receipt = await page.click("#dialog-alert");
- assertEqual(receipt.dialog?.type, "alert", "the action reports the dialog type");
+ // Current Ego Lite releases hand control to the user here. A native build
+ // with Agent-owned JavaScript dialogs continues through the same case and
+ // exercises the complete high-level dialog API instead.
+ await page.events();
+ const receipt = await page.click("#dialog-prompt");
+ assertEqual(receipt.dialog?.type, "prompt", "the action reports the dialog type");
+ assertEqual(receipt.dialog?.message, "Name from real E2E", "the action reports its message");
+ assertEqual(receipt.dialog?.defaultPrompt, "guest", "the action reports prompt defaults");
+ assertEqual(
+ receipt.dialog?.url,
+ dialogPageUrl,
+ "the action preserves the dialog Page URL"
+ );
+ const promptOpening = await waitForDialogEvent(
+ "Page.javascriptDialogOpening",
+ (params) => params.type === "prompt"
+ );
+ assertEqual(promptOpening.params.defaultPrompt, "guest", "the prompt opening event is preserved");
+ assertEqual(await page.acceptDialog("agent"), true, "acceptDialog supplies prompt text");
+ const promptClosed = await waitForDialogEvent(
+ "Page.javascriptDialogClosed",
+ (params) => params.result === true
+ );
+ assertEqual(promptClosed.params.userInput, "agent", "the prompt closing event preserves user input");
+ await page.waitForFunction(
+ () => document.querySelector("#dialog-result")?.dataset.prompt === "agent",
+ undefined,
+ { timeout: 2_000 }
+ );
+ assertEqual(
+ await page.evaluate("document.querySelector('#dialog-result').textContent"),
+ "prompt:agent",
+ "acceptDialog resumes page JavaScript"
+ );
+ assertEqual(await page.acceptDialog(), false, "acceptDialog is idempotent");
+
+ await page.events();
+ const confirmReceipt = await page.click("#dialog-confirm");
+ assertEqual(confirmReceipt.dialog?.type, "confirm", "the action reports a confirm");
+ await waitForDialogEvent(
+ "Page.javascriptDialogOpening",
+ (params) => params.type === "confirm"
+ );
+ assertEqual(await page.dismissDialog(), true, "dismissDialog closes a confirm");
+ await waitForDialogEvent(
+ "Page.javascriptDialogClosed",
+ (params) => params.result === false
+ );
+ await page.waitForFunction(
+ () => document.querySelector("#dialog-result")?.dataset.confirm === "false",
+ undefined,
+ { timeout: 2_000 }
+ );
+ assertEqual(await page.dismissDialog(), false, "dismissDialog is idempotent");
+
+ await page.events();
+ const alertReceipt = await page.click("#dialog-alert");
+ assertEqual(alertReceipt.dialog?.type, "alert", "the action reports an alert");
+ assertEqual(alertReceipt.dialog?.message, "Alert from real E2E", "the action reports the alert message");
+ await waitForDialogEvent(
+ "Page.javascriptDialogOpening",
+ (params) => params.type === "alert"
+ );
+ assertEqual(await page.acceptDialog(), true, "acceptDialog closes an alert");
+ await waitForDialogEvent(
+ "Page.javascriptDialogClosed",
+ (params) => params.result === true
+ );
+ await page.waitForFunction(
+ () => document.querySelector("#dialog-result")?.dataset.alert === "closed",
+ undefined,
+ { timeout: 2_000 }
+ );
+
+ const beforeUnloadUrl = baseUrl + "/secondary?page-dialogs=beforeunload";
+ await page.evaluate((url) => {
+ window.addEventListener("beforeunload", (event) => {
+ event.preventDefault();
+ event.returnValue = "Leave real E2E?";
+ });
+ const link = document.createElement("a");
+ link.id = "dialog-beforeunload";
+ link.textContent = "Leave page";
+ link.href = url;
+ document.body.prepend(link);
+ }, beforeUnloadUrl);
+ await page.events();
+ const beforeUnloadReceipt = await page.click("#dialog-beforeunload");
assertEqual(
- receipt.dialog?.message,
- "Alert from real E2E",
- "the action reports the dialog message"
+ beforeUnloadReceipt.dialog?.type,
+ "beforeunload",
+ "the action reports a beforeunload dialog"
+ );
+ await waitForDialogEvent(
+ "Page.javascriptDialogOpening",
+ (params) => params.type === "beforeunload"
+ );
+ assertEqual(
+ await page.acceptDialog(),
+ true,
+ "acceptDialog allows beforeunload navigation"
+ );
+ await waitForDialogEvent(
+ "Page.javascriptDialogClosed",
+ (params) => params.result === true
);
- cliLog(JSON.stringify({ dialogReceipt: true }));
+ await page.waitForURL(beforeUnloadUrl, { timeout: 3_000 });
+ cliLog(JSON.stringify({ dialogHandled: true }));
`;
}
@@ -42,16 +206,17 @@ export function pageJavaScriptDialogRecoveryCase() {
const saved = JSON.parse(
await readFile(join(tempDir, "dialog-hard-stop.json"), "utf8")
);
- // This is test-only simulation of the user explicitly asking the Agent to
- // resume. Production code never takes control back automatically.
+ // This is test-only recovery after the native hard stop. On a native build
+ // that lets the Agent handle JavaScript dialogs, takeover is a harmless
+ // no-op and this still cleans up the same Page.
const task = await takeOverTaskSpace(taskName);
const page = task.page(saved.label);
await page.close();
- assertEqual(page.targetId, saved.targetId, "takeover restores the dialog Page");
+ assertEqual(page.targetId, saved.targetId, "recovery restores the dialog Page");
assert(
!(await task.pages()).some((candidate) => candidate.label === saved.label),
- "recovery closes the blocked dialog Page"
+ "recovery closes the dialog Page"
);
`;
}
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-evaluate-timeout.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-evaluate-timeout.mjs
new file mode 100644
index 0000000..c3664b4
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-evaluate-timeout.mjs
@@ -0,0 +1,184 @@
+export function pageEvaluateTimeoutCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const page = await newPageAt(task, baseUrl + "/?page-evaluate-timeout=" + Date.now());
+
+ const syncStartedAt = Date.now();
+ let syncError;
+ try {
+ await page.evaluate(() => {
+ setTimeout(() => {
+ window.__scheduledBeforeEvaluateTimeout = "finished";
+ }, 15_500);
+ const deadline = Date.now() + 20_000;
+ while (Date.now() < deadline) {}
+ });
+ } catch (error) {
+ syncError = error;
+ }
+ assertEqual(
+ syncError?.code,
+ "EGO_PAGE_EVALUATION_TIMED_OUT",
+ "a long synchronous callback returns the Page timeout error"
+ );
+ assertEqual(syncError?.executionStopped, true, "synchronous execution is actually stopped");
+ assertEqual(
+ syncError?.mayHaveLateEffects,
+ true,
+ "termination does not claim to cancel work scheduled before it"
+ );
+ assertEqual(syncError?.pageResponsive, true, "the Page recovers from synchronous execution");
+ assert(
+ Date.now() - syncStartedAt < 18_000,
+ "the execution safety deadline fires before the callback's own 20 second loop"
+ );
+ const quickStartedAt = Date.now();
+ assertEqual(await page.evaluate("1 + 1"), 2, "the next evaluation succeeds");
+ assert(
+ Date.now() - quickStartedAt < 1_000,
+ "the next evaluation does not inherit the timed-out callback's delay"
+ );
+ await page.waitForFunction(
+ () => window.__scheduledBeforeEvaluateTimeout === "finished",
+ undefined,
+ { timeout: 3_000, polling: 50 }
+ );
+ assertEqual(
+ await page.evaluate("window.__scheduledBeforeEvaluateTimeout"),
+ "finished",
+ "real Chromium confirms that previously scheduled work can still run"
+ );
+
+ let userError;
+ try {
+ await page.evaluate(() => {
+ throw new Error("Execution was terminated");
+ });
+ } catch (error) {
+ userError = error;
+ }
+ assertEqual(
+ userError?.code,
+ undefined,
+ "user exception text is not mistaken for a protocol timeout"
+ );
+ assertIncludes(
+ userError?.message,
+ "Execution was terminated",
+ "the original user exception remains visible"
+ );
+
+ assertEqual(
+ await page.waitForFunction(
+ async () => {
+ await new Promise((resolve) => setTimeout(resolve, 1_200));
+ return true;
+ },
+ undefined,
+ { timeout: 2_500 }
+ ),
+ true,
+ "waitForFunction gives an async predicate the requested overall timeout"
+ );
+
+ await page.evaluate(() => {
+ delete window.__fallbackBlockStarted;
+ delete window.__fallbackBlockCompleted;
+ });
+ const fallbackStartedAt = Date.now();
+ let fallbackError;
+ try {
+ await page.evaluate(async () => {
+ setTimeout(() => {
+ window.__fallbackBlockStarted = true;
+ const deadline = Date.now() + 5_000;
+ while (Date.now() < deadline) {}
+ window.__fallbackBlockCompleted = true;
+ }, 13_500);
+ // Keep the evaluated Promise live past the transport timeout. An
+ // unreferenced never-settling Promise may be collected by Chromium
+ // before the scheduled blocking task starts.
+ await new Promise((resolve) => setTimeout(resolve, 20_000));
+ });
+ } catch (error) {
+ fallbackError = error;
+ }
+ assertEqual(
+ fallbackError?.code,
+ "EGO_PAGE_EVALUATION_TIMED_OUT",
+ "an unresponsive health probe uses the Page timeout error"
+ );
+ assertEqual(
+ fallbackError?.executionStopped,
+ true,
+ "the fallback confirms that Runtime.terminateExecution stopped the blocking execution"
+ );
+ assertEqual(
+ fallbackError?.pageResponsive,
+ true,
+ "the fallback health probe confirms that the Page recovered"
+ );
+ assert(
+ Date.now() - fallbackStartedAt < 18_000,
+ "the fallback interrupts the finite five-second block instead of waiting for it to finish"
+ );
+ assertEqual(
+ await page.evaluate("window.__fallbackBlockStarted"),
+ true,
+ "the finite blocking task started before transport recovery"
+ );
+ assertEqual(
+ await page.evaluate("window.__fallbackBlockCompleted"),
+ null,
+ "Runtime.terminateExecution interrupted the blocking task"
+ );
+ assertEqual(
+ await page.evaluate("6 * 7"),
+ 42,
+ "the Page remains usable after fallback termination"
+ );
+
+ await page.evaluate("delete window.__lateEvaluateSideEffect");
+ let asyncError;
+ try {
+ await page.evaluate(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 16_000));
+ window.__lateEvaluateSideEffect = "finished";
+ });
+ } catch (error) {
+ asyncError = error;
+ }
+ assertEqual(
+ asyncError?.code,
+ "EGO_PAGE_EVALUATION_TIMED_OUT",
+ "a long pending promise returns the Page timeout error"
+ );
+ assertEqual(
+ asyncError?.executionStopped,
+ false,
+ "a responsive pending promise is not reported as stopped"
+ );
+ assertEqual(
+ asyncError?.mayHaveLateEffects,
+ true,
+ "the error honestly reports possible late asynchronous effects"
+ );
+ assertEqual(
+ asyncError?.pageResponsive,
+ true,
+ "the health probe distinguishes a responsive Page from a blocked renderer"
+ );
+ await page.waitForFunction(
+ () => window.__lateEvaluateSideEffect === "finished",
+ undefined,
+ { timeout: 3_000, polling: 50 }
+ );
+ assertEqual(
+ await page.evaluate("window.__lateEvaluateSideEffect"),
+ "finished",
+ "the real browser demonstrates the documented late asynchronous side effect"
+ );
+
+ 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 38d353d..b88e1fd 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
@@ -1,18 +1,71 @@
export function pageLoadStatesCase() {
return `
const task = await taskSpace(taskName);
+ const uncommittedPage = await task.newPage();
+ let uncommittedError;
+ try {
+ await uncommittedPage.goto(baseUrl + "/slow-page?ms=1000", {
+ timeout: 100,
+ });
+ } catch (error) {
+ uncommittedError = error;
+ }
+ assert(uncommittedError, "goto reports a timeout before response headers");
+ assertEqual(
+ uncommittedError.code,
+ "EGO_NAVIGATION_TIMEOUT",
+ "an uncommitted timeout uses the navigation-timeout code"
+ );
+ assertEqual(
+ uncommittedError.committed,
+ false,
+ "goto does not claim that a document committed before response headers"
+ );
+ assert(
+ !uncommittedError.message.includes("Continue on this Page"),
+ "an uncommitted timeout does not recommend continuing on the old document"
+ );
+ await uncommittedPage.close();
+
const page = await newPageAt(task, "about:blank");
- await assertRejects(
- () => page.goto(baseUrl + "/streamed-page?ms=600", { timeout: 100 }),
- "timed out",
- "goto owns and reports its load timeout"
+ let navigationError;
+ try {
+ await page.goto(baseUrl + "/streamed-page?ms=1500", { timeout: 300 });
+ } catch (error) {
+ navigationError = error;
+ }
+ assert(navigationError, "goto reports its load timeout");
+ assertEqual(
+ navigationError.code,
+ "EGO_NAVIGATION_TIMEOUT",
+ "goto exposes a stable navigation-timeout code"
+ );
+ assertEqual(
+ navigationError.committed,
+ true,
+ "goto distinguishes a committed document from a failed navigation"
+ );
+ assertIncludes(
+ navigationError.url,
+ "/streamed-page?ms=1500",
+ "the timeout reports the committed URL"
+ );
+ assertEqual(
+ navigationError.readyState,
+ "loading",
+ "the timeout reports the document load state"
+ );
+ assertIncludes(
+ navigationError.message,
+ 'page.waitForLoadState("load")',
+ "the timeout suggests continuing from the committed Page"
);
assertIncludes(
await page.url(),
- "/streamed-page?ms=600",
+ "/streamed-page?ms=1500",
"a Page remains addressable after goto times out"
);
- await page.waitForLoadState("load", { timeout: 2_000 });
+ await page.waitForLoadState("load", { timeout: 3_000 });
const referer = baseUrl + "/navigation-source";
await page.goto(baseUrl + "/streamed-page?ms=1000", {
referer,
@@ -52,11 +105,16 @@ export function pageLoadStatesCase() {
"domcontentloaded returns while the slow resource still blocks load"
);
+ const loadTimeoutStartedAt = Date.now();
await assertRejects(
() => page.waitForLoadState("load", { timeout: 100 }),
"waitForLoadState(load) timed out",
"load does not resolve at the earlier DOMContentLoaded boundary"
);
+ assert(
+ Date.now() - loadTimeoutStartedAt < 500,
+ "a document-state wait stays inside its public timeout budget"
+ );
await page.waitForLoadState("load", { timeout: 3_000 });
assertEqual(
await page.evaluate("document.readyState"),
@@ -64,6 +122,219 @@ export function pageLoadStatesCase() {
"load resolves after the slow resource finishes"
);
+ const directNetworkIdlePage = await task.newPage();
+ const directNetworkIdleStartedAt = Date.now();
+ await directNetworkIdlePage.goto(
+ baseUrl + "/domcontentloaded-page?ms=700&direct-networkidle=" + Date.now(),
+ { waitUntil: "networkidle", timeout: 3_000 }
+ );
+ assert(
+ Date.now() - directNetworkIdleStartedAt >= 1_000,
+ "goto(networkidle) tracks requests before navigation starts"
+ );
+ assertEqual(
+ await directNetworkIdlePage.evaluate("document.readyState"),
+ "complete",
+ "goto(networkidle) waits for the slow resource and the idle window"
+ );
+ const reloadNetworkIdleStartedAt = Date.now();
+ await directNetworkIdlePage.reload({ waitUntil: "networkidle", timeout: 3_000 });
+ assert(
+ Date.now() - reloadNetworkIdleStartedAt >= 1_000,
+ "reload(networkidle) tracks requests before reload starts"
+ );
+ assertEqual(
+ await directNetworkIdlePage.evaluate("document.readyState"),
+ "complete",
+ "reload(networkidle) waits for the slow resource and the idle window"
+ );
+ const faviconPage = directNetworkIdlePage;
+ await faviconPage.goto(baseUrl + "/favicon-redirect-page", {
+ waitUntil: "commit",
+ timeout: 1_000,
+ });
+ const faviconEvents = [];
+ for (let attempt = 0; attempt < 20; attempt += 1) {
+ faviconEvents.push(...(await faviconPage.events()));
+ const requestUrls = faviconEvents
+ .filter((event) => event.method === "Network.requestWillBeSent")
+ .map((event) => event.params?.request?.url || "");
+ if (
+ requestUrls.some((url) => url.endsWith("/redirect/favicon.ico")) &&
+ requestUrls.some((url) => url.includes("case=favicon-redirect"))
+ ) break;
+ await faviconPage.waitForTimeout(25);
+ }
+ const faviconRequestUrls = faviconEvents
+ .filter((event) => event.method === "Network.requestWillBeSent")
+ .map((event) => event.params?.request?.url || "");
+ assert(
+ faviconRequestUrls.some((url) => url.endsWith("/redirect/favicon.ico")),
+ "the real browser requests the declared favicon"
+ );
+ assert(
+ faviconRequestUrls.some((url) => url.includes("case=favicon-redirect")),
+ "the real favicon request follows its redirect"
+ );
+ const faviconIdleStartedAt = Date.now();
+ await faviconPage.waitForLoadState("networkidle", {
+ timeout: 1_200,
+ idleMs: 200,
+ });
+ assert(
+ Date.now() - faviconIdleStartedAt < 1_000,
+ "a redirected favicon does not hold the Page network-idle boundary"
+ );
+ await faviconPage.close();
+
+ await page.cdp("Runtime.enable");
+ const networkEventMarker = "ego-networkidle-event-preserved";
+ await page.evaluate(({ url, marker }) => {
+ window.__egoSlowFetchFinished = false;
+ console.log(marker);
+ void fetch(url)
+ .then((response) => response.text())
+ .then(() => {
+ window.__egoSlowFetchFinished = true;
+ });
+ }, {
+ url: baseUrl + "/api/slow?ms=800&case=networkidle",
+ marker: networkEventMarker,
+ });
+ await page.waitForTimeout(100);
+ const networkIdleStartedAt = Date.now();
+ await page.waitForLoadState("networkidle", {
+ timeout: 3_000,
+ idleMs: 100,
+ });
+ const networkIdleElapsed = Date.now() - networkIdleStartedAt;
+ assert(
+ networkIdleElapsed >= 600,
+ "networkidle includes a slow request that began before the wait"
+ );
+ assertEqual(
+ await page.evaluate("window.__egoSlowFetchFinished"),
+ true,
+ "networkidle waits for the earlier request to finish"
+ );
+ const preservedEvents = await page.events();
+ assert(
+ preservedEvents.some(
+ (event) =>
+ event.method === "Runtime.consoleAPICalled" &&
+ event.params?.args?.some((argument) => argument.value === networkEventMarker)
+ ),
+ "networkidle does not consume the Page event stream"
+ );
+
+ const busyPage = await newPageAt(
+ task,
+ baseUrl + "/?page-network-isolation=busy"
+ );
+ const quietPage = page;
+ await quietPage.goto(baseUrl + "/secondary?page-network-isolation=quiet", {
+ waitUntil: "domcontentloaded",
+ timeout: 2_000,
+ });
+ await busyPage.cdp("Runtime.enable");
+ await quietPage.cdp("Runtime.enable");
+ await busyPage.events();
+ await quietPage.events();
+ const busyMarker = "ego-v2-busy-page-event";
+ const quietMarker = "ego-v2-quiet-page-event";
+ await busyPage.evaluate(({ url, marker }) => {
+ console.log(marker);
+ const request = () => void fetch(url).catch(() => {});
+ request();
+ window.__egoNetworkIsolationPulse = setInterval(request, 50);
+ }, {
+ url: baseUrl + "/api/slow?ms=2000&case=v2-page-isolation",
+ marker: busyMarker,
+ });
+ await quietPage.evaluate((marker) => console.log(marker), quietMarker);
+ await quietPage.waitForTimeout(100);
+ const quietIdleStartedAt = Date.now();
+ await quietPage.waitForLoadState("networkidle", {
+ timeout: 1_200,
+ idleMs: 200,
+ });
+ assert(
+ Date.now() - quietIdleStartedAt < 1_000,
+ "traffic on one Page does not keep another Page busy"
+ );
+ const busyEvents = await busyPage.events();
+ const quietEvents = await quietPage.events();
+ const hasConsoleMarker = (events, marker) =>
+ events.some(
+ (event) =>
+ event.method === "Runtime.consoleAPICalled" &&
+ event.params?.args?.some((argument) => argument.value === marker)
+ );
+ assert(hasConsoleMarker(busyEvents, busyMarker), "the busy Page keeps its event");
+ assert(
+ !hasConsoleMarker(busyEvents, quietMarker),
+ "the busy Page does not receive the quiet Page event"
+ );
+ assert(hasConsoleMarker(quietEvents, quietMarker), "the quiet Page keeps its event");
+ assert(
+ !hasConsoleMarker(quietEvents, busyMarker),
+ "the quiet Page does not receive the busy Page event"
+ );
+ await busyPage.evaluate(() => clearInterval(window.__egoNetworkIsolationPulse));
+ await busyPage.close();
+
+ const oopifPage = await task.newPage();
+ await oopifPage.goto(baseUrl + "/oopif-network?ms=800", {
+ waitUntil: "commit",
+ timeout: 1_000,
+ });
+ const oopifStartedAt = Date.now();
+ await oopifPage.waitForLoadState("networkidle", {
+ timeout: 3_000,
+ idleMs: 100,
+ });
+ assert(
+ Date.now() - oopifStartedAt >= 650,
+ "networkidle includes requests from a cross-process iframe"
+ );
+ const slowFrameTarget = (await task.cdp("Target.getTargets")).targetInfos.find(
+ (target) =>
+ target.type === "iframe" && target.url.includes("/slow-frame?ms=800")
+ )?.targetId;
+ assert(slowFrameTarget, "the slow cross-process iframe has a live target");
+ assertEqual(
+ await js("return document.readyState", slowFrameTarget),
+ "complete",
+ "networkidle returns only after the cross-process frame finishes loading"
+ );
+
+ await oopifPage.goto(baseUrl + "/oopif-network?ms=3000", {
+ waitUntil: "commit",
+ timeout: 1_000,
+ });
+ await oopifPage.waitForTimeout(100);
+ const oopifTimeoutStartedAt = Date.now();
+ await assertRejects(
+ () => oopifPage.waitForLoadState("networkidle", {
+ timeout: 250,
+ idleMs: 100,
+ }),
+ "networkidle) timed out",
+ "networkidle does not ignore a still-loading cross-process frame"
+ );
+ assert(
+ Date.now() - oopifTimeoutStartedAt < 1_000,
+ "an OOPIF network-idle wait stays inside its public timeout budget"
+ );
+ await oopifPage.evaluate(() => {
+ document.querySelector("iframe")?.remove();
+ });
+ await oopifPage.waitForLoadState("networkidle", {
+ timeout: 2_000,
+ idleMs: 100,
+ });
+ await oopifPage.close();
+
await page.evaluate((popupUrl) => {
const button = document.createElement("button");
button.id = "delayed-popup";
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-popup-waiter.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-popup-waiter.mjs
index e3c0156..39f2f9e 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-popup-waiter.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-popup-waiter.mjs
@@ -28,6 +28,40 @@ export function pagePopupWaiterCase() {
);
await firstPopup.close();
+ await source.evaluate((urls) => {
+ for (const [id, url] of Object.entries(urls)) {
+ const link = document.createElement("a");
+ link.id = id;
+ link.href = url;
+ link.target = "_blank";
+ link.textContent = id;
+ document.body.append(link);
+ }
+ }, {
+ "old-popup-link": baseUrl + "/secondary?popup-waiter=old",
+ "next-popup-link": baseUrl + "/secondary?popup-waiter=next",
+ });
+ const oldReceipt = await source.click("#old-popup-link");
+ const nextPopupPromise = source.waitForEvent("popup", { timeout: 3_000 });
+ const nextReceipt = await source.click("#next-popup-link");
+ const nextPopup = await nextPopupPromise;
+ assert(
+ nextPopup.label !== oldReceipt.popups[0].label,
+ "a new popup waiter ignores an unobserved popup from an earlier action"
+ );
+ assertEqual(
+ nextPopup.label,
+ nextReceipt.popups[0].label,
+ "the popup waiter resolves the popup created after it was armed"
+ );
+ assertIncludes(
+ await nextPopup.url(),
+ "popup-waiter=next",
+ "the future popup Page has the expected URL"
+ );
+ await task.page(oldReceipt.popups[0].label).close();
+ await nextPopup.close();
+
await source.evaluate((popupUrl) => {
const link = document.createElement("a");
link.id = "popup-waiter-link";
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-selector-compatibility.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-selector-compatibility.mjs
new file mode 100644
index 0000000..c3a1046
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-selector-compatibility.mjs
@@ -0,0 +1,199 @@
+export function pageSelectorCompatibilityCase() {
+ const apostropheSelector = JSON.stringify(
+ String.raw`button:text-is('can\'t')`,
+ );
+ const hexEscapeSelector = JSON.stringify(String.raw`button:text-is("\41 B")`);
+ return `
+ const task = await taskSpace(taskName);
+ const page = await newPageAt(
+ task,
+ baseUrl + "/same-origin-frame?page=selector-compatibility&run=" + Date.now()
+ );
+
+ await page.evaluate(() => {
+ const hasTextButton = document.createElement("button");
+ hasTextButton.id = "save-changes";
+ hasTextButton.innerHTML = "<span>Save</span> changes";
+ hasTextButton.addEventListener("click", () => {
+ document.documentElement.dataset.hasTextClicked = "true";
+ });
+
+ const exactButton = document.createElement("button");
+ exactButton.id = "exact-save";
+ exactButton.innerHTML = "Save <span>draft</span>";
+ exactButton.addEventListener("click", () => {
+ document.documentElement.dataset.textIsClicked = "true";
+ });
+
+ const nestedOnlyButton = document.createElement("button");
+ nestedOnlyButton.id = "nested-only-save";
+ nestedOnlyButton.innerHTML = "<span>Save</span>";
+ nestedOnlyButton.addEventListener("click", () => {
+ document.documentElement.dataset.textIsClicked = "wrong-target";
+ });
+
+ const apostropheButton = document.createElement("button");
+ apostropheButton.id = "apostrophe-label";
+ apostropheButton.textContent = "can't";
+ apostropheButton.addEventListener("click", () => {
+ document.documentElement.dataset.apostropheClicked = "true";
+ });
+
+ const hexEscapeButton = document.createElement("button");
+ hexEscapeButton.textContent = "AB";
+ hexEscapeButton.addEventListener("click", () => {
+ document.documentElement.dataset.hexEscapeClicked = "true";
+ });
+
+ const quotedTokenButton = document.createElement("button");
+ quotedTokenButton.dataset.value = ":has-text(";
+ quotedTokenButton.textContent = "Quoted compatibility token";
+ quotedTokenButton.addEventListener("click", () => {
+ document.documentElement.dataset.quotedTokenClicked = "true";
+ });
+
+ const emptyTextButton = document.createElement("button");
+ emptyTextButton.id = "empty-text-button";
+ emptyTextButton.setAttribute("aria-label", "Empty text action");
+ emptyTextButton.addEventListener("click", () => {
+ document.documentElement.dataset.emptyTextClicked = "true";
+ });
+
+ const duplicateHref = document.createElement("a");
+ duplicateHref.href = "/nav-target";
+ duplicateHref.textContent = "Alternate nav target";
+ duplicateHref.addEventListener("click", (event) => {
+ event.preventDefault();
+ document.documentElement.dataset.hrefNthClicked = "true";
+ });
+
+ document
+ .querySelector("main")
+ .prepend(
+ emptyTextButton,
+ quotedTokenButton,
+ hexEscapeButton,
+ apostropheButton,
+ nestedOnlyButton,
+ exactButton,
+ hasTextButton
+ );
+ document.querySelector("main").append(duplicateHref);
+ document.querySelectorAll(".duplicate-action").forEach((button, index) => {
+ if (index === 0) button.style.display = "none";
+ button.addEventListener("click", () => {
+ document.documentElement.dataset.duplicateIndex = String(index);
+ });
+ });
+ });
+
+ await page.click("css=#click-button");
+ assertEqual(
+ await page.evaluate(() => window.__fixtureState.clicks),
+ 1,
+ "css= aliases a CSS selector on a real page"
+ );
+
+ await page.click('button:has-text("save changes")');
+ assertEqual(
+ await page.evaluate("document.documentElement.dataset.hasTextClicked"),
+ "true",
+ ":has-text normalizes whitespace and ignores case"
+ );
+
+ await page.click('button:text-is("Save")');
+ assertEqual(
+ await page.evaluate("document.documentElement.dataset.textIsClicked"),
+ "true",
+ ":text-is performs an exact case-sensitive match"
+ );
+
+ await page.click(${apostropheSelector});
+ assertEqual(
+ await page.evaluate("document.documentElement.dataset.apostropheClicked"),
+ "true",
+ ":text-is decodes a quoted CSS string"
+ );
+
+ await page.click(${hexEscapeSelector});
+ assertEqual(
+ await page.evaluate("document.documentElement.dataset.hexEscapeClicked"),
+ "true",
+ ":text-is decodes a CSS hex escape and its terminator"
+ );
+
+ await page.click('[data-value=":has-text("]');
+ assertEqual(
+ await page.evaluate("document.documentElement.dataset.quotedTokenClicked"),
+ "true",
+ "raw CSS keeps compatibility-like text inside a quoted value"
+ );
+
+ await page.click('#empty-text-button:text-is("")');
+ assertEqual(
+ await page.evaluate("document.documentElement.dataset.emptyTextClicked"),
+ "true",
+ ":text-is matches a candidate with no immediate text"
+ );
+
+ await assertRejects(
+ () => page.click('button, a:has-text("Docs")'),
+ "Invalid locator",
+ "unsupported selector-list text filters fail explicitly"
+ );
+
+ await page.click(".duplicate-action >> nth=1");
+ assertEqual(
+ await page.evaluate("document.documentElement.dataset.duplicateIndex"),
+ "1",
+ "terminal nth selects by DOM order before actionability checks"
+ );
+ await page.evaluate(() => {
+ delete document.documentElement.dataset.duplicateIndex;
+ });
+ await page.click("text=Duplicate action >> nth=-1");
+ assertEqual(
+ await page.evaluate("document.documentElement.dataset.duplicateIndex"),
+ "1",
+ "terminal nth=-1 selects the last text-locator match"
+ );
+ await page.click("loc=href:/nav-target >> nth=-1");
+ assertEqual(
+ await page.evaluate("document.documentElement.dataset.hrefNthClicked"),
+ "true",
+ "terminal nth composes with an href locator"
+ );
+
+ await page.click('loc=role:button[name*="increment COUNTER"]');
+ assertEqual(
+ await page.evaluate(() => window.__fixtureState.clicks),
+ 2,
+ "role name*= matches an accessible-name substring without case sensitivity"
+ );
+
+ await page.click('nested-shadow-fixture:has-text("shadow ACTION")');
+ assertEqual(
+ await page.evaluate(() =>
+ document
+ .querySelector("#shadow-fixture")
+ .shadowRoot.querySelector("nested-shadow-fixture")
+ .shadowRoot.querySelector("#shadow-action").dataset.clicked
+ ),
+ "true",
+ ":has-text includes text from the candidate's open shadow root"
+ );
+
+ await page.click('button:has-text("Run iframe action")');
+ assertEqual(
+ await page.evaluate(() =>
+ document
+ .querySelector("#fixture-frame")
+ .contentDocument.querySelector("#iframe-result").textContent
+ ),
+ "clicked:true",
+ ":has-text routes a trusted click into a same-origin iframe"
+ );
+
+ await page.close();
+ `;
+}
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/profile-selection.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/profile-selection.mjs
index d8d5ad8..d086e95 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/profile-selection.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/profile-selection.mjs
@@ -25,12 +25,26 @@ export function profileSelectionCase() {
profileId: selectedProfile.id,
});
try {
- const page = await newPageAt(explicitTask, baseUrl + "/?profile=explicit");
+ const initialTabs = await explicitTask.tabs();
+ assertEqual(initialTabs.length, 1, "a new TaskSpace starts with one tab");
+ assertEqual(initialTabs[0].label, "p1", "the initial tab is managed as p1");
+ assertEqual(initialTabs[0].openedBy, "agent", "the initial tab is Agent-owned");
+ const initialTargetId = initialTabs[0].targetId;
+
+ const page = explicitTask.page("p1");
+ await page.goto(baseUrl + "/?profile=explicit");
assertEqual(
await page.title(),
"ego-lite helper e2e",
"the selected Profile TaskSpace is operable"
);
+ const navigatedTabs = await explicitTask.tabs();
+ assertEqual(navigatedTabs.length, 1, "using p1 does not create another tab");
+ assertEqual(
+ navigatedTabs[0].targetId,
+ initialTargetId,
+ "p1 keeps the native initial target"
+ );
await assertRejects(
() => taskSpace(explicitName, { profileId: selectedProfile.id }),
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs
index ca79cec..b1d3eb2 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs
@@ -83,7 +83,7 @@ export function taskSpaceCase() {
await takeOverTaskSpace();
await waitForAgentControl(taskName, { interval: 0.1, timeout: 5 });
const v2Task = await taskSpace(taskName + " v2 lifecycle");
- await newPageAt(v2Task, baseUrl + "/secondary?v2-lifecycle=handoff");
+ await v2Task.page("p1").goto(baseUrl + "/secondary?v2-lifecycle=handoff");
await v2Task.handOff();
const resumedTask = await takeOverTaskSpace(v2Task.spaceId);
await resumedTask.waitForControl({ interval: 100, timeout: 5_000 });
@@ -101,7 +101,7 @@ export function taskSpaceCase() {
);
const finishTask = await taskSpace(taskName + " v2 finish");
- await newPageAt(finishTask, baseUrl + "/secondary?v2-lifecycle=finish");
+ await finishTask.page("p1").goto(baseUrl + "/secondary?v2-lifecycle=finish");
const finishSpaceId = finishTask.spaceId;
await finishTask.finish();
assert(
@@ -116,9 +116,11 @@ export function taskSpaceCase() {
export function crossSpaceV2Case() {
return `
const firstTask = await taskSpace(taskName + " gate first");
- const firstPage = await newPageAt(firstTask, baseUrl + "/?space=first");
+ const firstPage = firstTask.page("p1");
+ await firstPage.goto(baseUrl + "/?space=first");
const secondTask = await taskSpace(taskName + " gate second");
- const secondPage = await newPageAt(secondTask, baseUrl + "/secondary?space=second");
+ const secondPage = secondTask.page("p1");
+ await secondPage.goto(baseUrl + "/secondary?space=second");
const [firstInfo, secondInfo] = await Promise.all([
firstPage.info(),
diff --git a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
index cc92426..7a2e0c7 100644
--- a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
@@ -78,6 +78,14 @@ export async function startFixtureServer(taskName) {
res.end();
return;
}
+ if (url.pathname === "/redirect/favicon.ico") {
+ res.writeHead(302, {
+ location: "/api/slow?ms=2000&case=favicon-redirect",
+ "cache-control": "no-store",
+ });
+ res.end();
+ return;
+ }
if (url.pathname === "/api/echo") {
let body = "";
req.on("data", (chunk) => {
@@ -87,6 +95,7 @@ export async function startFixtureServer(taskName) {
res.writeHead(200, {
"content-type": "text/plain",
"access-control-allow-origin": "*",
+ "cache-control": "no-store",
});
res.end(`echo:${req.method}:${body}`);
});
@@ -129,6 +138,7 @@ export async function startFixtureServer(taskName) {
res.writeHead(200, {
"content-type": "text/plain",
"access-control-allow-origin": "*",
+ "cache-control": "no-store",
});
res.end("slow fixture");
}, delayMs);
@@ -166,6 +176,19 @@ export async function startFixtureServer(taskName) {
res.end(pageHtml("frame", { iframeUrl: null }));
return;
}
+ if (url.pathname === "/slow-frame") {
+ const delayMs = Number(url.searchParams.get("ms") || 800);
+ res.writeHead(200, { "content-type": "text/html" });
+ res.end(`<!doctype html>
+ <html>
+ <head><title>Slow OOPIF fixture</title></head>
+ <body>
+ <h1>Slow OOPIF</h1>
+ <img src="/api/slow?ms=${delayMs}" alt="slow OOPIF resource">
+ </body>
+ </html>`);
+ return;
+ }
if (url.pathname === "/nav-target") {
res.writeHead(200, { "content-type": "text/html" });
res.end(pageHtml("nav-target"));
@@ -181,6 +204,16 @@ export async function startFixtureServer(taskName) {
res.end(pageHtml("home", { iframeUrl: "/frame.html" }));
return;
}
+ if (url.pathname === "/oopif-network") {
+ const delayMs = Number(url.searchParams.get("ms") || 800);
+ res.writeHead(200, { "content-type": "text/html" });
+ res.end(
+ pageHtml("home", {
+ iframeUrl: `${crossSiteBaseUrl}/slow-frame?ms=${delayMs}`,
+ }),
+ );
+ return;
+ }
if (url.pathname === "/visual") {
res.writeHead(200, { "content-type": "text/html" });
res.end(visualPageHtml());
@@ -236,6 +269,21 @@ export async function startFixtureServer(taskName) {
</html>`);
return;
}
+ if (url.pathname === "/favicon-redirect-page") {
+ res.writeHead(200, {
+ "content-type": "text/html",
+ "cache-control": "no-store",
+ });
+ res.end(`<!doctype html>
+ <html>
+ <head>
+ <title>Favicon redirect fixture</title>
+ <link rel="icon" href="/redirect/favicon.ico">
+ </head>
+ <body><h1>Favicon redirect fixture</h1></body>
+ </html>`);
+ return;
+ }
if (url.pathname === "/favicon.ico") {
res.writeHead(204);
res.end();
diff --git a/package/ego-browser/scripts/real-browser-e2e/runner.mjs b/package/ego-browser/scripts/real-browser-e2e/runner.mjs
index a43668f..ba918e3 100644
--- a/package/ego-browser/scripts/real-browser-e2e/runner.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/runner.mjs
@@ -14,16 +14,65 @@ const packageDir = join(runnerDir, "..", "..");
const egoBrowserSdkPath = join(packageDir, "dist", "out", "index.js");
const egoBrowserArgs = ["nodejs", "--sdk-path", egoBrowserSdkPath];
+export function parseOnlyCases(configured, availableCaseNames) {
+ const raw = typeof configured === "string" ? configured.trim() : "";
+ if (!raw) return new Set();
+
+ const available = [...availableCaseNames];
+ const availableSet = new Set(available);
+ let requested;
+ if (raw.startsWith("[")) {
+ let parsed;
+ try {
+ parsed = JSON.parse(raw);
+ } catch (error) {
+ throw new TypeError(
+ `EGO_BROWSER_REAL_E2E_ONLY must be a valid JSON array: ${error.message}`,
+ );
+ }
+ if (
+ !Array.isArray(parsed) ||
+ parsed.some((name) => typeof name !== "string" || !name.trim())
+ ) {
+ throw new TypeError(
+ "EGO_BROWSER_REAL_E2E_ONLY must be a JSON array of non-empty case names",
+ );
+ }
+ requested = parsed.map((name) => name.trim());
+ } else if (availableSet.has(raw)) {
+ // Exact matching comes first because a case name may itself contain commas.
+ requested = [raw];
+ } else {
+ requested = raw
+ .split(",")
+ .map((name) => name.trim())
+ .filter(Boolean);
+ }
+
+ if (requested.length === 0) {
+ throw new TypeError(
+ "EGO_BROWSER_REAL_E2E_ONLY must select at least one case",
+ );
+ }
+ const unknown = [...new Set(requested)].filter(
+ (name) => !availableSet.has(name),
+ );
+ if (unknown.length > 0) {
+ throw new Error(
+ `Unknown real-browser E2E case: ${unknown.join(", ")}. Available cases: ${available.join(", ")}`,
+ );
+ }
+ return new Set(requested);
+}
+
export async function runRealBrowserE2e() {
const egoBrowserCli = resolveEgoBrowserCli();
const keepTaskSpace =
process.env.EGO_BROWSER_REAL_E2E_KEEP === "1" ||
process.env.EGO_BROWSER_REAL_E2E_KEEP === "true";
- const onlyCases = new Set(
- (process.env.EGO_BROWSER_REAL_E2E_ONLY || "")
- .split(",")
- .map((name) => name.trim())
- .filter(Boolean),
+ const onlyCases = parseOnlyCases(
+ process.env.EGO_BROWSER_REAL_E2E_ONLY,
+ e2eCases.map((testCase) => testCase.name),
);
let server;
@@ -98,6 +147,7 @@ export async function runRealBrowserE2e() {
timeoutMs = 45000,
expectedOutput,
acceptedCompletionOutput,
+ pendingOnExpectedTermination,
) {
console.log(`-- ${name}`);
const source = egoSource(body, {
@@ -156,13 +206,21 @@ export async function runRealBrowserE2e() {
commandResult?.stderr,
) ?? 1)
: 1;
- recordResult(name, "pass", durationMs, assertions);
+ const status =
+ !completedWithAcceptedOutput && pendingOnExpectedTermination
+ ? "pending"
+ : "pass";
+ const message =
+ status === "pending" ? pendingOnExpectedTermination : undefined;
+ recordResult(name, status, durationMs, assertions, message);
console.log(
- `-- ${name} passed (${formatDuration(durationMs)}, ${
- completedWithAcceptedOutput
- ? `${assertions} assertions, accepted completion`
- : "expected termination"
- })`,
+ status === "pending"
+ ? `-- ${name} pending (${formatDuration(durationMs)}): ${message}`
+ : `-- ${name} passed (${formatDuration(durationMs)}, ${
+ completedWithAcceptedOutput
+ ? `${assertions} assertions, accepted completion`
+ : "expected termination"
+ })`,
);
} catch (error) {
const message = error?.message || String(error);
@@ -187,6 +245,7 @@ export async function runRealBrowserE2e() {
testCase.timeoutMs,
testCase.expectedOutput,
testCase.acceptedCompletionOutput,
+ testCase.pendingOnExpectedTermination,
);
return;
}
@@ -358,6 +417,7 @@ function printSummary(results, totalMs) {
const total = results.length;
const passed = results.filter((r) => r.status === "pass").length;
const failed = results.filter((r) => r.status === "fail").length;
+ const pending = results.filter((r) => r.status === "pending").length;
const skipped = results.filter((r) => r.status === "skip").length;
const totalAssertions = results.reduce((sum, r) => sum + r.assertionCount, 0);
@@ -367,6 +427,7 @@ function printSummary(results, totalMs) {
` Passed: ${passed}/${total}${total > 0 ? ` (${Math.round((passed / total) * 100)}%)` : ""}`,
);
if (failed > 0) console.log(` Failed: ${failed}/${total}`);
+ if (pending > 0) console.log(` Pending: ${pending}/${total}`);
if (skipped > 0) console.log(` Skipped: ${skipped}/${total}`);
console.log(` Total time: ${formatDuration(totalMs)}`);
console.log(` Assertions: ${totalAssertions}`);
@@ -381,7 +442,9 @@ function printSummary(results, totalMs) {
? "PASS"
: result.status === "fail"
? "FAIL"
- : "SKIP";
+ : result.status === "pending"
+ ? "PENDING"
+ : "SKIP";
const timing =
result.status === "skip"
? " "
@@ -405,5 +468,14 @@ function printSummary(results, totalMs) {
}
}
+ const pendingResults = results.filter((r) => r.status === "pending");
+ if (pendingResults.length > 0) {
+ console.log("");
+ console.log(" Pending:");
+ for (const result of pendingResults) {
+ console.log(` - ${result.name}: ${result.message}`);
+ }
+ }
+
console.log("");
}
diff --git a/package/ego-browser/src/browser-runtime.test.mjs b/package/ego-browser/src/browser-runtime.test.mjs
index 2718aa1..f938223 100644
--- a/package/ego-browser/src/browser-runtime.test.mjs
+++ b/package/ego-browser/src/browser-runtime.test.mjs
@@ -2,15 +2,45 @@ import test from "node:test";
import assert from "node:assert/strict";
import {
+ CdpRequestTimeoutError,
browserCdp,
drainBrowserEvents,
drainPageEvents,
ensureFrameSessions,
+ ensureNetworkTracking,
+ ensureSession,
invalidateSession,
+ networkActivity,
+ pageNetworkSessions,
prepareFileChooser,
subscribeBrowserEvents,
} from "../dist/src/browser-runtime.js";
+test("browserCdp exposes a typed transport timeout", async () => {
+ const previous = globalThis.ego;
+ globalThis.ego = { sendCDPMessage() {} };
+ try {
+ await assert.rejects(
+ () => browserCdp("Browser.getVersion", {}, undefined, 5),
+ (error) => {
+ assert(error instanceof CdpRequestTimeoutError);
+ assert.equal(error.code, "EGO_CDP_REQUEST_TIMEOUT");
+ assert.equal(error.method, "Browser.getVersion");
+ assert.equal(error.timeoutMs, 5);
+ assert.match(
+ error.message,
+ /CDP request timed out: Browser\.getVersion/,
+ );
+ return true;
+ },
+ );
+ } finally {
+ invalidateSession();
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ }
+});
+
test("frame sessions follow one Page target and are invalidated with it", async () => {
const previous = globalThis.ego;
const attachCounts = new Map();
@@ -25,17 +55,17 @@ test("frame sessions follow one Page target and are invalidated with it", async
{
targetId: "frame-child",
type: "iframe",
- parentId: "page-main",
+ parentFrameId: "same-process-frame",
},
{
targetId: "frame-grandchild",
type: "iframe",
- parentId: "frame-child",
+ parentFrameId: "same-process-inside-child",
},
{
targetId: "foreign-frame",
type: "iframe",
- parentId: "foreign-page",
+ parentFrameId: "foreign-page",
},
],
};
@@ -43,7 +73,22 @@ test("frame sessions follow one Page target and are invalidated with it", async
result = {
frameTree: {
frame: { id: "page-main" },
- childFrames: [{ frame: { id: "same-process-frame" } }],
+ childFrames: [
+ {
+ frame: { id: "same-process-frame" },
+ childFrames: [
+ {
+ frame: { id: "frame-child" },
+ childFrames: [
+ {
+ frame: { id: "same-process-inside-child" },
+ childFrames: [{ frame: { id: "frame-grandchild" } }],
+ },
+ ],
+ },
+ ],
+ },
+ ],
},
};
} else if (request.method === "Target.attachToTarget") {
@@ -65,6 +110,7 @@ test("frame sessions follow one Page target and are invalidated with it", async
[
["same-process-frame", "session:page-main"],
["frame-child", "session:frame-child"],
+ ["same-process-inside-child", "session:frame-child"],
["frame-grandchild", "session:frame-grandchild"],
],
);
@@ -82,6 +128,768 @@ test("frame sessions follow one Page target and are invalidated with it", async
}
});
+test("network tracking is continuous and does not consume Page events", async () => {
+ const previous = globalThis.ego;
+ const methods = [];
+ const runtime = {
+ sendCDPMessage(payload) {
+ const request = JSON.parse(payload);
+ methods.push([request.method, request.sessionId]);
+ const result =
+ request.method === "Target.attachToTarget"
+ ? { sessionId: "session:page-main" }
+ : {};
+ queueMicrotask(() => {
+ runtime.onCDPMessage(JSON.stringify({ id: request.id, result }));
+ });
+ },
+ };
+ globalThis.ego = runtime;
+
+ try {
+ const sessionId = await ensureSession("page-main");
+ assert.equal(sessionId, "session:page-main");
+ assert.equal(
+ methods.filter(([method]) => method === "Network.enable").length,
+ 1,
+ "a Page session starts network tracking before it is returned",
+ );
+
+ runtime.onCDPMessage(
+ JSON.stringify({
+ sessionId,
+ method: "Network.requestWillBeSent",
+ params: {
+ requestId: "favicon-without-terminal-event",
+ request: { url: "https://example.com/favicon.ico" },
+ },
+ }),
+ );
+ assert.equal(
+ networkActivity([sessionId]).inflight,
+ 0,
+ "favicon traffic must not keep a Page from reaching network idle",
+ );
+ assert.deepEqual(
+ drainPageEvents(sessionId).map((event) => event.method),
+ ["Network.requestWillBeSent"],
+ "ignoring favicon activity for idle does not hide its public event",
+ );
+
+ runtime.onCDPMessage(
+ JSON.stringify({
+ sessionId,
+ method: "Network.requestWillBeSent",
+ params: {
+ requestId: "favicon-without-terminal-event",
+ redirectResponse: { status: 302 },
+ request: { url: "https://example.com/assets/icon.png" },
+ },
+ }),
+ );
+ assert.equal(
+ networkActivity([sessionId]).inflight,
+ 0,
+ "a redirected favicon stays excluded for its entire request chain",
+ );
+ assert.deepEqual(
+ drainPageEvents(sessionId).map((event) => event.method),
+ ["Network.requestWillBeSent"],
+ "excluding a favicon redirect does not hide its public event",
+ );
+
+ runtime.onCDPMessage(
+ JSON.stringify({
+ sessionId,
+ method: "Network.loadingFinished",
+ params: { requestId: "favicon-without-terminal-event" },
+ }),
+ );
+ drainPageEvents(sessionId);
+ runtime.onCDPMessage(
+ JSON.stringify({
+ sessionId,
+ method: "Network.requestWillBeSent",
+ params: {
+ requestId: "favicon-without-terminal-event",
+ request: { url: "https://example.com/api/data" },
+ },
+ }),
+ );
+ assert.equal(
+ networkActivity([sessionId]).inflight,
+ 1,
+ "a favicon request id is released when a terminal event arrives",
+ );
+ runtime.onCDPMessage(
+ JSON.stringify({
+ sessionId,
+ method: "Network.loadingFinished",
+ params: { requestId: "favicon-without-terminal-event" },
+ }),
+ );
+ drainPageEvents(sessionId);
+
+ runtime.onCDPMessage(
+ JSON.stringify({
+ sessionId,
+ method: "Runtime.consoleAPICalled",
+ params: { value: "keep me" },
+ }),
+ );
+ runtime.onCDPMessage(
+ JSON.stringify({
+ sessionId,
+ method: "Network.requestWillBeSent",
+ params: { requestId: "slow-request" },
+ }),
+ );
+
+ assert.deepEqual(networkActivity([sessionId]).inflight, 1);
+ await ensureNetworkTracking([sessionId]);
+ assert.equal(
+ methods.filter(([method]) => method === "Network.enable").length,
+ 1,
+ "ensuring an initialized tracker is idempotent",
+ );
+ assert.deepEqual(
+ drainPageEvents(sessionId).map((event) => event.method),
+ ["Runtime.consoleAPICalled", "Network.requestWillBeSent"],
+ "reading tracker state leaves the public Page event queue intact",
+ );
+
+ runtime.onCDPMessage(
+ JSON.stringify({
+ sessionId,
+ method: "Network.loadingFinished",
+ params: { requestId: "slow-request" },
+ }),
+ );
+ assert.equal(networkActivity([sessionId]).inflight, 0);
+
+ await browserCdp("Network.disable", {}, sessionId);
+ runtime.onCDPMessage(
+ JSON.stringify({
+ sessionId,
+ method: "Network.loadingFinished",
+ params: { requestId: "late-after-disable" },
+ }),
+ );
+ assert.equal(
+ networkActivity([sessionId]).tracking,
+ false,
+ "a late event after Network.disable must not resurrect tracking",
+ );
+ await ensureNetworkTracking([sessionId]);
+ assert.equal(
+ methods.filter(([method]) => method === "Network.enable").length,
+ 2,
+ "the next sensitive operation must restore disabled tracking",
+ );
+ } finally {
+ invalidateSession();
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ }
+});
+
+test("Page network sessions include only its known OOPIF descendants", async () => {
+ const previous = globalThis.ego;
+ const runtime = {
+ sendCDPMessage(payload) {
+ const request = JSON.parse(payload);
+ let result = {};
+ if (request.method === "Target.getTargets") {
+ result = {
+ targetInfos: [
+ { targetId: "page-main", type: "page" },
+ {
+ targetId: "frame-child",
+ type: "iframe",
+ parentFrameId: "page-main",
+ },
+ {
+ targetId: "foreign-frame",
+ type: "iframe",
+ parentFrameId: "foreign-page",
+ },
+ ],
+ };
+ } else if (request.method === "Page.getFrameTree") {
+ result = {
+ frameTree: {
+ frame: { id: "page-main" },
+ childFrames: [{ frame: { id: "frame-child" } }],
+ },
+ };
+ } else if (request.method === "Target.attachToTarget") {
+ result = { sessionId: `session:${request.params.targetId}` };
+ }
+ queueMicrotask(() => {
+ runtime.onCDPMessage(JSON.stringify({ id: request.id, result }));
+ });
+ },
+ };
+ globalThis.ego = runtime;
+
+ try {
+ const mainSessionId = await ensureSession("page-main");
+ assert.deepEqual(await pageNetworkSessions(mainSessionId), [
+ "session:page-main",
+ "session:frame-child",
+ ]);
+ } finally {
+ invalidateSession();
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ }
+});
+
+test("a live auto-attached OOPIF survives a temporarily incomplete frame tree", async () => {
+ const previous = globalThis.ego;
+ const runtime = {
+ sendCDPMessage(payload) {
+ const request = JSON.parse(payload);
+ let result = {};
+ if (request.method === "Target.getTargets") {
+ result = {
+ targetInfos: [
+ { targetId: "page-main", type: "page" },
+ {
+ targetId: "frame-child",
+ type: "iframe",
+ parentFrameId: "same-process-parent",
+ },
+ ],
+ };
+ } else if (request.method === "Page.getFrameTree") {
+ // Target and frame-tree snapshots are not atomic. The target can be
+ // visible one protocol turn before its parent frame appears here.
+ result = { frameTree: { frame: { id: "page-main" } } };
+ } else if (request.method === "Target.attachToTarget") {
+ result = { sessionId: `session:${request.params.targetId}` };
+ }
+ queueMicrotask(() => {
+ runtime.onCDPMessage(JSON.stringify({ id: request.id, result }));
+ });
+ },
+ };
+ globalThis.ego = runtime;
+
+ try {
+ const mainSessionId = await ensureSession("page-main");
+ runtime.onCDPMessage(
+ JSON.stringify({
+ sessionId: mainSessionId,
+ method: "Target.attachedToTarget",
+ params: {
+ sessionId: "session:frame-child",
+ targetInfo: {
+ targetId: "frame-child",
+ type: "iframe",
+ parentFrameId: "same-process-parent",
+ },
+ waitingForDebugger: true,
+ },
+ }),
+ );
+ await new Promise((resolve) => setImmediate(resolve));
+
+ assert.deepEqual(await pageNetworkSessions(mainSessionId), [
+ "session:page-main",
+ "session:frame-child",
+ ]);
+ } finally {
+ invalidateSession();
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ }
+});
+
+test("Page network session discovery honors its transport timeout", async () => {
+ const previous = globalThis.ego;
+ const runtime = {
+ sendCDPMessage(payload) {
+ const request = JSON.parse(payload);
+ if (request.method === "Target.getTargets") return;
+ const result =
+ request.method === "Target.attachToTarget"
+ ? { sessionId: `session:${request.params.targetId}` }
+ : {};
+ queueMicrotask(() => {
+ runtime.onCDPMessage(JSON.stringify({ id: request.id, result }));
+ });
+ },
+ };
+ globalThis.ego = runtime;
+
+ try {
+ const mainSessionId = await ensureSession("page-main");
+ await assert.rejects(
+ () => pageNetworkSessions(mainSessionId, 10),
+ (error) => {
+ assert(error instanceof CdpRequestTimeoutError);
+ assert.equal(error.method, "Target.getTargets");
+ assert(error.timeoutMs > 0 && error.timeoutMs <= 10);
+ return true;
+ },
+ );
+ } finally {
+ invalidateSession();
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ }
+});
+
+test("a shorter network-tracking waiter does not cancel shared initialization", async () => {
+ const previous = globalThis.ego;
+ let delayedNetworkEnable;
+ const methods = [];
+ const runtime = {
+ sendCDPMessage(payload) {
+ const request = JSON.parse(payload);
+ methods.push([request.method, request.sessionId]);
+ let result = {};
+ if (request.method === "Target.attachToTarget") {
+ result = { sessionId: `session:${request.params.targetId}` };
+ } else if (request.method === "Target.getTargets") {
+ result = {
+ targetInfos: [
+ { targetId: "page-main", type: "page" },
+ {
+ targetId: "frame-child",
+ type: "iframe",
+ parentFrameId: "page-main",
+ },
+ ],
+ };
+ } else if (request.method === "Page.getFrameTree") {
+ result = {
+ frameTree: {
+ frame: { id: "page-main" },
+ childFrames: [
+ { frame: { id: "frame-child", parentId: "page-main" } },
+ ],
+ },
+ };
+ }
+ const respond = () => {
+ runtime.onCDPMessage(JSON.stringify({ id: request.id, result }));
+ };
+ if (
+ request.method === "Network.enable" &&
+ request.sessionId === "session:frame-child"
+ ) {
+ delayedNetworkEnable = respond;
+ setTimeout(respond, 80);
+ return;
+ }
+ queueMicrotask(respond);
+ },
+ };
+ globalThis.ego = runtime;
+
+ try {
+ const mainSessionId = await ensureSession("page-main");
+ runtime.onCDPMessage(
+ JSON.stringify({
+ sessionId: mainSessionId,
+ method: "Target.attachedToTarget",
+ params: {
+ sessionId: "session:frame-child",
+ targetInfo: {
+ targetId: "frame-child",
+ type: "iframe",
+ parentFrameId: "page-main",
+ },
+ waitingForDebugger: false,
+ },
+ }),
+ );
+ await new Promise((resolve) => setImmediate(resolve));
+
+ const discoveryStartedAt = performance.now();
+ assert.deepEqual(await pageNetworkSessions(mainSessionId, 10), [
+ "session:page-main",
+ "session:frame-child",
+ ]);
+ assert(
+ performance.now() - discoveryStartedAt < 60,
+ "best-effort initialization must stay inside discovery's budget",
+ );
+
+ const startedAt = performance.now();
+ await assert.rejects(
+ () => ensureNetworkTracking(["session:frame-child"], 10),
+ (error) => {
+ assert(error instanceof CdpRequestTimeoutError);
+ assert.equal(error.method, "Network.enable");
+ assert.equal(error.timeoutMs, 10);
+ return true;
+ },
+ );
+ assert(
+ performance.now() - startedAt < 60,
+ "the short waiter must honor its own budget",
+ );
+ assert.equal(typeof delayedNetworkEnable, "function");
+ assert.equal(
+ methods.filter(
+ ([method, sessionId]) =>
+ method === "Network.enable" && sessionId === "session:frame-child",
+ ).length,
+ 1,
+ "the short waiter must reuse the existing Network.enable request",
+ );
+
+ await new Promise((resolve) => setTimeout(resolve, 90));
+ await ensureNetworkTracking(["session:frame-child"], 10);
+ assert.equal(
+ methods.filter(
+ ([method, sessionId]) =>
+ method === "Network.enable" && sessionId === "session:frame-child",
+ ).length,
+ 1,
+ "the shared request still completes for later callers",
+ );
+ } finally {
+ invalidateSession();
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ }
+});
+
+test("a shorter session waiter does not cancel shared auto-attach initialization", async () => {
+ const previous = globalThis.ego;
+ const methods = [];
+ const runtime = {
+ sendCDPMessage(payload) {
+ const request = JSON.parse(payload);
+ methods.push([request.method, request.sessionId]);
+ let result = {};
+ if (request.method === "Target.attachToTarget") {
+ result = { sessionId: `session:${request.params.targetId}` };
+ } else if (request.method === "Target.getTargets") {
+ result = {
+ targetInfos: [
+ { targetId: "page-main", type: "page" },
+ {
+ targetId: "frame-child",
+ type: "iframe",
+ parentFrameId: "page-main",
+ },
+ ],
+ };
+ } else if (request.method === "Page.getFrameTree") {
+ result = {
+ frameTree: {
+ frame: { id: "page-main" },
+ childFrames: [
+ { frame: { id: "frame-child", parentId: "page-main" } },
+ ],
+ },
+ };
+ }
+ const respond = () => {
+ runtime.onCDPMessage(JSON.stringify({ id: request.id, result }));
+ };
+ if (
+ request.method === "Target.setAutoAttach" &&
+ request.sessionId === "session:frame-child"
+ ) {
+ setTimeout(respond, 80);
+ return;
+ }
+ queueMicrotask(respond);
+ },
+ };
+ globalThis.ego = runtime;
+
+ try {
+ const mainSessionId = await ensureSession("page-main");
+ runtime.onCDPMessage(
+ JSON.stringify({
+ sessionId: mainSessionId,
+ method: "Target.attachedToTarget",
+ params: {
+ sessionId: "session:frame-child",
+ targetInfo: {
+ targetId: "frame-child",
+ type: "iframe",
+ parentFrameId: "page-main",
+ },
+ waitingForDebugger: false,
+ },
+ }),
+ );
+ await new Promise((resolve) => setImmediate(resolve));
+
+ const discoveryStartedAt = performance.now();
+ assert.deepEqual(await pageNetworkSessions(mainSessionId, 10), [
+ "session:page-main",
+ "session:frame-child",
+ ]);
+ assert(
+ performance.now() - discoveryStartedAt < 60,
+ "shared auto-attach must stay inside discovery's budget",
+ );
+
+ const startedAt = performance.now();
+ assert.equal(await ensureSession("frame-child", 10), "session:frame-child");
+ assert(
+ performance.now() - startedAt < 60,
+ "best-effort auto-attach must not outlive the session wait budget",
+ );
+ assert.equal(
+ methods.filter(
+ ([method, sessionId]) =>
+ method === "Target.setAutoAttach" &&
+ sessionId === "session:frame-child",
+ ).length,
+ 1,
+ "the short waiter must reuse the existing auto-attach request",
+ );
+
+ await new Promise((resolve) => setTimeout(resolve, 90));
+ assert.equal(await ensureSession("frame-child", 10), "session:frame-child");
+ assert.equal(
+ methods.filter(
+ ([method, sessionId]) =>
+ method === "Target.setAutoAttach" &&
+ sessionId === "session:frame-child",
+ ).length,
+ 1,
+ "the shared auto-attach request still completes for later callers",
+ );
+ } finally {
+ invalidateSession();
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ }
+});
+
+test("an OOPIF document request can finish in its child session", async () => {
+ const previous = globalThis.ego;
+ const runtime = {
+ sendCDPMessage(payload) {
+ const request = JSON.parse(payload);
+ let result = {};
+ if (request.method === "Target.getTargets") {
+ result = {
+ targetInfos: [
+ { targetId: "page-main", type: "page" },
+ {
+ targetId: "frame-child",
+ type: "iframe",
+ parentFrameId: "page-main",
+ url: "https://frame.example/",
+ },
+ ],
+ };
+ } else if (request.method === "Page.getFrameTree") {
+ result = {
+ frameTree: {
+ frame: { id: "page-main" },
+ childFrames: [{ frame: { id: "frame-child" } }],
+ },
+ };
+ } else if (request.method === "Target.attachToTarget") {
+ result = { sessionId: `session:${request.params.targetId}` };
+ } else if (request.method === "Runtime.evaluate") {
+ result = { result: { value: "loading" } };
+ }
+ queueMicrotask(() => {
+ runtime.onCDPMessage(JSON.stringify({ id: request.id, result }));
+ });
+ },
+ emit(sessionId, method, params) {
+ runtime.onCDPMessage(JSON.stringify({ sessionId, method, params }));
+ },
+ };
+ globalThis.ego = runtime;
+
+ try {
+ const mainSession = await ensureSession("page-main");
+ const foreignSession = await ensureSession("page-foreign");
+ runtime.emit(mainSession, "Network.requestWillBeSent", {
+ requestId: "document-request",
+ frameId: "frame-child",
+ loaderId: "document-request",
+ type: "Document",
+ request: { url: "https://frame.example/" },
+ });
+ runtime.emit(foreignSession, "Network.requestWillBeSent", {
+ requestId: "document-request",
+ frameId: "foreign-frame",
+ loaderId: "document-request",
+ type: "Document",
+ request: { url: "https://foreign.example/" },
+ });
+
+ const sessions = await pageNetworkSessions(mainSession);
+ runtime.emit("session:frame-child", "Network.loadingFinished", {
+ requestId: "document-request",
+ });
+
+ assert.equal(networkActivity(sessions).inflight, 0);
+ assert.equal(
+ networkActivity([foreignSession]).inflight,
+ 1,
+ "a terminal event must not clear an unrelated Page's request",
+ );
+
+ runtime.emit(mainSession, "Network.requestWillBeSent", {
+ requestId: "reattached-document",
+ frameId: "frame-child",
+ loaderId: "reattached-document",
+ type: "Document",
+ });
+ await pageNetworkSessions(mainSession);
+ runtime.emit(mainSession, "Target.targetDestroyed", {
+ targetId: "frame-child",
+ });
+ assert.equal(
+ networkActivity([mainSession]).tracking,
+ true,
+ "destroying an OOPIF must not detach its parent Page session",
+ );
+ assert.equal(
+ networkActivity([mainSession]).inflight,
+ 0,
+ "destroying a reattached OOPIF removes its migrated document request",
+ );
+ } finally {
+ invalidateSession();
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ }
+});
+
+test("auto-attached OOPIFs are instrumented and resumed without waiting for Network.enable", async () => {
+ const previous = globalThis.ego;
+ const sent = [];
+ let delayedChildNetworkEnable;
+ const runtime = {
+ sendCDPMessage(payload) {
+ const request = JSON.parse(payload);
+ sent.push(request);
+ if (
+ request.method === "Network.enable" &&
+ request.sessionId === "session:frame-child"
+ ) {
+ delayedChildNetworkEnable = request;
+ return;
+ }
+ queueMicrotask(() => {
+ if (
+ request.method === "Target.setAutoAttach" &&
+ request.sessionId === "session:page-main"
+ ) {
+ runtime.onCDPMessage(
+ JSON.stringify({
+ sessionId: "session:page-main",
+ method: "Network.requestWillBeSent",
+ params: {
+ requestId: "oopif-document",
+ frameId: "frame-child",
+ loaderId: "oopif-document",
+ type: "Document",
+ },
+ }),
+ );
+ runtime.onCDPMessage(
+ JSON.stringify({
+ sessionId: "session:page-main",
+ method: "Target.attachedToTarget",
+ params: {
+ sessionId: "session:frame-child",
+ targetInfo: {
+ targetId: "frame-child",
+ type: "iframe",
+ parentFrameId: "same-process-parent",
+ },
+ waitingForDebugger: true,
+ },
+ }),
+ );
+ }
+ const result =
+ request.method === "Target.attachToTarget"
+ ? { sessionId: `session:${request.params.targetId}` }
+ : {};
+ runtime.onCDPMessage(JSON.stringify({ id: request.id, result }));
+ if (
+ request.method === "Runtime.runIfWaitingForDebugger" &&
+ request.sessionId === "session:frame-child" &&
+ delayedChildNetworkEnable
+ ) {
+ runtime.onCDPMessage(
+ JSON.stringify({ id: delayedChildNetworkEnable.id, result: {} }),
+ );
+ delayedChildNetworkEnable = undefined;
+ }
+ });
+ },
+ };
+ globalThis.ego = runtime;
+
+ try {
+ await ensureSession("page-main");
+ await new Promise((resolve) => setImmediate(resolve));
+
+ const mainAutoAttach = sent.find(
+ (request) =>
+ request.method === "Target.setAutoAttach" &&
+ request.sessionId === "session:page-main",
+ );
+ assert.equal(mainAutoAttach?.params?.autoAttach, true);
+ assert.equal(mainAutoAttach?.params?.waitForDebuggerOnStart, true);
+ assert.equal(mainAutoAttach?.params?.flatten, true);
+
+ const childNetworkIndex = sent.findIndex(
+ (request) =>
+ request.method === "Network.enable" &&
+ request.sessionId === "session:frame-child",
+ );
+ const childResumeIndex = sent.findIndex(
+ (request) =>
+ request.method === "Runtime.runIfWaitingForDebugger" &&
+ request.sessionId === "session:frame-child",
+ );
+ assert.ok(childNetworkIndex >= 0, "the child Network domain is enabled");
+ assert.ok(childResumeIndex >= 0, "the paused child is resumed");
+ assert.ok(
+ childNetworkIndex < childResumeIndex,
+ "Network.enable is sent before the child resumes",
+ );
+ assert.equal(
+ delayedChildNetworkEnable,
+ undefined,
+ "resuming does not await the Network.enable response",
+ );
+ assert.equal(
+ networkActivity(["session:page-main", "session:frame-child"]).inflight,
+ 1,
+ "enabling the child Network domain preserves the migrated request",
+ );
+ runtime.onCDPMessage(
+ JSON.stringify({
+ sessionId: "session:frame-child",
+ method: "Network.loadingFinished",
+ params: { requestId: "oopif-document" },
+ }),
+ );
+ assert.equal(
+ networkActivity(["session:page-main", "session:frame-child"]).inflight,
+ 0,
+ );
+ } finally {
+ invalidateSession();
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ }
+});
+
// Gap A: ensureSession() calls the raw listTabs binding to attach a session.
// When the task is blocked it returns { error, error_code }; the result must
// surface the ego-browser-owned wording for the code (not the native error
diff --git a/package/ego-browser/src/browser-runtime.ts b/package/ego-browser/src/browser-runtime.ts
index be050fa..6b1f180 100644
--- a/package/ego-browser/src/browser-runtime.ts
+++ b/package/ego-browser/src/browser-runtime.ts
@@ -14,6 +14,14 @@ const SESSION_LOST =
/Session (?:with given id )?not found|Target closed|No session/i;
const BROWSER_LEVEL = (method) =>
method.startsWith("Target.") || method.startsWith("Browser.");
+const OOPIF_AUTO_ATTACH_PARAMS = {
+ autoAttach: true,
+ waitForDebuggerOnStart: true,
+ flatten: true,
+ // The harness owns iframe sessions. Other related targets, such as workers,
+ // keep their browser-managed lifecycle and never need to be paused here.
+ filter: [{ type: "iframe", exclude: false }, { exclude: true }],
+};
const DIALOG_BLOCKED_METHOD = (method) =>
method.startsWith("Input.") ||
method.startsWith("Runtime.") ||
@@ -37,6 +45,32 @@ type EgoCdpCallbackRuntime = {
};
let callbackRuntime: EgoCdpCallbackRuntime | undefined;
+export class CdpRequestTimeoutError extends Error {
+ readonly code = "EGO_CDP_REQUEST_TIMEOUT";
+ readonly method: string;
+ readonly timeoutMs: number;
+ readonly sessionId?: string;
+
+ constructor(method: string, timeoutMs: number, sessionId?: string) {
+ super(`CDP request timed out: ${method}`);
+ this.name = "CdpRequestTimeoutError";
+ this.method = method;
+ this.timeoutMs = timeoutMs;
+ this.sessionId = sessionId;
+ }
+}
+
+export function isCdpRequestTimeoutError(
+ error: unknown,
+): error is CdpRequestTimeoutError {
+ return (
+ error instanceof CdpRequestTimeoutError ||
+ (Boolean(error) &&
+ typeof error === "object" &&
+ (error as { code?: unknown }).code === "EGO_CDP_REQUEST_TIMEOUT")
+ );
+}
+
/**
* Signals that a modal JavaScript dialog prevented a CDP command from
* completing. The dialog remains open; Page-level code decides whether to
@@ -97,6 +131,20 @@ function targetState(targetId) {
events: [],
pageEventsEnabled: false,
networkDomainEnabled: false,
+ networkEnableInflight: null,
+ autoAttachEnabled: false,
+ autoAttachInflight: null,
+ inflightNetworkRequests: new Map<
+ string,
+ {
+ requestId: string;
+ frameId?: string;
+ loaderId?: string;
+ type?: string;
+ }
+ >(),
+ ignoredFaviconRequestIds: new Set<string>(),
+ lastNetworkActivityAt: state.now(),
pendingDialog: null,
fileChooserInterception: null,
};
@@ -119,13 +167,24 @@ function registerSession(targetId, sessionId) {
target.sessionAt = Date.now();
target.pageEventsEnabled = false;
target.networkDomainEnabled = false;
+ target.networkEnableInflight = null;
+ target.autoAttachEnabled = false;
+ target.autoAttachInflight = null;
+ target.inflightNetworkRequests.clear();
+ target.ignoredFaviconRequestIds.clear();
+ target.lastNetworkActivityAt = state.now();
target.pendingDialog = null;
sessionTargets.set(sessionId, targetId);
}
function registerTargetParent(targetId: string, parentTargetId: string) {
const previousParent = parentTargets.get(targetId);
- if (previousParent === parentTargetId) return;
+ if (previousParent === parentTargetId) {
+ // A renderer swap can reattach the same frame target after a new document
+ // request has already started in the parent session.
+ migrateFrameRequests(targetId, parentTargetId);
+ return;
+ }
if (previousParent) {
const previousChildren = childTargets.get(previousParent);
previousChildren?.delete(targetId);
@@ -138,6 +197,48 @@ function registerTargetParent(targetId: string, parentTargetId: string) {
childTargets.set(parentTargetId, children);
}
children.add(targetId);
+ migrateFrameRequests(targetId, parentTargetId);
+}
+
+function migrateFrameRequests(targetId: string, parentTargetId: string): void {
+ const destination = targetState(targetId);
+ const rootTargetId = pageRootTargetId(parentTargetId);
+ for (const sourceTargetId of pageTreeTargetIds(rootTargetId)) {
+ if (sourceTargetId === targetId) continue;
+ const source = targetStates.get(sourceTargetId);
+ if (!source) continue;
+ for (const [requestId, request] of source.inflightNetworkRequests) {
+ if (request.frameId !== targetId) continue;
+ source.inflightNetworkRequests.delete(requestId);
+ destination.inflightNetworkRequests.set(requestId, request);
+ destination.lastNetworkActivityAt = Math.max(
+ destination.lastNetworkActivityAt,
+ source.lastNetworkActivityAt,
+ );
+ }
+ }
+}
+
+function pageRootTargetId(targetId: string): string {
+ let current = targetId;
+ const visited = new Set<string>();
+ while (parentTargets.has(current) && !visited.has(current)) {
+ visited.add(current);
+ current = parentTargets.get(current)!;
+ }
+ return current;
+}
+
+function pageTreeTargetIds(rootTargetId: string): string[] {
+ const result: string[] = [];
+ const visit = (targetId: string) => {
+ result.push(targetId);
+ for (const childTargetId of childTargets.get(targetId) || []) {
+ visit(childTargetId);
+ }
+ };
+ visit(rootTargetId);
+ return result;
}
function unregisterTargetParent(targetId: string) {
@@ -170,6 +271,12 @@ function clearTargetSession(targetId, { remove = false } = {}) {
target.events.length = 0;
target.pageEventsEnabled = false;
target.networkDomainEnabled = false;
+ target.networkEnableInflight = null;
+ target.autoAttachEnabled = false;
+ target.autoAttachInflight = null;
+ target.inflightNetworkRequests.clear();
+ target.ignoredFaviconRequestIds.clear();
+ target.lastNetworkActivityAt = state.now();
target.pendingDialog = null;
target.fileChooserInterception = null;
}
@@ -289,7 +396,7 @@ function rawCdp(
return new Promise<any>((resolve, reject) => {
const timer = setTimeout(() => {
pending.delete(id);
- reject(new Error(`CDP request timed out: ${method}`));
+ reject(new CdpRequestTimeoutError(method, timeoutMs, sessionId));
}, timeoutMs);
pending.set(id, {
method,
@@ -372,15 +479,37 @@ function recordCommandState(method, params, sessionId, response) {
if (!targetId) return;
const target = targetStates.get(targetId);
if (!target) return;
- if (method === "Network.enable") target.networkDomainEnabled = true;
- if (method === "Network.disable") target.networkDomainEnabled = false;
+ if (method === "Network.enable") {
+ if (!target.networkDomainEnabled) {
+ target.lastNetworkActivityAt = state.now();
+ }
+ target.networkDomainEnabled = true;
+ }
+ if (method === "Network.disable") {
+ target.networkDomainEnabled = false;
+ target.inflightNetworkRequests.clear();
+ target.ignoredFaviconRequestIds.clear();
+ target.lastNetworkActivityAt = state.now();
+ }
+ if (method === "Target.setAutoAttach") {
+ target.autoAttachEnabled = params?.autoAttach === true;
+ }
}
-export async function ensureSession(requestedTargetId = undefined) {
+export async function ensureSession(
+ requestedTargetId = undefined,
+ timeoutMs = RESPONSE_TIMEOUT_MS,
+) {
const cachedTargetId =
requestedTargetId || state.preferredTargetId || defaultTargetId;
const cached = cachedTargetId ? targetStates.get(cachedTargetId) : undefined;
if (cached?.sessionId && Date.now() - cached.sessionAt < SESSION_TTL_MS) {
+ await Promise.all([
+ enablePageEvents(cached.sessionId, timeoutMs),
+ enableNetworkTrackingForSession(cached.sessionId, false, timeoutMs),
+ enableOopifAutoAttach(cached.sessionId, timeoutMs),
+ ]);
+ cached.sessionAt = Date.now();
return cached.sessionId;
}
@@ -413,6 +542,7 @@ export async function ensureSession(requestedTargetId = undefined) {
"Target.attachToTarget",
{ targetId, flatten: true },
undefined,
+ timeoutMs,
);
const sessionId = attached.result?.sessionId || attached.sessionId;
if (!sessionId) {
@@ -420,7 +550,11 @@ export async function ensureSession(requestedTargetId = undefined) {
}
registerSession(targetId, sessionId);
}
- await enablePageEvents(target.sessionId);
+ await Promise.all([
+ enablePageEvents(target.sessionId, timeoutMs),
+ enableNetworkTrackingForSession(target.sessionId, false, timeoutMs),
+ enableOopifAutoAttach(target.sessionId, timeoutMs),
+ ]);
target.sessionAt = Date.now();
return target.sessionId;
} finally {
@@ -432,46 +566,91 @@ export async function ensureSession(requestedTargetId = undefined) {
/**
* Attach sessions for every live OOPIF that belongs to one top-level Page.
- * TargetInfo.parentId provides the ownership edge, so unrelated iframe targets
- * in the same task space are never searched by this Page.
+ * Standard CDP reports an iframe target's parent as a frame id. The frame tree
+ * is therefore needed to skip same-process frames and recover the nearest
+ * Page/OOPIF target ancestor without admitting unrelated iframe targets.
*/
-export async function ensureFrameSessions(pageTargetId: string) {
+export async function ensureFrameSessions(
+ pageTargetId: string,
+ timeoutMs = RESPONSE_TIMEOUT_MS,
+) {
if (typeof pageTargetId !== "string" || pageTargetId.length === 0) {
throw new TypeError("ensureFrameSessions requires a non-empty targetId");
}
- const pageSessionId = await ensureSession(pageTargetId);
+ const deadline = state.now() + Math.max(1, timeoutMs);
+ const remaining = () => Math.max(1, deadline - state.now());
+ const pageSessionId = await ensureSession(pageTargetId, remaining());
const [response, frameTreeResponse] = await Promise.all([
- browserCdp("Target.getTargets"),
- browserCdp("Page.getFrameTree", {}, pageSessionId),
+ browserCdp("Target.getTargets", {}, undefined, remaining()),
+ browserCdp("Page.getFrameTree", {}, pageSessionId, remaining()),
]);
const targetInfos =
response?.result?.targetInfos || response?.targetInfos || [];
- const byParent = new Map<string, any[]>();
- for (const info of targetInfos) {
- if (
- info?.type !== "iframe" ||
- typeof info.targetId !== "string" ||
- typeof info.parentId !== "string"
- ) {
- continue;
+ const frameTree =
+ frameTreeResponse?.result?.frameTree || frameTreeResponse?.frameTree;
+ const frameParents = new Map<string, string | undefined>();
+ const collectFrameGraph = (
+ tree: any,
+ recursiveParentId: string | undefined,
+ ) => {
+ const frameId = tree?.frame?.id;
+ if (typeof frameId !== "string") return;
+ const protocolParentId = tree?.frame?.parentId;
+ frameParents.set(
+ frameId,
+ typeof protocolParentId === "string"
+ ? protocolParentId
+ : recursiveParentId,
+ );
+ for (const child of tree?.childFrames || []) {
+ collectFrameGraph(child, frameId);
}
- const children = byParent.get(info.parentId) || [];
- children.push(info);
- byParent.set(info.parentId, children);
- }
+ };
+ if (frameTree) collectFrameGraph(frameTree, undefined);
+ const rootFrameId = frameTree?.frame?.id;
- const descendants: any[] = [];
- const visit = (parentTargetId: string) => {
- for (const info of byParent.get(parentTargetId) || []) {
- descendants.push(info);
- visit(info.targetId);
+ const iframeInfos = targetInfos.filter(
+ (info) => info?.type === "iframe" && typeof info.targetId === "string",
+ );
+ const iframeInfoByTarget = new Map(
+ iframeInfos.map((info) => [info.targetId as string, info]),
+ );
+ const reportedParentFrameId = (info: any): string | undefined => {
+ const parentFrameId = info?.parentFrameId ?? info?.parentId;
+ return typeof parentFrameId === "string" ? parentFrameId : undefined;
+ };
+ const parentFrameIdOf = (frameId: string): string | undefined => {
+ if (frameParents.has(frameId)) return frameParents.get(frameId);
+ return reportedParentFrameId(iframeInfoByTarget.get(frameId));
+ };
+ const ancestryToPage = (
+ frameId: string,
+ ): { belongs: boolean; depth: number } => {
+ let current: string | undefined = frameId;
+ let depth = 0;
+ const visited = new Set<string>();
+ while (current && !visited.has(current)) {
+ if (current === pageTargetId || current === rootFrameId) {
+ return { belongs: true, depth };
+ }
+ visited.add(current);
+ current = parentFrameIdOf(current);
+ depth += 1;
}
+ return { belongs: false, depth };
};
- visit(pageTargetId);
+ const descendants = iframeInfos
+ .map((info) => ({ info, ancestry: ancestryToPage(info.targetId) }))
+ .filter(({ ancestry }) => ancestry.belongs)
+ .sort((left, right) => left.ancestry.depth - right.ancestry.depth)
+ .map(({ info }) => info);
const liveTargetIds = new Set(
descendants.map((info) => info.targetId as string),
);
+ const allLiveIframeTargetIds = new Set(
+ iframeInfos.map((info) => info.targetId as string),
+ );
const knownDescendants: string[] = [];
const collectKnownDescendants = (parentTargetId: string) => {
for (const childTargetId of childTargets.get(parentTargetId) || []) {
@@ -480,28 +659,74 @@ export async function ensureFrameSessions(pageTargetId: string) {
}
};
collectKnownDescendants(pageTargetId);
- for (const knownTargetId of knownDescendants.reverse()) {
- if (!liveTargetIds.has(knownTargetId)) {
+ for (const knownTargetId of [...knownDescendants].reverse()) {
+ // Target.getTargets and Page.getFrameTree are separate snapshots. A live
+ // target can momentarily be absent from the frame tree during a swap, so
+ // only target disappearance is authoritative enough to discard a session.
+ if (!allLiveIframeTargetIds.has(knownTargetId)) {
clearTargetSessionTree(knownTargetId, { remove: true });
}
}
+ for (const knownTargetId of knownDescendants) {
+ if (
+ allLiveIframeTargetIds.has(knownTargetId) &&
+ !liveTargetIds.has(knownTargetId)
+ ) {
+ const info = iframeInfoByTarget.get(knownTargetId);
+ if (info) {
+ descendants.push(info);
+ liveTargetIds.add(knownTargetId);
+ }
+ }
+ }
+
+ const nearestTargetParent = (info: any): string => {
+ const ancestry = ancestryToPage(info.targetId);
+ if (!ancestry.belongs) {
+ const knownParentTargetId = parentTargets.get(info.targetId);
+ if (knownParentTargetId) return knownParentTargetId;
+ }
+ let current = parentFrameIdOf(info.targetId);
+ const visited = new Set<string>();
+ while (current && !visited.has(current)) {
+ if (current === pageTargetId || current === rootFrameId) {
+ return pageTargetId;
+ }
+ if (liveTargetIds.has(current)) return current;
+ visited.add(current);
+ current = parentFrameIdOf(current);
+ }
+ return pageTargetId;
+ };
+
+ const sessionByTarget = new Map<string, string>([
+ [pageTargetId, pageSessionId],
+ ]);
+ for (const info of descendants) {
+ const sessionId = await ensureSession(info.targetId, remaining());
+ registerTargetParent(info.targetId, nearestTargetParent(info));
+ sessionByTarget.set(info.targetId, sessionId);
+ }
const sessions = new Map<string, string>();
- const frameTree =
- frameTreeResponse?.result?.frameTree || frameTreeResponse?.frameTree;
- const collectSameProcessFrames = (tree: any, isRoot = false) => {
+ const collectFrameSessions = (
+ tree: any,
+ inheritedSessionId: string,
+ isRoot = false,
+ ) => {
const frameId = tree?.frame?.id;
- if (!isRoot && typeof frameId === "string") {
- sessions.set(frameId, pageSessionId);
- }
+ if (typeof frameId !== "string") return;
+ const sessionId = sessionByTarget.get(frameId) || inheritedSessionId;
+ if (!isRoot) sessions.set(frameId, sessionId);
for (const child of tree?.childFrames || []) {
- collectSameProcessFrames(child);
+ collectFrameSessions(child, sessionId);
}
};
- if (frameTree) collectSameProcessFrames(frameTree, true);
+ if (frameTree) collectFrameSessions(frameTree, pageSessionId, true);
for (const info of descendants) {
- registerTargetParent(info.targetId, info.parentId);
- sessions.set(info.targetId, await ensureSession(info.targetId));
+ if (!sessions.has(info.targetId)) {
+ sessions.set(info.targetId, sessionByTarget.get(info.targetId)!);
+ }
}
return sessions;
}
@@ -561,6 +786,64 @@ export function isNetworkDomainEnabled(sessionId) {
: false;
}
+/** Ensure Network events are available on every selected Page/OOPIF session. */
+export async function ensureNetworkTracking(
+ sessionIds: string[],
+ timeoutMs = RESPONSE_TIMEOUT_MS,
+): Promise<void> {
+ const unique = [...new Set(sessionIds.filter(Boolean))];
+ await Promise.all(
+ unique.map((sessionId) =>
+ enableNetworkTrackingForSession(sessionId, true, timeoutMs),
+ ),
+ );
+}
+
+/** Read continuous network state without consuming the public Page event queue. */
+export function networkActivity(sessionIds: string[]): {
+ tracking: boolean;
+ inflight: number;
+ lastActivityAt: number;
+} {
+ let tracking = sessionIds.length > 0;
+ let inflight = 0;
+ let lastActivityAt = 0;
+ for (const sessionId of new Set(sessionIds)) {
+ const targetId = sessionTargets.get(sessionId);
+ const target = targetId ? targetStates.get(targetId) : undefined;
+ if (
+ !target ||
+ target.sessionId !== sessionId ||
+ !target.networkDomainEnabled
+ ) {
+ tracking = false;
+ continue;
+ }
+ inflight += target.inflightNetworkRequests.size;
+ lastActivityAt = Math.max(lastActivityAt, target.lastNetworkActivityAt);
+ }
+ return { tracking, inflight, lastActivityAt };
+}
+
+/** Refresh and return the main and known OOPIF sessions for one Page. */
+export async function pageNetworkSessions(
+ sessionId: string,
+ timeoutMs = RESPONSE_TIMEOUT_MS,
+): Promise<string[]> {
+ const targetId = sessionTargets.get(sessionId);
+ if (!targetId) {
+ throw new Error(
+ "cannot resolve Page network sessions from a detached session",
+ );
+ }
+ const frameSessions = await ensureFrameSessions(targetId, timeoutMs);
+ const currentMainSession = targetStates.get(targetId)?.sessionId;
+ if (!currentMainSession) {
+ throw new Error("Page session was detached while refreshing network state");
+ }
+ return [...new Set([currentMainSession, ...frameSessions.values()])];
+}
+
/**
* Suppress the operating-system file picker and observe the next chooser in
* one Page session. The caller owns the short-lived interception and must
@@ -667,14 +950,14 @@ export function prepareFileChooser(
return interception;
}
-async function enablePageEvents(sessionId) {
+async function enablePageEvents(sessionId, timeoutMs = RESPONSE_TIMEOUT_MS) {
const targetId = sessionId ? sessionTargets.get(sessionId) : undefined;
const target = targetId ? targetStates.get(targetId) : undefined;
if (!target || target.pageEventsEnabled) {
return;
}
try {
- await rawCdp("Page.enable", {}, sessionId);
+ await rawCdp("Page.enable", {}, sessionId, timeoutMs);
target.pageEventsEnabled = true;
} catch {
// Dialog tracking is best-effort. Do not make all helpers fail on targets
@@ -682,6 +965,246 @@ async function enablePageEvents(sessionId) {
}
}
+async function enableNetworkTrackingForSession(
+ sessionId: string,
+ required = false,
+ timeoutMs = RESPONSE_TIMEOUT_MS,
+): Promise<void> {
+ const targetId = sessionId ? sessionTargets.get(sessionId) : undefined;
+ const target = targetId ? targetStates.get(targetId) : undefined;
+ if (!target || target.sessionId !== sessionId) {
+ if (required) {
+ throw new Error(
+ "cannot track network activity for a detached Page session",
+ );
+ }
+ return;
+ }
+ if (target.networkDomainEnabled) return;
+
+ let inflight = target.networkEnableInflight;
+ const reusedInflight = Boolean(inflight);
+ if (!inflight) {
+ inflight = rawCdp("Network.enable", {}, sessionId, timeoutMs).then(() => {
+ // Events and an OOPIF request migration can race ahead of this response.
+ // Network.disable and session replacement already clear stale state, so
+ // enabling must preserve everything observed for the current session.
+ if (target.sessionId === sessionId && !target.networkDomainEnabled) {
+ target.lastNetworkActivityAt = state.now();
+ target.networkDomainEnabled = true;
+ }
+ });
+ target.networkEnableInflight = inflight;
+ void inflight.then(
+ () => {
+ if (target.networkEnableInflight === inflight) {
+ target.networkEnableInflight = null;
+ }
+ },
+ () => {
+ if (target.networkEnableInflight === inflight) {
+ target.networkEnableInflight = null;
+ }
+ },
+ );
+ }
+
+ try {
+ await (reusedInflight
+ ? waitForSharedCdpRequest(
+ inflight,
+ "Network.enable",
+ sessionId,
+ timeoutMs,
+ )
+ : inflight);
+ } catch (error) {
+ if (required) throw error;
+ }
+ if (required && !target.networkDomainEnabled) {
+ throw new Error(
+ "network tracking was interrupted by a detached Page session",
+ );
+ }
+}
+
+async function enableOopifAutoAttach(
+ sessionId: string,
+ timeoutMs = RESPONSE_TIMEOUT_MS,
+): Promise<void> {
+ const targetId = sessionId ? sessionTargets.get(sessionId) : undefined;
+ const target = targetId ? targetStates.get(targetId) : undefined;
+ if (!target || target.sessionId !== sessionId || target.autoAttachEnabled) {
+ return;
+ }
+
+ let inflight = target.autoAttachInflight;
+ const reusedInflight = Boolean(inflight);
+ if (!inflight) {
+ inflight = rawCdp(
+ "Target.setAutoAttach",
+ OOPIF_AUTO_ATTACH_PARAMS,
+ sessionId,
+ timeoutMs,
+ ).then(() => {
+ if (target.sessionId === sessionId) target.autoAttachEnabled = true;
+ });
+ target.autoAttachInflight = inflight;
+ void inflight.then(
+ () => {
+ if (target.autoAttachInflight === inflight) {
+ target.autoAttachInflight = null;
+ }
+ },
+ () => {
+ if (target.autoAttachInflight === inflight) {
+ target.autoAttachInflight = null;
+ }
+ },
+ );
+ }
+ try {
+ await (reusedInflight
+ ? waitForSharedCdpRequest(
+ inflight,
+ "Target.setAutoAttach",
+ sessionId,
+ timeoutMs,
+ )
+ : inflight);
+ } catch {
+ // Page APIs still work on bridges without auto-attach. Frame discovery can
+ // attach explicitly later, but exact network-idle tracking needs support.
+ }
+}
+
+/** Bound one caller's wait without cancelling the shared CDP request. */
+function waitForSharedCdpRequest(
+ request: Promise<void>,
+ method: string,
+ sessionId: string,
+ timeoutMs: number,
+): Promise<void> {
+ const callerTimeoutMs = Math.max(1, timeoutMs);
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ reject(new CdpRequestTimeoutError(method, callerTimeoutMs, sessionId));
+ }, callerTimeoutMs);
+ request.then(
+ () => {
+ clearTimeout(timer);
+ resolve();
+ },
+ (error) => {
+ clearTimeout(timer);
+ reject(error);
+ },
+ );
+ });
+}
+
+function initializeAutoAttachedTarget(
+ sessionId: string,
+ waitingForDebugger: boolean,
+): void {
+ // 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.
+ const pageEvents = enablePageEvents(sessionId);
+ const networkEvents = enableNetworkTrackingForSession(sessionId);
+ const nestedFrames = enableOopifAutoAttach(sessionId);
+ const resume = waitingForDebugger
+ ? rawCdp("Runtime.runIfWaitingForDebugger", {}, sessionId).catch(() => {})
+ : Promise.resolve();
+ void Promise.allSettled([pageEvents, networkEvents, nestedFrames, resume]);
+}
+
+function finishNetworkRequest(targetId: string, requestId: string): void {
+ const now = state.now();
+ const rootTargetId = pageRootTargetId(targetId);
+ for (const pageTargetId of pageTreeTargetIds(rootTargetId)) {
+ const pageTarget = targetStates.get(pageTargetId);
+ if (!pageTarget) continue;
+ if (pageTarget.inflightNetworkRequests.delete(requestId)) {
+ pageTarget.lastNetworkActivityAt = now;
+ }
+ }
+}
+
+function isIgnoredFaviconRequest(targetId: string, requestId: string): boolean {
+ const rootTargetId = pageRootTargetId(targetId);
+ return pageTreeTargetIds(rootTargetId).some((pageTargetId) =>
+ targetStates.get(pageTargetId)?.ignoredFaviconRequestIds.has(requestId),
+ );
+}
+
+function clearIgnoredFaviconRequest(
+ targetId: string,
+ requestId: string,
+): boolean {
+ const rootTargetId = pageRootTargetId(targetId);
+ let deleted = false;
+ for (const pageTargetId of pageTreeTargetIds(rootTargetId)) {
+ deleted =
+ Boolean(
+ targetStates
+ .get(pageTargetId)
+ ?.ignoredFaviconRequestIds.delete(requestId),
+ ) || deleted;
+ }
+ return deleted;
+}
+
+function recordNetworkEvent(targetId: string, target, data): void {
+ // A response to Network.disable can be followed by a queued terminal event.
+ // Ignore it once tracking is off, while still accepting events that race the
+ // response to our own Network.enable request.
+ if (!target.networkDomainEnabled && !target.networkEnableInflight) return;
+ const requestId = data?.params?.requestId;
+ if (typeof requestId !== "string" || requestId.length === 0) return;
+
+ if (data.method === "Network.requestWillBeSent") {
+ const url = data.params?.request?.url;
+ // Chromium can omit the terminal event for its automatic favicon request.
+ // Playwright excludes favicons from network-idle accounting for the same
+ // reason, so they must never leave a permanent in-flight entry here.
+ if (
+ (typeof url === "string" && url.endsWith("/favicon.ico")) ||
+ isIgnoredFaviconRequest(targetId, requestId)
+ ) {
+ target.ignoredFaviconRequestIds.add(requestId);
+ if (target.inflightNetworkRequests.delete(requestId)) {
+ target.lastNetworkActivityAt = state.now();
+ }
+ return;
+ }
+ target.networkDomainEnabled = true;
+ target.inflightNetworkRequests.set(requestId, {
+ requestId,
+ ...(typeof data.params?.frameId === "string"
+ ? { frameId: data.params.frameId }
+ : {}),
+ ...(typeof data.params?.loaderId === "string"
+ ? { loaderId: data.params.loaderId }
+ : {}),
+ ...(typeof data.params?.type === "string"
+ ? { type: data.params.type }
+ : {}),
+ });
+ target.lastNetworkActivityAt = state.now();
+ return;
+ }
+ if (
+ data.method === "Network.loadingFinished" ||
+ data.method === "Network.loadingFailed"
+ ) {
+ target.networkDomainEnabled = true;
+ if (clearIgnoredFaviconRequest(targetId, requestId)) return;
+ finishNetworkRequest(targetId, requestId);
+ target.lastNetworkActivityAt = state.now();
+ }
+}
+
// Local send failures for ego.sendCDPMessage() arrive here instead of as a CDP
// response. The callback carries no request id, so task-level failures reject
// every pending request. User-control failures first probe the native task state:
@@ -802,11 +1325,12 @@ function handleMessage(message) {
data.method === "Target.detachedFromTarget" ||
data.method === "Target.targetDestroyed"
) {
- const sessionId = data.params?.sessionId || data.sessionId;
const targetId =
- (sessionId ? sessionTargets.get(sessionId) : undefined) ||
data.params?.targetId ||
- data.params?.targetInfo?.targetId;
+ data.params?.targetInfo?.targetId ||
+ (data.params?.sessionId
+ ? sessionTargets.get(data.params.sessionId)
+ : undefined);
if (targetId) {
clearTargetSessionTree(targetId, {
remove: data.method === "Target.targetDestroyed",
@@ -815,15 +1339,40 @@ function handleMessage(message) {
} else if (data.method === "Target.attachedToTarget") {
const sessionId = data.params?.sessionId;
const targetId = data.params?.targetInfo?.targetId;
- const parentTargetId = data.params?.targetInfo?.parentId;
- if (targetId && parentTargetId) {
+ const targetType = data.params?.targetInfo?.type;
+ const reportedParentFrameId =
+ data.params?.targetInfo?.parentFrameId ||
+ data.params?.targetInfo?.parentId;
+ // Target.attachedToTarget is emitted on the nearest owning target session.
+ // Prefer that target edge over parentFrameId, which may name a same-process
+ // frame and is not itself a debuggable target.
+ const sourceTargetId = data.sessionId
+ ? sessionTargets.get(data.sessionId)
+ : undefined;
+ const parentTargetId = sourceTargetId || reportedParentFrameId;
+ if (sessionId && targetId) registerSession(targetId, sessionId);
+ if (targetId && parentTargetId && targetId !== parentTargetId) {
registerTargetParent(targetId, parentTargetId);
}
- if (sessionId && targetId) registerSession(targetId, sessionId);
+ if (sessionId && targetType === "iframe") {
+ initializeAutoAttachedTarget(
+ sessionId,
+ data.params?.waitingForDebugger === true,
+ );
+ } else if (sessionId && data.params?.waitingForDebugger === true) {
+ // A foreign auto-attach configuration may still deliver other related
+ // target types. Never leave an unrelated worker paused by this runtime.
+ void rawCdp("Runtime.runIfWaitingForDebugger", {}, sessionId).catch(
+ () => {},
+ );
+ }
}
const sessionId = data.sessionId;
const targetId = sessionId ? sessionTargets.get(sessionId) : undefined;
const target = targetId ? targetStates.get(targetId) : undefined;
+ if (target && typeof data.method === "string") {
+ recordNetworkEvent(targetId, target, data);
+ }
if (data.method === "Page.javascriptDialogOpening") {
if (target) {
target.pendingDialog = data.params || {};
diff --git a/package/ego-browser/src/driver/action-target.test.mjs b/package/ego-browser/src/driver/action-target.test.mjs
new file mode 100644
index 0000000..ff61389
--- /dev/null
+++ b/package/ego-browser/src/driver/action-target.test.mjs
@@ -0,0 +1,135 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { ACTION_TARGET_STATE_HELPERS } from "../../dist/src/driver/action-target.js";
+
+function stateHelpers() {
+ return Function(`
+ ${ACTION_TARGET_STATE_HELPERS}
+ return { isActionTargetDisabled };
+ `)();
+}
+
+function element({
+ tagName = "DIV",
+ parentElement = null,
+ assignedSlot = null,
+ rootHost = null,
+ disabled = false,
+ ariaDisabled,
+ role,
+ href = false,
+ contentEditable = false,
+} = {}) {
+ return {
+ tagName,
+ parentElement,
+ assignedSlot,
+ disabled,
+ isContentEditable: contentEditable,
+ getAttribute(name) {
+ if (name === "aria-disabled") return ariaDisabled ?? null;
+ if (name === "role") return role ?? null;
+ return null;
+ },
+ hasAttribute(name) {
+ return name === "href" ? href : false;
+ },
+ getRootNode() {
+ return rootHost ? { nodeType: 11, host: rootHost } : { nodeType: 9 };
+ },
+ matches(selector) {
+ assert.equal(selector, ":disabled");
+ return disabled;
+ },
+ };
+}
+
+test("action enabled state follows native controls and composed ARIA ancestry", () => {
+ const { isActionTargetDisabled } = stateHelpers();
+
+ const disabledButton = element({ tagName: "BUTTON", disabled: true });
+ const nestedSpan = element({
+ tagName: "SPAN",
+ parentElement: disabledButton,
+ });
+ assert.equal(isActionTargetDisabled(nestedSpan), true);
+
+ const ariaContainer = element({ ariaDisabled: " TRUE " });
+ const inherited = element({
+ tagName: "BUTTON",
+ parentElement: ariaContainer,
+ });
+ assert.equal(isActionTargetDisabled(inherited), true);
+
+ const overridden = element({
+ tagName: "BUTTON",
+ parentElement: ariaContainer,
+ ariaDisabled: "false",
+ });
+ assert.equal(isActionTargetDisabled(overridden), false);
+
+ const nativeWins = element({
+ tagName: "BUTTON",
+ disabled: true,
+ ariaDisabled: "false",
+ });
+ assert.equal(isActionTargetDisabled(nativeWins), true);
+});
+
+test("action enabled state crosses shadow hosts and assigned slots", () => {
+ const { isActionTargetDisabled } = stateHelpers();
+
+ const host = element({ ariaDisabled: "true" });
+ const shadowChild = element({ tagName: "BUTTON", rootHost: host });
+ assert.equal(isActionTargetDisabled(shadowChild), true);
+
+ const slot = element({ tagName: "SLOT", rootHost: host });
+ const slottedChild = element({ tagName: "BUTTON", assignedSlot: slot });
+ assert.equal(isActionTargetDisabled(slottedChild), true);
+
+ const slottedOverride = element({
+ tagName: "BUTTON",
+ assignedSlot: slot,
+ ariaDisabled: "false",
+ });
+ assert.equal(isActionTargetDisabled(slottedOverride), false);
+});
+
+test("action enabled state uses the nearest interactive owner for ARIA", () => {
+ const { isActionTargetDisabled } = stateHelpers();
+
+ const disabledButton = element({
+ tagName: "BUTTON",
+ ariaDisabled: "true",
+ });
+ const unsupportedOverride = element({
+ tagName: "SPAN",
+ parentElement: disabledButton,
+ ariaDisabled: "false",
+ });
+ assert.equal(
+ isActionTargetDisabled(unsupportedOverride),
+ true,
+ "aria-disabled=false on button content does not override the button",
+ );
+
+ const innerButton = element({
+ parentElement: disabledButton,
+ role: "button",
+ ariaDisabled: "false",
+ });
+ const innerText = element({ tagName: "SPAN", parentElement: innerButton });
+ assert.equal(
+ isActionTargetDisabled(innerText),
+ false,
+ "a nested interactive owner can explicitly override its ancestor",
+ );
+
+ const unsupportedTarget = element({ ariaDisabled: "true" });
+ assert.equal(
+ isActionTargetDisabled(unsupportedTarget),
+ false,
+ "aria-disabled does not disable a target without a supporting role",
+ );
+});
diff --git a/package/ego-browser/src/driver/action-target.ts b/package/ego-browser/src/driver/action-target.ts
index 249698f..bad7d6e 100644
--- a/package/ego-browser/src/driver/action-target.ts
+++ b/package/ego-browser/src/driver/action-target.ts
@@ -45,9 +45,91 @@ export const COMPOSED_TREE_HELPERS = `
}
`;
+const ACTION_TARGET_STATE_FUNCTIONS = `
+ const nativeActionControlTags = new Set([
+ "BUTTON", "INPUT", "SELECT", "TEXTAREA", "OPTION", "OPTGROUP"
+ ]);
+ const ariaDisabledActionRoles = new Set([
+ "application", "button", "composite", "gridcell", "group", "input",
+ "link", "menuitem", "scrollbar", "separator", "tab", "checkbox",
+ "columnheader", "combobox", "grid", "listbox", "menu", "menubar",
+ "menuitemcheckbox", "menuitemradio", "option", "radio", "radiogroup",
+ "row", "rowheader", "searchbox", "select", "slider", "spinbutton",
+ "switch", "tablist", "textbox", "toolbar", "tree", "treegrid",
+ "treeitem"
+ ]);
+ function actionStateRole(element) {
+ const explicit = String(element?.getAttribute?.("role") || "")
+ .trim().toLowerCase().split(/\\s+/)[0];
+ if (explicit) return explicit;
+ const tag = String(element?.tagName || "").toUpperCase();
+ if (tag === "BUTTON" || tag === "SUMMARY") return "button";
+ if (tag === "INPUT") return "input";
+ if (tag === "SELECT") return "select";
+ if (tag === "TEXTAREA" || element?.isContentEditable) return "textbox";
+ if (tag === "OPTION") return "option";
+ if (tag === "OPTGROUP" || tag === "FIELDSET") return "group";
+ if (
+ (tag === "A" || tag === "AREA") &&
+ element?.hasAttribute?.("href")
+ ) return "link";
+ return "";
+ }
+ function supportsAriaDisabled(element) {
+ return ariaDisabledActionRoles.has(actionStateRole(element));
+ }
+ function actionStateOwner(element) {
+ let current = element;
+ while (current) {
+ if (supportsAriaDisabled(current)) return current;
+ current = composedParent(current);
+ }
+ return null;
+ }
+ function isNativelyDisabledForAction(element) {
+ let current = element;
+ while (current) {
+ const tag = String(current.tagName || "").toUpperCase();
+ if (
+ nativeActionControlTags.has(tag) &&
+ (current.disabled === true || current.matches?.(":disabled"))
+ ) {
+ return true;
+ }
+ current = composedParent(current);
+ }
+ return false;
+ }
+ function hasInheritedAriaDisabled(element) {
+ let current = actionStateOwner(element);
+ while (current) {
+ const value = String(
+ current.getAttribute?.("aria-disabled") ?? ""
+ ).trim().toLowerCase();
+ if (value === "true") return true;
+ if (value === "false") return false;
+ current = composedParent(current);
+ }
+ return false;
+ }
+ function isActionTargetDisabled(element) {
+ return (
+ isNativelyDisabledForAction(element) ||
+ hasInheritedAriaDisabled(element)
+ );
+ }
+`;
+
+/** Browser-side enabled semantics shared by resolution and final input checks. */
+export const ACTION_TARGET_STATE_HELPERS = `
+ ${COMPOSED_PARENT_HELPER}
+ ${ACTION_TARGET_STATE_FUNCTIONS}
+`;
+
/** Editing semantics layered on top of the shared composed-tree traversal. */
export const EDIT_ACTION_TARGET_HELPERS = `
${COMPOSED_TREE_HELPERS}
+ ${ACTION_TARGET_STATE_FUNCTIONS}
function isExplicitContentEditable(element) {
return Boolean(
element?.hasAttribute?.("contenteditable") &&
@@ -68,14 +150,22 @@ export const EDIT_ACTION_TARGET_HELPERS = `
}
function isEditableFocusTarget(element) {
const tag = String(element?.tagName || "").toUpperCase();
- if (isFillableActionTarget(element)) return !element.disabled;
- if (tag === "SELECT") return !element.disabled;
- return new Set(["textbox", "searchbox", "combobox", "spinbutton"]).has(
+ const editableRole = new Set([
+ "textbox", "searchbox", "combobox", "spinbutton"
+ ]).has(
String(element?.getAttribute?.("role") || "").toLowerCase()
);
+ return (
+ (isFillableActionTarget(element) || tag === "SELECT" || editableRole) &&
+ !isActionTargetDisabled(element)
+ );
}
function isStrongFocusTarget(element) {
- if (!element?.isConnected || element.disabled || element.closest?.("[inert]")) {
+ if (
+ !element?.isConnected ||
+ isActionTargetDisabled(element) ||
+ element.closest?.("[inert]")
+ ) {
return false;
}
if (isEditableFocusTarget(element)) return true;
@@ -99,14 +189,8 @@ export const EDIT_ACTION_TARGET_HELPERS = `
// Keeping one composed-tree definition prevents the two stages from disagreeing
// about shadow descendants, interactive ancestors, or modal blockers.
export const HIT_TARGET_HELPERS = `
- ${COMPOSED_PARENT_HELPER}
+ ${ACTION_TARGET_STATE_HELPERS}
function isExplicitInteractiveElement(element) {
- if (
- element?.matches?.(":disabled") ||
- element?.getAttribute?.("aria-disabled") === "true"
- ) {
- return false;
- }
const tag = String(element?.tagName || "").toUpperCase();
if (["BUTTON", "INPUT", "SELECT", "TEXTAREA", "OPTION", "SUMMARY", "LABEL"].includes(tag)) {
return true;
diff --git a/package/ego-browser/src/driver/nav.test.mjs b/package/ego-browser/src/driver/nav.test.mjs
index 73d03c2..58a643a 100644
--- a/package/ego-browser/src/driver/nav.test.mjs
+++ b/package/ego-browser/src/driver/nav.test.mjs
@@ -138,6 +138,25 @@ test("newTab throws when the binding returns no targetId", async () => {
);
});
+test("newTab makes the created target the preferred Page", async () => {
+ await withEgo(
+ {
+ async createTab() {
+ return { targetId: "target-new" };
+ },
+ },
+ async () => {
+ const restore = setOverrides({ preferredTargetId: "target-old" });
+ try {
+ assert.equal(await newTab("https://example.com/new"), "target-new");
+ assert.equal(state.preferredTargetId, "target-new");
+ } finally {
+ restore();
+ }
+ },
+ );
+});
+
test("closeTab closes an explicit target and returns its id", async () => {
const calls = [];
const restore = setOverrides({
@@ -204,15 +223,28 @@ test("closeTab closes the current tab and invalidates matching session state", a
]);
});
-test("browser runtime enables Page events and tracks pending native dialogs", async () => {
+test("browser runtime continuously enables Page and Network events", async () => {
await withCdpRuntime(async ({ runtime, sent }) => {
await browserCdp("Runtime.evaluate", { expression: "document.title" });
assert.deepEqual(
sent.map((request) => request.method),
- ["Target.attachToTarget", "Page.enable", "Runtime.evaluate"],
+ [
+ "Target.attachToTarget",
+ "Page.enable",
+ "Network.enable",
+ "Target.setAutoAttach",
+ "Runtime.evaluate",
+ ],
);
assert.equal(sent[1].sessionId, "session-1");
+ assert.equal(sent[2].sessionId, "session-1");
+ assert.deepEqual(sent[3].params, {
+ autoAttach: true,
+ waitForDebuggerOnStart: true,
+ flatten: true,
+ filter: [{ type: "iframe", exclude: false }, { exclude: true }],
+ });
runtime.emit("Page.javascriptDialogOpening", {
type: "alert",
diff --git a/package/ego-browser/src/driver/nav.ts b/package/ego-browser/src/driver/nav.ts
index 2dcbad3..7a61fa1 100644
--- a/package/ego-browser/src/driver/nav.ts
+++ b/package/ego-browser/src/driver/nav.ts
@@ -160,6 +160,9 @@ export async function newTab(url = "about:blank") {
if (!result.targetId) {
throw new Error("newTab returned no targetId");
}
+ // Native createTab activates the new tab. Keep the harness route in sync so
+ // the next target-less helper cannot remain attached to the previous Page.
+ setPreferredTarget(result.targetId);
return result.targetId;
}
diff --git a/package/ego-browser/src/driver/page-actions.ts b/package/ego-browser/src/driver/page-actions.ts
index a58b516..5514cd4 100644
--- a/package/ego-browser/src/driver/page-actions.ts
+++ b/package/ego-browser/src/driver/page-actions.ts
@@ -5,6 +5,7 @@ import {
} from "../element-resolver.js";
import { RefMap } from "../ref-map.js";
import {
+ ACTION_TARGET_STATE_HELPERS,
EDIT_ACTION_TARGET_HELPERS,
HIT_TARGET_HELPERS,
} from "./action-target.js";
@@ -37,13 +38,21 @@ export type PageFillOptions = {
timeout?: number;
};
+export type PageSelectOption =
+ | string
+ | {
+ value?: string;
+ label?: string;
+ index?: number;
+ };
+
/** Select option values from one visible, enabled select element. */
export async function selectOptionInPage(
services: PageActionServices,
sessionId: string,
refMap: RefMap,
selector: string,
- values: string[],
+ choices: PageSelectOption[],
iframeSessions = new Map<string, string>(),
): Promise<string[]> {
assertPageSelector(selector);
@@ -53,9 +62,9 @@ export async function selectOptionInPage(
refMap,
selector,
iframeSessions,
- { strict: true, actionability: "visible" },
+ { strict: true, actionability: "enabled" },
);
- const source = `function selectOptionsForAction(values) {
+ const source = `function selectOptionsForAction(choices) {
${EDIT_ACTION_TARGET_HELPERS}
let select = String(this.tagName || "").toUpperCase() === "SELECT"
? this
@@ -81,20 +90,47 @@ export async function selectOptionInPage(
!view || rect.width <= 0 || rect.height <= 0 ||
style?.display === "none" || style?.visibility === "hidden"
) return { error: "element is not visible" };
- if (select.disabled) return { error: "element is disabled" };
- if (!select.multiple && values.length > 1) {
- return { error: "multiple values require a multiple select" };
- }
+ if (isActionTargetDisabled(select)) return { error: "element is disabled" };
const options = Array.from(select.options);
const selected = [];
const selectedOptions = [];
- for (const value of values) {
- const option = options.find((candidate) => candidate.value === value);
- if (!option) return { error: 'option value "' + value + '" was not found' };
- if (option.disabled) return { error: 'option value "' + value + '" is disabled' };
+ let remaining = choices.slice();
+ const matches = (choice, candidate, index) =>
+ typeof choice === "string"
+ ? candidate.value === choice || candidate.label === choice
+ : (choice.value === undefined || candidate.value === choice.value) &&
+ (choice.label === undefined || candidate.label === choice.label) &&
+ (choice.index === undefined || index === choice.index);
+ for (let index = 0; index < options.length; index += 1) {
+ const option = options[index];
+ const matchingChoice = remaining.find((choice) =>
+ matches(choice, option, index)
+ );
+ if (matchingChoice === undefined) continue;
selectedOptions.push(option);
+ if (!select.multiple) {
+ remaining = [];
+ break;
+ }
+ remaining = remaining.filter(
+ (choice) => !matches(choice, option, index),
+ );
+ }
+ if (remaining.length > 0) {
+ const available = options
+ .map((candidate, index) =>
+ index + ': value=' + JSON.stringify(candidate.value) +
+ ', label=' + JSON.stringify(candidate.label),
+ )
+ .join('; ');
+ return {
+ error:
+ 'option ' + JSON.stringify(remaining[0]) +
+ ' was not found; available options: ' + (available || '(none)'),
+ };
}
- for (const option of options) option.selected = selectedOptions.includes(option);
+ for (const option of options) option.selected = false;
+ for (const option of selectedOptions) option.selected = true;
for (const option of select.selectedOptions) selected.push(option.value);
select.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
select.dispatchEvent(new Event("change", { bubbles: true }));
@@ -106,7 +142,7 @@ export async function selectOptionInPage(
{
functionDeclaration: source,
objectId: resolved.objectId,
- arguments: [{ value: values }],
+ arguments: [{ value: choices }],
returnByValue: true,
awaitPromise: false,
},
@@ -119,7 +155,8 @@ export async function selectOptionInPage(
"element is not visible",
"element is disabled",
]);
- throw transient.has(result.error)
+ throw transient.has(result.error) ||
+ result.error.includes(" was not found;")
? new ElementResolutionError(
`page.selectOption failed: ${result.error}`,
"transient",
@@ -199,7 +236,10 @@ export async function clickInPage(
refMap,
selector,
iframeSessions,
- { strict: true, actionability: "pointer" },
+ {
+ strict: true,
+ actionability: options.force ? "enabled" : "pointer-enabled",
+ },
);
try {
let point = await resolveElementPoint(
@@ -210,7 +250,6 @@ export async function clickInPage(
target.frameId,
"page.click",
options.force,
- true,
);
const buttons = pressedButtons(button);
await dispatchMouseEvent(services, target.sessionId, {
@@ -232,6 +271,12 @@ export async function clickInPage(
point.local,
);
point = { ...pagePoint, local: point.local };
+ await assertElementEnabled(
+ services,
+ target.sessionId,
+ target.objectId,
+ "page.click",
+ );
await dispatchMouseEvent(services, target.sessionId, {
type: "mouseMoved",
x: point.x,
@@ -245,7 +290,16 @@ export async function clickInPage(
// Moving the pointer or completing an earlier click can change layout.
// Recheck before every press so hover-created overlays fail closed.
// A same-process iframe must keep its native move/press sequence
- // contiguous; the initial check already covered its local hit target.
+ // contiguous; its state was checked immediately before that gesture's
+ // final move.
+ if (!target.frameId || count > 1) {
+ await assertElementEnabled(
+ services,
+ target.sessionId,
+ target.objectId,
+ "page.click",
+ );
+ }
if (!options.force && !target.frameId) {
await assertElementReceivesPointerEvents(
services,
@@ -310,7 +364,7 @@ export async function fillInPage(
refMap,
selector,
iframeSessions,
- { strict: true, actionability: "visible" },
+ { strict: true, actionability: "enabled" },
);
let actionObjectId: string | undefined;
try {
@@ -320,6 +374,7 @@ export async function fillInPage(
resolved.objectId,
);
const preparationSource = `function fillPreparation(value, clearFirst) {
+ ${ACTION_TARGET_STATE_HELPERS}
if (!this.isConnected) return { error: "element is not connected" };
const visibleCursorPoint = () => {
const rect = this.getBoundingClientRect();
@@ -343,7 +398,7 @@ export async function fillInPage(
!view || rect.width <= 0 || rect.height <= 0 ||
style?.visibility === "hidden" || style?.display === "none"
) return { error: "element is not visible" };
- if (this.disabled) return { error: "element is disabled" };
+ if (isActionTargetDisabled(this)) return { error: "element is disabled" };
if (this.readOnly) return { error: "element is read only" };
if (tag === "input") {
@@ -359,6 +414,7 @@ export async function fillInPage(
if (directTypes.has(type)) {
const nextValue = value.trim();
this.focus();
+ if (isActionTargetDisabled(this)) return { error: "element is disabled" };
this.value = nextValue;
if (this.value !== nextValue) return { error: "malformed value" };
this.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
@@ -370,6 +426,7 @@ export async function fillInPage(
}
this.focus();
+ if (isActionTargetDisabled(this)) return { error: "element is disabled" };
const cursorPoint = visibleCursorPoint();
const kind = this.isContentEditable ? "contenteditable" : tag;
const details = {
@@ -423,6 +480,12 @@ export async function fillInPage(
throw new Error("page.fill received an invalid preparation result");
}
+ await assertElementEnabled(
+ services,
+ resolved.sessionId,
+ actionObjectId,
+ "page.fill",
+ );
await dispatchFillInput(services, resolved.sessionId, value, clearFirst);
let outcome = await verifyFillOutcome(
services,
@@ -457,6 +520,12 @@ export async function fillInPage(
if (result?.status !== "needsinput") {
throw new Error("page.fill received an invalid preparation result");
}
+ await assertElementEnabled(
+ services,
+ resolved.sessionId,
+ actionObjectId,
+ "page.fill",
+ );
await dispatchFillInput(services, resolved.sessionId, value, clearFirst);
outcome = await verifyFillOutcome(
services,
@@ -544,7 +613,7 @@ export async function focusInPage(
refMap,
selector,
iframeSessions,
- { strict: true, actionability: "visible" },
+ { strict: true, actionability: "enabled" },
);
const source = `function focusElementForAction() {
if (!this.isConnected) return { error: "element is not connected" };
@@ -800,7 +869,6 @@ async function clickResolvedElement(
frameId,
"page.fill",
false,
- true,
);
await assertElementReceivesPointerEvents(
services,
@@ -822,6 +890,17 @@ async function clickResolvedElement(
buttons: 0,
modifiers: 0,
});
+ await assertElementEnabled(services, sessionId, objectId, "page.fill");
+ if (frameId) {
+ await dispatchMouseEvent(services, sessionId, {
+ type: "mouseMoved",
+ x: point.x,
+ y: point.y,
+ button: "none",
+ buttons: 0,
+ modifiers: 0,
+ });
+ }
await dispatchMouseEvent(services, sessionId, {
type: "mousePressed",
x: point.x,
@@ -898,7 +977,10 @@ export async function hoverInPage(
refMap,
selector,
iframeSessions,
- { strict: true, actionability: "pointer" },
+ {
+ strict: true,
+ actionability: options.force ? "visible" : "pointer",
+ },
);
try {
const point = await resolveElementPoint(
@@ -942,7 +1024,10 @@ export async function dragAndDropInPage(
refMap,
sourceSelector,
iframeSessions,
- { strict: true, actionability: "pointer" },
+ {
+ strict: true,
+ actionability: options.force ? "visible" : "pointer",
+ },
);
let target;
try {
@@ -952,7 +1037,10 @@ export async function dragAndDropInPage(
refMap,
targetSelector,
iframeSessions,
- { strict: true, actionability: "pointer" },
+ {
+ strict: true,
+ actionability: options.force ? "visible" : "pointer",
+ },
);
const sourcePoint = await resolveElementPoint(
services,
@@ -1146,7 +1234,6 @@ async function resolveElementPoint(
frameId?: string,
actionName = "page.click",
force = false,
- checkEnabled = false,
): Promise<{ x: number; y: number; local: { x: number; y: number } }> {
if (
position !== undefined &&
@@ -1183,11 +1270,6 @@ async function resolveElementPoint(
) {
return { error: "element is not visible in the viewport" };
}
- if (${checkEnabled ? "true" : "false"}) {
- const disabled = this.matches?.(":disabled") ||
- this.closest?.('[aria-disabled="true"]');
- if (disabled) return { error: "element is disabled" };
- }
const firstRect = { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
await new Promise((resolve) => {
let settled = false;
@@ -1315,6 +1397,38 @@ async function assertElementReceivesPointerEvents(
}
}
+async function assertElementEnabled(
+ services: PageActionServices,
+ sessionId: string,
+ objectId: string,
+ actionName: string,
+): Promise<void> {
+ const expression = `function() {
+ ${ACTION_TARGET_STATE_HELPERS}
+ if (!this.isConnected) return { error: "element is not connected" };
+ return isActionTargetDisabled(this)
+ ? { error: "element is disabled" }
+ : { ok: true };
+ }`;
+ const response = await services.cdp(
+ "Runtime.callFunctionOn",
+ {
+ functionDeclaration: expression,
+ objectId,
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ sessionId,
+ );
+ const result = runtimeValue(response, expression);
+ if (typeof result?.error === "string") {
+ throw new ElementResolutionError(
+ `${actionName} failed: ${result.error}`,
+ "transient",
+ );
+ }
+}
+
function fillPreparationError(message: string) {
const transient = new Set([
"element is not connected",
diff --git a/package/ego-browser/src/driver/page-keyboard.ts b/package/ego-browser/src/driver/page-keyboard.ts
index 503463a..0d8f91e 100644
--- a/package/ego-browser/src/driver/page-keyboard.ts
+++ b/package/ego-browser/src/driver/page-keyboard.ts
@@ -298,7 +298,16 @@ function resolveSmartModifier(
function keyDefinitionForString(input: string, shift: boolean): KeyDefinition {
const definition = keyboardLayout.get(input);
- if (!definition) throw new Error(`Unknown key: ${JSON.stringify(input)}`);
+ if (!definition) {
+ const arrow = new Map([
+ ["Left", "ArrowLeft"],
+ ["Right", "ArrowRight"],
+ ["Up", "ArrowUp"],
+ ["Down", "ArrowDown"],
+ ]).get(input);
+ const hint = arrow ? `. Use ${JSON.stringify(arrow)}` : "";
+ throw new Error(`Unknown key: ${JSON.stringify(input)}${hint}`);
+ }
return shift && definition.shifted ? definition.shifted : definition;
}
diff --git a/package/ego-browser/src/driver/page-waits.test.mjs b/package/ego-browser/src/driver/page-waits.test.mjs
index 8db14da..5727292 100644
--- a/package/ego-browser/src/driver/page-waits.test.mjs
+++ b/package/ego-browser/src/driver/page-waits.test.mjs
@@ -1,7 +1,10 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { waitForURLInPage } from "../../dist/src/driver/page-waits.js";
+import {
+ waitForLoadStateInPage,
+ waitForURLInPage,
+} from "../../dist/src/driver/page-waits.js";
test("waitForURLInPage recovers from a transient execution-context change", async () => {
let now = 0;
@@ -44,3 +47,114 @@ test("waitForURLInPage recovers from a transient execution-context change", asyn
),
);
});
+
+test("document load waits do not sleep past the budget after a slow probe", async () => {
+ let now = 0;
+ let calls = 0;
+ const services = {
+ async cdp(_method, _params, _sessionId, timeoutMs) {
+ calls += 1;
+ if (calls === 1) {
+ assert.equal(timeoutMs, 100);
+ now = 99;
+ } else {
+ assert.equal(timeoutMs, 1);
+ }
+ return { result: { value: "loading" } };
+ },
+ now: () => now,
+ async sleep(ms) {
+ now += ms;
+ },
+ };
+
+ await assert.rejects(
+ () =>
+ waitForLoadStateInPage(services, "session:page", "load", {
+ timeout: 100,
+ }),
+ /page\.waitForLoadState\(load\) timed out after 100ms/,
+ );
+
+ assert.equal(now, 100);
+});
+
+test("network-idle discovery stays within the Page wait timeout", async () => {
+ let discoveryTimeout;
+ const services = {
+ async pageNetworkSessions(sessionId, timeoutMs) {
+ assert.equal(sessionId, "session:page");
+ discoveryTimeout = timeoutMs;
+ return [sessionId];
+ },
+ async ensureNetworkTracking() {},
+ networkActivity() {
+ return { tracking: true, inflight: 0, lastActivityAt: -1_000 };
+ },
+ now: () => 0,
+ async sleep() {},
+ };
+
+ await waitForLoadStateInPage(services, "session:page", "networkidle", {
+ timeout: 123,
+ idleMs: 10,
+ });
+
+ assert.equal(discoveryTimeout, 123);
+});
+
+test("network-idle gives tracking only the budget left after discovery", async () => {
+ let now = 0;
+ let trackingTimeout;
+ const services = {
+ async pageNetworkSessions(_sessionId, timeoutMs) {
+ assert.equal(timeoutMs, 100);
+ now = 90;
+ return ["session:page"];
+ },
+ async ensureNetworkTracking(_sessionIds, timeoutMs) {
+ trackingTimeout = timeoutMs;
+ },
+ networkActivity() {
+ return { tracking: true, inflight: 0, lastActivityAt: -1_000 };
+ },
+ now: () => now,
+ async sleep() {},
+ };
+
+ await waitForLoadStateInPage(services, "session:page", "networkidle", {
+ timeout: 100,
+ idleMs: 10,
+ });
+
+ assert.equal(trackingTimeout, 10);
+});
+
+test("network-idle reports its public timeout when discovery exhausts the budget", async () => {
+ let now = 0;
+ const services = {
+ async pageNetworkSessions() {
+ now = 50;
+ const error = new Error("CDP request timed out: Page.getFrameTree");
+ error.code = "EGO_CDP_REQUEST_TIMEOUT";
+ throw error;
+ },
+ async ensureNetworkTracking() {},
+ networkActivity() {
+ throw new Error(
+ "network activity must not be read after discovery fails",
+ );
+ },
+ now: () => now,
+ async sleep() {},
+ };
+
+ await assert.rejects(
+ () =>
+ waitForLoadStateInPage(services, "session:page", "networkidle", {
+ timeout: 50,
+ idleMs: 10,
+ }),
+ /page\.waitForLoadState\(networkidle\) timed out after 50ms/,
+ );
+});
diff --git a/package/ego-browser/src/driver/page-waits.ts b/package/ego-browser/src/driver/page-waits.ts
index 618f11f..dcee285 100644
--- a/package/ego-browser/src/driver/page-waits.ts
+++ b/package/ego-browser/src/driver/page-waits.ts
@@ -11,8 +11,16 @@ type PageWaitServices = {
sessionId?: string,
timeoutMs?: number,
): Promise<any>;
- drainEvents(sessionId: string): any[];
- isNetworkDomainEnabled(sessionId: string): boolean;
+ ensureNetworkTracking(
+ sessionIds: string[],
+ timeoutMs?: number,
+ ): Promise<void>;
+ pageNetworkSessions(sessionId: string, timeoutMs?: number): Promise<string[]>;
+ networkActivity(sessionIds: string[]): {
+ tracking: boolean;
+ inflight: number;
+ lastActivityAt: number;
+ };
now(): number;
sleep(ms: number): Promise<void>;
};
@@ -47,6 +55,34 @@ export type PageWaitForURLHooks = {
interrupt?: (lastUrl: string) => Error | undefined;
};
+export class PageNavigationTimeoutError extends Error {
+ readonly code = "EGO_NAVIGATION_TIMEOUT";
+ readonly committed: boolean;
+ readonly url?: string;
+ readonly readyState?: string;
+ readonly waitUntil: PageGotoWaitUntil;
+ readonly timeoutMs: number;
+
+ constructor(
+ message: string,
+ details: {
+ committed: boolean;
+ url?: string;
+ readyState?: string;
+ waitUntil: PageGotoWaitUntil;
+ timeoutMs: number;
+ },
+ ) {
+ super(message);
+ this.name = "PageNavigationTimeoutError";
+ this.committed = details.committed;
+ this.url = details.url;
+ this.readyState = details.readyState;
+ this.waitUntil = details.waitUntil;
+ this.timeoutMs = details.timeoutMs;
+ }
+}
+
const VISIBILITY_FUNCTION =
"function(){if(typeof this.checkVisibility==='function')return this.checkVisibility({checkOpacity:true,checkVisibilityCSS:true});const s=getComputedStyle(this);const r=this.getBoundingClientRect();return s.display!=='none'&&s.visibility!=='hidden'&&s.opacity!=='0'&&r.width>0&&r.height>0;}";
@@ -196,20 +232,21 @@ export async function navigateInPage(
): Promise<void> {
const { timeoutMs, waitUntil, referer } = options;
const deadline = services.now() + timeoutMs;
- const ownsNetworkDomain =
- waitUntil === "networkidle" && !services.isNetworkDomainEnabled(sessionId);
- let enabledNetworkDomain = false;
+ let committed = false;
+ let navigation: {
+ frameId?: string;
+ loaderId?: string;
+ errorText?: string;
+ isDownload?: boolean;
+ } = {};
try {
// Network tracking must start before Page.navigate or the initial document
// requests can be missed by a network-idle wait.
- if (ownsNetworkDomain) {
- await services.cdp(
- "Network.enable",
- {},
- sessionId,
+ if (waitUntil === "networkidle") {
+ await services.ensureNetworkTracking(
+ [sessionId],
navigationTimeRemaining(services, deadline, timeoutMs, waitUntil),
);
- enabledNetworkDomain = true;
}
const response = await services.cdp(
"Page.navigate",
@@ -220,7 +257,7 @@ export async function navigateInPage(
sessionId,
navigationTimeRemaining(services, deadline, timeoutMs, waitUntil),
);
- const navigation = response?.result || response || {};
+ navigation = response?.result || response || {};
if (navigation.errorText) {
throw new Error(`page.goto failed: ${navigation.errorText}`);
}
@@ -236,6 +273,7 @@ export async function navigateInPage(
timeoutMs,
waitUntil,
);
+ committed = true;
if (waitUntil === "commit") return;
await waitForLoadStateInPage(services, sessionId, waitUntil, {
@@ -248,14 +286,143 @@ export async function navigateInPage(
});
} catch (error) {
if (services.now() >= deadline || isLoadStateTimeout(error)) {
- throw navigationTimeout(timeoutMs, waitUntil);
+ if (!committed && navigation.loaderId) {
+ committed = await navigationMatchesCurrentFrame(
+ services,
+ sessionId,
+ navigation,
+ 250,
+ );
+ }
+ const state = committed
+ ? await currentDocumentState(services, sessionId)
+ : {};
+ throw navigationTimeout(timeoutMs, waitUntil, {
+ committed,
+ ...state,
+ });
}
throw error;
- } finally {
- if (enabledNetworkDomain) {
- await services.cdp("Network.disable", {}, sessionId).catch(() => {});
+ }
+}
+
+/** Reload one Page and wait for the selected state of the new document. */
+export async function reloadInPage(
+ services: PageWaitServices,
+ sessionId: string,
+ options: Omit<PageNavigationOptions, "referer">,
+): Promise<void> {
+ const { timeoutMs, waitUntil } = options;
+ const deadline = services.now() + timeoutMs;
+ try {
+ const previousFrame = await mainFrame(
+ services,
+ sessionId,
+ reloadTimeRemaining(services, deadline, timeoutMs, waitUntil),
+ );
+ if (waitUntil === "networkidle") {
+ await services.ensureNetworkTracking(
+ [sessionId],
+ reloadTimeRemaining(services, deadline, timeoutMs, waitUntil),
+ );
+ }
+ await services.cdp(
+ "Page.reload",
+ previousFrame.loaderId === undefined
+ ? {}
+ : { loaderId: previousFrame.loaderId },
+ sessionId,
+ reloadTimeRemaining(services, deadline, timeoutMs, waitUntil),
+ );
+ await waitForReloadCommit(
+ services,
+ sessionId,
+ previousFrame,
+ deadline,
+ timeoutMs,
+ waitUntil,
+ );
+ if (waitUntil === "commit") return;
+ await waitForLoadStateInPage(services, sessionId, waitUntil, {
+ timeout: reloadTimeRemaining(services, deadline, timeoutMs, waitUntil),
+ });
+ } catch (error) {
+ if (services.now() >= deadline || isLoadStateTimeout(error)) {
+ throw reloadTimeout(timeoutMs, waitUntil);
}
+ throw error;
+ }
+}
+
+type MainFrame = { id?: string; loaderId?: string };
+
+async function mainFrame(
+ services: PageWaitServices,
+ sessionId: string,
+ timeoutMs: number,
+): Promise<MainFrame> {
+ const response = await services.cdp(
+ "Page.getFrameTree",
+ {},
+ sessionId,
+ timeoutMs,
+ );
+ return response?.result?.frameTree?.frame || response?.frameTree?.frame || {};
+}
+
+async function waitForReloadCommit(
+ services: PageWaitServices,
+ sessionId: string,
+ previousFrame: MainFrame,
+ deadline: number,
+ timeoutMs: number,
+ waitUntil: PageGotoWaitUntil,
+): Promise<void> {
+ while (services.now() <= deadline) {
+ const remaining = reloadTimeRemaining(
+ services,
+ deadline,
+ timeoutMs,
+ waitUntil,
+ );
+ try {
+ const frame = await mainFrame(
+ services,
+ sessionId,
+ Math.min(1_000, remaining),
+ );
+ if (
+ frame.loaderId &&
+ (frame.loaderId !== previousFrame.loaderId ||
+ (previousFrame.id && frame.id !== previousFrame.id))
+ ) {
+ return;
+ }
+ } catch (error) {
+ if (!isCdpTimeout(error, "Page.getFrameTree")) throw error;
+ }
+ const waitMs = deadline - services.now();
+ if (waitMs <= 0) break;
+ await services.sleep(Math.min(50, waitMs));
}
+ throw reloadTimeout(timeoutMs, waitUntil);
+}
+
+function reloadTimeRemaining(
+ services: PageWaitServices,
+ deadline: number,
+ timeoutMs: number,
+ waitUntil: PageGotoWaitUntil,
+): number {
+ const remaining = deadline - services.now();
+ if (remaining <= 0) throw reloadTimeout(timeoutMs, waitUntil);
+ return remaining;
+}
+
+function reloadTimeout(timeoutMs: number, waitUntil: PageGotoWaitUntil): Error {
+ return new Error(
+ `page.reload timed out after ${timeoutMs}ms waiting for ${waitUntil}`,
+ );
}
async function waitForNavigationCommit(
@@ -303,6 +470,32 @@ async function waitForNavigationCommit(
throw navigationTimeout(timeoutMs, waitUntil);
}
+async function navigationMatchesCurrentFrame(
+ services: PageWaitServices,
+ sessionId: string,
+ navigation: { frameId?: string; loaderId?: string },
+ timeoutMs: number,
+): Promise<boolean> {
+ try {
+ const response = await services.cdp(
+ "Page.getFrameTree",
+ {},
+ sessionId,
+ timeoutMs,
+ );
+ const frame =
+ response?.result?.frameTree?.frame || response?.frameTree?.frame;
+ return (
+ Boolean(navigation.loaderId) &&
+ frame?.loaderId === navigation.loaderId &&
+ (!navigation.frameId || frame?.id === navigation.frameId)
+ );
+ } catch {
+ // This is a best-effort timeout diagnostic, not a second navigation path.
+ return false;
+ }
+}
+
function navigationTimeRemaining(
services: PageWaitServices,
deadline: number,
@@ -317,12 +510,65 @@ function navigationTimeRemaining(
function navigationTimeout(
timeoutMs: number,
waitUntil: PageGotoWaitUntil,
-): Error {
- return new Error(
- `page.goto timed out after ${timeoutMs}ms waiting for ${waitUntil}`,
+ details: { committed?: boolean; url?: string; readyState?: string } = {},
+): PageNavigationTimeoutError {
+ const committed = details.committed === true;
+ const nextStep = navigationTimeoutNextStep(waitUntil);
+ const state = committed
+ ? `; navigation committed${details.url ? ` at ${JSON.stringify(details.url)}` : ""}${details.readyState ? ` with document.readyState=${JSON.stringify(details.readyState)}` : ""}. ${nextStep}`
+ : "";
+ return new PageNavigationTimeoutError(
+ `page.goto timed out after ${timeoutMs}ms waiting for ${waitUntil}${state}`,
+ {
+ committed,
+ url: details.url,
+ readyState: details.readyState,
+ waitUntil,
+ timeoutMs,
+ },
);
}
+function navigationTimeoutNextStep(waitUntil: PageGotoWaitUntil): string {
+ if (waitUntil === "commit") {
+ return "Continue on this Page; the requested document has committed.";
+ }
+ if (waitUntil === "networkidle") {
+ return 'Continue when the needed DOM state is observable, or call page.waitForLoadState("networkidle") if network quiescence is required.';
+ }
+ return `Continue on this Page; call page.waitForLoadState(${JSON.stringify(waitUntil)}) if that lifecycle state is still required.`;
+}
+
+async function currentDocumentState(
+ services: PageWaitServices,
+ sessionId: string,
+): Promise<{ url?: string; readyState?: string }> {
+ try {
+ const response = await services.cdp(
+ "Runtime.evaluate",
+ {
+ expression:
+ "({ __egoNavigationState: true, url: location.href, readyState: document.readyState })",
+ returnByValue: true,
+ timeout: 200,
+ },
+ sessionId,
+ 250,
+ );
+ const value = response?.result?.value;
+ if (!value || typeof value !== "object") return {};
+ return {
+ ...(typeof value.url === "string" ? { url: value.url } : {}),
+ ...(typeof value.readyState === "string"
+ ? { readyState: value.readyState }
+ : {}),
+ };
+ } catch {
+ // Diagnostics must not replace the navigation timeout.
+ return {};
+ }
+}
+
function isLoadStateTimeout(error: unknown): boolean {
return (
error instanceof Error &&
@@ -376,7 +622,7 @@ async function waitForDocumentReadyState(
})()`
: "document.readyState";
const deadline = services.now() + timeoutMs;
- while (services.now() <= deadline) {
+ while (services.now() < deadline) {
const remaining = Math.max(1, deadline - services.now());
let response;
try {
@@ -402,8 +648,9 @@ async function waitForDocumentReadyState(
if (state === "load" && value === "complete") return;
if (state === "domcontentloaded" && value?.domContentLoaded === true)
return;
- if (remaining <= 1) break;
- await services.sleep(Math.min(100, remaining));
+ const waitMs = deadline - services.now();
+ if (waitMs <= 0) break;
+ await services.sleep(Math.min(100, waitMs));
}
throw new Error(
`page.waitForLoadState(${state}) timed out after ${timeoutMs}ms`,
@@ -439,45 +686,53 @@ async function waitForNetworkIdle(
timeoutMs: number,
idleMs: number,
): Promise<void> {
- const ownsNetworkDomain = !services.isNetworkDomainEnabled(sessionId);
const deadline = services.now() + timeoutMs;
- let lastActivityAt = services.now();
- const inflight = new Set<string>();
- await services.cdp("Network.enable", {}, sessionId);
- try {
- while (services.now() <= deadline) {
- for (const event of services.drainEvents(sessionId)) {
- const method = event?.method || "";
- const requestId = event?.params?.requestId;
- if (method === "Network.requestWillBeSent" && requestId) {
- inflight.add(requestId);
- lastActivityAt = services.now();
- } else if (
- (method === "Network.loadingFinished" ||
- method === "Network.loadingFailed") &&
- requestId
- ) {
- inflight.delete(requestId);
- lastActivityAt = services.now();
- } else if (method.startsWith("Network.")) {
- lastActivityAt = services.now();
- }
- }
- if (inflight.size === 0 && services.now() - lastActivityAt >= idleMs) {
+ let sessionIds: string[] = [];
+ while (services.now() <= deadline) {
+ try {
+ // OOPIFs can appear while the Page is loading. Refreshing before every
+ // observation ensures a new child starts its own continuous tracker before
+ // the top-level Page can be declared idle.
+ const discoveryBudget = Math.max(1, deadline - services.now());
+ sessionIds = await services.pageNetworkSessions(
+ sessionId,
+ discoveryBudget,
+ );
+ const trackingBudget = deadline - services.now();
+ if (trackingBudget <= 0) break;
+ await services.ensureNetworkTracking(sessionIds, trackingBudget);
+ const activity = services.networkActivity(sessionIds);
+ if (
+ activity.tracking &&
+ activity.inflight === 0 &&
+ services.now() - activity.lastActivityAt >= idleMs
+ ) {
return;
}
- const remaining = deadline - services.now();
- if (remaining <= 0) break;
- await services.sleep(Math.min(50, remaining));
- }
- throw new Error(
- `page.waitForLoadState(networkidle) timed out after ${timeoutMs}ms`,
- );
- } finally {
- if (ownsNetworkDomain) {
- await services.cdp("Network.disable", {}, sessionId).catch(() => {});
+ } catch (error) {
+ if (!isRetryableNetworkRefreshError(error)) throw error;
+ if (services.now() >= deadline) break;
}
+ const waitMs = deadline - services.now();
+ if (waitMs <= 0) break;
+ await services.sleep(Math.min(50, waitMs));
}
+ throw new Error(
+ `page.waitForLoadState(networkidle) timed out after ${timeoutMs}ms`,
+ );
+}
+
+function isRetryableNetworkRefreshError(error: unknown): boolean {
+ if (
+ Boolean(error) &&
+ typeof error === "object" &&
+ (error as { code?: unknown }).code === "EGO_CDP_REQUEST_TIMEOUT"
+ ) {
+ return true;
+ }
+ return /CDP request timed out:|detached Page session|Session (?:with given id )?not found|Target closed|No session/i.test(
+ error instanceof Error ? error.message : String(error),
+ );
}
function cdpAdapter(services: PageWaitServices) {
diff --git a/package/ego-browser/src/driver/waits.test.mjs b/package/ego-browser/src/driver/waits.test.mjs
index 1336309..f69d253 100644
--- a/package/ego-browser/src/driver/waits.test.mjs
+++ b/package/ego-browser/src/driver/waits.test.mjs
@@ -3,6 +3,11 @@ import assert from "node:assert/strict";
import { setOverrides } from "../../dist/src/state.js";
import { cdp } from "../../dist/src/cdp-eval.js";
+import {
+ drainPageEvents,
+ ensureSession,
+ invalidateSession,
+} from "../../dist/src/browser-runtime.js";
import { waitForNetworkIdle } from "../../dist/src/driver/waits.js";
test("waitForNetworkIdle enables the Network domain and disables it afterwards", async () => {
@@ -86,3 +91,146 @@ test("waitForNetworkIdle survives a bridge that rejects Network.enable", async (
restore();
}
});
+
+test("browser waitForNetworkIdle preserves events and observes requests already in flight", async () => {
+ const previous = globalThis.ego;
+ const methods = [];
+ let now = 0;
+ let finished = false;
+ const runtime = {
+ async listTabs() {
+ return {
+ tabs: [
+ {
+ targetId: "page-main",
+ active: true,
+ title: "Main",
+ url: "https://example.com/",
+ },
+ ],
+ };
+ },
+ sendCDPMessage(payload) {
+ const request = JSON.parse(payload);
+ methods.push(request.method);
+ let result = {};
+ if (request.method === "Target.attachToTarget") {
+ result = { sessionId: `session:${request.params.targetId}` };
+ } else if (request.method === "Target.getTargets") {
+ result = { targetInfos: [{ targetId: "page-main", type: "page" }] };
+ } else if (request.method === "Page.getFrameTree") {
+ result = { frameTree: { frame: { id: "page-main" } } };
+ }
+ queueMicrotask(() => {
+ runtime.onCDPMessage(JSON.stringify({ id: request.id, result }));
+ });
+ },
+ emit(method, params) {
+ runtime.onCDPMessage(
+ JSON.stringify({
+ sessionId: "session:page-main",
+ method,
+ params,
+ }),
+ );
+ },
+ };
+ globalThis.ego = runtime;
+ const restore = setOverrides({
+ now: () => now,
+ sleep: async (ms) => {
+ now += ms;
+ if (!finished && now >= 100) {
+ finished = true;
+ runtime.emit("Network.loadingFinished", { requestId: "slow" });
+ }
+ },
+ });
+
+ try {
+ const sessionId = await ensureSession("page-main");
+ runtime.emit("Network.requestWillBeSent", {
+ requestId: "slow",
+ request: { url: "https://example.com/slow" },
+ });
+
+ assert.equal(await waitForNetworkIdle({ timeout: 1, idleMs: 200 }), true);
+ assert.ok(
+ now >= 300,
+ "the pre-existing request must delay the idle window",
+ );
+ assert.deepEqual(
+ drainPageEvents(sessionId).map((event) => event.method),
+ ["Network.requestWillBeSent", "Network.loadingFinished"],
+ "waiting must not consume the public event queue",
+ );
+ assert.equal(methods.includes("Network.disable"), false);
+ } finally {
+ restore();
+ invalidateSession();
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ }
+});
+
+test("browser waitForNetworkIdle does not hide a user-control hard stop", async () => {
+ const previous = globalThis.ego;
+ let failTargetRefresh = false;
+ const runtime = {
+ async listTabs() {
+ return {
+ tabs: [
+ {
+ targetId: "page-main",
+ active: true,
+ title: "Main",
+ url: "https://example.com/",
+ },
+ ],
+ };
+ },
+ async setAgentTaskState() {
+ return {
+ error: "camera",
+ error_code: "EGO_TASK_SPACE_USER_IN_CONTROL",
+ };
+ },
+ sendCDPMessage(payload) {
+ const request = JSON.parse(payload);
+ if (request.method === "Target.getTargets" && failTargetRefresh) {
+ queueMicrotask(() => {
+ runtime.onSendCDPMessageError(
+ "The task is under user control.",
+ "EGO_TASK_SPACE_USER_IN_CONTROL",
+ );
+ });
+ return;
+ }
+ const result =
+ request.method === "Target.attachToTarget"
+ ? { sessionId: `session:${request.params.targetId}` }
+ : {};
+ queueMicrotask(() => {
+ runtime.onCDPMessage(JSON.stringify({ id: request.id, result }));
+ });
+ },
+ };
+ globalThis.ego = runtime;
+
+ try {
+ await ensureSession("page-main");
+ failTargetRefresh = true;
+ await assert.rejects(
+ () => waitForNetworkIdle({ timeout: 1, idleMs: 10 }),
+ (error) => {
+ assert.equal(error.error_code, "EGO_TASK_SPACE_USER_IN_CONTROL");
+ assert.match(error.message, /camera access/);
+ return true;
+ },
+ );
+ } finally {
+ invalidateSession();
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ }
+});
diff --git a/package/ego-browser/src/driver/waits.ts b/package/ego-browser/src/driver/waits.ts
index 388195d..1e2e63f 100644
--- a/package/ego-browser/src/driver/waits.ts
+++ b/package/ego-browser/src/driver/waits.ts
@@ -5,10 +5,12 @@ import { ElementResolutionError } from "../element-resolver.js";
import { type WaitForLoadOptions, waitForDocumentLoad } from "./load.js";
import { drainEvents } from "./observe.js";
import {
- drainBrowserEvents,
+ ensureNetworkTracking,
ensureSession,
+ isCdpRequestTimeoutError,
isBrowserRuntime,
- isNetworkDomainEnabled,
+ networkActivity,
+ pageNetworkSessions,
} from "../browser-runtime.js";
type WaitForElementOptions = {
@@ -90,12 +92,9 @@ export async function waitForElement(
/**
* Wait until network events are idle.
- * Enables the CDP Network domain for the duration of the wait so that network
- * events are actually delivered (previously nothing enabled the domain, so this
- * could report "idle" without ever observing traffic). If the caller had
- * already enabled the domain, it is left enabled on return. Best-effort: if
- * the runtime does not deliver Network events, an idle window of idleMs still
- * resolves true.
+ * In the browser runtime this reads the continuous, Page-scoped tracker without
+ * consuming public events. Compatibility adapters retain the legacy temporary
+ * Network-domain observation and best-effort fallback.
* @param {{timeout?: number, idleMs?: number}} [options]
* @returns {Promise<boolean>} True when idle before timeout.
*/
@@ -105,20 +104,92 @@ export async function waitForNetworkIdle(
const timeout = options.timeout ?? 10.0;
const idleMs = options.idleMs ?? 500;
const deadline = state.now() + timeout * 1000;
+ if (isBrowserRuntime()) {
+ return waitForBrowserNetworkIdle(deadline, idleMs);
+ }
+
+ return waitForLegacyNetworkIdle(deadline, idleMs);
+}
+
+async function waitForBrowserNetworkIdle(
+ deadline: number,
+ idleMs: number,
+): Promise<boolean> {
+ const sessionId = await ensureSession(
+ undefined,
+ Math.max(1, deadline - state.now()),
+ );
+ let hasTracked = false;
+ while (state.now() < deadline) {
+ try {
+ const sessionIds = await pageNetworkSessions(
+ sessionId,
+ Math.max(1, deadline - state.now()),
+ );
+ await ensureNetworkTracking(
+ sessionIds,
+ Math.max(1, deadline - state.now()),
+ );
+ const activity = networkActivity(sessionIds);
+ hasTracked ||= activity.tracking;
+ if (
+ activity.tracking &&
+ activity.inflight === 0 &&
+ state.now() - activity.lastActivityAt >= idleMs
+ ) {
+ return true;
+ }
+ } catch (error) {
+ if (!hasTracked && isUnsupportedNetworkTrackingError(error)) {
+ return waitForPassiveIdle(deadline, idleMs);
+ }
+ if (!isRetryableNetworkRefreshError(error)) throw error;
+ // A frame can detach while its sessions are refreshed. Once real
+ // tracking has started, retry instead of converting uncertainty to idle.
+ }
+ const remaining = deadline - state.now();
+ if (remaining <= 0) break;
+ await state.sleep(Math.min(100, remaining));
+ }
+ return false;
+}
+
+function isUnsupportedNetworkTrackingError(error: unknown): boolean {
+ return /Network\.enable.*(?:not found|wasn't found|unsupported|unknown method)/i.test(
+ error instanceof Error ? error.message : String(error),
+ );
+}
+
+function isRetryableNetworkRefreshError(error: unknown): boolean {
+ if (isCdpRequestTimeoutError(error)) return true;
+ return /detached Page session|Session (?:with given id )?not found|Target closed|No session/i.test(
+ error instanceof Error ? error.message : String(error),
+ );
+}
+
+async function waitForPassiveIdle(
+ deadline: number,
+ idleMs: number,
+): Promise<boolean> {
+ const remaining = deadline - state.now();
+ if (remaining < idleMs) return false;
+ await state.sleep(idleMs);
+ return true;
+}
+
+async function waitForLegacyNetworkIdle(
+ deadline: number,
+ idleMs: number,
+): Promise<boolean> {
let lastActivity = state.now();
const inflight = new Set();
- const sessionId = isBrowserRuntime() ? await ensureSession() : undefined;
- const ownsNetworkDomain = sessionId
- ? !isNetworkDomainEnabled(sessionId)
- : !state.networkDomainEnabled;
- await cdp("Network.enable", {}, sessionId).catch(() => {
+ const ownsNetworkDomain = !state.networkDomainEnabled;
+ await cdp("Network.enable").catch(() => {
// Domain may be unsupported by the bridge; fall back to passive observation.
});
try {
while (state.now() < deadline) {
- const events = sessionId
- ? drainBrowserEvents(sessionId)
- : await drainEvents();
+ const events = await drainEvents();
for (const event of events) {
const method = event.method || "";
const params = event.params || {};
@@ -143,7 +214,7 @@ export async function waitForNetworkIdle(
return false;
} finally {
if (ownsNetworkDomain) {
- await cdp("Network.disable", {}, sessionId).catch(() => {
+ await cdp("Network.disable").catch(() => {
// Best-effort cleanup; keeps the event buffer from accumulating after the wait.
});
}
diff --git a/package/ego-browser/src/element-resolver.test.mjs b/package/ego-browser/src/element-resolver.test.mjs
index ac48af7..1d4cde2 100644
--- a/package/ego-browser/src/element-resolver.test.mjs
+++ b/package/ego-browser/src/element-resolver.test.mjs
@@ -144,6 +144,239 @@ test("CSS locators search nested open shadow roots", async () => {
assert.deepEqual(point, { x: 12, y: 34, sessionId: undefined });
});
+test("Playwright css= aliases the documented CSS locator", async () => {
+ const cdp = new FakeCDP(async (method, params) => {
+ if (method === "Runtime.evaluate") {
+ assert.match(params.expression, /button#target/);
+ assert.doesNotMatch(
+ params.expression,
+ /__egoQueryAllOpenShadow\("css=button/,
+ );
+ return { result: { value: { x: 7, y: 9 } } };
+ }
+ return {};
+ });
+
+ const point = await resolveElementCenter(
+ cdp,
+ undefined,
+ new RefMap(),
+ "css=button#target",
+ );
+
+ assert.deepEqual(point, { x: 7, y: 9, sessionId: undefined });
+});
+
+test("Playwright has-text and text-is pseudos keep their matching semantics", async () => {
+ const expressions = [];
+ const cdp = new FakeCDP(async (method, params) => {
+ if (method === "Runtime.evaluate") {
+ expressions.push(params.expression);
+ return { result: { value: { x: 11, y: 13 } } };
+ }
+ return {};
+ });
+
+ await resolveElementCenter(
+ cdp,
+ undefined,
+ new RefMap(),
+ 'button:has-text("Save changes")',
+ );
+ await resolveElementCenter(
+ cdp,
+ undefined,
+ new RefMap(),
+ "loc=css:button:text-is('Save')",
+ );
+
+ assert.match(expressions[0], /selector: "button"/);
+ assert.match(expressions[0], /mode: "substring"/);
+ assert.match(expressions[0], /toLowerCase\(\)\.includes/);
+ assert.match(expressions[1], /mode: "exact"/);
+ assert.match(expressions[1], /immediate\.some/);
+});
+
+test("Playwright text pseudos strictly decode quoted CSS strings", async () => {
+ const cdp = new FakeCDP(async (method, params) => {
+ if (method === "Runtime.evaluate") {
+ assert.match(params.expression, /can&apos;t|can't/);
+ return { result: { value: { x: 9, y: 11 } } };
+ }
+ return {};
+ });
+
+ const point = await resolveElementCenter(
+ cdp,
+ undefined,
+ new RefMap(),
+ String.raw`button:text-is('can\'t')`,
+ );
+
+ assert.deepEqual(point, { x: 9, y: 11, sessionId: undefined });
+});
+
+test("Playwright text pseudos decode CSS hex escapes and their terminator", async () => {
+ const cdp = new FakeCDP(async (method, params) => {
+ if (method === "Runtime.evaluate") {
+ assert.match(params.expression, /text: "AB"/);
+ return { result: { value: { x: 10, y: 12 } } };
+ }
+ return {};
+ });
+
+ const point = await resolveElementCenter(
+ cdp,
+ undefined,
+ new RefMap(),
+ String.raw`button:text-is("\41 B")`,
+ );
+
+ assert.deepEqual(point, { x: 10, y: 12, sessionId: undefined });
+});
+
+test("Playwright text-is matches an element with no immediate text", async () => {
+ const cdp = new FakeCDP(async (method, params) => {
+ if (method === "Runtime.evaluate") {
+ assert.match(params.expression, /expected === ""/);
+ assert.match(params.expression, /text\.immediate\.length === 0/);
+ return { result: { value: { x: 12, y: 14 } } };
+ }
+ return {};
+ });
+
+ const point = await resolveElementCenter(
+ cdp,
+ undefined,
+ new RefMap(),
+ '#empty:text-is("")',
+ );
+
+ assert.deepEqual(point, { x: 12, y: 14, sessionId: undefined });
+});
+
+test("raw CSS may contain compatibility tokens inside quoted values", async () => {
+ const cdp = new FakeCDP(async (method, params) => {
+ if (method === "Runtime.evaluate") {
+ assert.match(params.expression, /data-value/);
+ assert.match(params.expression, /:has-text/);
+ return { result: { value: { x: 13, y: 14 } } };
+ }
+ return {};
+ });
+
+ const point = await resolveElementCenter(
+ cdp,
+ undefined,
+ new RefMap(),
+ '[data-value=":has-text("]',
+ );
+
+ assert.deepEqual(point, { x: 13, y: 14, sessionId: undefined });
+});
+
+test("Playwright terminal nth selects before actionability filtering", async () => {
+ const cdp = new FakeCDP(async (method, params) => {
+ if (method === "Runtime.evaluate") {
+ assert.match(params.expression, /const values = Array\.from/);
+ assert.match(params.expression, /const index = 1/);
+ return { result: { value: { x: 15, y: 17 } } };
+ }
+ return {};
+ });
+
+ const point = await resolveElementCenter(
+ cdp,
+ undefined,
+ new RefMap(),
+ ".duplicate >> nth=1",
+ );
+
+ assert.deepEqual(point, { x: 15, y: 17, sessionId: undefined });
+});
+
+test("Playwright text filters compose with nth=-1 and quoted parentheses", async () => {
+ const cdp = new FakeCDP(async (method, params) => {
+ if (method === "Runtime.evaluate") {
+ assert.match(params.expression, /Save \(draft\)/);
+ assert.match(params.expression, /const index = -1 === -1/);
+ return { result: { value: { x: 19, y: 23 } } };
+ }
+ return {};
+ });
+
+ const point = await resolveElementCenter(
+ cdp,
+ undefined,
+ new RefMap(),
+ 'button:has-text("Save (draft)") >> nth=-1',
+ );
+
+ assert.deepEqual(point, { x: 19, y: 23, sessionId: undefined });
+});
+
+test("unsupported Playwright selector combinations fail before CDP", async () => {
+ const cdp = new FakeCDP(async () => {
+ throw new Error("unsupported selector syntax must not reach CDP");
+ });
+
+ for (const selector of [
+ "button:has-text(Save)",
+ 'button:has-text("a" "b")',
+ 'button, a:has-text("Docs")',
+ 'loc=css:button:not(:has-text("Save"))',
+ ".row >> visible=true",
+ ]) {
+ await assert.rejects(
+ () =>
+ resolveElementObjectId(
+ cdp,
+ "session:page",
+ new RefMap(),
+ selector,
+ new Map(),
+ { strict: true },
+ ),
+ (error) => {
+ assert.ok(error instanceof ElementResolutionError);
+ assert.equal(error.kind, "permanent");
+ assert.match(error.message, /Invalid locator/);
+ return true;
+ },
+ );
+ }
+ assert.deepEqual(cdp.calls, []);
+});
+
+test("role name*= uses a case-insensitive accessible-name substring", async () => {
+ const cdp = new FakeCDP(async (method) => {
+ if (method === "Accessibility.getFullAXTree") {
+ return {
+ nodes: [
+ {
+ role: { value: "button" },
+ name: { value: "Increment counter 42" },
+ backendDOMNodeId: 101,
+ },
+ ],
+ };
+ }
+ if (method === "DOM.getBoxModel") {
+ return { model: { content: [0, 0, 20, 0, 20, 10, 0, 10] } };
+ }
+ return {};
+ });
+
+ const point = await resolveElementCenter(
+ cdp,
+ "session:page",
+ new RefMap(),
+ 'loc=role:button[name*="increment COUNTER"]',
+ );
+
+ assert.deepEqual(point, { x: 10, y: 5, sessionId: "session:page" });
+});
+
test("invalid numeric CSS ids suggest a valid attribute selector", async () => {
const cdp = new FakeCDP(async (method) => {
if (method === "Runtime.evaluate") {
@@ -371,7 +604,7 @@ test("action resolution uses the sole usable CSS match", async () => {
new RefMap(),
"button.save",
new Map(),
- { strict: true, actionability: "visible" },
+ { strict: true, actionability: "enabled" },
),
{ objectId: "visible-button", sessionId: "session:page" },
);
@@ -395,7 +628,7 @@ test("action resolution prefers a sole actionable Page match over iframe matches
new RefMap(),
"button.save",
new Map([["frame-child", "session:frame-child"]]),
- { strict: true, actionability: "pointer" },
+ { strict: true, actionability: "pointer-enabled" },
),
{ objectId: "button:session:page", sessionId: "session:page" },
);
@@ -423,13 +656,13 @@ test("pointer action resolution skips a covered Page match for a frame match", a
new RefMap(),
"button.move",
new Map([["frame-child", "session:frame-child"]]),
- { strict: true, actionability: "pointer" },
+ { strict: true, actionability: "pointer-enabled" },
),
{ objectId: "frame-button", sessionId: "session:frame-child" },
);
});
-test("visible action resolution permits opacity-zero native controls", async () => {
+test("enabled action resolution permits opacity-zero native controls", async () => {
const cdp = new FakeCDP(async (method, params) => {
if (method !== "Runtime.evaluate") return {};
if (params.expression.includes("__egoActionableMatches")) {
@@ -448,7 +681,7 @@ test("visible action resolution permits opacity-zero native controls", async ()
new RefMap(),
"select.sort",
new Map(),
- { strict: true, actionability: "visible" },
+ { strict: true, actionability: "enabled" },
),
{ objectId: "transparent-select", sessionId: "session:page" },
);
@@ -619,7 +852,7 @@ test("same-process frame role matches keep their frame provenance", async () =>
new RefMap(),
'loc=role:listboxoption[name="Upload"]',
new Map([["frame-child", "session:page"]]),
- { actionability: "pointer" },
+ { actionability: "pointer-enabled" },
),
{
objectId: "upload-option",
@@ -659,7 +892,7 @@ test("a unique interactable frame role wins over a blocked Page duplicate", asyn
new RefMap(),
'loc=role:button[name="Duplicate"]',
new Map([["frame-child", "session:frame-child"]]),
- { actionability: "pointer" },
+ { actionability: "pointer-enabled" },
),
{ objectId: "node:session:frame-child", sessionId: "session:frame-child" },
);
@@ -694,7 +927,7 @@ test("role actions prefer the actionable Page match over a frame match", async (
new RefMap(),
'loc=role:button[name="Duplicate"]',
new Map([["frame-child", "session:frame-child"]]),
- { actionability: "pointer" },
+ { actionability: "pointer-enabled" },
),
{ objectId: "node:session:page", sessionId: "session:page" },
);
diff --git a/package/ego-browser/src/element-resolver.ts b/package/ego-browser/src/element-resolver.ts
index d4f0073..9875a93 100644
--- a/package/ego-browser/src/element-resolver.ts
+++ b/package/ego-browser/src/element-resolver.ts
@@ -1,7 +1,14 @@
import { parseRef } from "./ref-map.js";
-import { HIT_TARGET_HELPERS } from "./driver/action-target.js";
-
-type ElementActionability = "pointer" | "visible";
+import {
+ ACTION_TARGET_STATE_HELPERS,
+ HIT_TARGET_HELPERS,
+} from "./driver/action-target.js";
+
+type ElementActionability =
+ | "visible"
+ | "enabled"
+ | "pointer"
+ | "pointer-enabled";
type PageRuntimeContext = {
sessionId: string;
frameId?: string;
@@ -323,7 +330,11 @@ async function validateRoleLocatorBackendNodes(
(node) =>
!node.ignored &&
normalizeRole(extractAxString(node.role)) === entry.locator.role &&
- extractAxString(node.name) === entry.locator.name &&
+ roleNameMatches(
+ extractAxString(node.name),
+ entry.locator.name,
+ entry.locator.nameMode,
+ ) &&
Number.isInteger(node.backendDOMNodeId),
)
.map((node) => ({
@@ -836,6 +847,7 @@ async function resolveLocatorCenter(cdp, sessionId, locator, iframeSessions) {
locator.role,
locator.name,
locator.raw,
+ { nameMode: locator.nameMode },
);
const result = await send(
cdp,
@@ -907,6 +919,7 @@ async function resolveLocatorObjectId(
locator.name,
locator.raw,
{
+ nameMode: locator.nameMode,
strictGlobal: options.strictGlobal,
actionability: options.actionability,
},
@@ -1070,9 +1083,11 @@ async function findUniqueRoleMatch(
name,
raw,
{
+ nameMode = "exact",
strictGlobal = false,
actionability = undefined,
}: {
+ nameMode?: "exact" | "substring";
strictGlobal?: boolean;
actionability?: ElementActionability;
} = {},
@@ -1090,7 +1105,7 @@ async function findUniqueRoleMatch(
if (
!node.ignored &&
normalizeRole(extractAxString(node.role)) === normalizeRole(role) &&
- extractAxString(node.name) === name &&
+ roleNameMatches(extractAxString(node.name), name, nameMode) &&
node.backendDOMNodeId !== undefined &&
node.backendDOMNodeId !== null
) {
@@ -1213,7 +1228,7 @@ async function roleMatchActionability(
"Runtime.callFunctionOn",
{
functionDeclaration: `function() {
- ${actionability === "pointer" ? HIT_TARGET_HELPERS : ""}
+ ${actionabilityRequiresPointer(actionability) ? HIT_TARGET_HELPERS : ACTION_TARGET_STATE_HELPERS}
if (!this.isConnected) return { actionable: false };
const rect = this.getBoundingClientRect();
const view = this.ownerDocument?.defaultView;
@@ -1221,11 +1236,13 @@ async function roleMatchActionability(
const style = view.getComputedStyle(this);
const visible = !this.closest?.("[hidden], [inert]") &&
style.display !== "none" &&
- style.visibility !== "hidden" &&
- !this.matches?.(":disabled") &&
- this.getAttribute?.("aria-disabled") !== "true";
+ style.visibility !== "hidden";
if (!visible) return { actionable: false };
- if (${JSON.stringify(actionability)} === "pointer") {
+ if (
+ ${JSON.stringify(actionabilityRequiresEnabled(actionability))} &&
+ isActionTargetDisabled(this)
+ ) return { actionable: false, blocker: "element is disabled" };
+ if (${JSON.stringify(actionabilityRequiresPointer(actionability))}) {
const point = { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
const offscreen = point.x < 0 || point.y < 0 ||
point.x >= view.innerWidth || point.y >= view.innerHeight;
@@ -1503,7 +1520,11 @@ function parseRawSelector(input) {
const raw = String(input);
return raw.startsWith("xpath=")
? { kind: "xpath", selector: raw.slice(6), raw }
- : { kind: "css", selector: raw, raw };
+ : {
+ kind: "css",
+ selector: raw.startsWith("css=") ? raw.slice(4) : raw,
+ raw,
+ };
}
function buildRawSelectorCountJs(selector) {
@@ -1530,7 +1551,10 @@ function buildLocatorFindJs(locator) {
if (locator.kind === "text") {
return `(() => ${textElementsJs(locator)}[0] || null)()`;
}
- return `(() => ${hrefElementsJs(locator.href)}[0] || null)()`;
+ if (locator.kind === "href") {
+ return `(() => ${hrefElementsJs(locator.href)}[0] || null)()`;
+ }
+ return `(() => ${buildLocatorElementsJs(locator)}[0] || null)()`;
}
function buildLocatorActionableFindJs(
@@ -1552,7 +1576,7 @@ function buildActionableElementsJs(
actionability: ElementActionability,
) {
return `(() => {
- ${actionability === "pointer" ? HIT_TARGET_HELPERS : ""}
+ ${actionabilityRequiresPointer(actionability) ? HIT_TARGET_HELPERS : ACTION_TARGET_STATE_HELPERS}
const __egoActionableMatches = Array.from(${elementsExpression} || []).filter((element) => {
if (!element?.isConnected || element.closest?.("[hidden], [inert]")) return false;
const view = element.ownerDocument?.defaultView;
@@ -1561,11 +1585,13 @@ function buildActionableElementsJs(
const style = view.getComputedStyle(element);
const visible = rect.width > 0 && rect.height > 0 &&
style.display !== "none" &&
- style.visibility !== "hidden" &&
- !element.matches?.(":disabled") &&
- element.getAttribute?.("aria-disabled") !== "true";
+ style.visibility !== "hidden";
if (!visible) return false;
- if (${JSON.stringify(actionability)} !== "pointer") return true;
+ if (
+ ${JSON.stringify(actionabilityRequiresEnabled(actionability))} &&
+ isActionTargetDisabled(element)
+ ) return false;
+ if (!${JSON.stringify(actionabilityRequiresPointer(actionability))}) return true;
const point = { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
const offscreen = point.x < 0 || point.y < 0 ||
point.x >= view.innerWidth || point.y >= view.innerHeight;
@@ -1581,23 +1607,25 @@ async function firstActionabilityBlocker(
elementsExpression,
actionability: ElementActionability,
): Promise<string | undefined> {
- if (actionability !== "pointer") return undefined;
for (const context of contexts) {
try {
const result = await evaluateInContext(
cdp,
context,
`(() => {
- ${HIT_TARGET_HELPERS}
+ ${actionabilityRequiresPointer(actionability) ? HIT_TARGET_HELPERS : ACTION_TARGET_STATE_HELPERS}
for (const element of Array.from(${elementsExpression} || [])) {
if (!element?.isConnected || element.closest?.("[hidden], [inert]")) continue;
const view = element.ownerDocument?.defaultView;
const rect = element.getBoundingClientRect();
const style = view?.getComputedStyle(element);
if (!view || rect.width <= 0 || rect.height <= 0 ||
- style.display === "none" || style.visibility === "hidden" ||
- element.matches?.(":disabled") ||
- element.getAttribute?.("aria-disabled") === "true") continue;
+ style.display === "none" || style.visibility === "hidden") continue;
+ if (
+ ${JSON.stringify(actionabilityRequiresEnabled(actionability))} &&
+ isActionTargetDisabled(element)
+ ) return "element is disabled";
+ if (!${JSON.stringify(actionabilityRequiresPointer(actionability))}) continue;
const point = { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
if (point.x < 0 || point.y < 0 ||
point.x >= view.innerWidth || point.y >= view.innerHeight) continue;
@@ -1625,7 +1653,10 @@ function buildLocatorCountJs(locator) {
if (locator.kind === "text") {
return `(() => ${textElementsJs(locator)}.length)()`;
}
- return `(() => ${hrefElementsJs(locator.href)}.length)()`;
+ if (locator.kind === "href") {
+ return `(() => ${hrefElementsJs(locator.href)}.length)()`;
+ }
+ return `(() => ${buildLocatorElementsJs(locator)}.length)()`;
}
function buildBatchLocatorCountJs(locators) {
@@ -1660,11 +1691,21 @@ function buildLocatorElementsJs(locator) {
if (locator.kind === "text") {
return textElementsJs(locator);
}
- return hrefElementsJs(locator.href);
+ if (locator.kind === "href") {
+ return hrefElementsJs(locator.href);
+ }
+ if (locator.kind === "cssText") {
+ return cssTextElementsJs(locator);
+ }
+ if (locator.kind === "nth") {
+ return nthElementsJs(locator);
+ }
+ throw new Error(`Unsupported locator kind: ${locator.kind}`);
}
function buildMatchDiagnosticsJs(elementsExpression) {
return `(() => {
+ ${ACTION_TARGET_STATE_HELPERS}
const __egoDescribeMatches = (values) => {
const elements = Array.from(values || []).filter(Boolean);
const normalize = (value) =>
@@ -1693,10 +1734,7 @@ function buildMatchDiagnosticsJs(elementsExpression) {
role: element.getAttribute?.("role") || undefined,
name: name || undefined,
visible: isVisible,
- disabled: Boolean(
- element.disabled ||
- element.getAttribute?.("aria-disabled") === "true"
- )
+ disabled: isActionTargetDisabled(element)
};
});
const visibleCount = elements.filter(visible).length;
@@ -1710,6 +1748,18 @@ function buildMatchDiagnosticsJs(elementsExpression) {
})()`;
}
+function actionabilityRequiresEnabled(
+ actionability: ElementActionability,
+): boolean {
+ return actionability === "enabled" || actionability === "pointer-enabled";
+}
+
+function actionabilityRequiresPointer(
+ actionability: ElementActionability,
+): boolean {
+ return actionability === "pointer" || actionability === "pointer-enabled";
+}
+
function buildLocatorCenterJs(locator) {
return `(() => {
const count = ${buildLocatorCountJs(locator)};
@@ -1733,6 +1783,84 @@ function hrefElementsJs(href) {
})`;
}
+function cssTextElementsJs(locator) {
+ return `(() => {
+ const spec = {
+ selector: ${JSON.stringify(locator.selector)},
+ mode: ${JSON.stringify(locator.mode)},
+ text: ${JSON.stringify(locator.text)}
+ };
+ const normalize = (value) =>
+ String(value ?? "")
+ .replace(/[\\u200b\\u00ad]/g, "")
+ .replace(/[\\r\\n\\s\\t]+/g, " ")
+ .trim();
+ const expected = normalize(spec.text);
+ const elements = ${buildCssQueryAllJs(locator.selector)};
+
+ function shouldSkip(element) {
+ return (
+ element.tagName === "SCRIPT" ||
+ element.tagName === "NOSCRIPT" ||
+ element.tagName === "STYLE" ||
+ document.head?.contains(element)
+ );
+ }
+
+ function elementText(element) {
+ if (shouldSkip(element)) {
+ return { full: "", normalized: "", immediate: [] };
+ }
+ const type = String(element.getAttribute?.("type") || "").toLowerCase();
+ if (element.tagName === "INPUT" && (type === "button" || type === "submit")) {
+ const value = String(element.value || "");
+ return { full: value, normalized: normalize(value), immediate: [value] };
+ }
+
+ let full = "";
+ let currentImmediate = "";
+ const immediate = [];
+ const flushImmediate = () => {
+ if (currentImmediate) immediate.push(currentImmediate);
+ currentImmediate = "";
+ };
+ for (const child of element.childNodes) {
+ if (child.nodeType === Node.TEXT_NODE) {
+ full += child.nodeValue || "";
+ currentImmediate += child.nodeValue || "";
+ } else if (child.nodeType !== Node.COMMENT_NODE) {
+ flushImmediate();
+ if (child.nodeType === Node.ELEMENT_NODE) {
+ full += elementText(child).full;
+ }
+ }
+ }
+ flushImmediate();
+ if (element.shadowRoot) full += elementText(element.shadowRoot).full;
+ return { full, normalized: normalize(full), immediate };
+ }
+
+ return elements.filter((element) => {
+ const text = elementText(element);
+ if (spec.mode === "exact") {
+ return (
+ (expected === "" && text.immediate.length === 0) ||
+ text.immediate.some((value) => normalize(value) === expected)
+ );
+ }
+ return text.normalized.toLowerCase().includes(expected.toLowerCase());
+ });
+ })()`;
+}
+
+function nthElementsJs(locator) {
+ return `(() => {
+ const values = Array.from(${buildLocatorElementsJs(locator.locator)} || []);
+ const index = ${locator.index} === -1 ? values.length - 1 : ${locator.index};
+ return index >= 0 && index < values.length ? [values[index]] : [];
+ })()`;
+}
+
function textElementsJs(locator) {
return `(() => {
${OPEN_SHADOW_QUERY_HELPER}
@@ -1860,17 +1988,37 @@ function buildSelectorCenterJs(selector) {
}
function parseLocator(input) {
- let value = String(input || "").trim();
+ const raw = String(input || "").trim();
+ let value = raw;
if (value.startsWith("loc=")) {
value = value.slice(4);
}
+
+ const nth = parseTerminalNth(value);
+ if (nth?.valid) {
+ const locator = parseLocatorCore(nth.base, raw, true);
+ if (!locator || locator.kind === "role" || locator.kind === "nth") {
+ return null;
+ }
+ return { kind: "nth", locator, index: nth.index, raw };
+ }
+ if (nth) return null;
+
+ return parseLocatorCore(value, raw, false);
+}
+
+function parseLocatorCore(value, raw, allowRawCss) {
if (value.startsWith("css:")) {
const selector = value.slice(4);
- return selector ? { kind: "css", selector, raw: value } : null;
+ return parseCssLocator(selector, raw);
+ }
+ if (value.startsWith("css=")) {
+ const selector = value.slice(4);
+ return parseCssLocator(selector, raw);
}
if (value.startsWith("href:")) {
const href = value.slice(5);
- return href ? { kind: "href", href, raw: value } : null;
+ return href ? { kind: "href", href, raw } : null;
}
if (value.startsWith("text=")) {
const body = value.slice(5).trim();
@@ -1884,22 +2032,45 @@ function parseLocator(input) {
kind: "text",
mode: quoted ? "exact" : "substring",
text,
- raw: value,
+ raw,
}
: null;
}
- const roleMatch = /^role:([A-Za-z0-9_-]+)\[name=(.+)\]$/.exec(value);
+ const roleMatch = /^role:([A-Za-z0-9_-]+)\[name(\*=|=)(.+)\]$/.exec(value);
if (roleMatch) {
return {
kind: "role",
role: normalizeRole(roleMatch[1]),
- name: parseLocatorName(roleMatch[2]),
- raw: value,
+ nameMode: roleMatch[2] === "*=" ? "substring" : "exact",
+ name: parseLocatorName(roleMatch[3]),
+ raw,
};
}
+
+ if (allowRawCss || hasTerminalCssTextPseudo(value)) {
+ return parseCssLocator(value, raw);
+ }
return null;
}
+function parseCssLocator(selector, raw) {
+ const trimmed = selector.trim();
+ if (!trimmed) return null;
+ const text = parseTerminalCssText(trimmed);
+ if (text?.valid) {
+ return {
+ kind: "cssText",
+ selector: text.selector,
+ mode: text.mode,
+ text: text.text,
+ raw,
+ };
+ }
+ if (text) return null;
+ if (containsUnquotedTextPseudo(trimmed)) return null;
+ return { kind: "css", selector: trimmed, raw };
+}
+
function parseLocatorOrThrow(input) {
const locator = parseLocator(input);
if (locator) return locator;
@@ -1908,16 +2079,243 @@ function parseLocatorOrThrow(input) {
if (
value.startsWith("loc=") ||
value.startsWith("role:") ||
- value.startsWith("text=")
+ value.startsWith("text=") ||
+ value.startsWith("css=") ||
+ hasPlaywrightCompatibilitySyntax(value)
) {
throw new ElementResolutionError(
- `Invalid locator: ${value}. Expected loc=role:<role>[name="<exact name>"], loc=css:<selector>, loc=href:<substring>, or text=... for text matching`,
+ `Invalid locator: ${value}. Expected loc=role:<role>[name="<exact name>"], loc=role:<role>[name*="<name part>"], loc=css:<selector>, loc=href:<substring>, text=..., css=..., a terminal :has-text(...) or :text-is(...), or a terminal >> nth=N`,
"permanent",
);
}
return null;
}
+function parseTerminalNth(value) {
+ const separators = topLevelTokenPositions(value, ">>");
+ if (separators.length === 0) return undefined;
+ if (separators.length !== 1) return { valid: false };
+ const position = separators[0];
+ const base = value.slice(0, position).trim();
+ const tail = value.slice(position + 2).trim();
+ const match = /^nth=(-?\d+)$/.exec(tail);
+ if (!base || !match) return { valid: false };
+ const index = Number(match[1]);
+ if (!Number.isSafeInteger(index) || index < -1) return { valid: false };
+ return { valid: true, base, index };
+}
+
+function parseTerminalCssText(selector) {
+ const pseudos = [
+ { token: ":has-text(", mode: "substring" },
+ { token: ":text-is(", mode: "exact" },
+ ];
+ for (let index = 0; index < selector.length; index += 1) {
+ if (!isTopLevelPosition(selector, index)) continue;
+ const pseudo = pseudos.find(({ token }) =>
+ selector.startsWith(token, index),
+ );
+ if (!pseudo) continue;
+ const open = index + pseudo.token.length - 1;
+ const close = matchingParenPosition(selector, open);
+ if (close === -1 || selector.slice(close + 1).trim()) {
+ return { valid: false };
+ }
+ const base = selector.slice(0, index).trim();
+ const argument = selector.slice(open + 1, close).trim();
+ const string = parseCssString(argument);
+ if (
+ !base ||
+ topLevelTokenPositions(base, ",").length > 0 ||
+ !string.valid
+ ) {
+ return { valid: false };
+ }
+ return {
+ valid: true,
+ selector: base,
+ mode: pseudo.mode,
+ text: string.value,
+ };
+ }
+ return undefined;
+}
+
+function hasTerminalCssTextPseudo(value) {
+ return Boolean(parseTerminalCssText(value));
+}
+
+function hasPlaywrightCompatibilitySyntax(value) {
+ return (
+ containsUnquotedTextPseudo(value) ||
+ topLevelTokenPositions(value, ">>").length > 0
+ );
+}
+
+function containsUnquotedTextPseudo(value) {
+ const tokens = [":has-text(", ":text-is("];
+ let quote;
+ let escaped = false;
+ for (let index = 0; index < value.length; index += 1) {
+ const character = value[index];
+ if (quote) {
+ if (escaped) escaped = false;
+ else if (character === "\\") escaped = true;
+ else if (character === quote) quote = undefined;
+ continue;
+ }
+ if (character === '"' || character === "'") {
+ quote = character;
+ continue;
+ }
+ if (tokens.some((token) => value.startsWith(token, index))) return true;
+ }
+ return false;
+}
+
+function topLevelTokenPositions(value, token) {
+ const positions = [];
+ let quote;
+ let escaped = false;
+ let bracketDepth = 0;
+ let parenDepth = 0;
+ for (let index = 0; index < value.length; index += 1) {
+ const character = value[index];
+ if (quote) {
+ if (escaped) escaped = false;
+ else if (character === "\\") escaped = true;
+ else if (character === quote) quote = undefined;
+ continue;
+ }
+ if (character === '"' || character === "'") {
+ quote = character;
+ continue;
+ }
+ if (character === "[") bracketDepth += 1;
+ else if (character === "]") bracketDepth = Math.max(0, bracketDepth - 1);
+ else if (character === "(") parenDepth += 1;
+ else if (character === ")") parenDepth = Math.max(0, parenDepth - 1);
+ if (
+ bracketDepth === 0 &&
+ parenDepth === 0 &&
+ value.startsWith(token, index)
+ ) {
+ positions.push(index);
+ index += token.length - 1;
+ }
+ }
+ return positions;
+}
+
+function isTopLevelPosition(value, position) {
+ let quote;
+ let escaped = false;
+ let bracketDepth = 0;
+ let parenDepth = 0;
+ for (let index = 0; index < position; index += 1) {
+ const character = value[index];
+ if (quote) {
+ if (escaped) escaped = false;
+ else if (character === "\\") escaped = true;
+ else if (character === quote) quote = undefined;
+ continue;
+ }
+ if (character === '"' || character === "'") {
+ quote = character;
+ } else if (character === "[") {
+ bracketDepth += 1;
+ } else if (character === "]") {
+ bracketDepth = Math.max(0, bracketDepth - 1);
+ } else if (character === "(") {
+ parenDepth += 1;
+ } else if (character === ")") {
+ parenDepth = Math.max(0, parenDepth - 1);
+ }
+ }
+ return !quote && bracketDepth === 0 && parenDepth === 0;
+}
+
+function matchingParenPosition(value, open) {
+ let quote;
+ let escaped = false;
+ let depth = 0;
+ for (let index = open; index < value.length; index += 1) {
+ const character = value[index];
+ if (quote) {
+ if (escaped) escaped = false;
+ else if (character === "\\") escaped = true;
+ else if (character === quote) quote = undefined;
+ continue;
+ }
+ if (character === '"' || character === "'") {
+ quote = character;
+ continue;
+ }
+ if (character === "(") depth += 1;
+ if (character === ")" && --depth === 0) return index;
+ }
+ return -1;
+}
+
+function parseCssString(value) {
+ const quote = value[0];
+ if ((quote !== '"' && quote !== "'") || value.length < 2) {
+ return { valid: false };
+ }
+
+ let decoded = "";
+ for (let index = 1; index < value.length; index += 1) {
+ const character = value[index];
+ if (character === quote) {
+ return index === value.length - 1
+ ? { valid: true, value: decoded }
+ : { valid: false };
+ }
+ if (character === "\n" || character === "\r" || character === "\f") {
+ return { valid: false };
+ }
+ if (character !== "\\") {
+ decoded += character;
+ continue;
+ }
+
+ index += 1;
+ if (index >= value.length) return { valid: false };
+ if (value[index] === "\r" && value[index + 1] === "\n") index += 1;
+ if (
+ value[index] === "\n" ||
+ value[index] === "\r" ||
+ value[index] === "\f"
+ ) {
+ continue;
+ }
+
+ const hex = value.slice(index).match(/^[0-9a-fA-F]{1,6}/)?.[0];
+ if (!hex) {
+ decoded += value[index];
+ continue;
+ }
+ index += hex.length - 1;
+ const terminator = value[index + 1];
+ if (terminator === "\r") {
+ index += value[index + 2] === "\n" ? 2 : 1;
+ } else if (
+ terminator === "\n" ||
+ terminator === "\f" ||
+ terminator === "\t" ||
+ terminator === " "
+ ) {
+ index += 1;
+ }
+ const codePoint = Number.parseInt(hex, 16);
+ decoded +=
+ codePoint === 0 || codePoint > 0x10ffff
+ ? "\uFFFD"
+ : String.fromCodePoint(codePoint);
+ }
+ return { valid: false };
+}
+
function parseLocatorName(raw) {
const trimmed = raw.trim();
if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
@@ -1939,6 +2337,13 @@ function normalizeText(value) {
.trim();
}
+function roleNameMatches(actual, expected, mode = "exact") {
+ if (mode === "exact") return actual === expected;
+ return normalizeText(actual)
+ .toLowerCase()
+ .includes(normalizeText(expected).toLowerCase());
+}
+
function normalizeRole(value) {
const role = String(value || "").toLowerCase();
return (
diff --git a/package/ego-browser/src/helpers.test.mjs b/package/ego-browser/src/helpers.test.mjs
index 6aa5dce..11f74c2 100644
--- a/package/ego-browser/src/helpers.test.mjs
+++ b/package/ego-browser/src/helpers.test.mjs
@@ -1,5 +1,8 @@
import test from "node:test";
import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import * as helperExports from "../dist/src/helpers.js";
import {
@@ -17,6 +20,19 @@ import {
waitForAgentControl,
} from "../dist/src/helpers.js";
+const previousStateDir = process.env.EGO_BROWSER_STATE_DIR;
+const stateDir = await mkdtemp(join(tmpdir(), "ego-browser-helpers-"));
+process.env.EGO_BROWSER_STATE_DIR = stateDir;
+
+test.after(async () => {
+ if (previousStateDir === undefined) {
+ delete process.env.EGO_BROWSER_STATE_DIR;
+ } else {
+ process.env.EGO_BROWSER_STATE_DIR = previousStateDir;
+ }
+ await rm(stateDir, { recursive: true, force: true });
+});
+
function withEgo(ego, fn) {
const previous = globalThis.ego;
globalThis.ego = ego;
@@ -225,6 +241,10 @@ test("taskSpace creates a new space with an explicit browser profile", async ()
calls.push(["useTaskSpace", id]);
return id;
},
+ async listTabs() {
+ calls.push(["listTabs"]);
+ return { tabs: [{ targetId: "target-profile-initial" }] };
+ },
},
async () => {
const task = await taskSpace("work research", { profileId: "Profile 2" });
@@ -236,6 +256,162 @@ test("taskSpace creates a new space with an explicit browser profile", async ()
["listTaskSpaces"],
["createTaskSpace", "work research", "Profile 2"],
["useTaskSpace", 8],
+ ["listTabs"],
+ ]);
+});
+
+test("taskSpace manages a newly created space's default tab as p1", async () => {
+ const calls = [];
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ calls.push(["listTaskSpaces"]);
+ return { taskSpaces: [] };
+ },
+ async createTaskSpace(name) {
+ calls.push(["createTaskSpace", name]);
+ return { taskId: name, id: 9, name };
+ },
+ async useTaskSpace(id) {
+ calls.push(["useTaskSpace", id]);
+ },
+ async listTabs() {
+ calls.push(["listTabs"]);
+ return {
+ tabs: [
+ {
+ targetId: "target-initial",
+ url: "chrome://newtab/",
+ title: "New Tab",
+ active: true,
+ },
+ ],
+ };
+ },
+ },
+ async () => {
+ const task = await taskSpace("fresh research");
+ const pages = await task.pages();
+ assert.equal(pages.length, 1);
+ assert.equal(pages[0].label, "p1");
+ assert.equal(pages[0].targetId, "target-initial");
+ assert.equal(pages[0].openedBy, "agent");
+ },
+ );
+ assert.deepEqual(calls, [
+ ["listTaskSpaces"],
+ ["createTaskSpace", "fresh research"],
+ ["useTaskSpace", 9],
+ ["listTabs"],
+ ["useTaskSpace", 9],
+ ["listTabs"],
+ ]);
+});
+
+test("resolving an existing v2 space cannot interrupt fresh p1 discovery", async () => {
+ let selectedSpace;
+ let releaseFirstInventory;
+ let reportFirstInventory;
+ const firstInventoryStarted = new Promise((resolve) => {
+ reportFirstInventory = resolve;
+ });
+ const firstInventoryRelease = new Promise((resolve) => {
+ releaseFirstInventory = resolve;
+ });
+ let inventoryCalls = 0;
+
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ return {
+ taskSpaces: [
+ {
+ taskId: "existing",
+ id: 12,
+ name: "existing",
+ ownership: "agent",
+ },
+ ],
+ };
+ },
+ async createTaskSpace(name) {
+ return { taskId: name, id: 11, name };
+ },
+ async useTaskSpace(id) {
+ selectedSpace = id;
+ },
+ async listTabs() {
+ inventoryCalls += 1;
+ if (inventoryCalls === 1) {
+ reportFirstInventory();
+ await firstInventoryRelease;
+ }
+ return {
+ tabs: [
+ {
+ targetId:
+ selectedSpace === 11 ? "target-fresh" : "target-existing",
+ },
+ ],
+ };
+ },
+ },
+ async () => {
+ const freshPromise = taskSpace("fresh concurrent");
+ await firstInventoryStarted;
+ const existing = await taskSpace(12);
+ assert.equal(existing.spaceId, 12);
+ releaseFirstInventory();
+
+ const fresh = await freshPromise;
+ const pages = await fresh.pages();
+ assert.deepEqual(
+ pages.map((page) => [page.label, page.targetId]),
+ [["p1", "target-fresh"]],
+ );
+ },
+ );
+});
+
+test("taskSpace closes a new space when its default tab is ambiguous", async () => {
+ const calls = [];
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ calls.push(["listTaskSpaces"]);
+ return { taskSpaces: [] };
+ },
+ async createTaskSpace(name) {
+ calls.push(["createTaskSpace", name]);
+ return { taskId: name, id: 10, name };
+ },
+ async useTaskSpace(id) {
+ calls.push(["useTaskSpace", id]);
+ },
+ async closeTaskSpace() {
+ calls.push(["closeTaskSpace"]);
+ },
+ async listTabs() {
+ calls.push(["listTabs"]);
+ return {
+ tabs: [{ targetId: "target-a" }, { targetId: "target-b" }],
+ };
+ },
+ },
+ async () => {
+ await assert.rejects(
+ () => taskSpace("ambiguous runtime"),
+ /new task space expected one default tab, found 2/,
+ );
+ },
+ );
+ assert.deepEqual(calls, [
+ ["listTaskSpaces"],
+ ["createTaskSpace", "ambiguous runtime"],
+ ["useTaskSpace", 10],
+ ["listTabs"],
+ ["useTaskSpace", 10],
+ ["closeTaskSpace"],
]);
});
diff --git a/package/ego-browser/src/helpers.ts b/package/ego-browser/src/helpers.ts
index e800b55..070253c 100644
--- a/package/ego-browser/src/helpers.ts
+++ b/package/ego-browser/src/helpers.ts
@@ -173,6 +173,14 @@ export async function switchTaskSpace(nameOrId) {
* @returns {Promise<{taskId:string,id:number,name:string,createdBy?:string,ownership?:string,recentTabTitles?:string[]}>}
*/
export async function newTaskSpace(name, profileId?: string) {
+ return (await createTaskSpaceResolution(name, profileId)).descriptor;
+}
+
+async function createTaskSpaceResolution(
+ name,
+ profileId?: string,
+ options: { select?: boolean } = {},
+) {
const ego = globalThis.ego;
if (!ego || typeof ego.createTaskSpace !== "function") {
throw new Error("newTaskSpace requires ego.createTaskSpace");
@@ -192,11 +200,18 @@ export async function newTaskSpace(name, profileId?: string) {
taskSpaceNumericId(created, "newTaskSpace");
// The native create response currently omits ownership on some Ego Lite
// builds. Creation through this Agent API is itself authoritative.
- return selectTaskSpace(
- ego,
- { ...created, ownership: created.ownership || "agent" },
- "newTaskSpace",
- );
+ const createdByAgent = {
+ ...created,
+ ownership: created.ownership || "agent",
+ };
+ const descriptor =
+ options.select === false
+ ? createdByAgent
+ : await selectTaskSpace(ego, createdByAgent, "newTaskSpace");
+ return {
+ descriptor,
+ created: true,
+ };
}
/**
@@ -207,23 +222,49 @@ export async function newTaskSpace(name, profileId?: string) {
* @returns {Promise<{taskId:string,id:number,name:string,createdBy?:string,ownership?:string,recentTabTitles?:string[]}>}
*/
export async function useOrCreateTaskSpace(nameOrId) {
+ return (await resolveTaskSpace(nameOrId)).descriptor;
+}
+
+async function resolveTaskSpace(nameOrId, options: { select?: boolean } = {}) {
const spaces = await listTaskSpaces();
const existing = findMatchingTaskSpace(spaces, nameOrId);
if (!existing) {
if (typeof nameOrId === "number") {
throw new Error(`task space not found: ${nameOrId}`);
}
- return newTaskSpace(nameOrId);
+ return createTaskSpaceResolution(nameOrId, undefined, {
+ select: options.select,
+ });
}
if (isAgentOwned(existing.ownership)) {
- return selectTaskSpace(globalThis.ego, existing, "useOrCreateTaskSpace");
+ return {
+ descriptor:
+ options.select === false
+ ? existing
+ : await selectTaskSpace(
+ globalThis.ego,
+ existing,
+ "useOrCreateTaskSpace",
+ ),
+ created: false,
+ };
}
if (existing.ownership === "user") {
// Don't claim user-owned spaces here. Select it as-is; the user stays in
// control, so EGO_TASK_SPACE_USER_IN_CONTROL surfaces (as ego-browser's owned
// guidance, not the raw native text). Call claimTaskSpace(nameOrId) to take
// ownership.
- return selectTaskSpace(globalThis.ego, existing, "useOrCreateTaskSpace");
+ return {
+ descriptor:
+ options.select === false
+ ? existing
+ : await selectTaskSpace(
+ globalThis.ego,
+ existing,
+ "useOrCreateTaskSpace",
+ ),
+ created: false,
+ };
}
throw new Error(
`useOrCreateTaskSpace cannot use task space ${JSON.stringify(nameOrId)} with ownership ${JSON.stringify(existing.ownership)}`,
@@ -244,10 +285,9 @@ export async function taskSpace(
validatePublicApiOptions("taskSpace", options);
const { profileId } = options;
if (profileId === undefined) {
- const descriptor = await useOrCreateTaskSpace(nameOrId);
- const task = createTaskSpaceHandle(descriptor);
- await initializeTaskSpaceHandle(task);
- return task;
+ return initializeResolvedTaskSpace(
+ await resolveTaskSpace(nameOrId, { select: false }),
+ );
}
if (typeof nameOrId !== "string") {
throw new TypeError(
@@ -260,10 +300,27 @@ export async function taskSpace(
`taskSpace profileId only applies when creating a new task space; ${JSON.stringify(nameOrId)} already exists`,
);
}
- const descriptor = await newTaskSpace(nameOrId, profileId);
- const task = createTaskSpaceHandle(descriptor);
- await initializeTaskSpaceHandle(task);
- return task;
+ return initializeResolvedTaskSpace(
+ await createTaskSpaceResolution(nameOrId, profileId, { select: false }),
+ );
+}
+
+async function initializeResolvedTaskSpace(resolution) {
+ const task = createTaskSpaceHandle(resolution.descriptor);
+ if (!resolution.created) {
+ await initializeTaskSpaceHandle(task);
+ return task;
+ }
+
+ try {
+ await initializeTaskSpaceHandle(task, { created: true });
+ return task;
+ } catch (error) {
+ // A fresh space must not survive without its canonical p1 ledger entry.
+ // Preserve the initialization error if native rollback is unavailable.
+ await task.close().catch(() => {});
+ throw error;
+ }
}
/**
diff --git a/package/ego-browser/src/page-ledger.test.mjs b/package/ego-browser/src/page-ledger.test.mjs
index dddf848..6dc1520 100644
--- a/package/ego-browser/src/page-ledger.test.mjs
+++ b/package/ego-browser/src/page-ledger.test.mjs
@@ -45,6 +45,41 @@ test("page labels survive a new process and are never reused", async () => {
});
});
+test("a newly created space atomically replaces stale state with agent page p1", async () => {
+ await withTempLedger(async (rootDir) => {
+ const store = new PageLedgerStore({
+ rootDir,
+ browserInstanceId: "browser-current",
+ });
+ await store.addPage(7, "target-stale");
+ await store.closePage(7, "p1");
+
+ const initial = await store.initializeCreatedSpace(7, "target-initial");
+
+ assert.deepEqual(initial, {
+ label: "p1",
+ targetId: "target-initial",
+ openedBy: "agent",
+ });
+ assert.deepEqual(await store.read(7), {
+ browserInstanceId: "browser-current",
+ spaceId: 7,
+ nextLabel: 2,
+ usedLabels: ["p1"],
+ releasedLabels: [],
+ initialized: true,
+ userControlPending: false,
+ unmanagedTargets: {},
+ pages: {
+ p1: { targetId: "target-initial", openedBy: "agent" },
+ },
+ });
+
+ const next = await store.addPage(7, "target-next");
+ assert.equal(next.label, "p2");
+ });
+});
+
test("a reused space id starts conservatively in a new browser instance", async () => {
await withTempLedger(async (rootDir) => {
const firstBrowser = new PageLedgerStore({
diff --git a/package/ego-browser/src/page-ledger.ts b/package/ego-browser/src/page-ledger.ts
index 48afce2..97ee2fd 100644
--- a/package/ego-browser/src/page-ledger.ts
+++ b/package/ego-browser/src/page-ledger.ts
@@ -95,6 +95,25 @@ export class PageLedgerStore {
return cloneLedger(ledger);
}
+ /** Replace any stale state for a newly created space with its Agent-owned p1. */
+ async initializeCreatedSpace(
+ spaceId: number,
+ targetId: string,
+ ): Promise<ManagedPage> {
+ assertSpaceId(spaceId);
+ assertTargetId(targetId);
+ const browserInstanceId = await this.#currentBrowserInstanceId();
+ await this.#cleanupExpiredLedgers(browserInstanceId);
+ const ledger = emptyLedger(spaceId, browserInstanceId);
+ const label = nextAutomaticLabel(ledger, new Set());
+ const entry: PageLedgerEntry = { targetId, openedBy: "agent" };
+ ledger.initialized = true;
+ ledger.usedLabels.push(label);
+ ledger.pages[label] = entry;
+ await this.#writeAtomic(spaceId, ledger);
+ return { label, ...entry };
+ }
+
/** Remove all Page-model state after its task space is finished or closed. */
async discard(spaceId: number): Promise<void> {
assertSpaceId(spaceId);
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 926e49e..f48d7f4 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -5,6 +5,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { NativeOperationGate } from "../dist/src/native-gate.js";
+import { CdpRequestTimeoutError } from "../dist/src/browser-runtime.js";
import { PageLedgerStore } from "../dist/src/page-ledger.js";
import {
captureTaskSpaceUserBoundary,
@@ -49,6 +50,11 @@ function createFixture(rootDir) {
let focusResult = { focused: true };
let unsafeFillActivationTarget = null;
let selectedValues = [];
+ let selectOptions = [
+ { value: "nl", label: "Netherlands" },
+ { value: "one", label: "One" },
+ { value: "two", label: "Two" },
+ ];
let navigateOnNextClickUrl = null;
let elementPresent = true;
let elementVisible = true;
@@ -61,6 +67,8 @@ function createFixture(rootDir) {
let nowMs = 1_000;
const pageEvents = new Map();
const networkSessions = new Set();
+ const networkRequests = new Map();
+ const networkLastActivityAt = new Map();
const sessionOverrides = new Map();
const sessionTargets = new Map();
const snapshotOptions = [];
@@ -262,6 +270,17 @@ function createFixture(rootDir) {
},
};
}
+ if (params.expression.includes("__egoNavigationState")) {
+ return {
+ result: {
+ type: "object",
+ value: {
+ url: tab.url,
+ readyState: documentReadyState,
+ },
+ },
+ };
+ }
if (
/return __egoQueryAllOpenShadow\([^;]+\)\.length;/.test(
params.expression,
@@ -369,7 +388,24 @@ function createFixture(rootDir) {
};
}
if (params.functionDeclaration.includes("selectOptionsForAction")) {
- selectedValues = [...(params.arguments?.[0]?.value ?? [])];
+ const choices = params.arguments?.[0]?.value ?? [];
+ selectedValues = choices.map((choice) => {
+ const option =
+ typeof choice === "string"
+ ? selectOptions.find(
+ (candidate) =>
+ candidate.value === choice || candidate.label === choice,
+ )
+ : selectOptions.find(
+ (candidate, index) =>
+ (choice.value === undefined ||
+ candidate.value === choice.value) &&
+ (choice.label === undefined ||
+ candidate.label === choice.label) &&
+ (choice.index === undefined || index === choice.index),
+ );
+ return option?.value;
+ });
return {
result: { type: "object", value: { selected: selectedValues } },
};
@@ -510,11 +546,17 @@ function createFixture(rootDir) {
}
if (method === "DOM.setFileInputFiles") return {};
if (method === "Network.enable") {
+ if (!networkSessions.has(sessionId)) {
+ networkRequests.set(sessionId, new Set());
+ networkLastActivityAt.set(sessionId, nowMs);
+ }
networkSessions.add(sessionId);
return {};
}
if (method === "Network.disable") {
networkSessions.delete(sessionId);
+ networkRequests.delete(sessionId);
+ networkLastActivityAt.delete(sessionId);
return {};
}
if (method === "Browser.getVersion") {
@@ -561,6 +603,9 @@ function createFixture(rootDir) {
}
if (method === "Target.setDiscoverTargets") return {};
if (method === "Page.handleJavaScriptDialog") {
+ if (!pendingDialogs.has(sessionId)) {
+ throw new Error("No dialog is showing");
+ }
pendingDialogs.delete(sessionId);
return {};
}
@@ -637,8 +682,32 @@ function createFixture(rootDir) {
pageEvents.set(sessionId, []);
return events;
},
- isNetworkDomainEnabled(sessionId) {
- return networkSessions.has(sessionId);
+ async ensureNetworkTracking(sessionIds) {
+ for (const sessionId of new Set(sessionIds)) {
+ if (!networkSessions.has(sessionId)) {
+ await services.cdp("Network.enable", {}, sessionId);
+ }
+ }
+ },
+ async pageNetworkSessions(sessionId) {
+ return [sessionId];
+ },
+ networkActivity(sessionIds) {
+ let tracking = sessionIds.length > 0;
+ let inflight = 0;
+ let lastActivityAt = 0;
+ for (const sessionId of new Set(sessionIds)) {
+ if (!networkSessions.has(sessionId)) {
+ tracking = false;
+ continue;
+ }
+ inflight += networkRequests.get(sessionId)?.size ?? 0;
+ lastActivityAt = Math.max(
+ lastActivityAt,
+ networkLastActivityAt.get(sessionId) ?? 0,
+ );
+ }
+ return { tracking, inflight, lastActivityAt };
},
ensureSession: ensureTargetSession,
async ensureFrameSessions() {
@@ -691,6 +760,9 @@ function createFixture(rootDir) {
type: dialog.type ?? "alert",
message: dialog.message ?? "Confirm action",
url: dialog.url ?? "https://example.test/dialog",
+ ...(dialog.defaultPrompt === undefined
+ ? {}
+ : { defaultPrompt: dialog.defaultPrompt }),
};
},
rejectNextClickPoint() {
@@ -726,6 +798,9 @@ function createFixture(rootDir) {
configureUnsafeFillActivation(target) {
unsafeFillActivationTarget = target;
},
+ configureSelectOptions(options) {
+ selectOptions = options.map((option) => ({ ...option }));
+ },
fillText: () => fillText,
setElementState({ present = true, visible = true }) {
elementPresent = present;
@@ -755,6 +830,21 @@ function createFixture(rootDir) {
},
emitPageEvent(targetId, method, params = {}) {
const sessionId = `session:${targetId}`;
+ if (networkSessions.has(sessionId)) {
+ const requests = networkRequests.get(sessionId) || new Set();
+ if (method === "Network.requestWillBeSent" && params.requestId) {
+ requests.add(params.requestId);
+ networkLastActivityAt.set(sessionId, nowMs);
+ } else if (
+ (method === "Network.loadingFinished" ||
+ method === "Network.loadingFailed") &&
+ params.requestId
+ ) {
+ requests.delete(params.requestId);
+ networkLastActivityAt.set(sessionId, nowMs);
+ }
+ networkRequests.set(sessionId, requests);
+ }
const events = pageEvents.get(sessionId) || [];
events.push({ sessionId, method, params });
pageEvents.set(sessionId, events);
@@ -813,6 +903,78 @@ test("background discovery does not adopt the pre-existing tab baseline", async
});
});
+test("a created TaskSpace manages its sole default tab as agent page p1", async () => {
+ await withFixture(async (fixture) => {
+ fixture.addExternalTab("target-initial", "chrome://newtab/", {
+ active: true,
+ });
+ const ledger = new PageLedgerStore({ rootDir: fixture.rootDir });
+ const task = taskForRound(fixture, "round-a", { ledger });
+
+ await initializeTaskSpaceHandle(task, { created: true });
+
+ const [initial] = await task.pages();
+ assert.equal(initial.label, "p1");
+ assert.equal(initial.targetId, "target-initial");
+ assert.equal(initial.openedBy, "agent");
+
+ const next = await task.newPage();
+ assert.equal(next.label, "p2");
+ assert.notEqual(next.targetId, initial.targetId);
+ });
+});
+
+test("created-space initialization waits for a delayed default tab", async () => {
+ await withFixture(async (fixture) => {
+ fixture.addExternalTab("target-initial", "chrome://newtab/", {
+ active: true,
+ });
+ let inventories = 0;
+ const task = taskForRound(fixture, "round-a", {
+ async listTabs() {
+ inventories += 1;
+ if (inventories === 1) return [];
+ return fixture.services.listTabs();
+ },
+ });
+
+ await initializeTaskSpaceHandle(task, { created: true });
+
+ const [initial] = await task.pages();
+ assert.equal(initial.label, "p1");
+ assert.equal(initial.targetId, "target-initial");
+ assert(inventories >= 2);
+ });
+});
+
+test("created-space initialization refuses to guess between multiple tabs", async () => {
+ await withFixture(async (fixture) => {
+ fixture.addExternalTab("target-a", "chrome://newtab/", { active: true });
+ fixture.addExternalTab("target-b", "about:blank");
+ const ledger = new PageLedgerStore({ rootDir: fixture.rootDir });
+ const task = taskForRound(fixture, "round-a", { ledger });
+
+ await assert.rejects(
+ () => initializeTaskSpaceHandle(task, { created: true }),
+ /new task space expected one default tab, found 2/,
+ );
+ assert.deepEqual((await ledger.read(7)).pages, {});
+ });
+});
+
+test("created-space initialization times out when no default tab appears", async () => {
+ await withFixture(async (fixture) => {
+ const ledger = new PageLedgerStore({ rootDir: fixture.rootDir });
+ const task = taskForRound(fixture, "round-a", { ledger });
+
+ await assert.rejects(
+ () => initializeTaskSpaceHandle(task, { created: true }),
+ /new task space did not expose its default tab within 2000ms/,
+ );
+ assert.deepEqual((await ledger.read(7)).pages, {});
+ });
+});
+
test("background target discovery adopts a delayed popup and reports its opener", async () => {
await withFixture(async (fixture) => {
resetPageNotices();
@@ -1394,7 +1556,209 @@ test("Page.goto starts network tracking before a network-idle navigation", async
methods.indexOf("Network.enable") < methods.indexOf("Page.navigate"),
);
assert(
- methods.lastIndexOf("Network.disable") > methods.indexOf("Page.navigate"),
+ !methods.includes("Network.disable"),
+ "continuous tracking must remain enabled for requests that start before a later wait",
+ );
+ });
+});
+
+test("Page.goto timeout distinguishes a committed usable document", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/first");
+ fixture.setDocumentLifecycle({
+ readyState: "loading",
+ domContentLoaded: false,
+ });
+
+ await assert.rejects(
+ () =>
+ page.goto("https://example.test/streaming", {
+ timeout: 100,
+ waitUntil: "load",
+ }),
+ (error) => {
+ assert.equal(error.code, "EGO_NAVIGATION_TIMEOUT");
+ assert.equal(error.committed, true);
+ assert.equal(error.url, "https://example.test/streaming");
+ assert.equal(error.readyState, "loading");
+ assert.match(error.message, /navigation committed/);
+ assert.match(error.message, /waitForLoadState\("load"\)/);
+ return true;
+ },
+ );
+ });
+});
+
+test("Page.goto timeout reports when no new document committed", async () => {
+ await withFixture(async (fixture) => {
+ const baseCdp = fixture.services.cdp;
+ let nowMs = 0;
+ const task = taskForRound(fixture, "round-a", {
+ async cdp(method, params, sessionId, timeoutMs) {
+ if (
+ method === "Page.navigate" &&
+ params.url === "https://example.test/never-committed"
+ ) {
+ nowMs = 100;
+ throw new CdpRequestTimeoutError(method, timeoutMs, sessionId);
+ }
+ return baseCdp(method, params, sessionId, timeoutMs);
+ },
+ now: () => nowMs,
+ });
+ const page = await openTestPage(task, "https://example.test/first");
+ nowMs = 0;
+
+ await assert.rejects(
+ () =>
+ page.goto("https://example.test/never-committed", {
+ timeout: 100,
+ waitUntil: "load",
+ }),
+ (error) => {
+ assert.equal(error.code, "EGO_NAVIGATION_TIMEOUT");
+ assert.equal(error.committed, false);
+ assert.equal(error.url, undefined);
+ assert.equal(error.readyState, undefined);
+ assert.doesNotMatch(error.message, /Continue on this Page/);
+ return true;
+ },
+ );
+ });
+});
+
+test("Page.goto performs one final loader check at the timeout boundary", async () => {
+ await withFixture(async (fixture) => {
+ const baseCdp = fixture.services.cdp;
+ let nowMs = 0;
+ let frameChecks = 0;
+ const task = taskForRound(fixture, "round-a", {
+ async cdp(method, params, sessionId, timeoutMs) {
+ if (method === "Page.navigate") {
+ await baseCdp(method, params, sessionId, timeoutMs);
+ return {
+ result: { frameId: "frame-1", loaderId: "loader-new" },
+ };
+ }
+ if (method === "Page.getFrameTree") {
+ frameChecks += 1;
+ return {
+ result: {
+ frameTree: {
+ frame: {
+ id: "frame-1",
+ loaderId: frameChecks >= 3 ? "loader-new" : "loader-old",
+ },
+ },
+ },
+ };
+ }
+ return baseCdp(method, params, sessionId, timeoutMs);
+ },
+ now: () => nowMs,
+ async sleep(ms) {
+ nowMs += ms;
+ },
+ });
+ const page = await openTestPage(task, "https://example.test/first");
+ nowMs = 0;
+ frameChecks = 0;
+ fixture.setDocumentLifecycle({
+ readyState: "loading",
+ domContentLoaded: false,
+ });
+
+ await assert.rejects(
+ () =>
+ page.goto("https://example.test/boundary", {
+ timeout: 100,
+ waitUntil: "load",
+ }),
+ (error) => {
+ assert.equal(error.committed, true);
+ assert.equal(error.url, "https://example.test/boundary");
+ return true;
+ },
+ );
+ assert.equal(frameChecks, 3);
+ });
+});
+
+test("Page.reload reloads the current document and waits for the requested state", async () => {
+ await withFixture(async (fixture) => {
+ const baseCdp = fixture.services.cdp;
+ let loaderId = "loader-old";
+ let reloading = false;
+ let postReloadChecks = 0;
+ let reloadParams;
+ const task = taskForRound(fixture, "round-a", {
+ async cdp(method, params, sessionId, timeoutMs) {
+ if (method === "Page.getFrameTree") {
+ if (reloading) {
+ postReloadChecks += 1;
+ if (postReloadChecks >= 2) loaderId = "loader-new";
+ }
+ return {
+ result: {
+ frameTree: { frame: { id: "frame-1", loaderId } },
+ },
+ };
+ }
+ if (method === "Page.reload") {
+ reloadParams = params;
+ reloading = true;
+ return {};
+ }
+ return baseCdp(method, params, sessionId, timeoutMs);
+ },
+ });
+ const page = await openTestPage(task, "https://example.test/first");
+ fixture.setDocumentLifecycle({
+ readyState: "interactive",
+ domContentLoaded: true,
+ });
+ assert.deepEqual(
+ await page.reload({ timeout: 250, waitUntil: "domcontentloaded" }),
+ {},
+ );
+ assert.deepEqual(reloadParams, { loaderId: "loader-old" });
+ assert.equal(
+ postReloadChecks,
+ 2,
+ "reload waits for a new main-frame loader",
+ );
+ });
+});
+
+test("Page.reload times out when no new document commits", async () => {
+ await withFixture(async (fixture) => {
+ const baseCdp = fixture.services.cdp;
+ let nowMs = 0;
+ const task = taskForRound(fixture, "round-a", {
+ async cdp(method, params, sessionId, timeoutMs) {
+ if (method === "Page.getFrameTree") {
+ return {
+ result: {
+ frameTree: {
+ frame: { id: "frame-1", loaderId: "loader-old" },
+ },
+ },
+ };
+ }
+ if (method === "Page.reload") return {};
+ return baseCdp(method, params, sessionId, timeoutMs);
+ },
+ now: () => nowMs,
+ async sleep(ms) {
+ nowMs += ms;
+ },
+ });
+ const page = await openTestPage(task, "https://example.test/first");
+
+ await assert.rejects(
+ () => page.reload({ timeout: 100, waitUntil: "commit" }),
+ /page\.reload timed out after 100ms waiting for commit/,
);
});
});
@@ -1621,6 +1985,276 @@ test("Page evaluate preserves a large nested JSON argument", async () => {
});
});
+test("Page evaluate preserves user exceptions that resemble protocol timeouts", async () => {
+ await withFixture(async (fixture) => {
+ const baseCdp = fixture.services.cdp;
+ const task = taskForRound(fixture, "round-a", {
+ async cdp(method, params, sessionId, timeoutMs) {
+ if (
+ method === "Runtime.evaluate" &&
+ params.expression.includes("userTimeoutLikeError")
+ ) {
+ return {
+ result: {
+ type: "object",
+ subtype: "error",
+ description: "Error: Execution was terminated",
+ },
+ exceptionDetails: { text: "Uncaught" },
+ };
+ }
+ return baseCdp(method, params, sessionId, timeoutMs);
+ },
+ });
+ const page = await openTestPage(task, "https://example.test/evaluate");
+
+ await assert.rejects(
+ () =>
+ page.evaluate(function userTimeoutLikeError() {
+ throw new Error("Execution was terminated");
+ }),
+ (error) => {
+ assert.equal(error.code, undefined);
+ assert.match(error.message, /Execution was terminated/);
+ return true;
+ },
+ );
+ });
+});
+
+test("Page.waitForFunction gives one predicate the remaining overall timeout", async () => {
+ await withFixture(async (fixture) => {
+ const baseCdp = fixture.services.cdp;
+ let timedCall;
+ const task = taskForRound(fixture, "round-a", {
+ async cdp(method, params, sessionId, timeoutMs) {
+ if (
+ method === "Runtime.evaluate" &&
+ params.expression.includes("__egoWaitForFunction")
+ ) {
+ timedCall = { params, timeoutMs };
+ return {
+ result: {
+ type: "object",
+ value: {
+ matched: true,
+ url: "https://example.test/wait",
+ title: "wait",
+ },
+ },
+ };
+ }
+ return baseCdp(method, params, sessionId, timeoutMs);
+ },
+ });
+ const page = await openTestPage(task, "https://example.test/wait");
+
+ assert.equal(
+ await page.waitForFunction(
+ async () => {
+ await new Promise((resolve) => setTimeout(resolve, 1_500));
+ return true;
+ },
+ undefined,
+ { timeout: 2_500 },
+ ),
+ true,
+ );
+ assert.equal(timedCall.params.timeout, 2_500);
+ assert.equal(timedCall.timeoutMs, 2_750);
+ });
+});
+
+test("Page evaluate gives synchronous code an execution deadline", async () => {
+ await withFixture(async (fixture) => {
+ const baseCdp = fixture.services.cdp;
+ let first = true;
+ let timedCall;
+ const task = taskForRound(fixture, "round-a", {
+ async cdp(method, params, sessionId, timeoutMs) {
+ if (
+ first &&
+ method === "Runtime.evaluate" &&
+ params.expression.includes("__egoPageEvaluate")
+ ) {
+ first = false;
+ timedCall = { params, timeoutMs };
+ throw new Error("Execution was terminated");
+ }
+ return baseCdp(method, params, sessionId, timeoutMs);
+ },
+ });
+ const page = await openTestPage(task, "https://example.test/evaluate");
+
+ await assert.rejects(
+ () =>
+ page.evaluate(() => {
+ while (true) {}
+ }),
+ (error) => {
+ assert.equal(error.code, "EGO_PAGE_EVALUATION_TIMED_OUT");
+ assert.equal(error.executionStopped, true);
+ assert.equal(error.mayHaveLateEffects, true);
+ assert.equal(error.pageResponsive, true);
+ assert.match(error.message, /execution was stopped/i);
+ return true;
+ },
+ );
+ assert.equal(timedCall.params.timeout, 14_000);
+ assert.equal(timedCall.timeoutMs, 15_000);
+ assert.deepEqual(await page.evaluate((value) => value, "ready"), "ready");
+ });
+});
+
+test("Page evaluate distinguishes a responsive pending promise from a stuck renderer", async () => {
+ await withFixture(async (fixture) => {
+ const baseCdp = fixture.services.cdp;
+ let first = true;
+ let probes = 0;
+ const task = taskForRound(fixture, "round-a", {
+ async cdp(method, params, sessionId, timeoutMs) {
+ if (
+ first &&
+ method === "Runtime.evaluate" &&
+ params.expression.includes("__egoPageEvaluate")
+ ) {
+ first = false;
+ throw new CdpRequestTimeoutError(method, timeoutMs, sessionId);
+ }
+ if (method === "Runtime.evaluate" && params.expression === "1") {
+ probes += 1;
+ return { result: { type: "number", value: 1 } };
+ }
+ return baseCdp(method, params, sessionId, timeoutMs);
+ },
+ });
+ const page = await openTestPage(task, "https://example.test/evaluate");
+
+ await assert.rejects(
+ () => page.evaluate(async () => new Promise(() => {})),
+ (error) => {
+ assert.equal(error.code, "EGO_PAGE_EVALUATION_TIMED_OUT");
+ assert.equal(error.executionStopped, false);
+ assert.equal(error.mayHaveLateEffects, true);
+ assert.equal(error.pageResponsive, true);
+ assert.match(error.message, /still pending/i);
+ return true;
+ },
+ );
+ assert.equal(probes, 1);
+ assert.equal(
+ fixture.calls.some(
+ ([kind, method]) =>
+ kind === "cdp" && method === "Runtime.terminateExecution",
+ ),
+ false,
+ );
+ });
+});
+
+test("Page evaluate terminates execution only after its health probe also times out", async () => {
+ await withFixture(async (fixture) => {
+ const baseCdp = fixture.services.cdp;
+ let initial = true;
+ let healthChecks = 0;
+ let terminateCalls = 0;
+ const task = taskForRound(fixture, "round-a", {
+ async cdp(method, params, sessionId, timeoutMs) {
+ if (
+ initial &&
+ method === "Runtime.evaluate" &&
+ params.expression.includes("__egoPageEvaluate")
+ ) {
+ initial = false;
+ throw new CdpRequestTimeoutError(method, timeoutMs, sessionId);
+ }
+ if (method === "Runtime.evaluate" && params.expression === "1") {
+ healthChecks += 1;
+ if (healthChecks === 1) {
+ throw new CdpRequestTimeoutError(method, timeoutMs, sessionId);
+ }
+ return { result: { type: "number", value: 1 } };
+ }
+ if (method === "Runtime.terminateExecution") {
+ terminateCalls += 1;
+ return {};
+ }
+ return baseCdp(method, params, sessionId, timeoutMs);
+ },
+ });
+ const page = await openTestPage(task, "https://example.test/evaluate");
+
+ await assert.rejects(
+ () =>
+ page.evaluate(() => {
+ while (true) {}
+ }),
+ (error) => {
+ assert.equal(error.code, "EGO_PAGE_EVALUATION_TIMED_OUT");
+ assert.equal(error.executionStopped, true);
+ assert.equal(error.mayHaveLateEffects, true);
+ assert.equal(error.pageResponsive, true);
+ assert.match(error.message, /renderer stopped responding/i);
+ return true;
+ },
+ );
+ assert.equal(terminateCalls, 1);
+ assert.equal(healthChecks, 2);
+ });
+});
+
+test("Page evaluate retries when termination is consumed by the first recovery probe", async () => {
+ await withFixture(async (fixture) => {
+ const baseCdp = fixture.services.cdp;
+ let initial = true;
+ let healthChecks = 0;
+ let terminateCalls = 0;
+ const task = taskForRound(fixture, "round-a", {
+ async cdp(method, params, sessionId, timeoutMs) {
+ if (
+ initial &&
+ method === "Runtime.evaluate" &&
+ params.expression.includes("__egoPageEvaluate")
+ ) {
+ initial = false;
+ throw new CdpRequestTimeoutError(method, timeoutMs, sessionId);
+ }
+ if (method === "Runtime.evaluate" && params.expression === "1") {
+ healthChecks += 1;
+ if (healthChecks === 1) {
+ throw new CdpRequestTimeoutError(method, timeoutMs, sessionId);
+ }
+ if (healthChecks === 2) {
+ throw new Error("Execution was terminated");
+ }
+ return { result: { type: "number", value: 1 } };
+ }
+ if (method === "Runtime.terminateExecution") {
+ terminateCalls += 1;
+ return {};
+ }
+ return baseCdp(method, params, sessionId, timeoutMs);
+ },
+ });
+ const page = await openTestPage(task, "https://example.test/evaluate");
+
+ await assert.rejects(
+ () =>
+ page.evaluate(() => {
+ while (true) {}
+ }),
+ (error) => {
+ assert.equal(error.code, "EGO_PAGE_EVALUATION_TIMED_OUT");
+ assert.equal(error.executionStopped, true);
+ assert.equal(error.pageResponsive, true);
+ return true;
+ },
+ );
+ assert.equal(terminateCalls, 1);
+ assert.equal(healthChecks, 3);
+ });
+});
+
test("Page fetch activates its target and returns a structured non-2xx response", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
@@ -1795,7 +2429,8 @@ test("Page click returns a pending JavaScript dialog without waiting for input c
const activationsBeforeHandle = fixture.calls.filter(
([kind, method]) => kind === "cdp" && method === "Target.activateTarget",
).length;
- await page.cdp("Page.handleJavaScriptDialog", { accept: true });
+ assert.equal(await page.acceptDialog(), true);
+ assert.equal(await page.acceptDialog(), false);
assert.equal(
fixture.calls.filter(
([kind, method]) =>
@@ -1816,6 +2451,62 @@ test("Page click returns a pending JavaScript dialog without waiting for input c
});
});
+test("a no-dialog response keeps current snapshot refs", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/dialog");
+ await page.snapshot();
+
+ assert.equal(
+ fixture.services.pageRefs.forTarget(page.targetId).get("21")
+ .backendNodeId,
+ 21,
+ );
+ assert.equal(await page.dismissDialog(), false);
+ assert.equal(
+ fixture.services.pageRefs.forTarget(page.targetId).get("21")
+ .backendNodeId,
+ 21,
+ "an idempotent no-dialog call must not invalidate an unchanged DOM",
+ );
+ });
+});
+
+test("Page accepts prompt text and dismisses dialogs on its own session", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const first = await openTestPage(task, "https://example.test/first");
+ const second = await openTestPage(task, "https://example.test/second");
+
+ fixture.openDialogOnNextClick({
+ type: "prompt",
+ message: "Choose a name",
+ defaultPrompt: "guest",
+ });
+ const promptReceipt = await first.click("#prompt");
+ assert.equal(promptReceipt.dialog.defaultPrompt, "guest");
+ assert.equal(await second.dismissDialog(), false);
+ assert.equal(await first.acceptDialog("agent"), true);
+
+ fixture.openDialogOnNextClick({ type: "confirm", message: "Continue?" });
+ await first.click("#confirm");
+ assert.equal(await first.dismissDialog(), true);
+
+ const dialogCalls = fixture.calls.filter(
+ ([kind, method]) =>
+ kind === "cdp" && method === "Page.handleJavaScriptDialog",
+ );
+ assert.deepEqual(
+ dialogCalls.map(([, , params, sessionId]) => [params, sessionId]),
+ [
+ [{ accept: false }, "session:target-2"],
+ [{ accept: true, promptText: "agent" }, "session:target-1"],
+ [{ accept: false }, "session:target-1"],
+ ],
+ );
+ });
+});
+
test("Page fill uses its target session and reports no popup when none opened", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
@@ -2057,6 +2748,144 @@ test("Page selectOption selects values through the addressed Page", async () =>
});
});
+test("Page selectOption accepts Playwright-style labels, values, and indexes", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/form");
+
+ fixture.configureSelectOptions([
+ { value: "09", label: "September" },
+ { value: "10", label: "October" },
+ ]);
+ assert.deepEqual(await page.selectOption("#month", { label: "October" }), [
+ "10",
+ ]);
+ fixture.configureSelectOptions([
+ { value: "AZ", label: "Arizona" },
+ { value: "CA", label: "California" },
+ ]);
+ assert.deepEqual(await page.selectOption("#state", "Arizona"), ["AZ"]);
+ fixture.configureSelectOptions([
+ { value: "one", label: "One" },
+ { value: "two", label: "Two" },
+ ]);
+ assert.deepEqual(
+ await page.selectOption("#tags", [{ value: "one" }, { index: 1 }]),
+ ["one", "two"],
+ );
+ });
+});
+
+test("Page selectOption validates option descriptors", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/form");
+
+ assert.deepEqual(await page.selectOption("#month", null), []);
+ assert.deepEqual(await page.selectOption("#month", []), []);
+ await assert.rejects(
+ () => page.selectOption("#month", {}),
+ /must specify value, label, or index/,
+ );
+ await assert.rejects(
+ () => page.selectOption("#month", { index: -1 }),
+ /index must be a non-negative integer/,
+ );
+ await assert.rejects(
+ () => page.selectOption("#month", { text: "October" }),
+ /unknown field "text"/,
+ );
+ });
+});
+
+test("Page selectOption clears existing values before applying new choices", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/form");
+ await page.selectOption("#tags", ["one", "two"]);
+
+ const actionCall = fixture.calls.find(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Runtime.callFunctionOn" &&
+ params.functionDeclaration.includes("selectOptionsForAction"),
+ );
+ assert(actionCall, "selectOption sends its browser-side action function");
+ const selectOptionsForAction = Function(
+ `return (${actionCall[2].functionDeclaration})`,
+ )();
+ const options = [
+ { value: "one", label: "One", selected: false },
+ { value: "two", label: "Two", selected: false },
+ { value: "undefined", label: "Undefined", selected: true },
+ { value: "", label: "None", selected: false },
+ ];
+ const select = {
+ tagName: "SELECT",
+ isConnected: true,
+ disabled: false,
+ multiple: true,
+ options,
+ ownerDocument: {
+ defaultView: {
+ getComputedStyle: () => ({ display: "block", visibility: "visible" }),
+ },
+ },
+ getBoundingClientRect: () => ({ width: 100, height: 30 }),
+ get selectedOptions() {
+ return options.filter((option) => option.selected);
+ },
+ dispatchEvent() {},
+ };
+
+ assert.deepEqual(selectOptionsForAction.call(select, ["one", "two"]), {
+ selected: ["one", "two"],
+ });
+ assert.deepEqual(selectOptionsForAction.call(select, []), { selected: [] });
+ assert.deepEqual(selectOptionsForAction.call(select, [""]), {
+ selected: [""],
+ });
+ assert.deepEqual(
+ options.filter((option) => option.selected).map((option) => option.value),
+ [""],
+ "an empty string is a valid option value",
+ );
+ assert.deepEqual(selectOptionsForAction.call(select, []), { selected: [] });
+
+ options[1].disabled = true;
+ assert.deepEqual(selectOptionsForAction.call(select, [{ value: "two" }]), {
+ selected: ["two"],
+ });
+ assert.deepEqual(
+ options.filter((option) => option.selected).map((option) => option.value),
+ ["two"],
+ "a disabled option remains programmatically selectable",
+ );
+
+ options[1].disabled = false;
+ select.disabled = true;
+ assert.deepEqual(selectOptionsForAction.call(select, ["one"]), {
+ error: "element is disabled",
+ });
+ select.disabled = false;
+ assert.deepEqual(selectOptionsForAction.call(select, ["one"]), {
+ selected: ["one"],
+ });
+
+ select.getAttribute = (name) => (name === "aria-disabled" ? "true" : null);
+ assert.deepEqual(selectOptionsForAction.call(select, ["one"]), {
+ error: "element is disabled",
+ });
+
+ select.getAttribute = () => null;
+ options[1].getAttribute = (name) =>
+ name === "aria-disabled" ? "true" : null;
+ assert.deepEqual(selectOptionsForAction.call(select, ["two"]), {
+ selected: ["two"],
+ });
+ });
+});
+
test("Page action receipts do not inject observation probes", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
@@ -2752,6 +3581,25 @@ test("Page keyboard releases pressed modifiers when a chord fails", async () =>
});
});
+test("Page keyboard suggests Playwright arrow-key names", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/first");
+
+ for (const [legacy, supported] of [
+ ["Left", "ArrowLeft"],
+ ["Right", "ArrowRight"],
+ ["Up", "ArrowUp"],
+ ["Down", "ArrowDown"],
+ ]) {
+ await assert.rejects(
+ () => page.keyboard.press(legacy),
+ new RegExp(`Unknown key: "${legacy}"\\. Use "${supported}"`),
+ );
+ }
+ });
+});
+
test("low-level Page input skips action observers and returns no receipt", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "darwin" });
@@ -2982,7 +3830,7 @@ test("Page waits and events remain isolated to the addressed target", async () =
readyState: "complete",
domContentLoaded: true,
});
- await first.waitForLoadState("load", { timeout: 250 });
+ await first.waitForLoadState();
fixture.emitPageEvent(first.targetId, "Network.requestWillBeSent", {
requestId: "request-first",
});
@@ -3005,8 +3853,13 @@ test("Page waits and events remain isolated to the addressed target", async () =
["second"],
);
assert.deepEqual(
- (await first.events()).map((event) => event.params.value),
- ["first"],
+ (await first.events()).map((event) => event.method),
+ [
+ "Network.requestWillBeSent",
+ "Network.loadingFinished",
+ "Runtime.consoleAPICalled",
+ ],
+ "network-idle must preserve the addressed Page event stream",
);
assert(
@@ -3021,6 +3874,60 @@ test("Page waits and events remain isolated to the addressed target", async () =
});
});
+test("Page network-idle sees an earlier request without consuming events", async () => {
+ await withFixture(async (fixture) => {
+ let now = 0;
+ let childBusy = true;
+ let childFinishedAt = 0;
+ const task = taskForRound(fixture, "round-a", {
+ now: () => now,
+ async sleep(ms) {
+ now += ms;
+ if (childBusy && now >= 150) {
+ childBusy = false;
+ childFinishedAt = now;
+ }
+ },
+ async ensureNetworkTracking() {},
+ async pageNetworkSessions(sessionId) {
+ return [sessionId, "session:oopif-child"];
+ },
+ networkActivity(sessionIds) {
+ assert.deepEqual(sessionIds, [
+ "session:target-1",
+ "session:oopif-child",
+ ]);
+ return {
+ tracking: true,
+ inflight: childBusy ? 1 : 0,
+ lastActivityAt: childBusy ? 0 : childFinishedAt,
+ };
+ },
+ });
+ const page = await openTestPage(task, "https://example.test/network-idle");
+ fixture.emitPageEvent(page.targetId, "Runtime.consoleAPICalled", {
+ value: "preserve this event",
+ });
+
+ await page.waitForLoadState("networkidle", {
+ timeout: 500,
+ idleMs: 100,
+ });
+
+ assert.equal(
+ childBusy,
+ false,
+ "a request started before the wait must finish",
+ );
+ assert(now >= 250, "the idle window begins after the earlier request ends");
+ assert.deepEqual(
+ (await page.events()).map((event) => event.params.value),
+ ["preserve this event"],
+ "network-idle must not consume unrelated Page events",
+ );
+ });
+});
+
test("Page waitForURL follows a popup from about:blank without activating it", async () => {
await withFixture(async (fixture) => {
let elapsedMs = 0;
@@ -3083,19 +3990,26 @@ 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 () => {
+test("Page.waitForEvent ignores an older popup and resolves the next one", 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");
+ fixture.openPopupOnNextClick("https://example.test/old-popup");
- const receipt = await source.click("#open-popup");
- const popup = await source.waitForEvent("popup", { timeout: 1_000 });
+ const oldReceipt = await source.click("#open-old-popup");
+ fixture.openPopupOnNextClick("https://example.test/next-popup");
+ const popupPromise = source.waitForEvent("popup", { timeout: 1_000 });
+ const nextReceipt = await source.click("#open-next-popup");
+ const popup = await popupPromise;
- assert.equal(popup.label, receipt.popups[0].label);
- assert.equal(await popup.url(), "https://example.test/popup");
- assert.deepEqual(consumeUnhandledPageNotices(), []);
+ assert.notEqual(popup.label, oldReceipt.popups[0].label);
+ assert.equal(popup.label, nextReceipt.popups[0].label);
+ assert.equal(await popup.url(), "https://example.test/next-popup");
+ assert.deepEqual(
+ consumeUnhandledPageNotices().map((notice) => notice.targetId),
+ [oldReceipt.popups[0].targetId],
+ );
});
});
diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.ts
index 5f1578f..b8fa983 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -5,12 +5,15 @@ import {
browserCdp,
browserEgo,
drainPageEvents,
+ ensureNetworkTracking,
ensureSession,
ensureFrameSessions,
invalidateSession,
+ isCdpRequestTimeoutError,
isBrowserRuntime,
- isNetworkDomainEnabled,
isPageDialogOpenedError,
+ networkActivity,
+ pageNetworkSessions,
pendingDialog,
prepareFileChooser,
setPreferredTarget,
@@ -46,6 +49,7 @@ import {
type PageMouseButtonOptions,
type PageMouseClickOptions,
type PageMouseMoveOptions,
+ type PageSelectOption,
} from "./driver/page-actions.js";
import {
normalizeFilePaths,
@@ -60,6 +64,7 @@ import {
} from "./driver/page-keyboard.js";
import {
navigateInPage,
+ reloadInPage,
waitForLoadStateInPage,
waitForSelectorInPage,
waitForURLInPage,
@@ -130,6 +135,8 @@ type PageGotoOptions = {
waitUntil?: PageGotoWaitUntil;
};
+type PageReloadOptions = Pick<PageGotoOptions, "timeout" | "waitUntil">;
+
type PageSnapshotOptions = SnapshotOptions;
type PageScreenshotOptions = Omit<CaptureScreenshotOptions, "full"> & {
@@ -229,6 +236,10 @@ type OperationGate = {
type LedgerPort = {
read(spaceId: number): Promise<PageLedger>;
discard(spaceId: number): Promise<void>;
+ initializeCreatedSpace(
+ spaceId: number,
+ targetId: string,
+ ): Promise<ManagedPage>;
addPage(
spaceId: number,
targetId: string,
@@ -292,7 +303,16 @@ type PageModelServices = {
options: { timeoutMs: number; cancel: boolean },
): FileChooserInterception;
drainEvents(sessionId: string): any[];
- isNetworkDomainEnabled(sessionId: string): boolean;
+ ensureNetworkTracking(
+ sessionIds: string[],
+ timeoutMs?: number,
+ ): Promise<void>;
+ pageNetworkSessions(sessionId: string, timeoutMs?: number): Promise<string[]>;
+ networkActivity(sessionIds: string[]): {
+ tracking: boolean;
+ inflight: number;
+ lastActivityAt: number;
+ };
ensureSession(targetId: string): Promise<string>;
ensureFrameSessions(targetId: string): Promise<Map<string, string>>;
invalidateSession(targetId: string): void;
@@ -320,11 +340,49 @@ export type PageActionReceipt = {
dialog?: Record<string, unknown>;
};
+export class PageEvaluationTimeoutError extends Error {
+ readonly code = "EGO_PAGE_EVALUATION_TIMED_OUT";
+ readonly timeoutMs: number;
+ readonly executionStopped: boolean;
+ readonly mayHaveLateEffects: boolean;
+ readonly pageResponsive: boolean;
+
+ constructor(
+ message: string,
+ {
+ timeoutMs,
+ executionStopped,
+ mayHaveLateEffects,
+ pageResponsive,
+ }: {
+ timeoutMs: number;
+ executionStopped: boolean;
+ mayHaveLateEffects: boolean;
+ pageResponsive: boolean;
+ },
+ ) {
+ super(message);
+ this.name = "PageEvaluationTimeoutError";
+ this.timeoutMs = timeoutMs;
+ this.executionStopped = executionStopped;
+ this.mayHaveLateEffects = mayHaveLateEffects;
+ this.pageResponsive = pageResponsive;
+ }
+}
+
const PAGE_CLOSE_CONFIRM_TIMEOUT_MS = 2_000;
const PAGE_CLOSE_CONFIRM_INTERVAL_MS = 50;
+const CREATED_SPACE_TAB_TIMEOUT_MS = 2_000;
+const CREATED_SPACE_TAB_POLL_INTERVAL_MS = 50;
const DEFAULT_PAGE_ACTION_TIMEOUT_MS = 3_000;
const PAGE_ACTION_RESOLUTION_RETRY_MS = 500;
const CONTROL_POLL_INTERVAL_MS = 20_000;
+const PAGE_EVALUATE_EXECUTION_TIMEOUT_MS = 14_000;
+const PAGE_EVALUATE_TRANSPORT_TIMEOUT_MS = 15_000;
+const PAGE_EVALUATE_HEALTH_TIMEOUT_MS = 250;
+const PAGE_EVALUATE_HEALTH_EXECUTION_TIMEOUT_MS = 200;
+const PAGE_EVALUATE_TERMINATE_TIMEOUT_MS = 1_000;
+const WAIT_FOR_FUNCTION_TRANSPORT_GRACE_MS = 250;
const CONTROL_WAIT_TIMEOUT_MS = 600_000;
type RawActionRunner = (
@@ -532,6 +590,7 @@ const defaultPageRefs = new PageRefRegistry();
const unmanagedPageConstructorToken = Symbol("UnmanagedPage");
const captureUserBoundaryToken = Symbol("captureUserBoundary");
const initializeTaskSpaceToken = Symbol("initializeTaskSpace");
+const initializeCreatedSpaceToken = Symbol("initializeCreatedSpace");
const defaultGate: OperationGate = {
withSpace: defaultWithSpace,
@@ -602,7 +661,9 @@ const baseDefaultServices: Omit<PageModelServices, "ledger" | "pageBudget"> = {
pendingDialog,
prepareFileChooser,
drainEvents: drainPageEvents,
- isNetworkDomainEnabled,
+ ensureNetworkTracking,
+ pageNetworkSessions,
+ networkActivity,
ensureSession,
ensureFrameSessions,
invalidateSession,
@@ -658,10 +719,14 @@ export async function captureTaskSpaceUserBoundary(
await task.captureUserBoundary(captureUserBoundaryToken);
}
-/** Enable round-local discovery for pages that appear after an action returns. */
+/** Initialize Page state and round-local discovery before exposing a TaskSpace. */
export async function initializeTaskSpaceHandle(
task: TaskSpace,
+ options: { created?: boolean } = {},
): Promise<void> {
+ if (options.created) {
+ await task.initializeCreatedSpace(initializeCreatedSpaceToken);
+ }
await task.initializeBackgroundPageDiscovery(initializeTaskSpaceToken);
}
@@ -701,6 +766,52 @@ class TaskSpace {
return this.#userPage;
}
+ async initializeCreatedSpace(token: symbol): Promise<void> {
+ if (token !== initializeCreatedSpaceToken) {
+ throw new TypeError("created-space initialization is internal");
+ }
+ if (this.ownership !== "agent") {
+ throw new Error("only a newly created Agent TaskSpace can initialize p1");
+ }
+ await this.#services.gate.withSpace(this.id, async () => {
+ const targetId = await this.#waitForCreatedSpaceTab();
+ const page = await this.#services.ledger.initializeCreatedSpace(
+ this.id,
+ targetId,
+ );
+ this.#services.setPreferredTarget(page.targetId);
+ });
+ }
+
+ async #waitForCreatedSpaceTab(): Promise<string> {
+ const deadline = this.#services.now() + CREATED_SPACE_TAB_TIMEOUT_MS;
+ while (true) {
+ const tabs = await this.#services.listTabs();
+ if (tabs.length > 1) {
+ throw new Error(
+ `new task space expected one default tab, found ${tabs.length}`,
+ );
+ }
+ if (tabs.length === 1) {
+ const targetId = tabs[0]?.targetId;
+ if (typeof targetId !== "string" || targetId.length === 0) {
+ throw new Error("new task space default tab returned no targetId");
+ }
+ return targetId;
+ }
+
+ const remainingMs = deadline - this.#services.now();
+ if (remainingMs <= 0) {
+ throw new Error(
+ `new task space did not expose its default tab within ${CREATED_SPACE_TAB_TIMEOUT_MS}ms`,
+ );
+ }
+ await this.#services.sleep(
+ Math.min(CREATED_SPACE_TAB_POLL_INTERVAL_MS, remainingMs),
+ );
+ }
+ }
+
async initializeBackgroundPageDiscovery(token: symbol): Promise<void> {
if (token !== initializeTaskSpaceToken) {
throw new TypeError(
@@ -1268,6 +1379,23 @@ class Page {
return receipt;
}
+ async reload(options: PageReloadOptions = {}): Promise<PageActionReceipt> {
+ validatePublicApiOptions("Page.reload", options);
+ const timeoutMs = options.timeout ?? 15_000;
+ const waitUntil = options.waitUntil ?? "load";
+ const page = await this.#resolve();
+ const { receipt } = await this.#runActionBoundary(
+ page,
+ async (sessionId) => {
+ await reloadInPage(this.#services, sessionId, {
+ timeoutMs,
+ waitUntil,
+ });
+ },
+ );
+ return receipt;
+ }
+
async snapshot(options: PageSnapshotOptions = {}): Promise<string> {
validatePublicApiOptions("Page.snapshot", options);
const page = await this.#resolve();
@@ -1359,7 +1487,9 @@ class Page {
),
);
}, timeoutMs);
- for (const notice of peekUnhandledPageNotices()) onNotice(notice);
+
+ // Playwright-style event waits observe only future events. Replaying a
+ // pending notice here can return a popup from an earlier action.
// 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.
@@ -1402,6 +1532,19 @@ class Page {
});
}
+ /** Accept the JavaScript dialog currently blocking this Page, if any. */
+ async acceptDialog(promptText?: string): Promise<boolean> {
+ if (promptText !== undefined && typeof promptText !== "string") {
+ throw new TypeError("page.acceptDialog promptText must be a string");
+ }
+ return this.#handleJavaScriptDialog(true, promptText);
+ }
+
+ /** Dismiss the JavaScript dialog currently blocking this Page, if any. */
+ async dismissDialog(): Promise<boolean> {
+ return this.#handleJavaScriptDialog(false);
+ }
+
async evaluate<T = unknown>(
expression: string | ((argument: any) => T | Promise<T>),
argument?: unknown,
@@ -1454,17 +1597,31 @@ class Page {
try {
while (this.#services.now() <= deadline) {
const remaining = Math.max(1, deadline - this.#services.now());
+ const executionTimeoutMs = remaining;
+ const transportTimeoutMs =
+ remaining + WAIT_FOR_FUNCTION_TRANSPORT_GRACE_MS;
+ const evaluationStartedAt = this.#services.now();
try {
- const response = await this.#services.cdp(
- "Runtime.evaluate",
- {
- expression: source,
- returnByValue: true,
- awaitPromise: true,
- },
- sessionId,
- Math.min(1_000, remaining),
- );
+ let response;
+ try {
+ response = await this.#services.cdp(
+ "Runtime.evaluate",
+ {
+ expression: source,
+ returnByValue: true,
+ awaitPromise: true,
+ timeout: executionTimeoutMs,
+ },
+ sessionId,
+ transportTimeoutMs,
+ );
+ } catch (error) {
+ throw normalizeProtocolExecutionTimeout(
+ error,
+ this.#services.now() - evaluationStartedAt,
+ executionTimeoutMs,
+ );
+ }
const state = runtimeValue(response, source);
if (isWaitForFunctionState(state)) {
lastUrl = state.url;
@@ -1472,6 +1629,17 @@ class Page {
if (state.matched) return true as const;
}
} catch (error) {
+ if (isEvaluationExecutionDeadlineError(error)) {
+ break;
+ }
+ if (isRuntimeEvaluateTransportTimeout(error)) {
+ throw await recoverPageEvaluationTimeout(
+ this.#services,
+ sessionId,
+ "page.waitForFunction",
+ timeoutMs,
+ );
+ }
if (!isRetryablePageEvaluationError(error)) {
throw enrichPageCallbackReferenceError(
error,
@@ -1590,7 +1758,7 @@ class Page {
}
async waitForLoadState(
- state: "domcontentloaded" | "load" | "networkidle",
+ state: "domcontentloaded" | "load" | "networkidle" = "load",
options: PageWaitForLoadStateOptions = {},
): Promise<void> {
validatePublicApiOptions("Page.waitForLoadState", options);
@@ -1750,21 +1918,17 @@ class Page {
async selectOption(
selector: string,
- valueOrValues: string | string[],
+ valueOrValues: PageSelectOption | PageSelectOption[] | null,
options: { timeout?: number } = {},
): Promise<string[]> {
validatePublicApiOptions("Page.selectOption", options);
- const values =
- typeof valueOrValues === "string" ? [valueOrValues] : valueOrValues;
- if (
- !Array.isArray(values) ||
- values.length === 0 ||
- values.some((value) => typeof value !== "string")
- ) {
- throw new TypeError(
- "page.selectOption valueOrValues must be a string or a non-empty string array",
- );
- }
+ const choices =
+ valueOrValues === null
+ ? []
+ : Array.isArray(valueOrValues)
+ ? valueOrValues
+ : [valueOrValues];
+ choices.forEach(validateSelectOptionChoice);
const timeoutMs = options.timeout ?? DEFAULT_PAGE_ACTION_TIMEOUT_MS;
const page = await this.#resolve();
return this.#runInputBoundary(page, async (sessionId) => {
@@ -1780,7 +1944,7 @@ class Page {
sessionId,
refMap,
selector,
- values,
+ choices,
iframeSessions,
);
} catch (error) {
@@ -1988,8 +2152,24 @@ class Page {
expression,
hasArgument,
serializedArgument,
+ PAGE_EVALUATE_TRANSPORT_TIMEOUT_MS,
+ PAGE_EVALUATE_EXECUTION_TIMEOUT_MS,
);
} catch (error) {
+ if (isEvaluationExecutionDeadlineError(error)) {
+ throw evaluationExecutionDeadlineError(
+ "page.evaluate",
+ PAGE_EVALUATE_EXECUTION_TIMEOUT_MS,
+ );
+ }
+ if (isRuntimeEvaluateTransportTimeout(error)) {
+ throw await recoverPageEvaluationTimeout(
+ this.#services,
+ sessionId,
+ "page.evaluate",
+ PAGE_EVALUATE_TRANSPORT_TIMEOUT_MS,
+ );
+ }
if (typeof expression === "function") {
throw enrichPageCallbackReferenceError(error, "page.evaluate");
}
@@ -2077,6 +2257,32 @@ class Page {
return receipt;
}
+ async #handleJavaScriptDialog(
+ accept: boolean,
+ promptText?: string,
+ ): Promise<boolean> {
+ const page = await this.#resolve();
+ return this.#services.gate.withPage(page, async ({ sessionId }) => {
+ try {
+ await this.#services.cdp(
+ "Page.handleJavaScriptDialog",
+ {
+ accept,
+ ...(promptText === undefined ? {} : { promptText }),
+ },
+ sessionId,
+ );
+ // A handled dialog resumes its callback and may mutate the DOM. A
+ // no-dialog response leaves the page untouched, so its refs stay valid.
+ this.#services.pageRefs.clear(page.targetId);
+ return true;
+ } catch (error) {
+ if (isNoJavaScriptDialogError(error)) return false;
+ throw error;
+ }
+ });
+ }
+
async #runInputBoundary<T>(
page: PageTarget,
operation: (sessionId: string) => Promise<T>,
@@ -2273,38 +2479,64 @@ async function evaluateInSession<T>(
hasArgument: boolean,
serializedArgument?: unknown,
timeoutMs?: number,
+ executionTimeoutMs?: number,
): Promise<T> {
+ const startedAt = services.now();
if (typeof expression === "string") {
- const response = await services.cdp(
- "Runtime.evaluate",
- {
- expression,
- returnByValue: true,
- awaitPromise: true,
- },
- sessionId,
- timeoutMs,
- );
+ let response;
+ try {
+ response = await services.cdp(
+ "Runtime.evaluate",
+ {
+ expression,
+ returnByValue: true,
+ awaitPromise: true,
+ ...(executionTimeoutMs === undefined
+ ? {}
+ : { timeout: executionTimeoutMs }),
+ },
+ sessionId,
+ timeoutMs,
+ );
+ } catch (error) {
+ throw normalizeProtocolExecutionTimeout(
+ error,
+ services.now() - startedAt,
+ executionTimeoutMs,
+ );
+ }
return runtimeValue(response, expression) as T;
}
const source = expression.toString();
- const response = await services.cdp(
- "Runtime.evaluate",
- {
- expression: `(async function __egoPageEvaluate() {
+ let response;
+ try {
+ response = await services.cdp(
+ "Runtime.evaluate",
+ {
+ expression: `(async function __egoPageEvaluate() {
return await ${pageFunctionCallExpression(
source,
hasArgument,
serializedArgument,
)};
})()`,
- returnByValue: true,
- awaitPromise: true,
- },
- sessionId,
- timeoutMs,
- );
+ returnByValue: true,
+ awaitPromise: true,
+ ...(executionTimeoutMs === undefined
+ ? {}
+ : { timeout: executionTimeoutMs }),
+ },
+ sessionId,
+ timeoutMs,
+ );
+ } catch (error) {
+ throw normalizeProtocolExecutionTimeout(
+ error,
+ services.now() - startedAt,
+ executionTimeoutMs,
+ );
+ }
return runtimeValue(response, source) as T;
}
@@ -2403,13 +2635,167 @@ function waitForFunctionTimeoutError(
function isRetryablePageEvaluationError(error: unknown): boolean {
if (!(error instanceof Error)) return false;
return (
- error.message.includes("CDP request timed out: Runtime.evaluate") ||
error.message.includes("Execution context was destroyed") ||
error.message.includes("Cannot find context with specified id") ||
error.message.includes("Inspected target navigated")
);
}
+function isRuntimeEvaluateTransportTimeout(error: unknown): boolean {
+ return (
+ (isCdpRequestTimeoutError(error) && error.method === "Runtime.evaluate") ||
+ (error instanceof Error &&
+ error.message.includes("CDP request timed out: Runtime.evaluate"))
+ );
+}
+
+function isEvaluationExecutionDeadlineError(error: unknown): boolean {
+ return (
+ error instanceof Error &&
+ (error as Error & { code?: string }).code === "EGO_PAGE_EXECUTION_DEADLINE"
+ );
+}
+
+function isProtocolExecutionTimeout(
+ error: unknown,
+ elapsedMs?: number,
+ timeoutMs?: number,
+): boolean {
+ return (
+ error instanceof Error &&
+ (/Execution was terminated|Script execution timed out/i.test(
+ error.message,
+ ) ||
+ (error.message === "Internal error" &&
+ timeoutMs !== undefined &&
+ elapsedMs !== undefined &&
+ elapsedMs >= timeoutMs - 100))
+ );
+}
+
+function normalizeProtocolExecutionTimeout(
+ error: unknown,
+ elapsedMs: number,
+ timeoutMs?: number,
+): unknown {
+ if (!isProtocolExecutionTimeout(error, elapsedMs, timeoutMs)) return error;
+ if (error instanceof Error) {
+ (error as Error & { code?: string }).code = "EGO_PAGE_EXECUTION_DEADLINE";
+ }
+ return error;
+}
+
+function evaluationExecutionDeadlineError(
+ apiName: string,
+ timeoutMs: number,
+): PageEvaluationTimeoutError {
+ return new PageEvaluationTimeoutError(
+ `${apiName} exceeded its ${timeoutMs}ms page-execution safety limit. The current JavaScript execution was stopped and the Page is ready for another command, but work scheduled earlier may still produce late side effects.`,
+ {
+ timeoutMs,
+ executionStopped: true,
+ mayHaveLateEffects: true,
+ pageResponsive: true,
+ },
+ );
+}
+
+async function recoverPageEvaluationTimeout(
+ services: PageModelServices,
+ sessionId: string,
+ apiName: string,
+ timeoutMs: number,
+): Promise<PageEvaluationTimeoutError> {
+ if (await pageEvaluationHealthProbe(services, sessionId)) {
+ return new PageEvaluationTimeoutError(
+ `${apiName} timed out after ${timeoutMs}ms while waiting for page JavaScript. The Page is responsive, but the evaluation is still pending and may produce late side effects. Reload or close the Page when that would be unsafe.`,
+ {
+ timeoutMs,
+ executionStopped: false,
+ mayHaveLateEffects: true,
+ pageResponsive: true,
+ },
+ );
+ }
+
+ let terminationSent = false;
+ try {
+ await services.cdp(
+ "Runtime.terminateExecution",
+ {},
+ sessionId,
+ PAGE_EVALUATE_TERMINATE_TIMEOUT_MS,
+ );
+ terminationSent = true;
+ } catch (error) {
+ if (!isCdpRequestTimeoutError(error)) throw error;
+ }
+
+ if (
+ terminationSent &&
+ (await pageEvaluationHealthProbe(services, sessionId))
+ ) {
+ return new PageEvaluationTimeoutError(
+ `${apiName} timed out after ${timeoutMs}ms and the renderer stopped responding. The current execution was stopped and the Page recovered, but work scheduled earlier may still produce late side effects.`,
+ {
+ timeoutMs,
+ executionStopped: true,
+ mayHaveLateEffects: true,
+ pageResponsive: true,
+ },
+ );
+ }
+
+ return new PageEvaluationTimeoutError(
+ `${apiName} timed out after ${timeoutMs}ms and the Page is still unresponsive. Execution could not be confirmed stopped; reload or close the Page before continuing.`,
+ {
+ timeoutMs,
+ executionStopped: false,
+ mayHaveLateEffects: true,
+ pageResponsive: false,
+ },
+ );
+}
+
+async function pageEvaluationHealthProbe(
+ services: PageModelServices,
+ sessionId: string,
+): Promise<boolean> {
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ const startedAt = services.now();
+ try {
+ const response = await services.cdp(
+ "Runtime.evaluate",
+ {
+ expression: "1",
+ returnByValue: true,
+ awaitPromise: false,
+ timeout: PAGE_EVALUATE_HEALTH_EXECUTION_TIMEOUT_MS,
+ },
+ sessionId,
+ PAGE_EVALUATE_HEALTH_TIMEOUT_MS,
+ );
+ return response?.result?.value === 1;
+ } catch (error) {
+ if (isRuntimeEvaluateTransportTimeout(error)) return false;
+ if (
+ attempt === 0 &&
+ isProtocolExecutionTimeout(
+ error,
+ services.now() - startedAt,
+ PAGE_EVALUATE_HEALTH_EXECUTION_TIMEOUT_MS,
+ )
+ ) {
+ // Runtime.terminateExecution may consume the next evaluation rather
+ // than the original one. Probe once more before declaring the Page bad.
+ continue;
+ }
+ throw error;
+ }
+ }
+ return false;
+}
+
function enrichPageCallbackReferenceError(
error: unknown,
apiName: string,
@@ -2532,6 +2918,52 @@ function looksLikeWaitForFunctionOptions(value: unknown): boolean {
);
}
+function isNoJavaScriptDialogError(error: unknown): boolean {
+ if (!(error instanceof Error)) return false;
+ return /no (?:javascript )?dialog (?:is showing|is open|to handle)/i.test(
+ error.message,
+ );
+}
+
+function validateSelectOptionChoice(
+ choice: PageSelectOption,
+ index: number,
+): void {
+ const path = `page.selectOption valueOrValues[${index}]`;
+ if (typeof choice === "string") return;
+ if (!choice || typeof choice !== "object" || Array.isArray(choice)) {
+ throw new TypeError(
+ `${path} must be a string or an object with value, label, or index`,
+ );
+ }
+ const keys = Object.keys(choice);
+ const unknown = keys.find(
+ (key) => key !== "value" && key !== "label" && key !== "index",
+ );
+ if (unknown) {
+ throw new TypeError(`${path} has unknown field ${JSON.stringify(unknown)}`);
+ }
+ if (
+ choice.value === undefined &&
+ choice.label === undefined &&
+ choice.index === undefined
+ ) {
+ throw new TypeError(`${path} must specify value, label, or index`);
+ }
+ if (choice.value !== undefined && typeof choice.value !== "string") {
+ throw new TypeError(`${path}.value must be a string`);
+ }
+ if (choice.label !== undefined && typeof choice.label !== "string") {
+ throw new TypeError(`${path}.label must be a string`);
+ }
+ if (
+ choice.index !== undefined &&
+ (!Number.isInteger(choice.index) || choice.index < 0)
+ ) {
+ throw new TypeError(`${path}.index must be a non-negative integer`);
+ }
+}
+
function assertUrl(url: string): void {
if (typeof url !== "string" || url.length === 0) {
throw new TypeError("page URL must be a non-empty string");
diff --git a/package/ego-browser/src/public-api-schema.test.mjs b/package/ego-browser/src/public-api-schema.test.mjs
index 06ea715..f721d8a 100644
--- a/package/ego-browser/src/public-api-schema.test.mjs
+++ b/package/ego-browser/src/public-api-schema.test.mjs
@@ -21,11 +21,14 @@ test("the public API schema contains the v2 entry points and object methods", ()
"TaskSpace.tabs",
"TaskSpace.newPage",
"Page.snapshot",
+ "Page.reload",
"Page.targetId",
"Page.waitForEvent",
"Page.waitForURL",
"Page.waitForTimeout",
"Page.waitForFunction",
+ "Page.acceptDialog",
+ "Page.dismissDialog",
"Page.focus",
"Page.press",
"Page.selectOption",
@@ -91,11 +94,16 @@ test("the generated reference contains signatures and option descriptions", () =
assert.match(markdown, /`await profiles\(\)`/);
assert.match(markdown, /`await listTaskSpaces\(\)`/);
assert.match(markdown, /`await taskSpace\(nameOrId, \{ profileId\? \}\)`/);
+ assert.match(markdown, /a new space starts with managed Page p1/);
assert.match(markdown, /`await task\.newPage\(\)`/);
assert.match(
markdown,
/`await page\.goto\(url, \{ referer\?, timeout\?, waitUntil\? \}\)`/,
);
+ assert.match(
+ markdown,
+ /`await page\.reload\(\{ timeout\?, waitUntil\? \}\)`/,
+ );
assert.match(
markdown,
/`await page\.selectOption\(selector, valueOrValues, \{ timeout\? \}\)`/,
@@ -112,11 +120,19 @@ test("the generated reference contains signatures and option descriptions", () =
markdown,
/const popupPromise = page\.waitForEvent\("popup"\); await page\.click\(selector\)/,
);
+ assert.match(markdown, /page\.acceptDialog\(promptText\?\)/);
+ assert.match(markdown, /page\.dismissDialog\(\)/);
+ assert.doesNotMatch(markdown, /Page\.handleJavaScriptDialog/);
+ assert.match(markdown, /no state defaults to load/);
+ assert.match(markdown, /value-or-label string/);
+ assert.match(markdown, /\{ value\?, label\?, index\? \}/);
+ assert.match(markdown, /terminal `:has-text\("\.\.\."\)`/);
+ assert.match(markdown, /`loc=role:\.\.\.\[name\*="\.\.\."\]`/);
assert.doesNotMatch(markdown, /task\.openPage/);
assert.match(markdown, /Create and durably label a blank Page/);
assert.match(
markdown,
- /Maximum actionability wait in milliseconds; defaults to 3000/,
+ /Maximum wait for the element to become usable in milliseconds; defaults to 3000/,
);
assert.match(markdown, /missing parent directories are created/);
});
diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.ts
index 1399e14..cedde18 100644
--- a/package/ego-browser/src/public-api-schema.ts
+++ b/package/ego-browser/src/public-api-schema.ts
@@ -35,7 +35,7 @@ const timeout = option(
);
const actionTimeout = option(
"positiveMilliseconds",
- "Maximum actionability wait in milliseconds; defaults to 3000.",
+ "Maximum wait for the element to become usable in milliseconds; defaults to 3000.",
);
const delay = option("nonNegativeNumber", "Input delay in milliseconds.");
const button = option("string", "Mouse button.", ["left", "middle", "right"]);
@@ -66,7 +66,7 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
name: "taskSpace",
signature: "await taskSpace(nameOrId, { profileId? })",
summary:
- "Reuse or create an Agent-owned task space; profileId applies only to a new named space.",
+ "Reuse or create an Agent-owned task space; a new space starts with managed Page p1, and profileId applies only when creating it.",
options: {
profileId: option(
"nonEmptyString",
@@ -195,7 +195,8 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
{
name: "Page.goto",
signature: "await page.goto(url, { referer?, timeout?, waitUntil? })",
- summary: "Navigate this Page in place.",
+ summary:
+ "Navigate this Page in place. Timeout errors report whether the new document committed, plus its URL and readyState when available.",
options: {
referer: option(
"nonEmptyString",
@@ -209,6 +210,19 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
),
},
},
+ {
+ name: "Page.reload",
+ signature: "await page.reload({ timeout?, waitUntil? })",
+ summary: "Reload this Page and wait for the selected navigation state.",
+ options: {
+ timeout,
+ waitUntil: option(
+ "string",
+ "Completion state; defaults to load. networkidle requires 500ms without network activity.",
+ ["commit", "domcontentloaded", "load", "networkidle"],
+ ),
+ },
+ },
{
name: "Page.snapshot",
signature:
@@ -273,11 +287,23 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
signature: "await page.info()",
summary: "Read URL, title, viewport, scroll, and dialog state.",
},
+ {
+ name: "Page.acceptDialog",
+ signature: "await page.acceptDialog(promptText?)",
+ summary:
+ "Accept this Page's JavaScript dialog, optionally supplying prompt text; return false when none is open.",
+ },
+ {
+ name: "Page.dismissDialog",
+ signature: "await page.dismissDialog()",
+ summary:
+ "Dismiss this Page's JavaScript dialog; return false when none is open.",
+ },
{
name: "Page.evaluate",
signature: "await page.evaluate(fnOrString, argument?)",
summary:
- "Run JavaScript in this Page; callbacks receive JSON data but cannot capture Node.js variables.",
+ "Run JavaScript in this Page; callbacks receive JSON data but cannot capture Node.js variables. Safety-timeout errors report executionStopped, pageResponsive, and mayHaveLateEffects.",
},
{
name: "Page.waitForFunction",
@@ -357,8 +383,9 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
},
{
name: "Page.waitForLoadState",
- signature: "await page.waitForLoadState(state, { timeout?, idleMs? })",
- summary: "Wait for DOM content, load, or network-idle state.",
+ signature: "await page.waitForLoadState(state?, { timeout?, idleMs? })",
+ summary:
+ "Wait for DOM content, load, or network-idle state; no state defaults to load.",
options: {
timeout,
idleMs: option(
@@ -425,7 +452,8 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
{
name: "Page.selectOption",
signature: "await page.selectOption(selector, valueOrValues, { timeout? })",
- summary: "Select one or more option values and return the selected values.",
+ summary:
+ "Select by a value-or-label string or { value?, label?, index? }; arrays select multiple options, while null or [] clears the selection. The select must be enabled, but disabled options remain programmatically selectable.",
options: { timeout: actionTimeout },
},
{
@@ -621,9 +649,11 @@ export function publicApiMarkdown(): string {
"",
"Generated from `package/ego-browser/src/public-api-schema.ts`.",
"",
- 'High-level Page actions return a receipt that may contain `popups` or a synchronous `dialog`. Handle a returned dialog with `page.cdp("Page.handleJavaScriptDialog", { accept: true })` or `{ accept: false }` before continuing; prompts may also include `promptText`.',
+ "High-level Page actions return a receipt that may contain `popups` or a synchronous `dialog`. Handle a returned dialog with `page.acceptDialog(promptText?)` or `page.dismissDialog()` before continuing.",
+ "",
+ 'For an explicit popup wait, arm it before the action: `const popupPromise = page.waitForEvent("popup"); await page.click(selector); const popup = await popupPromise;`. Action receipts instead expose `{ label, targetId }` entries in `receipt.popups`; resolve one with `task.page(label)`.',
"",
- 'For an explicit popup wait, arm it before the action: `const popupPromise = page.waitForEvent("popup"); await page.click(selector); const popup = await popupPromise;`. The default workflow can read `receipt.popups` instead.',
+ 'Selectors accept refs, Ego locators, XPath, and raw CSS. A small compatibility subset also accepts `css=...`, terminal `:has-text("...")` and `:text-is("...")`, `>> nth=N` after CSS/text/href selectors (`N` is `-1` or non-negative), and `loc=role:...[name*="..."]`.',
];
for (const [group, entries] of groups) {
lines.push(
diff --git a/package/ego-browser/src/real-browser-runner.test.mjs b/package/ego-browser/src/real-browser-runner.test.mjs
index eb8077f..b015f9b 100644
--- a/package/ego-browser/src/real-browser-runner.test.mjs
+++ b/package/ego-browser/src/real-browser-runner.test.mjs
@@ -5,6 +5,7 @@ import {
MACOS_EGO_LITE_CLI,
resolveEgoBrowserCli,
} from "../scripts/real-browser-e2e/ego-browser-cli.mjs";
+import { parseOnlyCases } from "../scripts/real-browser-e2e/runner.mjs";
test("real-browser E2E honors an explicit Ego Lite CLI", () => {
assert.equal(
@@ -37,3 +38,53 @@ test("real-browser E2E falls back to PATH when no app-specific CLI exists", () =
"ego-browser",
);
});
+
+test("real-browser E2E selects an exact case name that contains commas", () => {
+ assert.deepEqual(
+ [
+ ...parseOnlyCases("wait, fetch, cdp, js, help", [
+ "wait, fetch, cdp, js, help",
+ "Page API alignment",
+ ]),
+ ],
+ ["wait, fetch, cdp, js, help"],
+ );
+});
+
+test("real-browser E2E accepts a JSON array for multiple exact case names", () => {
+ assert.deepEqual(
+ [
+ ...parseOnlyCases(
+ '["wait, fetch, cdp, js, help", "Page API alignment"]',
+ ["wait, fetch, cdp, js, help", "Page API alignment"],
+ ),
+ ],
+ ["wait, fetch, cdp, js, help", "Page API alignment"],
+ );
+});
+
+test("real-browser E2E keeps legacy comma-separated case selection", () => {
+ assert.deepEqual(
+ [
+ ...parseOnlyCases("first case, second case", [
+ "first case",
+ "second case",
+ ]),
+ ],
+ ["first case", "second case"],
+ );
+});
+
+test("real-browser E2E rejects unknown selected cases instead of skipping all", () => {
+ assert.throws(
+ () => parseOnlyCases("Page API aligment", ["Page API alignment"]),
+ /unknown real-browser E2E case.*Page API aligment.*Page API alignment/i,
+ );
+});
+
+test("real-browser E2E rejects an explicitly empty selection", () => {
+ assert.throws(
+ () => parseOnlyCases("[]", ["Page API alignment"]),
+ /must select at least one/i,
+ );
+});
diff --git a/package/ego-browser/src/run.ts b/package/ego-browser/src/run.ts
index b549784..429631c 100644
--- a/package/ego-browser/src/run.ts
+++ b/package/ego-browser/src/run.ts
@@ -41,7 +41,7 @@ Read the ego-browser skill for the default workflow and examples.
Typical usage:
ego-browser <<'JS'
const task = await taskSpace('demo')
- const page = await task.newPage()
+ const page = task.page('p1')
await page.goto('https://example.com')
console.log(await page.snapshot())
JS
@@ -52,7 +52,7 @@ Helpers are pre-imported and the browser connection is prepared automatically.
export const USAGE = `Usage:
ego-browser <<'JS'
const task = await taskSpace('demo')
- const page = await task.newPage()
+ const page = task.page('p1')
await page.goto('https://example.com')
console.log(await page.snapshot())
JS
diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.md
index b9189ce..2594aaa 100644
--- a/skills/ego-browser/SKILL.md
+++ b/skills/ego-browser/SKILL.md
@@ -16,7 +16,7 @@ Run JavaScript through a heredoc:
```bash
ego-browser nodejs <<'EOF'
const task = await taskSpace("inspect example page");
-const page = await task.newPage();
+const page = task.page("p1");
await page.goto("https://example.com");
console.log({ taskSpaceId: task.spaceId, page: page.label });
@@ -50,6 +50,8 @@ and diagnose the CLI or installation only if it fails.
persist; JavaScript variables do not.
- Name a new space after the goal and print `task.spaceId`. In later rounds,
resume that ID and restore Pages by label.
+- A new task space starts with Page `p1`; navigate it instead of opening
+ another Page.
- Reuse a Page with `goto()` instead of opening a new Page for every URL.
- All time values are milliseconds.
@@ -76,7 +78,8 @@ Pages receive permanent labels such as `p1`, `p2`, and `p3`. Prefer these labels
to custom `{ as }` values. Reuse or close Pages as the task proceeds; the runtime
reports the configured Page budget when it is reached.
-`task.newPage()` creates a blank Page. Navigate it separately with `page.goto()`.
+`task.newPage()` creates another blank Page when multiple Pages must stay open.
+Navigate it separately with `page.goto()`.
`await task.pages()` returns managed Pages. `await task.tabs()` returns every tab in the
space as `{ label?, page, targetId, title, url, active, openedBy }`. A tab
@@ -96,26 +99,26 @@ as user-owned when deciding whether a Page may be closed.
## Page operations
-Page methods follow Playwright conventions only where this Skill documents
-them. Supported Page API:
+ego-browser provides the following Page API:
- State and observation: `label`, `spaceId`, `openedBy`, `targetId`, `url()`,
- `title()`, `info()`, `events()`, `snapshot()`, `screenshot()`
-- Navigation and waits: `goto()`, `waitForURL()`, `waitForSelector()`,
- `waitForLoadState()`, `waitForFunction()`, `waitForTimeout()`
+ `title()`, `info()`, `snapshot()`, `screenshot()`
+- Navigation and waits: `goto()`, `reload()`, `waitForURL()`,
+ `waitForEvent()`, `waitForSelector()`, `waitForLoadState()`,
+ `waitForFunction()`, `waitForTimeout()`
- Elements: `click()`, `dblclick()`, `hover()`, `dragAndDrop()`, `fill()`,
`selectOption()`, `focus()`, `press()`, `setInputFiles()`,
`waitForFileChooser()`, `close()`
+- Dialogs: `acceptDialog(promptText?)`, `dismissDialog()`
- Pointer: `mouse.click()`, `move()`, `down()`, `up()`, `wheel()`
- Keyboard: `keyboard.down()`, `up()`, `press()`, `type()`, `insertText()`,
`paste()`
- Page code and protocols: `evaluate(fnOrString, argument)`,
`fetch(url, options)`, `cdp(method, params, options)`
-This boundary is strict. `page.evaluate()` callbacks run only inside the Page;
-they cannot read variables or Node.js modules from the surrounding heredoc.
-Define browser-side helpers inside the callback or pass one JSON-serializable
-value as its second argument.
+`page.evaluate()` callbacks run only inside the Page; they cannot read variables
+or Node.js modules from the surrounding heredoc. Define browser-side helpers
+inside the callback or pass one JSON-serializable value as its second argument.
### Semantic pages: snapshot and selectors
@@ -129,7 +132,7 @@ can act on it directly. If no decision depends on intermediate states, batch
deterministic actions and observe only after the last verified result.
The final snapshot is the next round's starting view of the changed page;
without it, that round usually has to spend a separate browser call observing
-before it can choose the next target.
+before it can choose the next target, which wastes compute.
Wait for the expected result: use `waitForURL()` for navigation,
`waitForSelector()` for element state, or `waitForFunction()` for application
@@ -138,6 +141,16 @@ captures the current moment; it does not wait for the page to become stable.
`page.snapshot()` captures the current viewport. For content outside it, use
`page.snapshot({ scope: "full_page" })`.
+`waitForLoadState()` defaults to `load`. `waitForFunction()` follows the
+Playwright argument order; pass `undefined` before options when there is no Page
+argument:
+
+```js
+await page.waitForFunction(() => window.appReady, undefined, {
+ timeout: 10_000,
+});
+```
+
```js
// Round 1: inspect and choose targets from this output.
const page = task.page("p1");
@@ -165,6 +178,12 @@ Selector actions require exactly one match. Unquoted text normalizes whitespace,
ignores case, and matches a substring; quoted text such as
`text="Save changes"` is exact and case-sensitive.
+A small Playwright-compatible selector subset is also accepted: `css=...`,
+terminal `:has-text("...")` and `:text-is("...")`, `>> nth=N` after a CSS,
+text, or href selector (`N` is `-1` or non-negative), plus
+`loc=role:...[name*="..."]` for accessible-name substrings. Other Playwright
+selector syntax is not supported.
+
When a selector identifies a wrapper, `focus()` and `press()` may use its
interactive ancestor or unique editable descendant; `fill()` and
`setInputFiles()` only continue to a unique compatible control.
@@ -176,6 +195,15 @@ context. CSS searches nested open shadow roots. Actions use an actionable match
in the top document first, then search frames when the top document has none.
Multiple actionable matches in the selected document or frame are ambiguous.
+Select options by value, visible label, or zero-based index. A string matches
+either value or label; pass an array for a multiple select:
+
+```js
+await page.selectOption("select[name=month]", { label: "October" });
+```
+
+Pass `null` or `[]` to clear the current selection.
+
### Visual pages: screenshot, mouse, and keyboard
Use a screenshot with mouse and keyboard operations for canvas, rich-text,
@@ -228,36 +256,46 @@ const rows = await page.evaluate(
);
```
+`page.evaluate()` has no timeout option. Keep long work in bounded calls; on a
+safety timeout, use `executionStopped` and `mayHaveLateEffects` to decide
+whether an unsafe follow-up requires reloading or closing the Page first.
+
Use documented Page methods first. If a wrapper is missing or does not work
reliably on the current page, use `page.cdp()` as a lower-level path for
diagnosis or control. It accepts Page, Runtime, DOM, Network, Input, and similar
commands; use `task.cdp()` for Target and Browser commands. Raw CDP invalidates
refs. Do not persist `page.targetId` across rounds.
-## Action results, popups, and dialogs
+## Action receipts, popups, and dialogs
-High-level actions return a receipt. New tabs are adopted and may appear in
-`receipt.popups`:
+When an action is expected to open a new Page, start the wait before the action:
```js
-const receipt = await page.click('a[target="_blank"]');
-for (const popup of receipt.popups ?? []) {
- const popupPage = task.page(popup.label);
- await popupPage.waitForURL(/\/expected-path(?:[?#]|$)/, { timeout: 10_000 });
-}
+const popupPromise = page.waitForEvent("popup");
+await page.click('a[target="_blank"]');
+const popupPage = await popupPromise;
+await popupPage.waitForLoadState();
```
-Continue a popup workflow on `task.page(popup.label)`. Wait for its URL when the
-destination matters.
+High-level actions also report immediately observed popups in `receipt.popups`
+as `{ label, targetId }`. Resolve the Page with
+`task.page(receipt.popups[0].label)` and continue there; wait for its URL when
+the destination matters.
+
+For uncommon protocol-event workflows, `await page.events()` returns and clears
+the buffered event array; it is not an EventEmitter.
A synchronous JavaScript dialog may appear as `receipt.dialog` or in
`page.info()`. Handle it before continuing:
```js
-await page.cdp("Page.handleJavaScriptDialog", { accept: true });
-// Use accept: false to dismiss it.
+await page.acceptDialog("prompt response");
+// Or: await page.dismissDialog();
```
+If Ego Lite hands control to the user before returning the dialog, stop and wait
+for the user; do not retry the action.
+
A receipt describes only the dispatched action and immediate popup or dialog
observations; it does not verify the resulting application state.
@@ -304,7 +342,7 @@ browser semantics.
Stop when the user takes control or the space is inactive or unassigned. Do not
retry or route around the stop. Permission prompts, device choosers, and
-JavaScript dialogs may trigger the same handoff; ask the user to handle them.
+other browser-owned prompts require the user to handle them.
When the user must act in the browser, call `await task.handOff()`, end the
round, and explain what they should do. After the user confirms, resume the
diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.md
index c6e22bd..fa57207 100644
--- a/skills/ego-browser/references/api.md
+++ b/skills/ego-browser/references/api.md
@@ -2,21 +2,23 @@
Generated from `package/ego-browser/src/public-api-schema.ts`.
-High-level Page actions return a receipt that may contain `popups` or a synchronous `dialog`. Handle a returned dialog with `page.cdp("Page.handleJavaScriptDialog", { accept: true })` or `{ accept: false }` before continuing; prompts may also include `promptText`.
+High-level Page actions return a receipt that may contain `popups` or a synchronous `dialog`. Handle a returned dialog with `page.acceptDialog(promptText?)` or `page.dismissDialog()` before continuing.
-For an explicit popup wait, arm it before the action: `const popupPromise = page.waitForEvent("popup"); await page.click(selector); const popup = await popupPromise;`. The default workflow can read `receipt.popups` instead.
+For an explicit popup wait, arm it before the action: `const popupPromise = page.waitForEvent("popup"); await page.click(selector); const popup = await popupPromise;`. Action receipts instead expose `{ label, targetId }` entries in `receipt.popups`; resolve one with `task.page(label)`.
+
+Selectors accept refs, Ego locators, XPath, and raw CSS. A small compatibility subset also accepts `css=...`, terminal `:has-text("...")` and `:text-is("...")`, `>> nth=N` after CSS/text/href selectors (`N` is `-1` or non-negative), and `loc=role:...[name*="..."]`.
## Entry points
-| API | Options | Purpose |
-| ------------------------------------------- | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
-| `await profiles()` | — | List browser profiles available for new task spaces. |
-| `await listTaskSpaces()` | — | List Agent-owned and user-owned spaces available to reuse or claim. |
-| `await taskSpace(nameOrId, { profileId? })` | `profileId` — Browser profile id returned by profiles(); new spaces only. | Reuse or create an Agent-owned task space; profileId applies only to a new named space. |
-| `await claimTaskSpace(spaceId)` | — | Claim a user-owned or inactive space after user approval and return TaskSpace. |
-| `await takeOverTaskSpace(spaceId)` | — | Resume an Agent-owned space after user approval and return TaskSpace. |
-| `fileChooser.isMultiple()` | — | Report whether the chooser accepts multiple files. |
-| `await fileChooser.setFiles(pathOrPaths)` | — | Set files on an intercepted chooser without a system dialog. |
+| API | Options | Purpose |
+| ------------------------------------------- | ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
+| `await profiles()` | — | List browser profiles available for new task spaces. |
+| `await listTaskSpaces()` | — | List Agent-owned and user-owned spaces available to reuse or claim. |
+| `await taskSpace(nameOrId, { profileId? })` | `profileId` — Browser profile id returned by profiles(); new spaces only. | Reuse or create an Agent-owned task space; a new space starts with managed Page p1, and profileId applies only when creating it. |
+| `await claimTaskSpace(spaceId)` | — | Claim a user-owned or inactive space after user approval and return TaskSpace. |
+| `await takeOverTaskSpace(spaceId)` | — | Resume an Agent-owned space after user approval and return TaskSpace. |
+| `fileChooser.isMultiple()` | — | Report whether the chooser accepts multiple files. |
+| `await fileChooser.setFiles(pathOrPaths)` | — | Set files on an intercepted chooser without a system dialog. |
## TaskSpace
@@ -40,39 +42,42 @@ For an explicit popup wait, arm it before the action: `const popupPromise = page
## Page
-| API | Options | Purpose |
-| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- |
-| `page.label` | — | Durable Page label used to restore the tab across rounds. |
-| `page.spaceId` | — | Numeric identifier of the Page's task space. |
-| `page.openedBy` | — | Conservative origin attribution for this Page. |
-| `page.targetId` | — | Internal browser target identifier for advanced Target-domain CDP only. |
-| `await page.goto(url, { referer?, timeout?, waitUntil? })` | `referer` — HTTP Referer header for the navigation.<br>`timeout` — Maximum duration in milliseconds.<br>`waitUntil` (commit, domcontentloaded, load, networkidle) — Completion state; defaults to load. networkidle requires 500ms without network activity. | Navigate this Page in place. |
-| `await page.snapshot({ scope?, includeActionMarks?, includeStableLocator? })` | `scope` (full_page, only_within_viewport) — Snapshot scope; defaults to only_within_viewport.<br>`includeActionMarks` — Include action marks.<br>`includeStableLocator` — Include stable locators. | Return a semantic snapshot of the current viewport with Page provenance. |
-| `await page.screenshot({ path?, fullPage?, clip?, raw? })` | `path` — Output path; missing parent directories are created.<br>`fullPage` — Capture the full scrollable page.<br>`clip` — CSS-pixel clipping rectangle.<br>`raw` — Bypass device-pixel-ratio correction. | Capture this Page to a PNG file. |
-| `await page.url()` | — | Read this Page's current URL. |
-| `await page.waitForURL(urlOrRegExp, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for an exact URL or regular-expression match. |
-| `await page.waitForEvent("popup", { timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for this Page's next popup; call before the triggering action. |
-| `await page.waitForTimeout(timeout)` | — | Wait a fixed number of milliseconds without activating this Page. |
-| `await page.title()` | — | Read this Page's current title. |
-| `await page.info()` | — | Read URL, title, viewport, scroll, and dialog state. |
-| `await page.evaluate(fnOrString, argument?)` | — | Run JavaScript in this Page; callbacks receive JSON data but cannot capture Node.js variables. |
-| `await page.waitForFunction(fnOrString, argument?, { timeout?, polling? })` | `timeout` — Maximum duration in milliseconds.<br>`polling` — Polling interval in milliseconds; defaults to 100. | Wait until a Page function or expression returns a truthy value. |
-| `await page.fetch(url, options?)` | `timeout` — Maximum duration in milliseconds.<br>`saveAs` — Write the response body to this path without text conversion.<br>`method` — HTTP method.<br>`headers` — Request headers.<br>`body` — Request body.<br>`cache` (default, no-store, reload, no-cache, force-cache, only-if-cached) — Fetch cache mode.<br>`credentials` (omit, same-origin, include) — Fetch credentials mode.<br>`integrity` — Subresource integrity value.<br>`keepalive` — Allow the request to outlive the page.<br>`mode` (cors, no-cors, same-origin) — Fetch request mode.<br>`redirect` (follow, error, manual) — Redirect handling mode.<br>`referrer` — Request referrer.<br>`referrerPolicy` — Request referrer policy. | Run window.fetch in this Page, obey browser CORS, and return a structured response. |
-| `await page.cdp(method, params?, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Send a CDP command through this Page's target session. |
-| `await page.waitForSelector(selector, { timeout?, state? })` | `timeout` — Maximum duration in milliseconds.<br>`state` (attached, detached, visible, hidden) — Required element state. | Wait for an element state in this Page. |
-| `await page.waitForLoadState(state, { timeout?, idleMs? })` | `timeout` — Maximum duration in milliseconds.<br>`idleMs` — Required network-idle window in milliseconds. | Wait for DOM content, load, or network-idle state. |
-| `await page.events()` | — | Read and clear CDP events buffered for this Page. |
-| `await page.click(selector, { button?, clickCount?, delay?, position?, force?, timeout? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Number of clicks.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Click an element with native CDP input. |
-| `await page.dblclick(selector, { button?, delay?, position?, force?, timeout? })` | `button` (left, middle, right) — Mouse button.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Double-click an element with native CDP input. |
-| `await page.hover(selector, { position?, force?, timeout? })` | `position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Move the mouse over an element. |
-| `await page.dragAndDrop(source, target, { button?, sourcePosition?, targetPosition?, force?, timeout? })` | `button` (left, middle, right) — Mouse button.<br>`sourcePosition` — CSS-pixel offset from the element's top-left corner.<br>`targetPosition` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Drag from one element to another. |
-| `await page.fill(selector, value, { clearFirst?, timeout? })` | `clearFirst` — Clear the current value before filling.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Fill the selected field, its editing host, or its unique fillable descendant, then confirm editing took effect. |
-| `await page.selectOption(selector, valueOrValues, { timeout? })` | `timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Select one or more option values and return the selected values. |
-| `await page.focus(selector, { timeout? })` | `timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Focus the element, its nearest interactive ancestor, or its unique editable descendant. |
-| `await page.press(selector, chord, { delay?, timeout? })` | `delay` — Input delay in milliseconds.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Focus one element and press a key or shortcut chord. |
-| `await page.setInputFiles(selector, pathOrPaths)` | — | Set files on a file input resolved from the input, its label, or a unique descendant. |
-| `page.waitForFileChooser({ timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for a dynamically created file chooser. |
-| `await page.close()` | — | Close this Page after confirming its tab disappeared. |
+| API | Options | Purpose |
+| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `page.label` | — | Durable Page label used to restore the tab across rounds. |
+| `page.spaceId` | — | Numeric identifier of the Page's task space. |
+| `page.openedBy` | — | Conservative origin attribution for this Page. |
+| `page.targetId` | — | Internal browser target identifier for advanced Target-domain CDP only. |
+| `await page.goto(url, { referer?, timeout?, waitUntil? })` | `referer` — HTTP Referer header for the navigation.<br>`timeout` — Maximum duration in milliseconds.<br>`waitUntil` (commit, domcontentloaded, load, networkidle) — Completion state; defaults to load. networkidle requires 500ms without network activity. | Navigate this Page in place. Timeout errors report whether the new document committed, plus its URL and readyState when available. |
+| `await page.reload({ timeout?, waitUntil? })` | `timeout` — Maximum duration in milliseconds.<br>`waitUntil` (commit, domcontentloaded, load, networkidle) — Completion state; defaults to load. networkidle requires 500ms without network activity. | Reload this Page and wait for the selected navigation state. |
+| `await page.snapshot({ scope?, includeActionMarks?, includeStableLocator? })` | `scope` (full_page, only_within_viewport) — Snapshot scope; defaults to only_within_viewport.<br>`includeActionMarks` — Include action marks.<br>`includeStableLocator` — Include stable locators. | Return a semantic snapshot of the current viewport with Page provenance. |
+| `await page.screenshot({ path?, fullPage?, clip?, raw? })` | `path` — Output path; missing parent directories are created.<br>`fullPage` — Capture the full scrollable page.<br>`clip` — CSS-pixel clipping rectangle.<br>`raw` — Bypass device-pixel-ratio correction. | Capture this Page to a PNG file. |
+| `await page.url()` | — | Read this Page's current URL. |
+| `await page.waitForURL(urlOrRegExp, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for an exact URL or regular-expression match. |
+| `await page.waitForEvent("popup", { timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for this Page's next popup; call before the triggering action. |
+| `await page.waitForTimeout(timeout)` | — | Wait a fixed number of milliseconds without activating this Page. |
+| `await page.title()` | — | Read this Page's current title. |
+| `await page.info()` | — | Read URL, title, viewport, scroll, and dialog state. |
+| `await page.acceptDialog(promptText?)` | — | Accept this Page's JavaScript dialog, optionally supplying prompt text; return false when none is open. |
+| `await page.dismissDialog()` | — | Dismiss this Page's JavaScript dialog; return false when none is open. |
+| `await page.evaluate(fnOrString, argument?)` | — | Run JavaScript in this Page; callbacks receive JSON data but cannot capture Node.js variables. Safety-timeout errors report executionStopped, pageResponsive, and mayHaveLateEffects. |
+| `await page.waitForFunction(fnOrString, argument?, { timeout?, polling? })` | `timeout` — Maximum duration in milliseconds.<br>`polling` — Polling interval in milliseconds; defaults to 100. | Wait until a Page function or expression returns a truthy value. |
+| `await page.fetch(url, options?)` | `timeout` — Maximum duration in milliseconds.<br>`saveAs` — Write the response body to this path without text conversion.<br>`method` — HTTP method.<br>`headers` — Request headers.<br>`body` — Request body.<br>`cache` (default, no-store, reload, no-cache, force-cache, only-if-cached) — Fetch cache mode.<br>`credentials` (omit, same-origin, include) — Fetch credentials mode.<br>`integrity` — Subresource integrity value.<br>`keepalive` — Allow the request to outlive the page.<br>`mode` (cors, no-cors, same-origin) — Fetch request mode.<br>`redirect` (follow, error, manual) — Redirect handling mode.<br>`referrer` — Request referrer.<br>`referrerPolicy` — Request referrer policy. | Run window.fetch in this Page, obey browser CORS, and return a structured response. |
+| `await page.cdp(method, params?, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Send a CDP command through this Page's target session. |
+| `await page.waitForSelector(selector, { timeout?, state? })` | `timeout` — Maximum duration in milliseconds.<br>`state` (attached, detached, visible, hidden) — Required element state. | Wait for an element state in this Page. |
+| `await page.waitForLoadState(state?, { timeout?, idleMs? })` | `timeout` — Maximum duration in milliseconds.<br>`idleMs` — Required network-idle window in milliseconds. | Wait for DOM content, load, or network-idle state; no state defaults to load. |
+| `await page.events()` | — | Read and clear CDP events buffered for this Page. |
+| `await page.click(selector, { button?, clickCount?, delay?, position?, force?, timeout? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Number of clicks.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000. | Click an element with native CDP input. |
+| `await page.dblclick(selector, { button?, delay?, position?, force?, timeout? })` | `button` (left, middle, right) — Mouse button.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000. | Double-click an element with native CDP input. |
+| `await page.hover(selector, { position?, force?, timeout? })` | `position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000. | Move the mouse over an element. |
+| `await page.dragAndDrop(source, target, { button?, sourcePosition?, targetPosition?, force?, timeout? })` | `button` (left, middle, right) — Mouse button.<br>`sourcePosition` — CSS-pixel offset from the element's top-left corner.<br>`targetPosition` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000. | Drag from one element to another. |
+| `await page.fill(selector, value, { clearFirst?, timeout? })` | `clearFirst` — Clear the current value before filling.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000. | Fill the selected field, its editing host, or its unique fillable descendant, then confirm editing took effect. |
+| `await page.selectOption(selector, valueOrValues, { timeout? })` | `timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000. | Select by a value-or-label string or { value?, label?, index? }; arrays select multiple options, while null or [] clears the selection. The select must be enabled, but disabled options remain programmatically selectable. |
+| `await page.focus(selector, { timeout? })` | `timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000. | Focus the element, its nearest interactive ancestor, or its unique editable descendant. |
+| `await page.press(selector, chord, { delay?, timeout? })` | `delay` — Input delay in milliseconds.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000. | Focus one element and press a key or shortcut chord. |
+| `await page.setInputFiles(selector, pathOrPaths)` | — | Set files on a file input resolved from the input, its label, or a unique descendant. |
+| `page.waitForFileChooser({ timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for a dynamically created file chooser. |
+| `await page.close()` | — | Close this Page after confirming its tab disappeared. |
## Page.mouse