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): harden page targeting and snapshot locators

Autea2adff638e71
diff --git a/docs/native-sdk-lifecycle-requirement.md b/docs/native-sdk-lifecycle-requirement.md
index c314026..28ffe57 100644
--- a/docs/native-sdk-lifecycle-requirement.md
+++ b/docs/native-sdk-lifecycle-requirement.md
@@ -1,4 +1,6 @@
-# Embedded SDK disposal
+# Embedded SDK host requirements
+
+## Disposal
When Ego Lite unloads or replaces an embedded ego-browser Node context, it
should call and await the module's exported `disposeEgoSdk()` function before
@@ -16,3 +18,17 @@ before.
Acceptance: load the SDK, complete one CDP command, leave another command
pending, call `disposeEgoSdk()`, then verify that the pending command rejects
and both native callback slots are empty before the Node context is destroyed.
+
+## Syntax diagnostics
+
+The `ego-browser nodejs` host compiles the heredoc before the embedded SDK can
+inspect it. When compilation fails, report the message, one-based line and
+column, and the corresponding source line. The direct JavaScript entry point
+already provides this diagnostic, but it cannot recover source location after
+the host has reduced the failure to a generic `node:internal/vm` stack.
+
+No new Agent API is needed. The host may either pass the uncompiled source to
+the SDK executor or format the V8 compile error itself.
+
+Acceptance: run a heredoc containing an invalid token on line 4 and verify that
+stderr identifies line 4, points to the token, and prints the source line.
diff --git a/docs/native-snapshot-ref-requirement.md b/docs/native-snapshot-ref-requirement.md
index 243f4d1..f185c0c 100644
--- a/docs/native-snapshot-ref-requirement.md
+++ b/docs/native-snapshot-ref-requirement.md
@@ -1,4 +1,6 @@
-# Snapshot refs for iframe content
+# Native snapshot metadata requirements
+
+## Snapshot refs for iframe content
`ego.snapshot()` already includes text from ordinary iframes and OOPIFs, but
actionable nodes inside those frames are currently omitted from `refs`. The
@@ -28,6 +30,24 @@ Acceptance: one page contains a same-origin iframe and a cross-origin OOPIF,
with repeated backend node ids in different renderers. Every printed button and
textbox has a distinct ref, and each ref resolves to the node in its own frame.
-This is not required for JS session routing: ego-browser can already operate
-frame content with semantic locators. It completes the snapshot/ref experience
-without asking JS to parse and rewrite native snapshot text.
+ego-browser now backfills a missing `frameId` from the frame AX tree when one
+backend node id has only one possible owner. Native metadata is still required
+when renderer-local backend ids repeat, and for actionable frame nodes omitted
+from `refs` entirely.
+
+## Stable locator correctness
+
+A stable locator must resolve uniquely to the same node that produced the
+snapshot ref. It is invalid when it matches no node, matches more than one node,
+or uniquely matches a different `backendNodeId`.
+
+Please cover at least these cases in native tests:
+
+- repeated controls in one document, such as buttons with the same name;
+- a hidden copy and a visible editor sharing the same accessible name;
+- the same role and name in the top-level document and an iframe;
+- a locator whose element type does not match the source node.
+
+Return `ambiguous` or `unstable`, or omit the locator, when uniqueness and node
+identity cannot both be established. The JS runtime validates advertised
+locators and downgrades invalid ones as a compatibility safeguard.
diff --git a/package/ego-browser/README.md b/package/ego-browser/README.md
index bbaf39c..370690d 100644
--- a/package/ego-browser/README.md
+++ b/package/ego-browser/README.md
@@ -19,7 +19,8 @@ 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.openPage('https://example.com', { as: 'main' })
+const page = await task.newPage()
+await page.goto('https://example.com')
console.log(await page.snapshot())
EOF
```
@@ -90,6 +91,15 @@ 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.
+- `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.
- New public APIs must be added to `public-api-schema.ts`; runtime validation,
default `help()`, the generated reference, and the Skill must remain aligned.
- Embedded hosts should await the exported `disposeEgoSdk()` hook before
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs
index a703e2b..06e2b35 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs
@@ -55,7 +55,7 @@ export function helperSurfaceCase() {
}
assertEqual(typeof globalThis.newTab, "undefined", "internal newTab is not exposed");
const defaultHelp = help();
- assertIncludes(defaultHelp, "TaskSpace.openPage", "default help presents the v2 object API");
+ assertIncludes(defaultHelp, "TaskSpace.newPage", "default help presents the v2 object API");
assertIncludes(defaultHelp, "TaskSpace.pages", "default help presents managed Pages");
assertIncludes(defaultHelp, "TaskSpace.tabs", "default help presents tab inventory");
assertIncludes(defaultHelp, "profiles", "default help presents browser profile selection");
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-click-hit-target.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-click-hit-target.mjs
index bc21462..8fccc3b 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-click-hit-target.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-click-hit-target.mjs
@@ -1,9 +1,7 @@
export function pageClickHitTargetCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.openPage(baseUrl + "/?workflow=page-click-hit-target", {
- as: "page-click-hit-target",
- });
+ const page = await newPageAt(task, baseUrl + "/?workflow=page-click-hit-target");
await page.evaluate(() => {
const target = document.createElement("button");
@@ -140,6 +138,38 @@ export function pageClickHitTargetCase() {
"raw CSS Page actions reject ambiguous selectors"
);
+ await page.evaluate(() => {
+ const hiddenButton = document.createElement("button");
+ hiddenButton.className = "usable-duplicate";
+ hiddenButton.hidden = true;
+ const visibleButton = document.createElement("button");
+ visibleButton.className = "usable-duplicate";
+ visibleButton.textContent = "Only usable action";
+ visibleButton.addEventListener("click", () => window.__usableDuplicateClicks++);
+ window.__usableDuplicateClicks = 0;
+ document.body.append(hiddenButton, visibleButton);
+
+ const hiddenInput = document.createElement("input");
+ hiddenInput.className = "fillable-duplicate";
+ hiddenInput.hidden = true;
+ const visibleInput = document.createElement("input");
+ visibleInput.className = "fillable-duplicate";
+ visibleInput.id = "visible-fillable-duplicate";
+ document.body.append(hiddenInput, visibleInput);
+ });
+ await page.click(".usable-duplicate");
+ assertEqual(
+ await page.evaluate("window.__usableDuplicateClicks"),
+ 1,
+ "click uses the sole visible, enabled duplicate"
+ );
+ await page.fill(".fillable-duplicate", "filled");
+ assertEqual(
+ await page.evaluate("document.querySelector('#visible-fillable-duplicate').value"),
+ "filled",
+ "fill uses the sole visible, enabled duplicate"
+ );
+
await page.close();
`;
}
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-delayed-popup.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-delayed-popup.mjs
index f3fb7ae..a0021f8 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-delayed-popup.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-delayed-popup.mjs
@@ -1,9 +1,7 @@
export function pageDelayedPopupScheduleCase() {
return `
const task = await taskSpace(taskName);
- const source = await task.openPage(baseUrl + "/?delayed-popup=schedule", {
- as: "late-popup-source",
- });
+ const source = await newPageAt(task, baseUrl + "/?delayed-popup=schedule");
const ledgerPath = join(
process.env.EGO_BROWSER_STATE_DIR,
"space-" + task.spaceId + ".json"
@@ -12,6 +10,7 @@ export function pageDelayedPopupScheduleCase() {
await writeFile(
join(tempDir, "delayed-popup-state.json"),
JSON.stringify({
+ sourceLabel: source.label,
beforeTargets: Object.values(beforeLedger.pages).map((entry) => entry.targetId),
})
);
@@ -38,12 +37,11 @@ export function pageDelayedPopupScheduleCase() {
export function pageDelayedPopupResumeCase() {
return `
const task = await taskSpace(taskName);
- const source = task.page("late-popup-source");
- await source.waitForTimeout(1_000);
-
const saved = JSON.parse(
await readFile(join(tempDir, "delayed-popup-state.json"), "utf8")
);
+ const source = task.page(saved.sourceLabel);
+ await source.waitForTimeout(1_000);
const beforeTargets = new Set(saved.beforeTargets);
const ledger = JSON.parse(
await readFile(
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 ff89ef7..5c02b27 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,9 +1,7 @@
export function pageJavaScriptDialogHandoffCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.openPage(baseUrl + "/?page-dialogs=" + Date.now(), {
- as: "page-dialogs",
- });
+ const page = await newPageAt(task, baseUrl + "/?page-dialogs=" + Date.now());
await page.evaluate(() => {
const button = document.createElement("button");
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-drag-and-draw.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-drag-and-draw.mjs
index 4a8e10a..f791559 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-drag-and-draw.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-drag-and-draw.mjs
@@ -1,9 +1,7 @@
export function pageDragAndDrawCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.openPage(baseUrl + "/pointer-workbench", {
- as: "pointer-workbench",
- });
+ const page = await newPageAt(task, baseUrl + "/pointer-workbench");
const beforePath = join(artifactDir, "pointer-workbench-before.png");
const afterPath = join(artifactDir, "pointer-workbench-after.png");
await page.screenshot({ path: beforePath });
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-keyboard.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-keyboard.mjs
index 67b35be..c2bad00 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-keyboard.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-keyboard.mjs
@@ -1,9 +1,7 @@
export function pageKeyboardInterfaceCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.openPage(baseUrl + "/?workflow=page-keyboard-interface", {
- as: "page-keyboard-interface",
- });
+ const page = await newPageAt(task, baseUrl + "/?workflow=page-keyboard-interface");
await page.evaluate(() => {
const input = document.querySelector("#text-area");
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
index 45fafe2..da8a575 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
@@ -2,7 +2,7 @@ export function pageLabelCreateCase() {
return `
const task = await taskSpace(taskName);
await openOrReuseTab(baseUrl + "/?inventory=unknown", { wait: true, timeout: 10 });
- const page = await task.openPage(baseUrl + "/?managed=p1");
+ const page = await newPageAt(task, baseUrl + "/?managed=p1");
assertEqual(page.label, "p1", "first managed page receives p1");
assertEqual(page.spaceId, task.id, "page carries its task-space id");
assertEqual(typeof page.targetId, "string", "new page exposes its target id");
@@ -45,6 +45,42 @@ export function pageLabelRestoreCase() {
const fetched = await page.fetch("/api/text", { timeout: 2_000 });
assertEqual(fetched.status, 200, "a restored Page can make a page-context request");
assertEqual(fetched.body, "server text fixture", "the restored Page fetch returns its body");
+ const selected = await page.selectOption("#dropdown", "beta");
+ assertEqual(JSON.stringify(selected), JSON.stringify(["beta"]), "selectOption returns selected values");
+ assertEqual(
+ await page.evaluate("window.__fixtureState.dropdownValue"),
+ "beta",
+ "selectOption dispatches the page's change behavior"
+ );
+ await page.evaluate(() => {
+ const select = document.createElement("select");
+ select.id = "transparent-dropdown";
+ select.style.cssText = "display:block;width:160px;height:32px;opacity:0";
+ select.innerHTML = '<option value="alpha">Alpha</option><option value="gamma">Gamma</option>';
+ select.addEventListener("change", () => {
+ window.__fixtureState.transparentDropdownValue = select.value;
+ });
+ document.body.append(select);
+ });
+ assertEqual(
+ JSON.stringify(await page.selectOption("#transparent-dropdown", "gamma")),
+ JSON.stringify(["gamma"]),
+ "selectOption accepts an opacity-zero native control"
+ );
+ assertEqual(
+ await page.evaluate("window.__fixtureState.transparentDropdownValue"),
+ "gamma",
+ "the transparent select dispatches its change behavior"
+ );
+ const downloadedPath = join(tempDir, "page-fetch-image.png");
+ const downloaded = await page.fetch("/api/image.png", { saveAs: downloadedPath });
+ assertEqual(downloaded.savedPath, downloadedPath, "page.fetch reports its binary output path");
+ assertEqual(downloaded.body, undefined, "binary page.fetch does not expose a text body");
+ assertEqual(
+ (await readFile(downloadedPath)).subarray(0, 8).toString("hex"),
+ "89504e470d0a1a0a",
+ "page.fetch preserves binary response bytes"
+ );
const before = await listTabs();
await page.goto(baseUrl + "/nav-target?managed=restored");
const after = await listTabs();
@@ -71,7 +107,7 @@ export function pageLabelCloseCase() {
"a closed label fails closed"
);
- const next = await task.openPage(baseUrl + "/secondary?managed=p2");
+ const next = await newPageAt(task, baseUrl + "/secondary?managed=p2");
assertEqual(next.label, "p2", "closed labels are never reused");
await closeTab(next.targetId);
for (let attempt = 0; attempt < 20; attempt += 1) {
@@ -88,7 +124,7 @@ export function pageLabelCloseCase() {
"page p2 was closed",
"reconciliation permanently retires an externally closed label"
);
- const afterExternalClose = await task.openPage(baseUrl + "/secondary?managed=p3");
+ const afterExternalClose = await newPageAt(task, baseUrl + "/secondary?managed=p3");
assertEqual(afterExternalClose.label, "p3", "reconciliation frees budget without reusing labels");
await afterExternalClose.close();
`;
@@ -97,7 +133,7 @@ export function pageLabelCloseCase() {
export function pageLabelHardStopCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.openPage(baseUrl + "/secondary?managed=hard-stop");
+ const page = await newPageAt(task, baseUrl + "/secondary?managed=hard-stop");
await writeFile(
join(tempDir, "hard-stop-page.json"),
JSON.stringify({ label: page.label, targetId: page.targetId })
@@ -124,19 +160,19 @@ export function pageBudgetCase() {
const task = await taskSpace(taskName);
const managed = [];
for (let index = 0; index < 3; index += 1) {
- managed.push(await task.openPage(baseUrl + "/secondary?budget=" + index));
+ managed.push(await newPageAt(task, baseUrl + "/secondary?budget=" + index));
const inventory = await task.tabs();
assertEqual(
inventory.filter((item) => item.label !== undefined).length,
index + 1,
- "each openPage is visible to managed-page inventory"
+ "each newPage is visible to managed-page inventory"
);
}
const beforeReject = await listTabs();
await assertRejects(
- () => task.openPage(baseUrl + "/secondary?budget=blocked"),
+ () => newPageAt(task, baseUrl + "/secondary?budget=blocked"),
"Page budget reached (3/3)",
- "openPage applies managed-page backpressure"
+ "newPage applies managed-page backpressure"
);
const afterReject = await listTabs();
assertEqual(afterReject.length, beforeReject.length, "budget rejects before creating a browser tab");
@@ -189,9 +225,7 @@ export function pageAdoptionCase() {
assertEqual(adoptedAgain.targetId, source.targetId, "a released tab can be adopted again");
await task.release(adoptedAgain.label);
- const agentPage = await task.openPage(baseUrl + "/secondary?release=agent", {
- as: "agent-owned",
- });
+ const agentPage = await newPageAt(task, baseUrl + "/secondary?release=agent");
await assertRejects(
() => task.release(agentPage.label),
"was created by the agent; close it instead",
@@ -204,12 +238,8 @@ export function pageAdoptionCase() {
export function pageBasicOperationsCase() {
return `
const task = await taskSpace(taskName);
- const first = await task.openPage(baseUrl + "/?page-api=first", {
- as: "page-api-first",
- });
- const second = await task.openPage(baseUrl + "/secondary?page-api=second", {
- as: "page-api-second",
- });
+ const first = await newPageAt(task, baseUrl + "/?page-api=first");
+ const second = await newPageAt(task, baseUrl + "/secondary?page-api=second");
assertEqual((await currentTab()).targetId, second.targetId, "second page starts active");
assertIncludes(await first.url(), "page-api=first", "page.url reads its own target");
@@ -227,7 +257,11 @@ export function pageBasicOperationsCase() {
"waitForTimeout does not activate its Page"
);
const baselineSnapshot = await first.snapshot();
- assertIncludes(baselineSnapshot, 'page-api-first', "snapshot identifies its source Page");
+ assertIncludes(
+ baselineSnapshot,
+ "[" + first.label + " ",
+ "snapshot identifies its source Page"
+ );
assertIncludes(baselineSnapshot, 'space "' + taskName + '"', "snapshot identifies its task space");
await first.evaluate(() => {
const marker = document.createElement("p");
@@ -417,15 +451,9 @@ export function pageActionsAndPopupCase() {
.filter((item) => item.label === undefined)
.map((item) => item.targetId);
assert(unknownBefore.length > 0, "the control-boundary inventory keeps pre-existing tabs untracked");
- const source = await task.openPage(baseUrl + "/?page-actions=source", {
- as: "page-actions-source",
- });
- const comparison = await task.openPage(baseUrl + "/secondary?page-actions=comparison", {
- as: "page-actions-comparison",
- });
- const budgetFiller = await task.openPage(baseUrl + "/secondary?page-actions=budget", {
- as: "page-actions-budget",
- });
+ const source = await newPageAt(task, baseUrl + "/?page-actions=source");
+ const comparison = await newPageAt(task, baseUrl + "/secondary?page-actions=comparison");
+ const budgetFiller = await newPageAt(task, baseUrl + "/secondary?page-actions=budget");
assertEqual((await currentTab()).targetId, budgetFiller.targetId, "the budget page starts active");
await source.evaluate(() => {
@@ -443,6 +471,30 @@ export function pageActionsAndPopupCase() {
),
"page.fill uses native text input without synthetic duplicate events"
);
+ await source.evaluate(() => {
+ const price = document.createElement("input");
+ price.id = "formatted-price";
+ price.inputMode = "numeric";
+ price.value = "$600,000";
+ window.__formattedPricePointerDowns = 0;
+ price.addEventListener("pointerdown", () => window.__formattedPricePointerDowns++);
+ price.addEventListener("input", () => {
+ const digits = price.value.replace(/\\D/g, "");
+ price.value = digits ? "$" + Number(digits).toLocaleString("en-US") : "";
+ });
+ document.body.append(price);
+ });
+ await source.fill("#formatted-price", "610000");
+ assertEqual(
+ await source.evaluate("document.querySelector('#formatted-price').value"),
+ "$610,000",
+ "page.fill accepts application formatting"
+ );
+ assertEqual(
+ await source.evaluate("window.__formattedPricePointerDowns"),
+ 0,
+ "a semantically equivalent formatted value is not typed twice"
+ );
assertEqual((await currentTab()).targetId, source.targetId, "page.fill activates and keeps its page current");
await source.evaluate(() => {
@@ -648,8 +700,16 @@ export function pageActionsAndPopupCase() {
assertEqual(rawState.rawClickTrusted, true, "page.mouse.click uses trusted input");
await source.evaluate("window.scrollTo(0, 0)");
- const scrolled = await source.scrollBy(300);
- assert(scrolled.y > 0, "page.scrollBy scrolls the addressed document");
+ await source.mouse.move(10, 10);
+ await source.mouse.wheel(0, 300);
+ assertEqual(
+ await source.waitForFunction("window.scrollY > 0", undefined, {
+ timeout: 2_000,
+ polling: 25,
+ }),
+ true,
+ "page.mouse.wheel scrolls the addressed document asynchronously"
+ );
const innerScrollPoint = await source.evaluate(() => {
const element = document.querySelector("#inner-scroll");
element.scrollIntoView({ block: "center" });
@@ -745,9 +805,9 @@ export function pageActionsAndPopupCase() {
"tabs that existed before the action remain untracked"
);
await assertRejects(
- () => task.openPage(baseUrl + "/secondary?page-actions=blocked"),
+ () => newPageAt(task, baseUrl + "/secondary?page-actions=blocked"),
"Page budget reached (4/3)",
- "an adopted popup can exceed the budget and backpressure later openPage calls"
+ "an adopted popup can exceed the budget and backpressure later newPage calls"
);
await reconciledPopup.page.close();
@@ -760,12 +820,8 @@ export function pageActionsAndPopupCase() {
export function pageComplexEvaluateCase() {
return `
const task = await taskSpace(taskName);
- const source = await task.openPage(baseUrl + "/?page-evaluate=complex", {
- as: "complex-evaluate-source",
- });
- const comparison = await task.openPage(baseUrl + "/secondary?page-evaluate=comparison", {
- as: "complex-evaluate-comparison",
- });
+ const source = await newPageAt(task, baseUrl + "/?page-evaluate=complex");
+ const comparison = await newPageAt(task, baseUrl + "/secondary?page-evaluate=comparison");
assertEqual((await currentTab()).targetId, comparison.targetId, "comparison page starts active");
const complexInput = {
@@ -937,12 +993,8 @@ export function pageComplexEvaluateCase() {
export function pageFetchCase() {
return `
const task = await taskSpace(taskName);
- const source = await task.openPage(baseUrl + "/nested/page-fetch/source", {
- as: "page-fetch-source",
- });
- const comparison = await task.openPage(baseUrl + "/secondary?page-fetch=comparison", {
- as: "page-fetch-comparison",
- });
+ const source = await newPageAt(task, baseUrl + "/nested/page-fetch/source");
+ const comparison = await newPageAt(task, baseUrl + "/secondary?page-fetch=comparison");
await source.evaluate(() => {
document.cookie = "egoPageFetch=page-cookie; path=/";
});
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 d27d3fc..38d353d 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,7 +1,18 @@
export function pageLoadStatesCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.openPage("about:blank", { as: "page-load-states" });
+ 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"
+ );
+ assertIncludes(
+ await page.url(),
+ "/streamed-page?ms=600",
+ "a Page remains addressable after goto times out"
+ );
+ await page.waitForLoadState("load", { timeout: 2_000 });
const referer = baseUrl + "/navigation-source";
await page.goto(baseUrl + "/streamed-page?ms=1000", {
referer,
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-media-playback.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-media-playback.mjs
index 18efb8e..2f1d39b 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-media-playback.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-media-playback.mjs
@@ -1,9 +1,7 @@
export function pageMediaPlaybackCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.openPage(baseUrl + "/media-workbench", {
- as: "media-workbench",
- });
+ const page = await newPageAt(task, baseUrl + "/media-workbench");
await page.waitForSelector('body[data-media-ready="true"]', {
timeout: 10_000,
});
@@ -43,9 +41,7 @@ export function pageMediaPlaybackCase() {
"video can be unmuted through the UI"
);
- const other = await task.openPage(baseUrl + "/?workflow=media-page-switch", {
- as: "media-other",
- });
+ const other = await newPageAt(task, baseUrl + "/?workflow=media-page-switch");
await other.snapshot();
await page.click("#audio-play");
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-oopif.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-oopif.mjs
index 0dfe388..d9b2243 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-oopif.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-oopif.mjs
@@ -1,9 +1,7 @@
export function pageOopifActionCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.openPage(baseUrl + "/?page-api=oopif", {
- as: "oopif-page",
- });
+ const page = await newPageAt(task, baseUrl + "/?page-api=oopif");
const snapshot = await page.snapshot({ scope: "full_page" });
assertIncludes(snapshot, "Run iframe action", "snapshot includes cross-site iframe content");
assertIncludes(snapshot, "Iframe field", "snapshot includes the iframe input");
@@ -28,33 +26,56 @@ export function pageOopifActionCase() {
"Page.fill writes through the iframe session"
);
- const sameOrigin = await task.openPage(baseUrl + "/same-origin-frame", {
- as: "same-origin-frame",
- });
+ const sameOrigin = await newPageAt(task, baseUrl + "/same-origin-frame");
assertIncludes(
await sameOrigin.snapshot({ scope: "full_page" }),
"Run iframe action",
"snapshot includes same-process iframe content"
);
- await sameOrigin.click('loc=role:button[name="Run iframe action"]');
- await sameOrigin.fill('loc=role:textbox[name="Iframe field"]', "same process");
+ await sameOrigin.evaluate(() => {
+ const frame = document.querySelector("#fixture-frame");
+ frame.style.cssText =
+ "position:fixed;left:20px;top:80px;width:500px;height:300px;z-index:20";
+ const covered = document.createElement("button");
+ covered.id = "covered-frame-duplicate";
+ covered.textContent = "Run iframe action";
+ covered.style.cssText =
+ "position:fixed;left:100px;top:120px;width:220px;height:60px;z-index:10";
+ covered.addEventListener("click", () => covered.dataset.clicked = "true");
+ document.body.append(covered);
+ });
+ await sameOrigin.click('text="Run iframe action"');
+ await sameOrigin.fill('loc=css:#iframe-field', "same process");
const sameOriginState = await sameOrigin.evaluate(() => {
const frame = document.querySelector("#fixture-frame");
return {
+ coveredClicked: document.querySelector("#covered-frame-duplicate")?.dataset.clicked,
result: frame?.contentDocument?.querySelector("#iframe-result")?.textContent,
value: frame?.contentDocument?.querySelector("#iframe-field")?.value,
};
});
+ assertEqual(
+ sameOriginState.coveredClicked,
+ undefined,
+ "the covered top-document duplicate is not clicked"
+ );
assertEqual(sameOriginState.result, "clicked:true", "Page.click works in a same-process iframe");
assertEqual(sameOriginState.value, "same process", "Page.fill works in a same-process iframe");
await sameOrigin.close();
+ await writeFile(
+ join(tempDir, "oopif-page.json"),
+ JSON.stringify({ label: page.label })
+ );
`;
}
export function pageOopifRestoreCase() {
return `
const task = await taskSpace(taskName);
- const page = task.page("oopif-page");
+ const saved = JSON.parse(
+ await readFile(join(tempDir, "oopif-page.json"), "utf8")
+ );
+ const page = task.page(saved.label);
const snapshot = await page.snapshot({ scope: "full_page" });
assertIncludes(snapshot, "Run iframe action", "a later round observes the iframe");
await page.click('text="Run iframe action"');
@@ -74,7 +95,7 @@ export function pageOopifRestoreCase() {
await page.close();
await assertRejects(
() => page.snapshot(),
- "page oopif-page was closed",
+ "page " + page.label + " was closed",
"closing the Page retires its OOPIF-capable handle"
);
`;
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 b2165a6..e3c0156 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
@@ -1,9 +1,7 @@
export function pagePopupWaiterCase() {
return `
const task = await taskSpace(taskName);
- const source = await task.openPage(baseUrl + "/?page=popup-waiter", {
- as: "popup-waiter-source",
- });
+ const source = await newPageAt(task, baseUrl + "/?page=popup-waiter");
try {
await source.evaluate((popupUrl) => {
const button = document.createElement("button");
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-screenshot.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-screenshot.mjs
index 0705827..54064a4 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-screenshot.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-screenshot.mjs
@@ -1,9 +1,7 @@
export function pageScrolledScreenshotCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.openPage(baseUrl + "/?workflow=page-scrolled-screenshot", {
- as: "page-scrolled-screenshot",
- });
+ const page = await newPageAt(task, baseUrl + "/?workflow=page-scrolled-screenshot");
await page.evaluate(() => {
document.documentElement.style.cssText = "margin:0;padding:0";
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-shadow-dom.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-shadow-dom.mjs
index 067f290..0295227 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-shadow-dom.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-shadow-dom.mjs
@@ -1,7 +1,7 @@
export function pageShadowDomCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.openPage(baseUrl + "/?page=shadow-dom", { as: "shadow-dom" });
+ const page = await newPageAt(task, baseUrl + "/?page=shadow-dom");
try {
const snapshot = await page.snapshot({ scope: "full_page" });
assertIncludes(snapshot, "Shadow field", "snapshot exposes the shadow input");
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-snapshot-locators.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-snapshot-locators.mjs
index 32f6e13..47721c6 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-snapshot-locators.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-snapshot-locators.mjs
@@ -1,9 +1,7 @@
export function pageSnapshotLocatorCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.openPage(baseUrl + "/?workflow=page-snapshot-locators", {
- as: "page-snapshot-locators",
- });
+ const page = await newPageAt(task, baseUrl + "/?workflow=page-snapshot-locators");
await page.evaluate(() => {
const region = document.createElement("section");
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-text-locators.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-text-locators.mjs
index 0e1c276..099fbb1 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-text-locators.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-text-locators.mjs
@@ -1,9 +1,7 @@
export function pageTextLocatorCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.openPage(baseUrl + "/?page=text-locators", {
- as: "text-locators",
- });
+ const page = await newPageAt(task, baseUrl + "/?page=text-locators");
try {
await page.evaluate(() => {
const region = document.createElement("section");
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 ee96927..d8d5ad8 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,9 +25,7 @@ export function profileSelectionCase() {
profileId: selectedProfile.id,
});
try {
- const page = await explicitTask.openPage(baseUrl + "/?profile=explicit", {
- as: "profile-check",
- });
+ const page = await newPageAt(explicitTask, baseUrl + "/?profile=explicit");
assertEqual(
await page.title(),
"ego-lite helper e2e",
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 18d5a2b..ca79cec 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 v2Task.openPage(baseUrl + "/secondary?v2-lifecycle=handoff");
+ await newPageAt(v2Task, 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 finishTask.openPage(baseUrl + "/secondary?v2-lifecycle=finish");
+ await newPageAt(finishTask, baseUrl + "/secondary?v2-lifecycle=finish");
const finishSpaceId = finishTask.spaceId;
await finishTask.finish();
assert(
@@ -116,9 +116,9 @@ export function taskSpaceCase() {
export function crossSpaceV2Case() {
return `
const firstTask = await taskSpace(taskName + " gate first");
- const firstPage = await firstTask.openPage(baseUrl + "/?space=first");
+ const firstPage = await newPageAt(firstTask, baseUrl + "/?space=first");
const secondTask = await taskSpace(taskName + " gate second");
- const secondPage = await secondTask.openPage(baseUrl + "/secondary?space=second");
+ const secondPage = await newPageAt(secondTask, baseUrl + "/secondary?space=second");
const [firstInfo, secondInfo] = await Promise.all([
firstPage.info(),
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/workflow-chains.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/workflow-chains.mjs
index 3a8b80e..000ff99 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/workflow-chains.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/workflow-chains.mjs
@@ -1,9 +1,7 @@
export function v1V2ActionParityCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.openPage(baseUrl + "/?workflow=parity", {
- as: "workflow-parity",
- });
+ const page = await newPageAt(task, baseUrl + "/?workflow=parity");
await page.evaluate(() => {
window.__parityEvents = [];
@@ -111,9 +109,7 @@ export function v1V2ActionParityCase() {
export function portableKeyboardWorkflowCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.openPage(baseUrl + "/?workflow=keyboard", {
- as: "workflow-keyboard",
- });
+ const page = await newPageAt(task, baseUrl + "/?workflow=keyboard");
await page.fill("#text-input", "portable clipboard");
await page.keyboard.press("ControlOrMeta+A");
@@ -165,7 +161,7 @@ export function portableKeyboardWorkflowCase() {
export function pureCdpWorkflowCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.openPage("about:blank", { as: "workflow-cdp" });
+ const page = await newPageAt(task, "about:blank");
const destination = baseUrl + "/?workflow=cdp";
await page.cdp("Page.navigate", { url: destination }, { timeout: 5_000 });
@@ -249,12 +245,8 @@ export function pureCdpWorkflowCase() {
export function snapshotWorkflowCase() {
return `
const task = await taskSpace(taskName);
- const first = await task.openPage(baseUrl + "/?workflow=snapshot-a", {
- as: "workflow-snapshot-a",
- });
- const second = await task.openPage(baseUrl + "/?workflow=snapshot-b", {
- as: "workflow-snapshot-b",
- });
+ const first = await newPageAt(task, baseUrl + "/?workflow=snapshot-a");
+ const second = await newPageAt(task, baseUrl + "/?workflow=snapshot-b");
const firstSnapshot = await first.snapshot();
const secondSnapshot = await second.snapshot();
@@ -287,7 +279,7 @@ export function snapshotWorkflowCase() {
export function visualWorkflowCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.openPage(baseUrl + "/visual", { as: "workflow-visual" });
+ const page = await newPageAt(task, baseUrl + "/visual");
const snapshot = await page.snapshot();
assert(
!snapshot.includes("CLICK") && !snapshot.includes("DONE"),
diff --git a/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs b/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs
index 86e8564..300c9dc 100644
--- a/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs
@@ -159,6 +159,12 @@ export function egoSource(body, context) {
throw new Error(message + ": expected rejection");
}
+ async function newPageAt(task, url, options = {}) {
+ const page = await task.newPage();
+ await page.goto(url, options);
+ return page;
+ }
+
async function waitForJsValue(expression, expected, message, debugExpression = null) {
const deadline = Date.now() + 2000;
let last;
diff --git a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
index 516252c..cc92426 100644
--- a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
@@ -48,6 +48,19 @@ export async function startFixtureServer(taskName) {
res.end("server text fixture");
return;
}
+ if (url.pathname === "/api/image.png") {
+ const png = Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
+ "base64",
+ );
+ res.writeHead(200, {
+ "content-type": "image/png",
+ "content-length": png.length,
+ "access-control-allow-origin": "*",
+ });
+ res.end(png);
+ return;
+ }
if (url.pathname === "/api/header") {
res.writeHead(200, {
"content-type": "text/plain",
diff --git a/package/ego-browser/scripts/real-browser-e2e/runner.mjs b/package/ego-browser/scripts/real-browser-e2e/runner.mjs
index 4d2b2f6..a43668f 100644
--- a/package/ego-browser/scripts/real-browser-e2e/runner.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/runner.mjs
@@ -147,7 +147,7 @@ export async function runRealBrowserE2e() {
`the browser script did not report the expected hard stop: ${expectedOutput}`,
);
}
- // The marker is written only after openPage() has returned. Its presence
+ // The marker is written only after newPage() and goto() have returned. Its presence
// distinguishes the intended hard stop from an unrelated startup error.
await stat(join(tempDir, markerName));
const assertions = completedWithAcceptedOutput
diff --git a/package/ego-browser/src/driver/action-target.ts b/package/ego-browser/src/driver/action-target.ts
index 638552c..249698f 100644
--- a/package/ego-browser/src/driver/action-target.ts
+++ b/package/ego-browser/src/driver/action-target.ts
@@ -94,3 +94,118 @@ export const EDIT_ACTION_TARGET_HELPERS = `
]).has(String(element.getAttribute?.("role") || "").toLowerCase());
}
`;
+
+// Shared by resolver-level candidate selection and the final pointer check.
+// 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}
+ 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;
+ }
+ if (tag === "A" && element.hasAttribute?.("href")) return true;
+ if (
+ element?.hasAttribute?.("contenteditable") &&
+ element.getAttribute("contenteditable") !== "false"
+ ) return true;
+ return new Set([
+ "button",
+ "checkbox",
+ "link",
+ "menuitem",
+ "menuitemcheckbox",
+ "menuitemradio",
+ "option",
+ "radio",
+ "slider",
+ "spinbutton",
+ "switch",
+ "tab",
+ "textbox",
+ "treeitem"
+ ]).has(String(element?.getAttribute?.("role") || "").toLowerCase());
+ }
+ function isInteractiveElement(element) {
+ return isExplicitInteractiveElement(element) || Boolean(element?.isContentEditable);
+ }
+ function hitElementAtPoint(target, point) {
+ const roots = [];
+ let parent = target;
+ while (parent) {
+ const root = parent.getRootNode ? parent.getRootNode() : null;
+ if (!root || typeof root.elementsFromPoint !== "function") break;
+ roots.push(root);
+ if (root.nodeType === 9) break;
+ parent = root.host;
+ }
+ let hitElement;
+ for (let index = roots.length - 1; index >= 0; index -= 1) {
+ const root = roots[index];
+ const elements = root.elementsFromPoint(point.x, point.y);
+ const innerElement = elements[0] || root.elementFromPoint(point.x, point.y);
+ if (!innerElement) break;
+ hitElement = innerElement;
+ if (index > 0 && innerElement !== roots[index - 1].host) break;
+ }
+ return hitElement;
+ }
+ function interceptingElementAtPoint(target, point) {
+ const hitElement = hitElementAtPoint(target, point);
+ let current = hitElement;
+ while (current && current !== target) current = composedParent(current);
+ if (current === target) return null;
+
+ current = target;
+ while (current && current !== hitElement) current = composedParent(current);
+ if (current === hitElement && isInteractiveElement(hitElement)) return null;
+
+ return hitElement || document.documentElement;
+ }
+ function accessibleName(element) {
+ const labelledBy = String(element?.getAttribute?.("aria-labelledby") || "")
+ .split(/\s+/)
+ .filter(Boolean)
+ .map((id) => element.ownerDocument?.getElementById(id)?.textContent || "")
+ .join(" ");
+ const heading = element?.querySelector?.("h1,h2,h3,h4,h5,h6")?.textContent || "";
+ return String(
+ element?.getAttribute?.("aria-label") ||
+ labelledBy ||
+ heading ||
+ element?.getAttribute?.("title") ||
+ ""
+ ).replace(/\s+/g, " ").trim().slice(0, 120);
+ }
+ function describeHitTarget(element) {
+ let modal = element;
+ while (modal) {
+ if (
+ modal.getAttribute?.("role") === "dialog" ||
+ modal.getAttribute?.("aria-modal") === "true"
+ ) {
+ const name = accessibleName(modal);
+ return name ? 'dialog "' + name.replaceAll('"', '\\"') + '"' : "dialog";
+ }
+ modal = composedParent(modal);
+ }
+ const tag = String(element.tagName || "unknown").toLowerCase();
+ const id = element.id
+ ? ' id="' + String(element.id).slice(0, 80).replaceAll('"', '&quot;') + '"'
+ : "";
+ const role = element.getAttribute?.("role")
+ ? ' role="' + String(element.getAttribute("role")).slice(0, 80).replaceAll('"', '&quot;') + '"'
+ : "";
+ const href = tag === "a" && element.hasAttribute?.("href")
+ ? ' href="' + String(element.getAttribute("href")).slice(0, 120).replaceAll('"', '&quot;') + '"'
+ : "";
+ return "<" + tag + id + role + href + ">";
+ }
+`;
diff --git a/package/ego-browser/src/driver/page-actions.ts b/package/ego-browser/src/driver/page-actions.ts
index b39dd71..a58b516 100644
--- a/package/ego-browser/src/driver/page-actions.ts
+++ b/package/ego-browser/src/driver/page-actions.ts
@@ -5,8 +5,8 @@ import {
} from "../element-resolver.js";
import { RefMap } from "../ref-map.js";
import {
- COMPOSED_PARENT_HELPER,
EDIT_ACTION_TARGET_HELPERS,
+ HIT_TARGET_HELPERS,
} from "./action-target.js";
type PageActionServices = {
@@ -37,6 +37,104 @@ export type PageFillOptions = {
timeout?: number;
};
+/** Select option values from one visible, enabled select element. */
+export async function selectOptionInPage(
+ services: PageActionServices,
+ sessionId: string,
+ refMap: RefMap,
+ selector: string,
+ values: string[],
+ iframeSessions = new Map<string, string>(),
+): Promise<string[]> {
+ assertPageSelector(selector);
+ const resolved = await resolveElementObjectId(
+ cdpAdapter(services),
+ sessionId,
+ refMap,
+ selector,
+ iframeSessions,
+ { strict: true, actionability: "visible" },
+ );
+ const source = `function selectOptionsForAction(values) {
+ ${EDIT_ACTION_TARGET_HELPERS}
+ let select = String(this.tagName || "").toUpperCase() === "SELECT"
+ ? this
+ : null;
+ if (!select && this.control?.tagName === "SELECT") select = this.control;
+ if (!select) {
+ const candidates = composedDescendantMatches(
+ this,
+ (element) => String(element.tagName || "").toUpperCase() === "SELECT",
+ true,
+ );
+ if (candidates.length > 1) {
+ return { error: "element contains multiple select controls" };
+ }
+ select = candidates[0] || null;
+ }
+ if (!select) return { error: "element is not a select control" };
+ if (!select.isConnected) return { error: "element is not connected" };
+ const view = select.ownerDocument.defaultView;
+ const rect = select.getBoundingClientRect();
+ const style = view?.getComputedStyle(select);
+ if (
+ !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" };
+ }
+ 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' };
+ selectedOptions.push(option);
+ }
+ for (const option of options) option.selected = selectedOptions.includes(option);
+ 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 }));
+ return { selected };
+ }`;
+ try {
+ const response = await services.cdp(
+ "Runtime.callFunctionOn",
+ {
+ functionDeclaration: source,
+ objectId: resolved.objectId,
+ arguments: [{ value: values }],
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ resolved.sessionId,
+ );
+ const result = runtimeValue(response, source);
+ if (typeof result?.error === "string") {
+ const transient = new Set([
+ "element is not connected",
+ "element is not visible",
+ "element is disabled",
+ ]);
+ throw transient.has(result.error)
+ ? new ElementResolutionError(
+ `page.selectOption failed: ${result.error}`,
+ "transient",
+ )
+ : new Error(`page.selectOption failed: ${result.error}`);
+ }
+ if (!Array.isArray(result?.selected)) {
+ throw new Error("page.selectOption received an invalid selection result");
+ }
+ return result.selected;
+ } finally {
+ await releaseObject(services, resolved.sessionId, resolved.objectId);
+ }
+}
+
export type PageHoverOptions = {
position?: { x: number; y: number };
force?: boolean;
@@ -75,6 +173,12 @@ type MouseMoveState = PageMouseMoveOptions & {
const INPUT_EVENT_DELAY_MS = 25;
const FILL_VERIFICATION_ATTEMPTS = 5;
const FILL_VERIFICATION_INTERVAL_MS = 50;
+type FillOutcome =
+ | "exact"
+ | "equivalent"
+ | "transformed"
+ | "appended"
+ | "unchanged";
/** Click an element through one explicit target session and Page ref map. */
export async function clickInPage(
@@ -95,7 +199,7 @@ export async function clickInPage(
refMap,
selector,
iframeSessions,
- { strict: true },
+ { strict: true, actionability: "pointer" },
);
try {
let point = await resolveElementPoint(
@@ -206,7 +310,7 @@ export async function fillInPage(
refMap,
selector,
iframeSessions,
- { strict: true },
+ { strict: true, actionability: "visible" },
);
let actionObjectId: string | undefined;
try {
@@ -229,6 +333,9 @@ export async function fillInPage(
return { x: (left + right) / 2, y: (top + bottom) / 2 };
};
const tag = this.nodeName.toLowerCase();
+ const observed = tag === "input" || tag === "textarea"
+ ? this.value
+ : (this.innerText ?? this.textContent ?? "");
const view = this.ownerDocument.defaultView;
const rect = this.getBoundingClientRect();
const style = view?.getComputedStyle(this);
@@ -265,7 +372,13 @@ export async function fillInPage(
this.focus();
const cursorPoint = visibleCursorPoint();
const kind = this.isContentEditable ? "contenteditable" : tag;
- if (!clearFirst) return { status: "needsinput", kind, cursorPoint };
+ const details = {
+ status: "needsinput",
+ kind,
+ cursorPoint,
+ before: String(observed)
+ };
+ if (!clearFirst) return details;
if (tag === "input" || tag === "textarea") {
this.select();
} else {
@@ -275,7 +388,7 @@ export async function fillInPage(
selection?.removeAllRanges();
selection?.addRange(range);
}
- return { status: "needsinput", kind, cursorPoint };
+ return details;
}`;
const prepare = async () => {
const preparation = await services.cdp(
@@ -311,22 +424,26 @@ export async function fillInPage(
}
await dispatchFillInput(services, resolved.sessionId, value, clearFirst);
- if (
- await verifyFilledValue(
- services,
- resolved.sessionId,
- actionObjectId,
- value,
- clearFirst,
- )
- ) {
+ let outcome = await verifyFillOutcome(
+ services,
+ resolved.sessionId,
+ actionObjectId,
+ String(result?.before ?? ""),
+ value,
+ clearFirst,
+ );
+ if (fillOutcomeAccepted(outcome)) {
return;
}
- if (result?.kind === "contenteditable") {
- // Some editors do not install their internal editing state until they
- // receive a real pointer activation. Retry only after proving that the
- // ordinary fill had no observable effect, which avoids duplicate input.
+ if (
+ result?.kind === "contenteditable" ||
+ result?.kind === "input" ||
+ result?.kind === "textarea"
+ ) {
+ // Some controls append because their editing state is not installed
+ // until a real pointer activation. Retry only an unchanged or appended
+ // result so application formatting is never typed twice.
await clickResolvedElement(
services,
resolved.sessionId,
@@ -341,15 +458,15 @@ export async function fillInPage(
throw new Error("page.fill received an invalid preparation result");
}
await dispatchFillInput(services, resolved.sessionId, value, clearFirst);
- if (
- await verifyFilledValue(
- services,
- resolved.sessionId,
- actionObjectId,
- value,
- clearFirst,
- )
- ) {
+ outcome = await verifyFillOutcome(
+ services,
+ resolved.sessionId,
+ actionObjectId,
+ String(result?.before ?? ""),
+ value,
+ clearFirst,
+ );
+ if (fillOutcomeAccepted(outcome)) {
return;
}
}
@@ -427,7 +544,7 @@ export async function focusInPage(
refMap,
selector,
iframeSessions,
- { strict: true },
+ { strict: true, actionability: "visible" },
);
const source = `function focusElementForAction() {
if (!this.isConnected) return { error: "element is not connected" };
@@ -557,36 +674,34 @@ async function dispatchFillInput(
}
}
-async function verifyFilledValue(
+async function verifyFillOutcome(
services: PageActionServices,
sessionId: string,
objectId: string,
+ before: string,
value: string,
clearFirst: boolean,
-): Promise<boolean> {
- const source = `function verifyFilledValue(value, clearFirst) {
+): Promise<FillOutcome> {
+ const source = `function readFilledValue() {
if (!this.isConnected) return { error: "element is not connected" };
const tag = this.nodeName.toLowerCase();
const observed = tag === "input" || tag === "textarea"
? this.value
: (this.innerText ?? this.textContent ?? "");
- const normalize = (text) => String(text)
- .replace(/\\r\\n?/g, "\\n")
- .replace(/\\u200b/g, "");
- const actual = normalize(observed);
- const expected = normalize(value);
return {
- matches: clearFirst ? actual === expected : actual.includes(expected),
+ actual: String(observed),
+ type: tag === "input" ? this.type.toLowerCase() : ""
};
}`;
- let consecutiveMatches = 0;
+ let prior;
+ let consecutiveReads = 0;
+ let lastOutcome: FillOutcome = "unchanged";
for (let attempt = 0; attempt < FILL_VERIFICATION_ATTEMPTS; attempt += 1) {
const response = await services.cdp(
"Runtime.callFunctionOn",
{
functionDeclaration: source,
objectId,
- arguments: [{ value }, { value: clearFirst }],
returnByValue: true,
awaitPromise: false,
},
@@ -598,17 +713,77 @@ async function verifyFilledValue(
// could duplicate text on a replacement element.
throw new Error(`page.fill could not verify the result: ${result.error}`);
}
- if (result?.matches === true) {
- consecutiveMatches += 1;
- if (consecutiveMatches === 2) return true;
+ const outcome = classifyFillOutcome(
+ before,
+ value,
+ String(result?.actual ?? ""),
+ clearFirst,
+ String(result?.type ?? ""),
+ );
+ lastOutcome = outcome;
+ const reading = `${outcome}\u0000${String(result?.actual ?? "")}`;
+ if (reading === prior) {
+ consecutiveReads += 1;
+ if (consecutiveReads === 2) return outcome;
} else {
- consecutiveMatches = 0;
+ prior = reading;
+ consecutiveReads = 1;
}
if (attempt + 1 < FILL_VERIFICATION_ATTEMPTS) {
await services.sleep(FILL_VERIFICATION_INTERVAL_MS);
}
}
- return false;
+ return lastOutcome;
+}
+
+function fillOutcomeAccepted(outcome: FillOutcome): boolean {
+ return (
+ outcome === "exact" || outcome === "equivalent" || outcome === "transformed"
+ );
+}
+
+function classifyFillOutcome(
+ beforeValue: string,
+ expectedValue: string,
+ actualValue: string,
+ clearFirst: boolean,
+ inputType: string,
+): FillOutcome {
+ const normalize = (text: string) =>
+ String(text)
+ .replace(/\r\n?/g, "\n")
+ .replace(/\u200b/g, "");
+ const before = normalize(beforeValue);
+ const expected = normalize(expectedValue);
+ const actual = normalize(actualValue);
+ if (clearFirst ? actual === expected : actual.includes(expected)) {
+ return "exact";
+ }
+ if (
+ inputType === "number" &&
+ expected.trim() !== "" &&
+ actual.trim() !== "" &&
+ Number(actual) === Number(expected)
+ ) {
+ return "equivalent";
+ }
+ const integerExpected = expected.normalize("NFKC").trim();
+ if (/^\d+$/.test(integerExpected)) {
+ const actualDigits = actual.normalize("NFKC").replace(/\D/g, "");
+ if (actualDigits === integerExpected) return "equivalent";
+ const beforeDigits = before.normalize("NFKC").replace(/\D/g, "");
+ if (
+ clearFirst &&
+ beforeDigits.length > 0 &&
+ actualDigits === beforeDigits + integerExpected
+ ) {
+ return "appended";
+ }
+ }
+ if (clearFirst && actual === before + expected && before.length > 0) {
+ return "appended";
+ }
+ return actual === before ? "unchanged" : "transformed";
}
async function clickResolvedElement(
@@ -723,7 +898,7 @@ export async function hoverInPage(
refMap,
selector,
iframeSessions,
- { strict: true },
+ { strict: true, actionability: "pointer" },
);
try {
const point = await resolveElementPoint(
@@ -767,7 +942,7 @@ export async function dragAndDropInPage(
refMap,
sourceSelector,
iframeSessions,
- { strict: true },
+ { strict: true, actionability: "pointer" },
);
let target;
try {
@@ -777,7 +952,7 @@ export async function dragAndDropInPage(
refMap,
targetSelector,
iframeSessions,
- { strict: true },
+ { strict: true, actionability: "pointer" },
);
const sourcePoint = await resolveElementPoint(
services,
@@ -1160,95 +1335,6 @@ function exceptionDescription(response: any): string {
);
}
-// This is a compact adaptation of Playwright's composed-tree hit-target check.
-// It handles ordinary descendants, slots, and nested shadow roots without
-// exposing an injected helper or trusting only document.elementFromPoint().
-const HIT_TARGET_HELPERS = `
- ${COMPOSED_PARENT_HELPER}
- 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;
- }
- if (tag === "A" && element.hasAttribute?.("href")) return true;
- if (
- element?.hasAttribute?.("contenteditable") &&
- element.getAttribute("contenteditable") !== "false"
- ) return true;
- return new Set([
- "button",
- "checkbox",
- "link",
- "menuitem",
- "menuitemcheckbox",
- "menuitemradio",
- "option",
- "radio",
- "slider",
- "spinbutton",
- "switch",
- "tab",
- "textbox",
- "treeitem"
- ]).has(String(element?.getAttribute?.("role") || "").toLowerCase());
- }
- function isInteractiveElement(element) {
- return isExplicitInteractiveElement(element) || Boolean(element?.isContentEditable);
- }
- function hitElementAtPoint(target, point) {
- const roots = [];
- let parent = target;
- while (parent) {
- const root = parent.getRootNode ? parent.getRootNode() : null;
- if (!root || typeof root.elementsFromPoint !== "function") break;
- roots.push(root);
- if (root.nodeType === 9) break;
- parent = root.host;
- }
- let hitElement;
- for (let index = roots.length - 1; index >= 0; index -= 1) {
- const root = roots[index];
- const elements = root.elementsFromPoint(point.x, point.y);
- const innerElement = elements[0] || root.elementFromPoint(point.x, point.y);
- if (!innerElement) break;
- hitElement = innerElement;
- if (index > 0 && innerElement !== roots[index - 1].host) break;
- }
- return hitElement;
- }
- function interceptingElementAtPoint(target, point) {
- const hitElement = hitElementAtPoint(target, point);
- let current = hitElement;
- while (current && current !== target) current = composedParent(current);
- if (current === target) return null;
-
- // A child with pointer-events:none can legitimately resolve to its
- // interactive ancestor. A real pointer click reaches that ancestor, so it
- // is compatible with the requested action rather than an overlay.
- current = target;
- while (current && current !== hitElement) current = composedParent(current);
- if (current === hitElement && isInteractiveElement(hitElement)) return null;
-
- return hitElement || document.documentElement;
- }
- function describeHitTarget(element) {
- const tag = String(element.tagName || "unknown").toLowerCase();
- const id = element.id
- ? ' id="' + String(element.id).slice(0, 80).replaceAll('"', '&quot;') + '"'
- : "";
- const href = tag === "a" && element.hasAttribute?.("href")
- ? ' href="' + String(element.getAttribute("href")).slice(0, 120).replaceAll('"', '&quot;') + '"'
- : "";
- return "<" + tag + id + href + ">";
- }
-`;
-
function assertPageSelector(selector: unknown): asserts selector is string {
if (typeof selector !== "string" || selector.trim().length === 0) {
throw new TypeError("Page actions require a non-empty selector string");
diff --git a/package/ego-browser/src/element-resolver.test.mjs b/package/ego-browser/src/element-resolver.test.mjs
index dd48728..43df462 100644
--- a/package/ego-browser/src/element-resolver.test.mjs
+++ b/package/ego-browser/src/element-resolver.test.mjs
@@ -290,6 +290,107 @@ test("ambiguous raw CSS selectors fail instead of choosing the first match", asy
);
});
+test("action resolution uses the sole usable CSS match", async () => {
+ const cdp = new FakeCDP(async (method, params) => {
+ if (method !== "Runtime.evaluate") return {};
+ if (params.expression.includes("__egoActionableMatches")) {
+ return params.returnByValue
+ ? { result: { value: 1 } }
+ : { result: { objectId: "visible-button" } };
+ }
+ return { result: { value: 2 } };
+ });
+
+ assert.deepEqual(
+ await resolveElementObjectId(
+ cdp,
+ "session:page",
+ new RefMap(),
+ "button.save",
+ new Map(),
+ { strict: true, actionability: "visible" },
+ ),
+ { objectId: "visible-button", sessionId: "session:page" },
+ );
+});
+
+test("action resolution prefers a sole actionable Page match over iframe matches", async () => {
+ const cdp = new FakeCDP(async (method, params, sessionId) => {
+ if (method !== "Runtime.evaluate") return {};
+ if (params.expression.includes("__egoActionableMatches")) {
+ return params.returnByValue
+ ? { result: { value: 1 } }
+ : { result: { objectId: `button:${sessionId}` } };
+ }
+ return { result: { value: 1 } };
+ });
+
+ assert.deepEqual(
+ await resolveElementObjectId(
+ cdp,
+ "session:page",
+ new RefMap(),
+ "button.save",
+ new Map([["frame-child", "session:frame-child"]]),
+ { strict: true, actionability: "pointer" },
+ ),
+ { objectId: "button:session:page", sessionId: "session:page" },
+ );
+});
+
+test("pointer action resolution skips a covered Page match for a frame match", async () => {
+ const cdp = new FakeCDP(async (method, params, sessionId) => {
+ if (method !== "Runtime.evaluate") return {};
+ if (params.expression.includes("__egoActionableMatches")) {
+ assert.match(params.expression, /elementsFromPoint/);
+ if (params.returnByValue) {
+ return {
+ result: { value: sessionId === "session:frame-child" ? 1 : 0 },
+ };
+ }
+ return { result: { objectId: "frame-button" } };
+ }
+ return { result: { value: 1 } };
+ });
+
+ assert.deepEqual(
+ await resolveElementObjectId(
+ cdp,
+ "session:page",
+ new RefMap(),
+ "button.move",
+ new Map([["frame-child", "session:frame-child"]]),
+ { strict: true, actionability: "pointer" },
+ ),
+ { objectId: "frame-button", sessionId: "session:frame-child" },
+ );
+});
+
+test("visible 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")) {
+ assert.doesNotMatch(params.expression, /style\.opacity/);
+ return params.returnByValue
+ ? { result: { value: 1 } }
+ : { result: { objectId: "transparent-select" } };
+ }
+ return { result: { value: 1 } };
+ });
+
+ assert.deepEqual(
+ await resolveElementObjectId(
+ cdp,
+ "session:page",
+ new RefMap(),
+ "select.sort",
+ new Map(),
+ { strict: true, actionability: "visible" },
+ ),
+ { objectId: "transparent-select", sessionId: "session:page" },
+ );
+});
+
test("ambiguous raw XPath selectors fail instead of choosing the first match", async () => {
const cdp = new FakeCDP(async (method, params) => {
if (method === "Runtime.evaluate") {
@@ -358,7 +459,114 @@ test("semantic locators search cross-process iframe sessions", async () => {
});
});
-test("a Page document match wins before iframe fallback", async () => {
+test("text locators search same-process iframe execution contexts", async () => {
+ const cdp = new FakeCDP(async (method, params, sessionId) => {
+ assert.equal(sessionId, "session:page");
+ if (method === "Page.createIsolatedWorld") {
+ assert.equal(params.frameId, "frame-child");
+ return { executionContextId: 77 };
+ }
+ if (method === "Runtime.evaluate") {
+ const inFrame = params.contextId === 77;
+ if (params.returnByValue) {
+ return { result: { value: inFrame ? 1 : 0 } };
+ }
+ return {
+ result: inFrame
+ ? { objectId: "same-process-upload" }
+ : { type: "undefined" },
+ };
+ }
+ return {};
+ });
+
+ assert.deepEqual(
+ await resolveElementObjectId(
+ cdp,
+ "session:page",
+ new RefMap(),
+ 'text="Upload"',
+ new Map([["frame-child", "session:page"]]),
+ { strict: true },
+ ),
+ {
+ objectId: "same-process-upload",
+ sessionId: "session:page",
+ frameId: "frame-child",
+ },
+ );
+});
+
+test("snapshot role aliases resolve against standard accessibility roles", async () => {
+ const cdp = new FakeCDP(async (method) => {
+ if (method === "Accessibility.getFullAXTree") {
+ return {
+ nodes: [
+ {
+ role: { value: "option" },
+ name: { value: "Upload" },
+ backendDOMNodeId: 201,
+ },
+ ],
+ };
+ }
+ if (method === "DOM.resolveNode") {
+ return { object: { objectId: "upload-option" } };
+ }
+ return {};
+ });
+
+ assert.deepEqual(
+ await resolveElementObjectId(
+ cdp,
+ "session:page",
+ new RefMap(),
+ 'loc=role:listboxoption[name="Upload"]',
+ ),
+ { objectId: "upload-option", sessionId: "session:page" },
+ );
+});
+
+test("same-process frame role matches keep their frame provenance", async () => {
+ const cdp = new FakeCDP(async (method, params) => {
+ if (method === "Accessibility.getFullAXTree") {
+ return {
+ nodes: [
+ {
+ role: { value: "option" },
+ name: { value: "Upload" },
+ backendDOMNodeId: 201,
+ },
+ ],
+ };
+ }
+ if (method === "DOM.resolveNode") {
+ return { object: { objectId: "upload-option" } };
+ }
+ if (method === "Runtime.callFunctionOn") {
+ return { result: { value: { actionable: true } } };
+ }
+ return {};
+ });
+
+ assert.deepEqual(
+ await resolveElementObjectId(
+ cdp,
+ "session:page",
+ new RefMap(),
+ 'loc=role:listboxoption[name="Upload"]',
+ new Map([["frame-child", "session:page"]]),
+ { actionability: "pointer" },
+ ),
+ {
+ objectId: "upload-option",
+ sessionId: "session:page",
+ frameId: "frame-child",
+ },
+ );
+});
+
+test("a unique interactable frame role wins over a blocked Page duplicate", async () => {
const cdp = new FakeCDP(async (method, _params, sessionId) => {
if (method === "Accessibility.getFullAXTree") {
return {
@@ -374,6 +582,10 @@ test("a Page document match wins before iframe fallback", async () => {
if (method === "DOM.resolveNode") {
return { object: { objectId: `node:${sessionId}` } };
}
+ if (method === "Runtime.callFunctionOn") {
+ assert.match(_params.functionDeclaration, /elementsFromPoint/);
+ return { result: { value: sessionId === "session:frame-child" } };
+ }
return {};
});
@@ -384,7 +596,78 @@ test("a Page document match wins before iframe fallback", async () => {
new RefMap(),
'loc=role:button[name="Duplicate"]',
new Map([["frame-child", "session:frame-child"]]),
+ { actionability: "pointer" },
+ ),
+ { objectId: "node:session:frame-child", sessionId: "session:frame-child" },
+ );
+});
+
+test("role actions prefer the actionable Page match over a frame match", async () => {
+ const cdp = new FakeCDP(async (method, _params, sessionId) => {
+ if (method === "Accessibility.getFullAXTree") {
+ return {
+ nodes: [
+ {
+ role: { value: "button" },
+ name: { value: "Duplicate" },
+ backendDOMNodeId: sessionId === "session:page" ? 1 : 2,
+ },
+ ],
+ };
+ }
+ if (method === "DOM.resolveNode") {
+ return { object: { objectId: `node:${sessionId}` } };
+ }
+ if (method === "Runtime.callFunctionOn") {
+ return { result: { value: true } };
+ }
+ return {};
+ });
+
+ assert.deepEqual(
+ await resolveElementObjectId(
+ cdp,
+ "session:page",
+ new RefMap(),
+ 'loc=role:button[name="Duplicate"]',
+ new Map([["frame-child", "session:frame-child"]]),
+ { actionability: "pointer" },
),
{ objectId: "node:session:page", sessionId: "session:page" },
);
});
+
+test("strict global role validation rejects a hidden duplicate", async () => {
+ const cdp = new FakeCDP(async (method, _params, sessionId) => {
+ if (method === "Accessibility.getFullAXTree") {
+ return {
+ nodes: [
+ {
+ role: { value: "textbox" },
+ name: { value: "Prompt" },
+ backendDOMNodeId: sessionId === "session:page" ? 1 : 2,
+ },
+ ],
+ };
+ }
+ return {};
+ });
+
+ await assert.rejects(
+ () =>
+ resolveElementObjectId(
+ cdp,
+ "session:page",
+ new RefMap(),
+ 'loc=role:textbox[name="Prompt"]',
+ new Map([["frame-child", "session:frame-child"]]),
+ { strictGlobal: true },
+ ),
+ (error) => {
+ assert.ok(error instanceof ElementResolutionError);
+ assert.equal(error.kind, "permanent");
+ assert.match(error.message, /matched 2 elements/);
+ return true;
+ },
+ );
+});
diff --git a/package/ego-browser/src/element-resolver.ts b/package/ego-browser/src/element-resolver.ts
index 1951921..191945b 100644
--- a/package/ego-browser/src/element-resolver.ts
+++ b/package/ego-browser/src/element-resolver.ts
@@ -1,4 +1,12 @@
import { parseRef } from "./ref-map.js";
+import { HIT_TARGET_HELPERS } from "./driver/action-target.js";
+
+type ElementActionability = "pointer" | "visible";
+type PageRuntimeContext = {
+ sessionId: string;
+ frameId?: string;
+ contextId?: number;
+};
export class ElementResolutionError extends Error {
kind: "transient" | "permanent";
@@ -114,7 +122,11 @@ export async function resolveElementObjectId(
refMap,
selectorOrRef,
iframeSessions = new Map(),
- options: { strict?: boolean } = {},
+ options: {
+ strict?: boolean;
+ strictGlobal?: boolean;
+ actionability?: ElementActionability;
+ } = {},
): Promise<{ objectId: string; sessionId: string; frameId?: string }> {
const refId = parseRef(selectorOrRef);
if (refId) {
@@ -185,34 +197,43 @@ export async function resolveElementObjectId(
const locator = parseLocator(selectorOrRef);
if (locator) {
- return resolveLocatorObjectId(cdp, sessionId, locator, iframeSessions);
+ return resolveLocatorObjectId(
+ cdp,
+ sessionId,
+ locator,
+ iframeSessions,
+ options,
+ );
}
- const sessions = pageSessions(sessionId, iframeSessions);
+ const contexts = await runtimePageContexts(cdp, sessionId, iframeSessions);
if (options.strict) {
return resolveRawSelectorObjectId(
cdp,
- sessions,
+ contexts,
parseRawSelector(selectorOrRef),
+ { actionability: options.actionability },
);
}
- for (const candidateSessionId of sessions) {
- const result = await send(
+ for (const context of contexts) {
+ const result = await evaluateInContext(
cdp,
- "Runtime.evaluate",
- {
- expression: buildFindElementJs(selectorOrRef),
- returnByValue: false,
- awaitPromise: false,
- objectGroup: "ego-browser",
- },
- candidateSessionId,
+ context,
+ buildFindElementJs(selectorOrRef),
+ false,
+ "ego-browser",
);
if (result.exceptionDetails) {
throw invalidSelectorError(selectorOrRef, result);
}
const objectId = result.result?.objectId;
- if (objectId) return { objectId, sessionId: candidateSessionId };
+ if (objectId) {
+ return {
+ objectId,
+ sessionId: context.sessionId,
+ ...(context.frameId ? { frameId: context.frameId } : {}),
+ };
+ }
}
throw new ElementResolutionError(
`Element not found: ${selectorOrRef}`,
@@ -220,18 +241,23 @@ export async function resolveElementObjectId(
);
}
-async function resolveRawSelectorObjectId(cdp, sessions, selector) {
- const match = await findUniqueRawSelectorSession(cdp, sessions, selector);
- const result = await send(
+async function resolveRawSelectorObjectId(
+ cdp,
+ contexts,
+ selector,
+ { actionability = undefined }: { actionability?: ElementActionability } = {},
+) {
+ const match = await findUniqueRawSelectorContext(cdp, contexts, selector, {
+ actionability,
+ });
+ const result = await evaluateInContext(
cdp,
- "Runtime.evaluate",
- {
- expression: buildFindElementJs(selector.raw),
- returnByValue: false,
- awaitPromise: false,
- objectGroup: "ego-browser",
- },
- match.sessionId,
+ match,
+ match.actionable
+ ? `(() => ${buildActionableElementsJs(buildRawSelectorElementsJs(selector), actionability)}[0] || null)()`
+ : buildFindElementJs(selector.raw),
+ false,
+ "ego-browser",
);
if (result.exceptionDetails) {
throw invalidSelectorError(selector.raw, result);
@@ -243,27 +269,93 @@ async function resolveRawSelectorObjectId(cdp, sessions, selector) {
"transient",
);
}
- return { objectId, sessionId: match.sessionId };
+ return {
+ objectId,
+ sessionId: match.sessionId,
+ ...(match.frameId ? { frameId: match.frameId } : {}),
+ };
}
-async function findUniqueRawSelectorSession(cdp, sessions, selector) {
- const mainCount = await rawSelectorCount(cdp, sessions[0], selector);
+async function findUniqueRawSelectorContext(
+ cdp,
+ contexts,
+ selector,
+ { actionability = undefined }: { actionability?: ElementActionability } = {},
+) {
+ if (actionability) {
+ const mainCount = await rawSelectorCount(cdp, contexts[0], selector);
+ const mainActionable = mainCount
+ ? await rawSelectorActionableCount(
+ cdp,
+ contexts[0],
+ selector,
+ actionability,
+ )
+ : 0;
+ if (mainActionable === 1) {
+ return { ...contexts[0], actionable: true };
+ }
+ if (mainActionable > 1) {
+ throw await rawSelectorCountError(
+ cdp,
+ [contexts[0]],
+ selector,
+ mainCount,
+ );
+ }
+ const matches = [];
+ let totalCount = mainCount;
+ let actionableCount = 0;
+ for (const context of contexts.slice(1)) {
+ const count = await rawSelectorCount(cdp, context, selector);
+ totalCount += count;
+ if (count === 0) continue;
+ const actionable = await rawSelectorActionableCount(
+ cdp,
+ context,
+ selector,
+ actionability,
+ );
+ actionableCount += actionable;
+ if (actionable > 0) matches.push({ ...context, actionable });
+ }
+ if (totalCount === 0) {
+ throw new ElementResolutionError(
+ `Selector ${selector.raw} matched 0 elements`,
+ "transient",
+ );
+ }
+ if (actionableCount === 1) {
+ return { ...matches[0], actionable: true };
+ }
+ if (actionableCount === 0) {
+ const blocker = await firstActionabilityBlocker(
+ cdp,
+ contexts,
+ buildRawSelectorElementsJs(selector),
+ actionability,
+ );
+ throw new ElementResolutionError(
+ `Selector ${selector.raw} matched ${totalCount} elements, but none can receive input${blocker ? `; ${blocker}` : ""}`,
+ "transient",
+ );
+ }
+ throw await rawSelectorCountError(cdp, matches, selector, totalCount);
+ }
+
+ const mainCount = await rawSelectorCount(cdp, contexts[0], selector);
if (mainCount > 1) {
- throw await rawSelectorCountError(cdp, [sessions[0]], selector, mainCount);
+ throw await rawSelectorCountError(cdp, [contexts[0]], selector, mainCount);
}
- if (mainCount === 1) return { sessionId: sessions[0] };
+ if (mainCount === 1) return contexts[0];
const matches = [];
let count = 0;
- for (const candidateSessionId of sessions.slice(1)) {
- const candidateCount = await rawSelectorCount(
- cdp,
- candidateSessionId,
- selector,
- );
+ for (const context of contexts.slice(1)) {
+ const candidateCount = await rawSelectorCount(cdp, context, selector);
count += candidateCount;
if (candidateCount > 0) {
- matches.push({ count: candidateCount, sessionId: candidateSessionId });
+ matches.push({ count: candidateCount, ...context });
}
}
if (count === 0) {
@@ -273,26 +365,17 @@ async function findUniqueRawSelectorSession(cdp, sessions, selector) {
);
}
if (count > 1) {
- throw await rawSelectorCountError(
- cdp,
- matches.map((match) => match.sessionId),
- selector,
- count,
- );
+ throw await rawSelectorCountError(cdp, matches, selector, count);
}
return matches[0];
}
-async function rawSelectorCount(cdp, sessionId, selector) {
- const result = await send(
+async function rawSelectorCount(cdp, context, selector) {
+ const result = await evaluateInContext(
cdp,
- "Runtime.evaluate",
- {
- expression: buildRawSelectorCountJs(selector),
- returnByValue: true,
- awaitPromise: false,
- },
- sessionId,
+ context,
+ buildRawSelectorCountJs(selector),
+ true,
);
if (result.exceptionDetails) {
throw invalidSelectorError(selector.raw, result);
@@ -300,12 +383,30 @@ async function rawSelectorCount(cdp, sessionId, selector) {
return Number(result.result?.value || 0);
}
-async function rawSelectorCountError(cdp, sessions, selector, count) {
+async function rawSelectorActionableCount(
+ cdp,
+ context,
+ selector,
+ actionability: ElementActionability,
+) {
+ const result = await evaluateInContext(
+ cdp,
+ context,
+ `(() => ${buildActionableElementsJs(buildRawSelectorElementsJs(selector), actionability)}.length)()`,
+ true,
+ );
+ if (result.exceptionDetails) {
+ throw invalidSelectorError(selector.raw, result);
+ }
+ return Number(result.result?.value || 0);
+}
+
+async function rawSelectorCountError(cdp, contexts, selector, count) {
return ambiguityError(
`Selector ${selector.raw} matched ${count} elements`,
await collectMatchDiagnostics(
cdp,
- sessions,
+ contexts,
buildRawSelectorElementsJs(selector),
),
);
@@ -357,6 +458,63 @@ function pageContexts(sessionId, iframeSessions) {
return contexts;
}
+async function runtimePageContexts(
+ cdp,
+ sessionId,
+ iframeSessions,
+): Promise<PageRuntimeContext[]> {
+ const contexts = pageContexts(sessionId, iframeSessions);
+ return Promise.all(
+ contexts.map(async (context) => {
+ if (!context.frameId) return context;
+ try {
+ const result = await send(
+ cdp,
+ "Page.createIsolatedWorld",
+ {
+ frameId: context.frameId,
+ worldName: "ego-browser-locator",
+ grantUniveralAccess: true,
+ },
+ context.sessionId,
+ );
+ if (!Number.isInteger(result?.executionContextId)) {
+ throw new Error("Page.createIsolatedWorld returned no context id");
+ }
+ return { ...context, contextId: result.executionContextId };
+ } catch (error) {
+ throw new ElementResolutionError(
+ `Frame ${context.frameId} is not ready: ${error?.message || String(error)}`,
+ "transient",
+ );
+ }
+ }),
+ );
+}
+
+function evaluateInContext(
+ cdp,
+ context: PageRuntimeContext,
+ expression: string,
+ returnByValue: boolean,
+ objectGroup?: string,
+) {
+ return send(
+ cdp,
+ "Runtime.evaluate",
+ {
+ expression,
+ returnByValue,
+ awaitPromise: false,
+ ...(context.contextId !== undefined
+ ? { contextId: context.contextId }
+ : {}),
+ ...(objectGroup ? { objectGroup } : {}),
+ },
+ context.sessionId,
+ );
+}
+
async function resolveLocatorCenter(cdp, sessionId, locator, iframeSessions) {
const sessions = pageSessions(sessionId, iframeSessions);
if (locator.kind === "role") {
@@ -378,16 +536,18 @@ async function resolveLocatorCenter(cdp, sessionId, locator, iframeSessions) {
const match =
sessions.length === 1
? { sessionId: sessions[0] }
- : await findUniqueLocatorSession(cdp, sessions, locator);
- const result = await send(
+ : await findUniqueLocatorContext(
+ cdp,
+ sessions.map((candidateSessionId) => ({
+ sessionId: candidateSessionId,
+ })),
+ locator,
+ );
+ const result = await evaluateInContext(
cdp,
- "Runtime.evaluate",
- {
- expression: buildLocatorCenterJs(locator),
- returnByValue: true,
- awaitPromise: false,
- },
- match.sessionId,
+ match,
+ buildLocatorCenterJs(locator),
+ true,
);
if (result.exceptionDetails) {
throw new ElementResolutionError(
@@ -401,7 +561,7 @@ async function resolveLocatorCenter(cdp, sessionId, locator, iframeSessions) {
if (kind === "permanent") {
throw await locatorCountError(
cdp,
- [match.sessionId],
+ [match],
locator,
matchCount(value.error),
);
@@ -417,8 +577,16 @@ async function resolveLocatorCenter(cdp, sessionId, locator, iframeSessions) {
return { x: value.x, y: value.y, sessionId: match.sessionId };
}
-async function resolveLocatorObjectId(cdp, sessionId, locator, iframeSessions) {
- const sessions = pageSessions(sessionId, iframeSessions);
+async function resolveLocatorObjectId(
+ cdp,
+ sessionId,
+ locator,
+ iframeSessions,
+ options: {
+ strictGlobal?: boolean;
+ actionability?: ElementActionability;
+ } = {},
+) {
if (locator.kind === "role") {
const match = await findUniqueRoleMatch(
cdp,
@@ -426,6 +594,10 @@ async function resolveLocatorObjectId(cdp, sessionId, locator, iframeSessions) {
locator.role,
locator.name,
locator.raw,
+ {
+ strictGlobal: options.strictGlobal,
+ actionability: options.actionability,
+ },
);
const result = await send(
cdp,
@@ -449,17 +621,19 @@ async function resolveLocatorObjectId(cdp, sessionId, locator, iframeSessions) {
...(match.frameId ? { frameId: match.frameId } : {}),
};
}
- const match = await findUniqueLocatorSession(cdp, sessions, locator);
- const result = await send(
+ const contexts = await runtimePageContexts(cdp, sessionId, iframeSessions);
+ const match = await findUniqueLocatorContext(cdp, contexts, locator, {
+ strictGlobal: options.strictGlobal,
+ actionability: options.actionability,
+ });
+ const result = await evaluateInContext(
cdp,
- "Runtime.evaluate",
- {
- expression: buildLocatorFindJs(locator),
- returnByValue: false,
- awaitPromise: false,
- objectGroup: "ego-browser",
- },
- match.sessionId,
+ match,
+ match.actionable
+ ? buildLocatorActionableFindJs(locator, options.actionability)
+ : buildLocatorFindJs(locator),
+ false,
+ "ego-browser",
);
const objectId = result.result?.objectId;
if (!objectId) {
@@ -468,23 +642,101 @@ async function resolveLocatorObjectId(cdp, sessionId, locator, iframeSessions) {
"transient",
);
}
- return { objectId, sessionId: match.sessionId };
+ return {
+ objectId,
+ sessionId: match.sessionId,
+ ...(match.frameId ? { frameId: match.frameId } : {}),
+ };
}
-async function findUniqueLocatorSession(cdp, sessions, locator) {
+async function findUniqueLocatorContext(
+ cdp,
+ contexts,
+ locator,
+ {
+ strictGlobal = false,
+ actionability = undefined,
+ }: {
+ strictGlobal?: boolean;
+ actionability?: ElementActionability;
+ } = {},
+) {
+ if (actionability) {
+ const mainCount = await locatorCount(cdp, contexts[0], locator);
+ const mainActionable = mainCount
+ ? await locatorActionableCount(cdp, contexts[0], locator, actionability)
+ : 0;
+ if (mainActionable === 1) {
+ return { count: 1, ...contexts[0], actionable: true };
+ }
+ if (mainActionable > 1) {
+ throw await locatorCountError(cdp, [contexts[0]], locator, mainCount);
+ }
+ const matches = [];
+ let totalCount = mainCount;
+ let actionableCount = 0;
+ for (const context of contexts.slice(1)) {
+ const count = await locatorCount(cdp, context, locator);
+ totalCount += count;
+ if (count === 0) continue;
+ const actionable = await locatorActionableCount(
+ cdp,
+ context,
+ locator,
+ actionability,
+ );
+ actionableCount += actionable;
+ if (actionable > 0) {
+ matches.push({
+ count,
+ actionable,
+ ...context,
+ });
+ }
+ }
+ if (totalCount === 0) {
+ throw new ElementResolutionError(
+ `Locator ${locator.raw} matched 0 elements`,
+ "transient",
+ );
+ }
+ if (actionableCount === 1) {
+ return { ...matches[0], count: 1, actionable: true };
+ }
+ if (actionableCount === 0) {
+ const blocker = await firstActionabilityBlocker(
+ cdp,
+ contexts,
+ buildLocatorElementsJs(locator),
+ actionability,
+ );
+ throw new ElementResolutionError(
+ `Locator ${locator.raw} matched ${totalCount} elements, but none can receive input${blocker ? `; ${blocker}` : ""}`,
+ "transient",
+ );
+ }
+ throw await locatorCountError(cdp, matches, locator, totalCount);
+ }
+
const matches = [];
let count = 0;
- const mainCount = await locatorCount(cdp, sessions[0], locator);
- if (mainCount > 1) {
- throw await locatorCountError(cdp, [sessions[0]], locator, mainCount);
+ const mainCount = await locatorCount(cdp, contexts[0], locator);
+ if (mainCount > 1 && !strictGlobal) {
+ throw await locatorCountError(cdp, [contexts[0]], locator, mainCount);
+ }
+ if (mainCount === 1 && !strictGlobal) {
+ return { count: 1, ...contexts[0] };
+ }
+ count += mainCount;
+ if (mainCount > 0) {
+ matches.push({ count: mainCount, ...contexts[0] });
}
- if (mainCount === 1) return { count: 1, sessionId: sessions[0] };
- for (const candidateSessionId of sessions.slice(1)) {
- const candidateCount = await locatorCount(cdp, candidateSessionId, locator);
+ for (const context of contexts.slice(1)) {
+ const candidateCount = await locatorCount(cdp, context, locator);
count += candidateCount;
if (candidateCount > 0) {
- matches.push({ count: candidateCount, sessionId: candidateSessionId });
+ matches.push({ count: candidateCount, ...context });
}
}
if (count === 0) {
@@ -494,17 +746,25 @@ async function findUniqueLocatorSession(cdp, sessions, locator) {
);
}
if (count > 1) {
- throw await locatorCountError(
- cdp,
- matches.map((match) => match.sessionId),
- locator,
- count,
- );
+ throw await locatorCountError(cdp, matches, locator, count);
}
return matches[0];
}
-async function findUniqueRoleMatch(cdp, contexts, role, name, raw) {
+async function findUniqueRoleMatch(
+ cdp,
+ contexts,
+ role,
+ name,
+ raw,
+ {
+ strictGlobal = false,
+ actionability = undefined,
+ }: {
+ strictGlobal?: boolean;
+ actionability?: ElementActionability;
+ } = {},
+) {
const matchesIn = async (selectedContexts) => {
const matches = [];
for (const context of selectedContexts) {
@@ -517,7 +777,7 @@ async function findUniqueRoleMatch(cdp, contexts, role, name, raw) {
for (const node of result.nodes || []) {
if (
!node.ignored &&
- extractAxString(node.role) === role &&
+ normalizeRole(extractAxString(node.role)) === normalizeRole(role) &&
extractAxString(node.name) === name &&
node.backendDOMNodeId !== undefined &&
node.backendDOMNodeId !== null
@@ -533,33 +793,195 @@ async function findUniqueRoleMatch(cdp, contexts, role, name, raw) {
return matches;
};
- // Preserve Page locator behavior: a top-level match wins. Only fall back to
- // frames when the Page document has no match at all.
- const mainMatches = await matchesIn(contexts.slice(0, 1));
- const matches =
- mainMatches.length > 0 ? mainMatches : await matchesIn(contexts.slice(1));
- if (matches.length === 0) {
+ const rawMainMatches = await matchesIn(contexts.slice(0, 1));
+ let cachedFrameMatches;
+ const matchesWithFrameProvenance = async () => {
+ cachedFrameMatches ||= matchesIn(contexts.slice(1));
+ const frames = await cachedFrameMatches;
+ const framedNodeKeys = new Set(
+ frames
+ .filter((match) => match.frameId)
+ .map((match) => `${match.sessionId}\u0000${match.backendNodeId}`),
+ );
+ const main = rawMainMatches.filter(
+ (match) =>
+ !framedNodeKeys.has(`${match.sessionId}\u0000${match.backendNodeId}`),
+ );
+ return { main, frames };
+ };
+ if (strictGlobal) {
+ const { main, frames } = await matchesWithFrameProvenance();
+ const matches = [...main, ...frames];
+ if (matches.length === 0) {
+ throw new ElementResolutionError(
+ `Locator ${raw} matched 0 elements`,
+ "transient",
+ );
+ }
+ if (matches.length === 1) return matches[0];
+ throw ambiguityError(`Locator ${raw} matched ${matches.length} elements`);
+ }
+
+ if (!actionability) {
+ const matches =
+ rawMainMatches.length > 0
+ ? rawMainMatches
+ : (await matchesWithFrameProvenance()).frames;
+ if (matches.length === 0) {
+ throw new ElementResolutionError(
+ `Locator ${raw} matched 0 elements`,
+ "transient",
+ );
+ }
+ if (matches.length === 1) return matches[0];
+ throw ambiguityError(`Locator ${raw} matched ${matches.length} elements`);
+ }
+
+ const classify = async (matches) => {
+ const actionable = [];
+ let blocker;
+ for (const match of matches) {
+ const result = await roleMatchActionability(cdp, match, actionability);
+ if (result.actionable) actionable.push(match);
+ else blocker ||= result.blocker;
+ }
+ return { actionable, blocker };
+ };
+ const provenance = await matchesWithFrameProvenance();
+ const mainMatches = provenance.main;
+ const main = await classify(mainMatches);
+ if (main.actionable.length === 1) return main.actionable[0];
+ if (main.actionable.length > 1) {
+ throw ambiguityError(
+ `Locator ${raw} matched ${mainMatches.length} elements`,
+ );
+ }
+
+ const frames = provenance.frames;
+ const frame = await classify(frames);
+ const total = mainMatches.length + frames.length;
+ if (total === 0) {
throw new ElementResolutionError(
`Locator ${raw} matched 0 elements`,
"transient",
);
}
- if (matches.length > 1) {
- throw ambiguityError(`Locator ${raw} matched ${matches.length} elements`);
+ if (frame.actionable.length === 1) return frame.actionable[0];
+ if (frame.actionable.length === 0) {
+ const blocker = main.blocker || frame.blocker;
+ throw new ElementResolutionError(
+ `Locator ${raw} matched ${total} elements, but none can receive input${blocker ? `; ${blocker}` : ""}`,
+ "transient",
+ );
}
- return matches[0];
+ throw ambiguityError(`Locator ${raw} matched ${total} elements`);
}
-async function locatorCount(cdp, sessionId, locator) {
- const result = await send(
+/** Classify one AX match with the same rules used for DOM selectors. */
+async function roleMatchActionability(
+ cdp,
+ match,
+ actionability: ElementActionability,
+): Promise<{ actionable: boolean; blocker?: string }> {
+ let objectId;
+ try {
+ const resolved = await send(
+ cdp,
+ "DOM.resolveNode",
+ {
+ backendNodeId: match.backendNodeId,
+ objectGroup: "ego-browser",
+ },
+ match.sessionId,
+ );
+ objectId = resolved.object?.objectId;
+ if (!objectId) return { actionable: false };
+ const result = await send(
+ cdp,
+ "Runtime.callFunctionOn",
+ {
+ functionDeclaration: `function() {
+ ${actionability === "pointer" ? HIT_TARGET_HELPERS : ""}
+ if (!this.isConnected) return { actionable: false };
+ const rect = this.getBoundingClientRect();
+ const view = this.ownerDocument?.defaultView;
+ if (!view || rect.width <= 0 || rect.height <= 0) return { actionable: false };
+ 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";
+ if (!visible) return { actionable: false };
+ if (${JSON.stringify(actionability)} === "pointer") {
+ 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;
+ if (!offscreen) {
+ const interceptor = interceptingElementAtPoint(this, point);
+ if (interceptor) {
+ return {
+ actionable: false,
+ blocker: describeHitTarget(interceptor) + " intercepts pointer events"
+ };
+ }
+ }
+ }
+ return { actionable: true };
+ }`,
+ objectId,
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ match.sessionId,
+ );
+ const value = result.result?.value;
+ if (typeof value === "boolean") return { actionable: value };
+ return {
+ actionable: value?.actionable === true,
+ ...(typeof value?.blocker === "string" ? { blocker: value.blocker } : {}),
+ };
+ } catch {
+ return { actionable: false };
+ } finally {
+ if (objectId) {
+ await send(
+ cdp,
+ "Runtime.releaseObject",
+ { objectId },
+ match.sessionId,
+ ).catch(() => {});
+ }
+ }
+}
+
+async function locatorCount(cdp, context, locator) {
+ const result = await evaluateInContext(
cdp,
- "Runtime.evaluate",
- {
- expression: buildLocatorCountJs(locator),
- returnByValue: true,
- awaitPromise: false,
- },
- sessionId,
+ context,
+ buildLocatorCountJs(locator),
+ true,
+ );
+ if (result.exceptionDetails) {
+ throw new ElementResolutionError(
+ `Invalid selector: ${locator.raw}: ${exceptionText(result)}`,
+ "permanent",
+ );
+ }
+ return Number(result.result?.value || 0);
+}
+
+async function locatorActionableCount(
+ cdp,
+ context,
+ locator,
+ actionability: ElementActionability,
+) {
+ const result = await evaluateInContext(
+ cdp,
+ context,
+ buildLocatorActionableCountJs(locator, actionability),
+ true,
);
if (result.exceptionDetails) {
throw new ElementResolutionError(
@@ -570,7 +992,7 @@ async function locatorCount(cdp, sessionId, locator) {
return Number(result.result?.value || 0);
}
-async function locatorCountError(cdp, sessions, locator, count) {
+async function locatorCountError(cdp, contexts, locator, count) {
if (locator.kind === "role") {
return ambiguityError(`Locator ${locator.raw} matched ${count} elements`);
}
@@ -578,7 +1000,7 @@ async function locatorCountError(cdp, sessions, locator, count) {
`Locator ${locator.raw} matched ${count} elements`,
await collectMatchDiagnostics(
cdp,
- sessions,
+ contexts,
buildLocatorElementsJs(locator),
),
);
@@ -589,7 +1011,7 @@ function matchCount(message) {
return match ? Number(match[1]) : 0;
}
-async function collectMatchDiagnostics(cdp, sessions, elementsExpression) {
+async function collectMatchDiagnostics(cdp, contexts, elementsExpression) {
const combined: {
visible: number;
hidden: number;
@@ -602,16 +1024,12 @@ async function collectMatchDiagnostics(cdp, sessions, elementsExpression) {
}>;
} = { visible: 0, hidden: 0, candidates: [] };
try {
- for (const sessionId of sessions) {
- const result = await send(
+ for (const context of contexts) {
+ const result = await evaluateInContext(
cdp,
- "Runtime.evaluate",
- {
- expression: buildMatchDiagnosticsJs(elementsExpression),
- returnByValue: true,
- awaitPromise: false,
- },
- sessionId,
+ context,
+ buildMatchDiagnosticsJs(elementsExpression),
+ true,
);
const value = result.result?.value;
if (
@@ -687,7 +1105,7 @@ async function findBackendNodeIdByRoleName(
continue;
}
if (
- extractAxString(node.role) !== role ||
+ normalizeRole(extractAxString(node.role)) !== normalizeRole(role) ||
extractAxString(node.name) !== name
) {
continue;
@@ -720,7 +1138,7 @@ async function findUniqueBackendNodeIdByRoleName(cdp, sessionId, role, name) {
continue;
}
if (
- extractAxString(node.role) === role &&
+ normalizeRole(extractAxString(node.role)) === normalizeRole(role) &&
extractAxString(node.name) === name
) {
matches.push(node);
@@ -803,6 +1221,91 @@ function buildLocatorFindJs(locator) {
return `(() => ${hrefElementsJs(locator.href)}[0] || null)()`;
}
+function buildLocatorActionableFindJs(
+ locator,
+ actionability: ElementActionability,
+) {
+ return `(() => ${buildActionableElementsJs(buildLocatorElementsJs(locator), actionability)}[0] || null)()`;
+}
+
+function buildLocatorActionableCountJs(
+ locator,
+ actionability: ElementActionability,
+) {
+ return `(() => ${buildActionableElementsJs(buildLocatorElementsJs(locator), actionability)}.length)()`;
+}
+
+function buildActionableElementsJs(
+ elementsExpression,
+ actionability: ElementActionability,
+) {
+ return `(() => {
+ ${actionability === "pointer" ? HIT_TARGET_HELPERS : ""}
+ const __egoActionableMatches = Array.from(${elementsExpression} || []).filter((element) => {
+ if (!element?.isConnected || element.closest?.("[hidden], [inert]")) return false;
+ const view = element.ownerDocument?.defaultView;
+ if (!view) return false;
+ const rect = element.getBoundingClientRect();
+ 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";
+ if (!visible) return false;
+ if (${JSON.stringify(actionability)} !== "pointer") 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;
+ return offscreen || !interceptingElementAtPoint(element, point);
+ });
+ return __egoActionableMatches;
+ })()`;
+}
+
+async function firstActionabilityBlocker(
+ cdp,
+ contexts,
+ 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}
+ 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;
+ 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;
+ const interceptor = interceptingElementAtPoint(element, point);
+ if (interceptor) {
+ return describeHitTarget(interceptor) + " intercepts pointer events";
+ }
+ }
+ return null;
+ })()`,
+ true,
+ );
+ if (typeof result.result?.value === "string") return result.result.value;
+ } catch {
+ // Keep the original actionability error when diagnostics fail.
+ }
+ }
+ return undefined;
+}
+
function buildLocatorCountJs(locator) {
if (locator.kind === "css") {
return buildCssCountJs(locator.selector);
@@ -1052,7 +1555,7 @@ function parseLocator(input) {
if (roleMatch) {
return {
kind: "role",
- role: roleMatch[1],
+ role: normalizeRole(roleMatch[1]),
name: parseLocatorName(roleMatch[2]),
raw: value,
};
@@ -1081,6 +1584,16 @@ function normalizeText(value) {
.trim();
}
+function normalizeRole(value) {
+ const role = String(value || "").toLowerCase();
+ return (
+ {
+ listboxoption: "option",
+ textfield: "textbox",
+ }[role] || role
+ );
+}
+
function boxModelCenter(model: any = {}) {
const content = model.content || [];
if (content.length < 8) {
diff --git a/package/ego-browser/src/helpers.test.mjs b/package/ego-browser/src/helpers.test.mjs
index 698d698..1f5df5e 100644
--- a/package/ego-browser/src/helpers.test.mjs
+++ b/package/ego-browser/src/helpers.test.mjs
@@ -194,8 +194,8 @@ test("taskSpace returns the new object model for a resolved space", async () =>
assert.equal(task.spaceId, 7);
assert.equal(task.name, "Research");
assert.equal(task.ownership, "agent");
- assert.equal(typeof task.openPage, "function");
- assert.equal(task.newPage, undefined);
+ assert.equal(typeof task.newPage, "function");
+ assert.equal(task.openPage, undefined);
assert.equal(typeof task.page, "function");
assert.equal(typeof task.pages, "function");
assert.equal(typeof task.tabs, "function");
@@ -598,7 +598,7 @@ test("claimTaskSpace returns a TaskSpace after claiming and selecting", async ()
ownership: "agent",
});
assert.equal(task.spaceId, 7);
- assert.equal(typeof task.openPage, "function");
+ assert.equal(typeof task.newPage, "function");
},
);
assert.deepEqual(calls, [
@@ -642,7 +642,7 @@ test("takeOverTaskSpace returns a TaskSpace when a space is specified", async ()
const task = await takeOverTaskSpace(7);
assert.equal(task.spaceId, 7);
assert.equal(task.ownership, "agent");
- assert.equal(typeof task.openPage, "function");
+ assert.equal(typeof task.newPage, "function");
},
);
assert.deepEqual(calls, [
diff --git a/package/ego-browser/src/page-actions.test.mjs b/package/ego-browser/src/page-actions.test.mjs
index cf856c7..94a201f 100644
--- a/package/ego-browser/src/page-actions.test.mjs
+++ b/package/ego-browser/src/page-actions.test.mjs
@@ -26,6 +26,9 @@ test("Page click translates same-process iframe coordinates to the Page viewport
return { object: { objectId: "iframe-button" } };
}
if (method === "Runtime.callFunctionOn") {
+ if (params.functionDeclaration.includes("actionable: false")) {
+ return { result: { value: { actionable: true } } };
+ }
return params.functionDeclaration.includes("getBoundingClientRect")
? { result: { value: { x: 10, y: 20 } } }
: { result: { value: { ok: true } } };
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 9d11ac4..322fbba 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -1,6 +1,6 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { mkdtemp, rm } from "node:fs/promises";
+import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -43,9 +43,12 @@ function createFixture(rootDir) {
let interceptedClickPointsRemaining = 0;
let fillElementKind = "input";
let fillText = "";
+ let fillTransform = null;
+ let fillInsertionCount = 0;
let ignoredFillInsertionsRemaining = 0;
let focusResult = { focused: true };
let unsafeFillActivationTarget = null;
+ let selectedValues = [];
let navigateOnNextClickUrl = null;
let elementPresent = true;
let elementVisible = true;
@@ -121,6 +124,16 @@ function createFixture(rootDir) {
if (method === "Runtime.evaluate") {
const targetId = targetForSession(sessionId);
const tab = tabs.get(targetId);
+ if (params.expression.includes("__egoActionableMatches")) {
+ return params.returnByValue === false
+ ? {
+ result: {
+ type: "object",
+ objectId: elementVisible ? `element:${targetId}` : undefined,
+ },
+ }
+ : { result: { type: "number", value: elementVisible ? 1 : 0 } };
+ }
if (params.expression.includes("__egoWaitForFunction")) {
return {
result: {
@@ -284,20 +297,24 @@ function createFixture(rootDir) {
status: "needsinput",
kind: fillElementKind,
cursorPoint: { x: 40, y: 60 },
+ before: fillText,
},
},
};
}
- if (params.functionDeclaration.includes("verifyFilledValue")) {
- const expected = params.arguments?.[0]?.value ?? "";
- const clearFirst = params.arguments?.[1]?.value ?? true;
+ if (params.functionDeclaration.includes("selectOptionsForAction")) {
+ selectedValues = [...(params.arguments?.[0]?.value ?? [])];
+ return {
+ result: { type: "object", value: { selected: selectedValues } },
+ };
+ }
+ if (params.functionDeclaration.includes("readFilledValue")) {
return {
result: {
type: "object",
value: {
- matches: clearFirst
- ? fillText === expected
- : fillText.includes(expected),
+ actual: fillText,
+ type: fillElementKind === "input" ? "text" : "",
},
},
};
@@ -317,6 +334,8 @@ function createFixture(rootDir) {
};
}
if (params.functionDeclaration.includes("window.fetch")) {
+ const binary =
+ params.arguments?.[0]?.value?.responseType === "base64";
return {
result: {
type: "object",
@@ -329,7 +348,12 @@ function createFixture(rootDir) {
"content-type": "text/plain",
"x-fixture": "page-fetch",
},
- body: "short and stout",
+ ...(binary
+ ? {
+ bodyBase64:
+ Buffer.from("\x89PNG\r\n\x1a\n").toString("base64"),
+ }
+ : { body: "short and stout" }),
},
},
};
@@ -395,7 +419,10 @@ function createFixture(rootDir) {
if (ignoredFillInsertionsRemaining > 0) {
ignoredFillInsertionsRemaining -= 1;
} else {
- fillText = params.text;
+ fillInsertionCount += 1;
+ fillText = fillTransform
+ ? fillTransform(params.text, fillText, fillInsertionCount)
+ : params.text;
}
return {};
}
@@ -605,9 +632,16 @@ function createFixture(rootDir) {
navigateOnNextClick(url) {
navigateOnNextClickUrl = url;
},
- configureFill({ kind = "input", initialText = "", ignoreInsertions = 0 }) {
+ configureFill({
+ kind = "input",
+ initialText = "",
+ ignoreInsertions = 0,
+ transform = null,
+ }) {
fillElementKind = kind;
fillText = initialText;
+ fillTransform = transform;
+ fillInsertionCount = 0;
ignoredFillInsertionsRemaining = ignoreInsertions;
},
configureFocusResult(result) {
@@ -637,6 +671,9 @@ function createFixture(rootDir) {
setSession(targetId, sessionId) {
sessionOverrides.set(targetId, sessionId);
},
+ selectedValues() {
+ return [...selectedValues];
+ },
emitPageEvent(targetId, method, params = {}) {
const sessionId = `session:${targetId}`;
const events = pageEvents.get(sessionId) || [];
@@ -662,6 +699,12 @@ function taskForRound(fixture, roundId, overrides = {}) {
);
}
+async function openTestPage(task, url, gotoOptions = {}) {
+ const page = await task.newPage();
+ await page.goto(url, gotoOptions);
+ return page;
+}
+
async function waitForLedgerTarget(ledger, spaceId, targetId) {
for (let attempt = 0; attempt < 50; attempt += 1) {
const entry = Object.entries((await ledger.read(spaceId)).pages).find(
@@ -681,7 +724,7 @@ test("background discovery does not adopt the pre-existing tab baseline", async
const task = taskForRound(fixture, "round-a", { ledger });
await initializeTaskSpaceHandle(task);
- const page = await task.openPage("https://example.test/managed");
+ const page = await openTestPage(task, "https://example.test/managed");
assert.equal(page.label, "p1");
assert.deepEqual((await ledger.read(7)).unmanagedTargets, {
@@ -697,7 +740,7 @@ test("background target discovery adopts a delayed popup and reports its opener"
const ledger = new PageLedgerStore({ rootDir: fixture.rootDir });
const task = taskForRound(fixture, "round-a", { ledger });
await initializeTaskSpaceHandle(task);
- const source = await task.openPage("https://example.test/source");
+ const source = await openTestPage(task, "https://example.test/source");
fixture.addExternalTab("target-delayed", "https://example.test/delayed", {
openerId: source.targetId,
});
@@ -731,7 +774,7 @@ test("using a delayed popup suppresses its notice before round output", async ()
const ledger = new PageLedgerStore({ rootDir: fixture.rootDir });
const task = taskForRound(fixture, "round-a", { ledger });
await initializeTaskSpaceHandle(task);
- const source = await task.openPage("https://example.test/source");
+ const source = await openTestPage(task, "https://example.test/source");
fixture.addExternalTab("target-delayed", "https://example.test/delayed", {
openerId: source.targetId,
});
@@ -757,7 +800,7 @@ test("tab reconciliation reports a late page without requiring an explicit wait"
await withFixture(async (fixture) => {
resetPageNotices();
const task = taskForRound(fixture, "round-a");
- const source = await task.openPage("https://example.test/source");
+ const source = await openTestPage(task, "https://example.test/source");
fixture.addExternalTab("target-delayed", "https://example.test/delayed", {
openerId: source.targetId,
});
@@ -847,7 +890,8 @@ test("Page.waitForTimeout validates and waits in milliseconds without activating
waits.push(ms);
},
});
- const page = await task.openPage("https://example.test/timer");
+ const page = await openTestPage(task, "https://example.test/timer");
+ waits.length = 0;
fixture.calls.length = 0;
await page.waitForTimeout(125);
@@ -868,8 +912,8 @@ test("Page.waitForTimeout validates and waits in milliseconds without activating
test("Page.waitForFunction polls one Page with one JSON argument", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.openPage("https://example.test/first");
- const second = await task.openPage("https://example.test/second");
+ const first = await openTestPage(task, "https://example.test/first");
+ const second = await openTestPage(task, "https://example.test/second");
fixture.setWaitFunctionResults([false, false, true]);
fixture.calls.length = 0;
@@ -907,7 +951,7 @@ test("Page.waitForFunction polls one Page with one JSON argument", async () => {
test("Page.waitForFunction validates input and reports its timeout", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
await assert.rejects(
() =>
@@ -939,7 +983,7 @@ test("Page.waitForFunction validates input and reports its timeout", async () =>
test("Page.evaluate explains that its callback cannot capture Node variables", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
await assert.rejects(
() => page.evaluate(() => missingClosureForE2E),
@@ -963,12 +1007,12 @@ test("v2 methods reject option fields that are absent from the public schema", a
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
await assert.rejects(
- () => task.openPage("https://example.test/unknown", { reuse: true }),
- /task\.openPage received unknown option: reuse/,
+ () => task.newPage({ reuse: true }),
+ /task\.newPage does not accept arguments/,
);
assert.equal(fixture.tabs.size, 0, "validation runs before creating a tab");
- const page = await task.openPage("https://example.test/options");
+ const page = await openTestPage(task, "https://example.test/options");
await assert.rejects(
() => page.click("button", { trial: true }),
/page\.click received unknown option: trial/,
@@ -999,7 +1043,7 @@ test("TaskSpace uses spaceId and owns handoff, finish, and close", async () => {
await task.handOff();
const finishTask = taskForRound(fixture, "round-b", services);
- await finishTask.openPage("https://example.test/managed");
+ await finishTask.newPage();
await finishTask.finish();
assert.deepEqual((await ledger.read(7)).pages, {});
@@ -1024,7 +1068,10 @@ test("handoff preserves user-created tabs as unknown and captures the active use
const firstRound = taskForRound(fixture, "round-a", {
async handOffTaskSpace() {},
});
- const agentPage = await firstRound.openPage("https://example.test/agent");
+ const agentPage = await openTestPage(
+ firstRound,
+ "https://example.test/agent",
+ );
await firstRound.handOff();
assert.equal(agentPage.label, "p1");
fixture.addExternalTab("target-user", "https://example.test/user-created", {
@@ -1061,7 +1108,7 @@ test("failed native handoff removes the pending user-control boundary", async ()
throw new Error("native handoff failed");
},
});
- await task.openPage("https://example.test/agent");
+ await openTestPage(task, "https://example.test/agent");
await assert.rejects(() => task.handOff(), /native handoff failed/);
assert.equal((await ledger.read(7)).userControlPending, false);
@@ -1077,7 +1124,7 @@ test("TaskSpace keeps Page state when native finish fails", async () => {
throw new Error("native finish failed");
},
});
- await task.openPage("https://example.test/managed");
+ await openTestPage(task, "https://example.test/managed");
await assert.rejects(() => task.finish(), /native finish failed/);
@@ -1090,7 +1137,10 @@ test("TaskSpace keeps Page state when native finish fails", async () => {
test("a page label restores in a new round and goto reuses its target", async () => {
await withFixture(async (fixture) => {
const firstRound = taskForRound(fixture, "round-a");
- const created = await firstRound.openPage("https://example.test/first");
+ const created = await openTestPage(
+ firstRound,
+ "https://example.test/first",
+ );
assert.equal(created.label, "p1");
assert.equal(created.spaceId, 7);
@@ -1119,11 +1169,12 @@ test("a page label restores in a new round and goto reuses its target", async ()
test("Page.goto accepts Playwright-style navigation options", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
fixture.setDocumentLifecycle({
readyState: "interactive",
domContentLoaded: true,
});
+ fixture.calls.length = 0;
await page.goto("https://example.test/second", {
referer: "https://example.test/source",
@@ -1179,7 +1230,9 @@ test("Page.goto commit waits for this navigation without waiting for the DOM", a
committed = true;
},
});
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
+ commitChecks = 0;
+ committed = false;
fixture.setDocumentLifecycle({
readyState: "loading",
domContentLoaded: false,
@@ -1207,7 +1260,7 @@ test("Page.goto commit waits for this navigation without waiting for the DOM", a
test("Page.goto starts network tracking before a network-idle navigation", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
const callsBeforeGoto = fixture.calls.length;
await page.goto("https://example.test/second", {
@@ -1228,63 +1281,26 @@ test("Page.goto starts network tracking before a network-idle navigation", async
});
});
-test("openPage waits for the document created by this call, not an already-complete placeholder", async () => {
+test("newPage creates a managed blank Page and leaves navigation to goto", async () => {
await withFixture(async (fixture) => {
const requestedUrl = "https://example.test/created-document";
- const baseCreateTab = fixture.services.createTab;
- const baseCdp = fixture.services.cdp;
- let now = 10_000;
- let targetId;
- let sleepCount = 0;
+ const task = taskForRound(fixture, "round-a");
- const task = taskForRound(fixture, "round-a", {
- async createTab(url) {
- targetId = await baseCreateTab(url);
- fixture.tabs.get(targetId).url = "chrome://newtab/";
- return targetId;
- },
- async cdp(method, params, sessionId, timeoutMs) {
- if (method === "Runtime.evaluate") {
- if (params.expression === "document.readyState") {
- return { result: { type: "string", value: "complete" } };
- }
- if (params.expression.includes("performance.timeOrigin")) {
- const tab = fixture.tabs.get(targetId);
- return {
- result: {
- type: "object",
- value: {
- readyState: "complete",
- url: tab.url,
- timeOrigin: tab.url === requestedUrl ? now : now - 5_000,
- },
- },
- };
- }
- }
- return baseCdp(method, params, sessionId, timeoutMs);
- },
- now: () => now,
- async sleep(ms) {
- sleepCount += 1;
- now += ms;
- fixture.tabs.get(targetId).url = requestedUrl;
- },
- });
+ const page = await task.newPage();
- const page = await task.openPage(requestedUrl);
+ assert.equal(fixture.tabs.get(page.targetId).url, "about:blank");
+ assert.equal(page.label, "p1");
- assert.equal(page.targetId, targetId);
- assert.equal(sleepCount, 1);
- assert.equal(fixture.tabs.get(targetId).url, requestedUrl);
+ await page.goto(requestedUrl);
+ assert.equal(fixture.tabs.get(page.targetId).url, requestedUrl);
});
});
test("snapshot activates the addressed page, not whichever tab was current", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.openPage("https://example.test/first");
- await task.openPage("https://example.test/second");
+ const first = await openTestPage(task, "https://example.test/first");
+ await openTestPage(task, "https://example.test/second");
assert.equal(fixture.activeTarget(), "target-2");
assert.match(
@@ -1298,7 +1314,7 @@ test("snapshot activates the addressed page, not whichever tab was current", asy
test("snapshot defaults to the viewport, reports its source, and validates options", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/before");
+ const page = await openTestPage(task, "https://example.test/before");
assert.match(
await page.snapshot(),
@@ -1327,8 +1343,8 @@ test("snapshot defaults to the viewport, reports its source, and validates optio
test("metadata reads stay target-scoped while evaluate and screenshot activate their Page", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.openPage("https://example.test/first");
- await task.openPage("https://example.test/second");
+ const first = await openTestPage(task, "https://example.test/first");
+ await openTestPage(task, "https://example.test/second");
assert.equal(fixture.activeTarget(), "target-2");
assert.equal(await first.url(), "https://example.test/first");
@@ -1404,7 +1420,7 @@ test("metadata reads stay target-scoped while evaluate and screenshot activate t
test("Page evaluate rejects ambiguous or non-serializable arguments", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/evaluate");
+ const page = await openTestPage(task, "https://example.test/evaluate");
const cyclic = {};
cyclic.self = cyclic;
@@ -1426,7 +1442,10 @@ test("Page evaluate rejects ambiguous or non-serializable arguments", async () =
test("Page evaluate preserves a large nested JSON argument", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/evaluate-complex");
+ const page = await openTestPage(
+ task,
+ "https://example.test/evaluate-complex",
+ );
const argument = {
marker: "复杂 input 😀 quotes: \" ' ` and a newline\n",
config: {
@@ -1453,8 +1472,8 @@ test("Page evaluate preserves a large nested JSON argument", async () => {
test("Page fetch activates its target and returns a structured non-2xx response", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.openPage("https://example.test/first");
- await task.openPage("https://example.test/second");
+ const first = await openTestPage(task, "https://example.test/first");
+ await openTestPage(task, "https://example.test/second");
const response = await first.fetch("/api/teapot", {
method: "POST",
@@ -1491,6 +1510,7 @@ test("Page fetch activates its target and returns a structured non-2xx response"
body: "payload",
},
timeoutMs: 250,
+ responseType: "text",
},
},
]);
@@ -1502,7 +1522,7 @@ test("Page fetch activates its target and returns a structured non-2xx response"
test("Page fetch validates its JSON options and millisecond timeout", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/fetch");
+ const page = await openTestPage(task, "https://example.test/fetch");
const cyclic = {};
cyclic.self = cyclic;
@@ -1521,6 +1541,20 @@ test("Page fetch validates its JSON options and millisecond timeout", async () =
});
});
+test("Page fetch saves a binary response without converting it to text", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/fetch");
+ const path = join(fixture.rootDir, "downloads", "image.png");
+
+ const response = await page.fetch("/image.png", { saveAs: path });
+
+ assert.equal(response.savedPath, path);
+ assert.equal(response.body, undefined);
+ assert.deepEqual(await readFile(path), Buffer.from("\x89PNG\r\n\x1a\n"));
+ });
+});
+
test("Page click fails closed when native mouse dispatch times out", async () => {
await withFixture(async (fixture) => {
fixture.tabs.set("target-user", {
@@ -1530,8 +1564,8 @@ test("Page click fails closed when native mouse dispatch times out", async () =>
active: false,
});
const task = taskForRound(fixture, "round-a", { pageBudget: 2 });
- const first = await task.openPage("https://example.test/first");
- await task.openPage("https://example.test/second");
+ const first = await openTestPage(task, "https://example.test/first");
+ await openTestPage(task, "https://example.test/second");
fixture.openPopupOnNextClick("https://example.test/popup");
fixture.timeoutNextMouseDispatch();
@@ -1568,7 +1602,7 @@ test("Page click fails closed when native mouse dispatch times out", async () =>
test("Page click returns a pending JavaScript dialog without waiting for input completion", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/dialog");
+ const page = await openTestPage(task, "https://example.test/dialog");
fixture.openDialogOnNextClick();
assert.deepEqual(await page.click("#open-dialog"), {
@@ -1613,8 +1647,8 @@ test("Page click returns a pending JavaScript dialog without waiting for input c
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");
- const first = await task.openPage("https://example.test/first");
- await task.openPage("https://example.test/second");
+ const first = await openTestPage(task, "https://example.test/first");
+ await openTestPage(task, "https://example.test/second");
assert.deepEqual(await first.fill("#text-input", "filled"), {});
const insertText = fixture.calls.find(
@@ -1669,7 +1703,7 @@ test("Page fill uses its target session and reports no popup when none opened",
test("Page fill retries an unchanged contenteditable once with a real click", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/editor");
+ const page = await openTestPage(task, "https://example.test/editor");
fixture.configureFill({
kind: "contenteditable",
initialText: "old text",
@@ -1702,7 +1736,7 @@ test("Page fill retries an unchanged contenteditable once with a real click", as
test("Page fill refuses a pointer fallback that would activate an interactive descendant", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/editor");
+ const page = await openTestPage(task, "https://example.test/editor");
fixture.configureFill({
kind: "contenteditable",
initialText: "linked text",
@@ -1735,7 +1769,7 @@ test("Page fill refuses a pointer fallback that would activate an interactive de
test("Page fill rejects when a contenteditable still ignores the pointer fallback", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/editor");
+ const page = await openTestPage(task, "https://example.test/editor");
fixture.configureFill({
kind: "contenteditable",
initialText: "old text",
@@ -1750,32 +1784,111 @@ test("Page fill rejects when a contenteditable still ignores the pointer fallbac
});
});
-test("Page fill does not click a regular input when the site rejects its value", async () => {
+test("Page fill retries an unchanged regular input once with a real click", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/form");
+ const page = await openTestPage(task, "https://example.test/form");
fixture.configureFill({ kind: "input", ignoreInsertions: 1 });
fixture.calls.length = 0;
- await assert.rejects(
- () => page.fill("input[name=email]", "[email protected]"),
- /did not accept the text/i,
+ assert.deepEqual(
+ await page.fill("input[name=email]", "[email protected]"),
+ {},
);
+ assert.equal(fixture.fillText(), "[email protected]");
+ assert.deepEqual(
+ fixture.calls
+ .filter(
+ ([kind, method]) =>
+ kind === "cdp" && method === "Input.dispatchMouseEvent",
+ )
+ .map(([, , params]) => params.type),
+ ["mouseMoved", "mousePressed", "mouseReleased"],
+ );
+ });
+});
+
+test("Page fill accepts application formatting without a pointer retry", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/formatted");
+ fixture.configureFill({
+ kind: "input",
+ initialText: "$600,000",
+ transform: (text) => `$${Number(text).toLocaleString("en-US")}`,
+ });
+ fixture.calls.length = 0;
+
+ assert.deepEqual(await page.fill("#price", "610000"), {});
+ assert.equal(fixture.fillText(), "$610,000");
assert.equal(
- fixture.calls.some(
- ([kind, method]) =>
- kind === "cdp" && method === "Input.dispatchMouseEvent",
- ),
- false,
- "only contenteditable elements may receive the pointer fallback",
+ fixture.calls.filter(
+ ([kind, method]) => kind === "cdp" && method === "Input.insertText",
+ ).length,
+ 1,
+ "a semantically equivalent formatted value must not be typed twice",
+ );
+ });
+});
+
+test("Page fill retries an appended value and accepts the transformed retry", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/formatted");
+ fixture.configureFill({
+ kind: "input",
+ initialText: "$600,000",
+ transform: (text, current, attempt) =>
+ attempt === 1
+ ? current + text
+ : `$${Number(text).toLocaleString("en-US")}`,
+ });
+ fixture.calls.length = 0;
+
+ assert.deepEqual(await page.fill("#price", "610000"), {});
+ assert.equal(fixture.fillText(), "$610,000");
+ assert.equal(
+ fixture.calls.filter(
+ ([kind, method]) => kind === "cdp" && method === "Input.insertText",
+ ).length,
+ 2,
);
});
});
+test("Page fill accepts a controlled component transformation", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/controlled");
+ fixture.configureFill({
+ kind: "input",
+ initialText: "old",
+ transform: (text) => text.toUpperCase(),
+ });
+
+ assert.deepEqual(await page.fill("#controlled", "hello"), {});
+ assert.equal(fixture.fillText(), "HELLO");
+ });
+});
+
+test("Page selectOption selects values through the addressed Page", 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("#country", "nl"), ["nl"]);
+ assert.deepEqual(await page.selectOption("#tags", ["one", "two"]), [
+ "one",
+ "two",
+ ]);
+ assert.deepEqual(fixture.selectedValues(), ["one", "two"]);
+ });
+});
+
test("Page action receipts do not inject observation probes", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/before");
+ const page = await openTestPage(task, "https://example.test/before");
fixture.navigateOnNextClick("https://example.test/after");
fixture.calls.length = 0;
@@ -1796,8 +1909,8 @@ test("Page action receipts do not inject observation probes", async () => {
test("Page pointer methods dispatch through the addressed target session", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.openPage("https://example.test/first");
- await task.openPage("https://example.test/second");
+ const first = await openTestPage(task, "https://example.test/first");
+ await openTestPage(task, "https://example.test/second");
await first.dblclick("button.primary");
await first.hover("button.primary");
@@ -1845,7 +1958,7 @@ test("Page pointer methods dispatch through the addressed target session", async
test("Page mouse movement updates the Ego Lite agent cursor", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
await page.click("button.primary");
await page.hover("button.primary");
@@ -1879,7 +1992,7 @@ test("agent cursor rendering failures do not make successful page input retryabl
throw new Error("agent cursor overlay unavailable");
},
});
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
await page.click("button.primary");
@@ -1906,7 +2019,7 @@ test("agent cursor animation does not delay page input completion", async () =>
return animation;
},
});
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
const outcome = await Promise.race([
page.mouse.move(20, 30).then(() => "action-complete"),
@@ -1923,8 +2036,8 @@ test("agent cursor animation does not delay page input completion", async () =>
test("Page mouse primitives preserve button state on one target", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.openPage("https://example.test/first");
- await task.openPage("https://example.test/second");
+ const first = await openTestPage(task, "https://example.test/first");
+ await openTestPage(task, "https://example.test/second");
await first.mouse.move(20, 30);
await first.mouse.down();
@@ -1962,7 +2075,7 @@ test("Page mouse primitives preserve button state on one target", async () => {
test("Page mouse mirrors Playwright state, steps, and keyboard modifiers", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "darwin" });
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
await page.keyboard.down("Shift");
await page.mouse.move(30, 20, { steps: 3 });
@@ -2016,19 +2129,20 @@ test("Page mouse mirrors Playwright state, steps, and keyboard modifiers", async
});
});
-test("Page scrollBy evaluates in the addressed page", async () => {
+test("Page mouse.wheel scrolls the addressed page", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.openPage("https://example.test/first");
- await task.openPage("https://example.test/second");
+ const first = await openTestPage(task, "https://example.test/first");
+ await openTestPage(task, "https://example.test/second");
- assert.deepEqual(await first.scrollBy(450), { x: 0, y: 450 });
+ await first.mouse.wheel(0, 450);
const scrollCall = fixture.calls.find(
([kind, method, params]) =>
kind === "cdp" &&
- method === "Runtime.callFunctionOn" &&
- params.functionDeclaration.includes("window.scrollBy"),
+ method === "Input.dispatchMouseEvent" &&
+ params.type === "mouseWheel" &&
+ params.deltaY === 450,
);
assert.equal(scrollCall[3], `session:${first.targetId}`);
assert.equal(fixture.activeTarget(), first.targetId);
@@ -2038,8 +2152,8 @@ test("Page scrollBy evaluates in the addressed page", async () => {
test("Page keyboard press and type use the addressed target session", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.openPage("https://example.test/first");
- await task.openPage("https://example.test/second");
+ const first = await openTestPage(task, "https://example.test/first");
+ await openTestPage(task, "https://example.test/second");
await first.keyboard.press("Meta+A");
await first.keyboard.type("hello 世界");
@@ -2080,7 +2194,7 @@ test("Page keyboard press and type use the addressed target session", async () =
test("Page focus and selector-scoped press resolve and focus one element", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "darwin" });
- const page = await task.openPage("https://example.test/editor");
+ const page = await openTestPage(task, "https://example.test/editor");
assert.deepEqual(await page.focus("[contenteditable]"), {});
assert.deepEqual(
@@ -2113,7 +2227,7 @@ test("Page focus and selector-scoped press resolve and focus one element", async
test("Page focus accepts a uniquely retargeted descendant", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/editor");
+ const page = await openTestPage(task, "https://example.test/editor");
fixture.configureFocusResult({ focused: true, retargeted: "descendant" });
assert.deepEqual(await page.focus("#editor-wrapper"), {});
@@ -2123,7 +2237,7 @@ test("Page focus accepts a uniquely retargeted descendant", async () => {
test("Page focus reports ambiguous candidates once as a permanent failure", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/editor");
+ const page = await openTestPage(task, "https://example.test/editor");
fixture.configureFocusResult({
error: "element contains multiple editable targets",
details: {
@@ -2163,7 +2277,7 @@ test("Page focus reports ambiguous candidates once as a permanent failure", asyn
test("Page keyboard paste restores the clipboard after the native shortcut", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "darwin" });
- const page = await task.openPage("https://example.test/table");
+ const page = await openTestPage(task, "https://example.test/table");
assert.deepEqual(await page.keyboard.paste("a\tb\nc\td"), {});
@@ -2193,7 +2307,7 @@ test("Page keyboard paste restores the clipboard after the native shortcut", asy
test("Page keyboard paste forwards plain-text and HTML clipboard representations", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "darwin" });
- const page = await task.openPage("https://example.test/table");
+ const page = await openTestPage(task, "https://example.test/table");
const content = {
text: "A\tB",
html: "<table><tr><td>A</td><td>B</td></tr></table>",
@@ -2230,7 +2344,7 @@ test("Page keyboard paste still restores the clipboard when input fails", async
return fixture.services.cdp(method, params, sessionId, timeoutMs);
},
});
- const page = await task.openPage("https://example.test/table");
+ const page = await openTestPage(task, "https://example.test/table");
await assert.rejects(
() => page.keyboard.paste("one\ttwo"),
@@ -2243,7 +2357,7 @@ test("Page keyboard paste still restores the clipboard when input fails", async
test("Page keyboard type uses the main keyboard for digits and period", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
await page.keyboard.type("0123456789.");
@@ -2272,7 +2386,7 @@ test("Page keyboard type uses the main keyboard for digits and period", async ()
test("Page keyboard mirrors Playwright key state and the US layout", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "darwin" });
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
await page.keyboard.down("Shift");
await page.keyboard.down("a");
@@ -2321,7 +2435,7 @@ test("Page keyboard mirrors Playwright key state and the US layout", async () =>
test("Page keyboard maps portable editing shortcuts on macOS", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "darwin" });
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
await page.keyboard.press("ControlOrMeta+A");
await page.keyboard.press("ControlOrMeta+C");
@@ -2359,7 +2473,7 @@ test("Page keyboard maps portable editing shortcuts on macOS", async () => {
test("Page keyboard accepts case-insensitive modifier names", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "darwin" });
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
await page.keyboard.press("ALT+CONTROL+META+SHIFT+A");
await page.keyboard.press("CONTROLORMETA+A");
@@ -2382,7 +2496,7 @@ test("Page keyboard accepts case-insensitive modifier names", async () => {
test("Page keyboard maps portable editing shortcuts on Windows", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "win32" });
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
await page.keyboard.press("ControlOrMeta+A");
await page.keyboard.press("ControlOrMeta+C");
@@ -2415,7 +2529,7 @@ test("Page keyboard maps portable editing shortcuts on Windows", async () => {
test("Page keyboard type emits physical keys when possible and inserts unsupported text", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "darwin" });
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
await page.keyboard.type("Aé", { delay: 12 });
@@ -2445,7 +2559,7 @@ test("Page keyboard type emits physical keys when possible and inserts unsupport
test("Page keyboard releases pressed modifiers when a chord fails", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "darwin" });
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
await assert.rejects(
() => page.keyboard.press("Shift+DefinitelyUnknown"),
@@ -2469,7 +2583,7 @@ test("Page keyboard releases pressed modifiers when a chord fails", async () =>
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" });
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
fixture.calls.length = 0;
assert.equal(await page.mouse.move(10, 20), undefined);
@@ -2480,8 +2594,6 @@ test("low-level Page input skips action observers and returns no receipt", async
assert.equal(await page.keyboard.up("Shift"), undefined);
assert.equal(await page.keyboard.type("a"), undefined);
assert.equal(await page.keyboard.insertText("é"), undefined);
- assert.deepEqual(await page.scrollBy(50), { x: 0, y: 50 });
-
assert.equal(
fixture.calls.some(
([kind, method, params]) =>
@@ -2498,8 +2610,8 @@ test("low-level Page input skips action observers and returns no receipt", async
test("Page keyboard omits synthetic dispatch while file input stays target-scoped", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.openPage("https://example.test/first");
- await task.openPage("https://example.test/second");
+ const first = await openTestPage(task, "https://example.test/first");
+ await openTestPage(task, "https://example.test/second");
assert.equal(first.keyboard.dispatch, undefined);
await first.setInputFiles("#upload", ["/tmp/one.txt", "/tmp/two.txt"]);
@@ -2516,7 +2628,7 @@ test("Page keyboard omits synthetic dispatch while file input stays target-scope
test("Page.setInputFiles resolves labels without opening a system chooser", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/upload");
+ const page = await openTestPage(task, "https://example.test/upload");
await page.setInputFiles("label[for=upload]", [
"/tmp/one.txt",
@@ -2550,7 +2662,10 @@ test("Page.setInputFiles resolves labels without opening a system chooser", asyn
test("Page.waitForFileChooser handles a dynamically created file input", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/dynamic-upload");
+ const page = await openTestPage(
+ task,
+ "https://example.test/dynamic-upload",
+ );
fixture.openFileChooserOnNextClick({
backendNodeId: 91,
mode: "selectMultiple",
@@ -2584,7 +2699,10 @@ test("Page.waitForFileChooser handles a dynamically created file input", async (
test("FileChooser.setFiles uses the current Page session after reconnect", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/dynamic-upload");
+ const page = await openTestPage(
+ task,
+ "https://example.test/dynamic-upload",
+ );
fixture.openFileChooserOnNextClick({ backendNodeId: 92 });
const chooserPromise = page.waitForFileChooser();
@@ -2607,7 +2725,7 @@ test("FileChooser.setFiles uses the current Page session after reconnect", async
test("unhandled file choosers are cancelled before a system dialog appears", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/upload-guard");
+ const page = await openTestPage(task, "https://example.test/upload-guard");
fixture.openFileChooserOnNextClick();
await assert.rejects(
@@ -2631,8 +2749,8 @@ test("unhandled file choosers are cancelled before a system dialog appears", asy
test("Page and TaskSpace CDP commands preserve their intended scope", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.openPage("https://example.test/first");
- await task.openPage("https://example.test/second");
+ const first = await openTestPage(task, "https://example.test/first");
+ await openTestPage(task, "https://example.test/second");
const pageResult = await first.cdp(
"Runtime.evaluate",
@@ -2673,8 +2791,8 @@ test("Page and TaskSpace CDP commands preserve their intended scope", async () =
test("Page waits and events remain isolated to the addressed target", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.openPage("https://example.test/first");
- const second = await task.openPage("https://example.test/second");
+ const first = await openTestPage(task, "https://example.test/first");
+ const second = await openTestPage(task, "https://example.test/second");
assert.equal(
await first.waitForSelector("#ready", {
@@ -2745,7 +2863,7 @@ test("Page waitForURL follows a popup from about:blank without activating it", a
}
},
});
- const source = await task.openPage("https://example.test/source");
+ const source = await openTestPage(task, "https://example.test/source");
fixture.openPopupOnNextClick("about:blank");
const receipt = await source.click("#open-popup");
popupTargetId = receipt.popups[0].targetId;
@@ -2780,7 +2898,7 @@ test("Page.waitForEvent arms before a click and resolves the opened popup", asyn
await withFixture(async (fixture) => {
resetPageNotices();
const task = taskForRound(fixture, "round-a");
- const source = await task.openPage("https://example.test/source");
+ const source = await openTestPage(task, "https://example.test/source");
fixture.openPopupOnNextClick("https://example.test/popup");
const popupPromise = source.waitForEvent("popup", { timeout: 1_000 });
@@ -2796,7 +2914,7 @@ test("Page.waitForEvent arms before a click and resolves the opened popup", asyn
test("Page.waitForEvent rejects unsupported events and times out cleanly", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const source = await task.openPage("https://example.test/source");
+ const source = await openTestPage(task, "https://example.test/source");
assert.throws(
() => source.waitForEvent("download", { timeout: 10 }),
@@ -2813,7 +2931,7 @@ test("Page.waitForURL immediately reports a matching popup opened by this Page",
await withFixture(async (fixture) => {
resetPageNotices();
const task = taskForRound(fixture, "round-a");
- const source = await task.openPage("https://example.test/source");
+ const source = await openTestPage(task, "https://example.test/source");
fixture.openPopupOnNextClick("https://example.test/drive/home");
await source.click("#open-popup");
@@ -2836,7 +2954,7 @@ test("Page.waitForURL still succeeds when the opener itself reaches the URL", as
await withFixture(async (fixture) => {
resetPageNotices();
const task = taskForRound(fixture, "round-a");
- const source = await task.openPage("https://example.test/source");
+ const source = await openTestPage(task, "https://example.test/source");
const expectedUrl = "https://example.test/drive/home";
fixture.openPopupOnNextClick(expectedUrl);
fixture.navigateOnNextClick(expectedUrl);
@@ -2849,7 +2967,7 @@ test("Page.waitForURL still succeeds when the opener itself reaches the URL", as
test("Page waitForURL validates its matcher and reports the last URL", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("about:blank");
+ const page = await openTestPage(task, "about:blank");
await assert.rejects(
() => page.waitForURL("https://example.test/never", { timeout: 10 }),
@@ -2874,7 +2992,7 @@ test("Page waitForURL retries a transient evaluation timeout", async () => {
await withFixture(async (fixture) => {
const expectedUrl = "https://example.test/after-timeout";
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage(expectedUrl);
+ const page = await openTestPage(task, expectedUrl);
fixture.timeoutNextUrlEvaluation();
await page.waitForURL(expectedUrl, { timeout: 2_000 });
@@ -2885,7 +3003,7 @@ test("Page waitForURL retries a transient evaluation timeout", async () => {
test("Page waitForSelector supports Playwright-style element states", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
fixture.setElementState({ present: true, visible: false });
assert.equal(
@@ -2918,7 +3036,7 @@ test("Page waitForSelector supports Playwright-style element states", async () =
test("Page wait methods reject invalid states and millisecond timeouts", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
fixture.setDocumentLifecycle({
readyState: "interactive",
@@ -2962,8 +3080,8 @@ test("Page wait methods reject invalid states and millisecond timeouts", async (
test("Page actions resolve snapshot refs inside the addressed page", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.openPage("https://example.test/first");
- const second = await task.openPage("https://example.test/second");
+ const first = await openTestPage(task, "https://example.test/first");
+ const second = await openTestPage(task, "https://example.test/second");
await first.snapshot();
await second.snapshot();
@@ -2999,7 +3117,10 @@ test("Page actions resolve snapshot refs inside the addressed page", async () =>
test("a new round refreshes the addressed Page before resolving a ref", async () => {
await withFixture(async (fixture) => {
const firstRound = taskForRound(fixture, "round-a");
- const created = await firstRound.openPage("https://example.test/first");
+ const created = await openTestPage(
+ firstRound,
+ "https://example.test/first",
+ );
await created.snapshot();
const snapshotsBefore = fixture.calls.filter(
([kind]) => kind === "snapshot",
@@ -3025,7 +3146,7 @@ test("a new round refreshes the addressed Page before resolving a ref", async ()
test("an unknown Page ref fails after one target-scoped refresh", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
await assert.rejects(() => page.click("@99"), /Unknown ref: 99/);
assert.deepEqual(
@@ -3038,7 +3159,7 @@ test("an unknown Page ref fails after one target-scoped refresh", async () => {
test("Page click scrolls the element into view before computing its point", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
await page.click("#offscreen");
@@ -3060,7 +3181,7 @@ test("Page click scrolls the element into view before computing its point", asyn
test("Page click retries a transient visibility change before dispatching input", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
fixture.rejectNextClickPoint();
assert.deepEqual(await page.click("#temporarily-hidden"), {});
@@ -3087,7 +3208,7 @@ test("Page click retries a transient visibility change before dispatching input"
test("Page click reports the last transient state after its timeout", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
fixture.rejectClickPoints(100);
await assert.rejects(
@@ -3116,7 +3237,7 @@ test("Page click reports the last transient state after its timeout", async () =
test("Page click waits for a temporary pointer interceptor", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
fixture.interceptNextClickPoint();
assert.deepEqual(await page.click("#covered", { timeout: 100 }), {});
@@ -3135,7 +3256,7 @@ test("Page click waits for a temporary pointer interceptor", async () => {
test("Page click times out while a pointer interceptor remains", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
fixture.interceptClickPoints(100);
await assert.rejects(
@@ -3156,7 +3277,7 @@ test("Page click times out while a pointer interceptor remains", async () => {
test("Page click force bypasses only the pointer interception check", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
fixture.interceptClickPoints(100);
assert.deepEqual(
@@ -3177,7 +3298,7 @@ test("Page click force bypasses only the pointer interception check", async () =
test("close leaves an anchor tab and the next page gets a new label", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.openPage("https://example.test/first");
+ const first = await openTestPage(task, "https://example.test/first");
await first.close();
assert.equal(fixture.tabs.has("target-1"), false);
@@ -3191,7 +3312,7 @@ test("close leaves an anchor tab and the next page gets a new label", async () =
/page p1 was closed/,
);
- const second = await task.openPage("https://example.test/second");
+ const second = await openTestPage(task, "https://example.test/second");
assert.equal(second.label, "p2");
assert.equal(second.targetId, "target-3");
});
@@ -3217,7 +3338,7 @@ test("close waits for the target to disappear before retiring its label", async
return [...fixture.tabs.values()];
},
});
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
await page.close();
@@ -3237,7 +3358,7 @@ test("close keeps the page managed when the target never disappears", async () =
return fixture.services.cdp(method, params, sessionId, timeoutMs);
},
});
- const page = await task.openPage("https://example.test/first");
+ const page = await openTestPage(task, "https://example.test/first");
await assert.rejects(() => page.close(), /did not close within 2000ms/);
@@ -3265,7 +3386,7 @@ test("a ledger failure closes the newly created uncommitted tab", async () => {
);
await assert.rejects(
- () => task.openPage("https://example.test/uncommitted"),
+ () => openTestPage(task, "https://example.test/uncommitted"),
/ledger unavailable/,
);
assert.equal(fixture.tabs.size, 0);
@@ -3286,7 +3407,7 @@ test("pages returns managed Page handles while tabs returns the complete invento
active: false,
});
const task = taskForRound(fixture, "round-a");
- const managed = await task.openPage("https://example.test/managed");
+ const managed = await openTestPage(task, "https://example.test/managed");
fixture.tabs.set("target-popup", {
targetId: "target-popup",
url: "https://example.test/popup",
@@ -3331,7 +3452,7 @@ test("pages returns managed Page handles while tabs returns the complete invento
test("tabs automatically manages a tab created during agent control", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- await task.openPage("https://example.test/managed");
+ await openTestPage(task, "https://example.test/managed");
fixture.tabs.set("target-popup", {
targetId: "target-popup",
url: "https://example.test/popup",
@@ -3428,7 +3549,7 @@ test("adopt applies the managed-page budget before changing the ledger", async (
active: false,
});
const task = taskForRound(fixture, "round-a", { pageBudget: 1 });
- await task.openPage("https://example.test/managed");
+ await openTestPage(task, "https://example.test/managed");
const untracked = (await task.tabs()).find(
(item) => item.targetId === "target-user",
).page;
@@ -3471,7 +3592,7 @@ test("release leaves an adopted page open and retires its label", async () => {
test("release refuses to orphan a page created by the agent", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const created = await task.openPage("https://example.test/agent");
+ const created = await openTestPage(task, "https://example.test/agent");
await assert.rejects(
() => task.release(created.label),
@@ -3485,7 +3606,7 @@ test("release refuses to orphan a page created by the agent", async () => {
test("tabs retires a managed label when its browser tab disappeared", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.openPage("https://example.test/managed");
+ const page = await openTestPage(task, "https://example.test/managed");
fixture.tabs.delete(page.targetId);
assert.deepEqual(await task.tabs(), []);
@@ -3496,14 +3617,14 @@ test("tabs retires a managed label when its browser tab disappeared", async () =
});
});
-test("openPage rejects before creating a tab when the managed budget is full", async () => {
+test("newPage rejects before creating a tab when the managed budget is full", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { pageBudget: 2 });
- const first = await task.openPage("https://example.test/first");
- await task.openPage("https://example.test/second");
+ const first = await openTestPage(task, "https://example.test/first");
+ await openTestPage(task, "https://example.test/second");
await assert.rejects(
- () => task.openPage("https://example.test/third"),
+ () => openTestPage(task, "https://example.test/third"),
(error) => {
assert.match(
error.message,
@@ -3528,20 +3649,20 @@ test("openPage rejects before creating a tab when the managed budget is full", a
);
await first.close();
- const replacement = await task.openPage("https://example.test/third");
+ const replacement = await openTestPage(task, "https://example.test/third");
assert.equal(replacement.label, "p3");
assert.equal(fixture.tabs.size, 2);
});
});
-test("a tab closed outside the runtime frees budget on the next openPage", async () => {
+test("a tab closed outside the runtime frees budget on the next newPage", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { pageBudget: 2 });
- const first = await task.openPage("https://example.test/first");
- await task.openPage("https://example.test/second");
+ const first = await openTestPage(task, "https://example.test/first");
+ await openTestPage(task, "https://example.test/second");
fixture.tabs.delete(first.targetId);
- const replacement = await task.openPage("https://example.test/third");
+ const replacement = await openTestPage(task, "https://example.test/third");
assert.equal(replacement.label, "p3");
assert.equal(fixture.tabs.size, 2);
@@ -3552,10 +3673,10 @@ test("a tab closed outside the runtime frees budget on the next openPage", async
});
});
-test("openPage never closes a managed page when native returns its target again", async () => {
+test("newPage never closes a managed page when native returns its target again", async () => {
await withFixture(async (fixture) => {
const firstTask = taskForRound(fixture, "round-a");
- const first = await firstTask.openPage("https://example.test/first");
+ const first = await openTestPage(firstTask, "https://example.test/first");
const closeCallsBefore = fixture.calls.filter(
([kind, method]) => kind === "cdp" && method === "Target.closeTarget",
).length;
@@ -3566,7 +3687,7 @@ test("openPage never closes a managed page when native returns its target again"
});
await assert.rejects(
- () => secondTask.openPage("https://example.test/second"),
+ () => openTestPage(secondTask, "https://example.test/second"),
/did not create a distinct tab.*already page p1/,
);
diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.ts
index 0c77a99..192a482 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -1,3 +1,6 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { dirname } from "node:path";
+
import {
browserCdp,
browserEgo,
@@ -33,6 +36,7 @@ import {
mouseButtonInPage,
mouseButtonMask,
moveMouseInPage,
+ selectOptionInPage,
wheelInPage,
type MouseButton,
type PageClickOptions,
@@ -78,6 +82,7 @@ import {
type PageOrigin,
} from "./page-ledger.js";
import { PageRefRegistry } from "./page-ref-registry.js";
+import { preparePageSnapshotResult } from "./snapshot-result.js";
import {
clearSpacePageNotices,
forgetPageNotice,
@@ -111,11 +116,6 @@ function isRetryableElementStateError(
);
}
-type OpenPageOptions = {
- as?: string;
- timeout?: number;
-};
-
type AdoptPageOptions = {
as?: string;
};
@@ -161,6 +161,7 @@ type PageWaitForFunctionOptions = {
export type PageFetchOptions = {
timeout?: number;
+ saveAs?: string;
method?: string;
headers?: Record<string, string>;
body?: string;
@@ -186,15 +187,19 @@ export type PageFetchResponse = {
statusText: string;
url: string;
headers: Record<string, string>;
- body: string;
+ body?: string;
+ savedPath?: string;
};
type PageFetchPayload = {
url: string;
options: Record<string, unknown>;
timeoutMs: number;
+ responseType: "text" | "base64";
};
+type PageFetchResult = PageFetchResponse & { bodyBase64?: string };
+
type PageTarget = {
spaceId: number;
targetId: string;
@@ -531,12 +536,12 @@ const baseDefaultServices: Omit<PageModelServices, "ledger" | "pageBudget"> = {
gate: defaultGate,
pageRefs: defaultPageRefs,
async createTab(url) {
- const result = await invokeEgo("task.openPage", () =>
+ const result = await invokeEgo("task.newPage", () =>
browserEgo().createTab(url),
);
const targetId = result?.targetId || result?.result?.targetId;
if (typeof targetId !== "string" || targetId.length === 0) {
- throw new Error("task.openPage returned no targetId");
+ throw new Error("task.newPage returned no targetId");
}
return targetId;
},
@@ -907,35 +912,30 @@ class TaskSpace {
});
}
- async openPage(
- url = "about:blank",
- options: OpenPageOptions = {},
- ): Promise<Page> {
- assertUrl(url);
- validatePublicApiOptions("TaskSpace.openPage", options);
- const timeoutMs = options.timeout ?? 15_000;
+ async newPage(...args: unknown[]): Promise<Page> {
+ if (args.length > 0) {
+ throw new TypeError("task.newPage does not accept arguments");
+ }
return this.#services.gate.withSpace(this.id, async () => {
const { ledger, tabs } = await this.#reconcilePages();
const managedCount = Object.keys(ledger.pages).length;
if (managedCount >= this.#services.pageBudget) {
throw pageBudgetError(this, this.#services.pageBudget, ledger, tabs);
}
- const creationStartedAtMs = this.#services.now();
- const targetId = await this.#services.createTab(url);
+ const targetId = await this.#services.createTab("about:blank");
this.#services.setPreferredTarget(targetId);
const existingManaged = Object.entries(ledger.pages).find(
([, page]) => page.targetId === targetId,
);
if (existingManaged) {
throw new Error(
- `task.openPage did not create a distinct tab; target ${targetId} is already page ${existingManaged[0]}`,
+ `task.newPage did not create a distinct tab; target ${targetId} is already page ${existingManaged[0]}`,
);
}
const existedBeforeCreate = tabs.some((tab) => tab.targetId === targetId);
let entry: ManagedPage;
try {
entry = await this.#services.ledger.addPage(this.id, targetId, {
- as: options.as,
openedBy: "agent",
});
} catch (error) {
@@ -951,23 +951,8 @@ class TaskSpace {
}
throw error;
}
- const page = new Page(this, entry.label, this.#services, entry);
- try {
- const sessionId = await this.#services.ensureSession(targetId);
- await waitForCreatedDocument(
- this.#services,
- sessionId,
- url,
- creationStartedAtMs,
- timeoutMs,
- );
- } catch (error) {
- throw new Error(
- `page ${entry.label} was created but did not finish loading; retrieve it with task.page('${entry.label}'): ${error?.message || error}`,
- { cause: error },
- );
- }
- return page;
+ await this.#services.ensureSession(targetId);
+ return new Page(this, entry.label, this.#services, entry);
});
}
@@ -1282,7 +1267,7 @@ class Page {
async snapshot(options: PageSnapshotOptions = {}): Promise<string> {
validatePublicApiOptions("Page.snapshot", options);
const page = await this.#resolve();
- return this.#services.gate.withPage(page, async () => {
+ return this.#services.gate.withPage(page, async ({ sessionId }) => {
await this.#activate(page.targetId);
const result = await this.#services.snapshot({
...options,
@@ -1290,6 +1275,16 @@ class Page {
includeActionMarks: options.includeActionMarks ?? true,
includeStableLocator: options.includeStableLocator ?? true,
});
+ const iframeSessions =
+ Array.isArray(result?.refs) && result.refs.length > 0
+ ? await this.#services.ensureFrameSessions(page.targetId)
+ : new Map<string, string>();
+ await preparePageSnapshotResult(
+ this.#services,
+ sessionId,
+ iframeSessions,
+ result,
+ );
this.#services.pageRefs.replace(page.targetId, result?.refs || []);
const content = result?.content || "";
const header = await this.#snapshotHeader(page);
@@ -1484,11 +1479,11 @@ class Page {
options: PageFetchOptions = {},
): Promise<PageFetchResponse> {
assertUrl(url);
- const payload = pageFetchPayload(url, options);
+ const { payload, saveAs } = pageFetchPayload(url, options);
const page = await this.#resolve();
return this.#services.gate.withPage(page, async ({ sessionId }) => {
await this.#activate(page.targetId);
- return evaluateInSession<PageFetchResponse>(
+ const response = await evaluateInSession<PageFetchResult>(
this.#services,
sessionId,
fetchInPage,
@@ -1496,6 +1491,14 @@ class Page {
payload,
payload.timeoutMs + 1_000,
);
+ if (!saveAs) return response;
+ if (typeof response.bodyBase64 !== "string") {
+ throw new Error("page.fetch received no binary response body");
+ }
+ await mkdir(dirname(saveAs), { recursive: true });
+ await writeFile(saveAs, Buffer.from(response.bodyBase64, "base64"));
+ const { bodyBase64: _bodyBase64, ...metadata } = response;
+ return { ...metadata, savedPath: saveAs };
});
}
@@ -1537,7 +1540,7 @@ class Page {
const page = await this.#resolve();
return this.#services.gate.withPage(page, async ({ sessionId }) => {
await this.#activate(page.targetId);
- const refMap = await this.#refMapForAction(page, selector);
+ const refMap = await this.#refMapForAction(page, sessionId, selector);
const iframeSessions = await this.#services.ensureFrameSessions(
page.targetId,
);
@@ -1711,6 +1714,58 @@ class Page {
);
}
+ async selectOption(
+ selector: string,
+ valueOrValues: string | string[],
+ 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 timeoutMs = options.timeout ?? DEFAULT_PAGE_ACTION_TIMEOUT_MS;
+ const page = await this.#resolve();
+ return this.#runInputBoundary(page, async (sessionId) => {
+ const deadline = this.#services.now() + timeoutMs;
+ while (true) {
+ try {
+ const refMap = await this.#refMapForAction(page, sessionId, selector);
+ const iframeSessions = await this.#services.ensureFrameSessions(
+ page.targetId,
+ );
+ return await selectOptionInPage(
+ this.#services,
+ sessionId,
+ refMap,
+ selector,
+ values,
+ iframeSessions,
+ );
+ } catch (error) {
+ if (!isRetryableElementStateError(error)) throw error;
+ const remainingMs = deadline - this.#services.now();
+ if (remainingMs <= 0) {
+ throw new ElementResolutionError(
+ `page.selectOption timed out after ${timeoutMs}ms: ${error.message}`,
+ "transient",
+ );
+ }
+ await this.#services.sleep(
+ Math.min(PAGE_ACTION_RESOLUTION_RETRY_MS, remainingMs),
+ );
+ }
+ }
+ });
+ }
+
async focus(
selector: string,
options: { timeout?: number } = {},
@@ -1817,36 +1872,6 @@ class Page {
})();
}
- async scrollBy(
- deltaY: number,
- options: { deltaX?: number; behavior?: ScrollBehavior } = {},
- ): Promise<{ x: number; y: number }> {
- validatePublicApiOptions("Page.scrollBy", options);
- if (!Number.isFinite(deltaY)) {
- throw new TypeError("page.scrollBy requires a finite deltaY");
- }
- return this.#runValueAction((sessionId) =>
- evaluateInSession<{ x: number; y: number }>(
- this.#services,
- sessionId,
- function (input) {
- window.scrollBy({
- left: input.deltaX,
- top: input.deltaY,
- behavior: input.behavior,
- });
- return { x: window.scrollX, y: window.scrollY };
- },
- true,
- {
- deltaX: options.deltaX ?? 0,
- deltaY,
- behavior: options.behavior ?? "auto",
- },
- ),
- );
- }
-
async close(): Promise<void> {
const page = await this.#resolve();
await this.#services.gate.withSpace(this.spaceId, async () => {
@@ -1965,7 +1990,11 @@ class Page {
const deadline = this.#services.now() + timeoutMs;
while (true) {
try {
- const refMap = await this.#refMapForAction(page, ...selectors);
+ const refMap = await this.#refMapForAction(
+ page,
+ sessionId,
+ ...selectors,
+ );
const iframeSessions = await this.#services.ensureFrameSessions(
page.targetId,
);
@@ -2006,13 +2035,6 @@ class Page {
}
}
- async #runValueAction<T>(
- operation: (sessionId: string) => Promise<T>,
- ): Promise<T> {
- const page = await this.#resolve();
- return this.#runInputBoundary(page, operation);
- }
-
async #runObservedAction(
operation: (sessionId: string) => Promise<void>,
): Promise<PageActionReceipt> {
@@ -2121,6 +2143,7 @@ class Page {
async #refMapForAction(
page: PageTarget,
+ sessionId: string,
...selectors: string[]
): Promise<RefMap> {
let refs = this.#services.pageRefs.forTarget(page.targetId);
@@ -2135,6 +2158,16 @@ class Page {
includeActionMarks: true,
includeStableLocator: true,
});
+ const iframeSessions =
+ Array.isArray(result?.refs) && result.refs.length > 0
+ ? await this.#services.ensureFrameSessions(page.targetId)
+ : new Map<string, string>();
+ await preparePageSnapshotResult(
+ this.#services,
+ sessionId,
+ iframeSessions,
+ result,
+ );
refs = this.#services.pageRefs.replace(page.targetId, result?.refs || []);
return refs;
}
@@ -2356,16 +2389,20 @@ function serializeJsonValue(value: unknown, message: string): unknown {
function pageFetchPayload(
url: string,
options: PageFetchOptions,
-): PageFetchPayload {
+): { payload: PageFetchPayload; saveAs?: string } {
validatePublicApiOptions("Page.fetch", options);
- const { timeout = 20_000, ...requestOptions } = options;
+ const { timeout = 20_000, saveAs, ...requestOptions } = options;
return {
- url,
- options: serializeJsonValue(
- requestOptions,
- "page.fetch options must be JSON-serializable",
- ) as Record<string, unknown>,
- timeoutMs: timeout,
+ payload: {
+ url,
+ options: serializeJsonValue(
+ requestOptions,
+ "page.fetch options must be JSON-serializable",
+ ) as Record<string, unknown>,
+ timeoutMs: timeout,
+ responseType: saveAs ? "base64" : "text",
+ },
+ ...(saveAs ? { saveAs } : {}),
};
}
@@ -2373,6 +2410,7 @@ async function fetchInPage({
url,
options,
timeoutMs,
+ responseType,
}: PageFetchPayload): Promise<PageFetchResponse> {
const controller = new AbortController();
const timer = window.setTimeout(() => controller.abort(), timeoutMs);
@@ -2385,14 +2423,22 @@ async function fetchInPage({
response.headers.forEach((value, key) => {
headers[key] = value;
});
- return {
+ const metadata = {
ok: response.ok,
status: response.status,
statusText: response.statusText,
url: response.url,
headers,
- body: await response.text(),
};
+ if (responseType === "text") {
+ return { ...metadata, body: await response.text() };
+ }
+ const bytes = new Uint8Array(await response.arrayBuffer());
+ let binary = "";
+ for (let offset = 0; offset < bytes.length; offset += 0x8000) {
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
+ }
+ return { ...metadata, bodyBase64: btoa(binary) } as PageFetchResult;
} catch (error) {
if (controller.signal.aborted) {
throw new Error(`page.fetch timed out after ${timeoutMs}ms`);
@@ -2403,71 +2449,6 @@ async function fetchInPage({
}
}
-async function waitForCreatedDocument(
- services: PageModelServices,
- sessionId: string,
- requestedUrl: string,
- creationStartedAtMs: number,
- timeoutMs: number,
-): Promise<void> {
- const deadline = services.now() + timeoutMs;
- while (services.now() <= deadline) {
- const remaining = Math.max(1, deadline - services.now());
- const response = await services.cdp(
- "Runtime.evaluate",
- {
- // createTab() can return while the target still exposes an already
- // complete Chrome placeholder document. Read all three values in one
- // evaluation so openPage resolves only after the requested navigation
- // has committed a document created during this call.
- expression:
- "({readyState:document.readyState,url:location.href,timeOrigin:performance.timeOrigin})",
- returnByValue: true,
- },
- sessionId,
- Math.min(1_000, remaining),
- );
- const observation = response?.result?.value;
- if (
- isCreatedDocumentReady(observation, requestedUrl, creationStartedAtMs)
- ) {
- return;
- }
- await services.sleep(Math.min(100, remaining));
- }
- throw new Error(`task.openPage timed out after ${timeoutMs}ms`);
-}
-
-function isCreatedDocumentReady(
- observation: any,
- requestedUrl: string,
- creationStartedAtMs: number,
-): boolean {
- if (
- observation?.readyState !== "complete" ||
- typeof observation?.url !== "string" ||
- typeof observation?.timeOrigin !== "number" ||
- observation.timeOrigin < creationStartedAtMs
- ) {
- return false;
- }
-
- if (isBrowserPlaceholderUrl(requestedUrl)) {
- return observation.url === requestedUrl;
- }
- return !isBrowserPlaceholderUrl(observation.url);
-}
-
-function isBrowserPlaceholderUrl(url: string): boolean {
- return (
- url === "" ||
- url === ":" ||
- url === "about:blank" ||
- url === "chrome://newtab/" ||
- url === "chrome://new-tab-page/"
- );
-}
-
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 ce56c6b..06ea715 100644
--- a/package/ego-browser/src/public-api-schema.test.mjs
+++ b/package/ego-browser/src/public-api-schema.test.mjs
@@ -19,7 +19,7 @@ test("the public API schema contains the v2 entry points and object methods", ()
"TaskSpace.userPage",
"TaskSpace.pages",
"TaskSpace.tabs",
- "TaskSpace.openPage",
+ "TaskSpace.newPage",
"Page.snapshot",
"Page.targetId",
"Page.waitForEvent",
@@ -28,12 +28,14 @@ test("the public API schema contains the v2 entry points and object methods", ()
"Page.waitForFunction",
"Page.focus",
"Page.press",
+ "Page.selectOption",
"Page.keyboard.press",
"Page.keyboard.paste",
]) {
assert(names.has(name), `missing public API schema entry: ${name}`);
}
assert.equal(names.has("TaskSpace.listPages"), false);
+ assert.equal(names.has("Page.scrollBy"), false);
});
test("schema-driven option validation rejects unknown and invalid fields", () => {
@@ -45,6 +47,7 @@ test("schema-driven option validation rejects unknown and invalid fields", () =>
force: true,
timeout: 500,
});
+ validatePublicApiOptions("Page.fetch", { saveAs: "/tmp/image.png" });
for (const waitUntil of [
"commit",
"domcontentloaded",
@@ -63,7 +66,7 @@ test("schema-driven option validation rejects unknown and invalid fields", () =>
);
assert.throws(
() => validatePublicApiOptions("Page.click", { trial: true }),
- /unknown option: trial/,
+ /unknown option: trial\. Expected: await page\.click\(selector, \{ button\?, clickCount\?, delay\?, position\?, force\?, timeout\? \}\)/,
);
assert.throws(
() => validatePublicApiOptions("Page.goto", { timeout: 0 }),
@@ -88,13 +91,14 @@ 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, /`await task\.newPage\(\)`/);
assert.match(
markdown,
- /`await task\.openPage\(url, \{ as\?, timeout\? \}\)`/,
+ /`await page\.goto\(url, \{ referer\?, timeout\?, waitUntil\? \}\)`/,
);
assert.match(
markdown,
- /`await page\.goto\(url, \{ referer\?, timeout\?, waitUntil\? \}\)`/,
+ /`await page\.selectOption\(selector, valueOrValues, \{ timeout\? \}\)`/,
);
assert.match(
markdown,
@@ -108,8 +112,8 @@ test("the generated reference contains signatures and option descriptions", () =
markdown,
/const popupPromise = page\.waitForEvent\("popup"\); await page\.click\(selector\)/,
);
- assert.match(markdown, /`as` — Permanent Page label\.<br>`timeout`/);
- assert.match(markdown, /Open and durably label a new Page/);
+ 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/,
diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.ts
index a269799..51af73e 100644
--- a/package/ego-browser/src/public-api-schema.ts
+++ b/package/ego-browser/src/public-api-schema.ts
@@ -123,13 +123,9 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
summary: "List managed Pages and unmanaged tabs in this space.",
},
{
- name: "TaskSpace.openPage",
- signature: "await task.openPage(url, { as?, timeout? })",
- summary: "Open and durably label a new Page.",
- options: {
- as: option("string", "Permanent Page label."),
- timeout,
- },
+ name: "TaskSpace.newPage",
+ signature: "await task.newPage()",
+ summary: "Create and durably label a blank Page.",
},
{
name: "TaskSpace.adopt",
@@ -302,6 +298,10 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
summary: "Run window.fetch in this Page and return a structured response.",
options: {
timeout,
+ saveAs: option(
+ "nonEmptyString",
+ "Write the response body to this path without text conversion.",
+ ),
method: option("string", "HTTP method."),
headers: option("stringRecord", "Request headers."),
body: option("string", "Request body."),
@@ -415,12 +415,18 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
name: "Page.fill",
signature: "await page.fill(selector, value, { clearFirst?, timeout? })",
summary:
- "Fill the selected field, its editing host, or its unique fillable descendant, then verify the value.",
+ "Fill the selected field, its editing host, or its unique fillable descendant, then confirm editing took effect.",
options: {
clearFirst: option("boolean", "Clear the current value before filling."),
timeout: actionTimeout,
},
},
+ {
+ name: "Page.selectOption",
+ signature: "await page.selectOption(selector, valueOrValues, { timeout? })",
+ summary: "Select one or more option values and return the selected values.",
+ options: { timeout: actionTimeout },
+ },
{
name: "Page.focus",
signature: "await page.focus(selector, { timeout? })",
@@ -456,19 +462,6 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
signature: "await fileChooser.setFiles(pathOrPaths)",
summary: "Set files on an intercepted chooser without a system dialog.",
},
- {
- name: "Page.scrollBy",
- signature: "await page.scrollBy(deltaY, { deltaX?, behavior? })",
- summary: "Scroll this Page by CSS-pixel deltas.",
- options: {
- deltaX: option("finiteNumber", "Horizontal CSS-pixel delta."),
- behavior: option("string", "Scroll behavior.", [
- "auto",
- "instant",
- "smooth",
- ]),
- },
- },
{
name: "Page.close",
signature: "await page.close()",
@@ -569,20 +562,41 @@ export function validatePublicApiOptions(name: string, value: unknown): void {
throw new Error(`public API schema has no options for ${name}`);
}
if (!value || typeof value !== "object" || Array.isArray(value)) {
- throw new TypeError(`${displayName(name)} options must be an object`);
+ throw new TypeError(
+ validationMessage(
+ entry,
+ `${displayName(name)} options must be an object`,
+ ),
+ );
}
for (const [key, optionValue] of Object.entries(value)) {
const specification = entry.options[key];
if (!specification) {
throw new TypeError(
- `${displayName(name)} received unknown option: ${key}`,
+ validationMessage(
+ entry,
+ `${displayName(name)} received unknown option: ${key}`,
+ ),
);
}
if (optionValue === undefined) continue;
- validateOptionValue(displayName(name), key, optionValue, specification);
+ try {
+ validateOptionValue(displayName(name), key, optionValue, specification);
+ } catch (error) {
+ if (error instanceof TypeError) {
+ throw new TypeError(validationMessage(entry, error.message), {
+ cause: error,
+ });
+ }
+ throw error;
+ }
}
}
+function validationMessage(entry: PublicApiEntry, message: string): string {
+ return `${message}. Expected: ${entry.signature}`;
+}
+
export function publicApiMarkdown(): string {
const groups = new Map<string, PublicApiEntry[]>();
for (const entry of PUBLIC_API_SCHEMA) {
diff --git a/package/ego-browser/src/run.ts b/package/ego-browser/src/run.ts
index 9de843e..b549784 100644
--- a/package/ego-browser/src/run.ts
+++ b/package/ego-browser/src/run.ts
@@ -41,7 +41,8 @@ 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.openPage('https://example.com', { as: 'p1' })
+ const page = await task.newPage()
+ await page.goto('https://example.com')
console.log(await page.snapshot())
JS
@@ -51,7 +52,8 @@ 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.openPage('https://example.com', { as: 'p1' })
+ const page = await task.newPage()
+ await page.goto('https://example.com')
console.log(await page.snapshot())
JS
`;
diff --git a/package/ego-browser/src/snapshot-result.test.mjs b/package/ego-browser/src/snapshot-result.test.mjs
new file mode 100644
index 0000000..ac9f9d2
--- /dev/null
+++ b/package/ego-browser/src/snapshot-result.test.mjs
@@ -0,0 +1,135 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ enrichSnapshotRefFrames,
+ sanitizeSnapshotLocators,
+ validateSnapshotLocator,
+} from "../dist/src/snapshot-result.js";
+
+test("invalid native snapshot locators are hidden without removing their refs", async () => {
+ const result = {
+ content: [
+ 'textfield "Prompt" [ref=10, loc=css:input[aria-label="Prompt"]]',
+ 'button "Save" [ref=11, loc=role:button[name="Save"]]',
+ ].join("\n"),
+ refs: [
+ {
+ backendNodeId: 10,
+ role: "textfield",
+ name: "Prompt",
+ loc: 'css:input[aria-label="Prompt"]',
+ },
+ {
+ backendNodeId: 11,
+ role: "button",
+ name: "Save",
+ loc: 'role:button[name="Save"]',
+ },
+ ],
+ };
+
+ await sanitizeSnapshotLocators(
+ result,
+ async (ref) => ref.backendNodeId === 11,
+ );
+
+ assert.match(result.content, /ref=10, loc=unstable/);
+ assert.doesNotMatch(result.content, /loc=css:input/);
+ assert.match(result.content, /ref=11, loc=role:button/);
+ assert.equal(result.refs[0].loc, "unstable");
+ assert.equal(result.refs[1].loc, 'role:button[name="Save"]');
+});
+
+test("stable locator validation requires one match for the original backend node", async () => {
+ const responses = new Map([
+ ["zero", { count: 0 }],
+ ["duplicate", { count: 2 }],
+ ["wrong", { count: 1, resolvedBackendNodeId: 99 }],
+ ["same", { count: 1, resolvedBackendNodeId: 10 }],
+ ]);
+
+ const cdp = {
+ async sendRaw(method, params) {
+ if (method === "Runtime.evaluate") {
+ const key = [...responses.keys()].find((candidate) =>
+ params.expression.includes(`#${candidate}`),
+ );
+ const response = responses.get(key);
+ if (params.returnByValue) {
+ return { result: { value: response.count } };
+ }
+ return {
+ result:
+ response.count === 1
+ ? { objectId: `node:${response.resolvedBackendNodeId}` }
+ : {},
+ };
+ }
+ if (method === "DOM.describeNode") {
+ return {
+ node: {
+ backendNodeId: Number(params.objectId.slice("node:".length)),
+ },
+ };
+ }
+ return {};
+ },
+ };
+
+ for (const [selector, expected] of [
+ ["zero", false],
+ ["duplicate", false],
+ ["wrong", false],
+ ["same", true],
+ ]) {
+ assert.equal(
+ await validateSnapshotLocator(cdp, "session:page", new Map(), {
+ backendNodeId: 10,
+ loc: `css:#${selector}`,
+ }),
+ expected,
+ selector,
+ );
+ }
+});
+
+test("snapshot refs inherit their same-process and OOPIF frame ids", async () => {
+ const refs = [
+ { backendNodeId: 10, role: "button", name: "Top" },
+ { backendNodeId: 20, role: "button", name: "Same process" },
+ { backendNodeId: 30, role: "button", name: "OOPIF" },
+ ];
+ const calls = [];
+ const services = {
+ async cdp(method, params, sessionId) {
+ calls.push([method, params, sessionId]);
+ assert.equal(method, "Accessibility.getFullAXTree");
+ if (params.frameId === "frame-same") {
+ return { nodes: [{ backendDOMNodeId: 20 }] };
+ }
+ if (sessionId === "session:oopif") {
+ return { nodes: [{ backendDOMNodeId: 30 }] };
+ }
+ return { nodes: [] };
+ },
+ };
+
+ await enrichSnapshotRefFrames(
+ services,
+ "session:page",
+ new Map([
+ ["frame-same", "session:page"],
+ ["frame-oopif", "session:oopif"],
+ ]),
+ refs,
+ );
+
+ assert.equal(refs[0].frameId, undefined);
+ assert.equal(refs[1].frameId, "frame-same");
+ assert.equal(refs[2].frameId, "frame-oopif");
+ assert.deepEqual(calls, [
+ ["Accessibility.getFullAXTree", { frameId: "frame-same" }, "session:page"],
+ ["Accessibility.getFullAXTree", {}, "session:oopif"],
+ ]);
+});
diff --git a/package/ego-browser/src/snapshot-result.ts b/package/ego-browser/src/snapshot-result.ts
new file mode 100644
index 0000000..02a30af
--- /dev/null
+++ b/package/ego-browser/src/snapshot-result.ts
@@ -0,0 +1,180 @@
+import { resolveElementObjectId } from "./element-resolver.js";
+import { RefMap } from "./ref-map.js";
+
+type SnapshotRef = {
+ backendNodeId?: number;
+ frameId?: string;
+ loc?: string;
+ name?: string;
+ refId?: number | string;
+ role?: string;
+};
+
+type SnapshotResult = {
+ content?: string;
+ refs?: SnapshotRef[];
+};
+
+type CdpAdapter = {
+ sendRaw(
+ method: string,
+ params?: Record<string, unknown>,
+ sessionId?: string,
+ ): Promise<any>;
+};
+
+type SnapshotServices = {
+ cdp(
+ method: string,
+ params?: Record<string, unknown>,
+ sessionId?: string,
+ ): Promise<any>;
+};
+
+/**
+ * Add frame provenance that older native snapshots omit.
+ *
+ * One AX-tree read per frame is enough to map every unique backend node in the
+ * snapshot. Repeated backend ids cannot be disambiguated without native
+ * `refId`/`frameId` support, so those refs deliberately remain unscoped.
+ */
+export async function enrichSnapshotRefFrames(
+ services: SnapshotServices,
+ pageSessionId: string,
+ iframeSessions: Map<string, string>,
+ refs: SnapshotRef[] = [],
+): Promise<void> {
+ if (!(iframeSessions instanceof Map) || iframeSessions.size === 0) return;
+
+ const refsByBackendNode = new Map<number, SnapshotRef[]>();
+ for (const ref of refs) {
+ if (ref.frameId || !Number.isInteger(ref.backendNodeId)) continue;
+ const matches = refsByBackendNode.get(ref.backendNodeId!) || [];
+ matches.push(ref);
+ refsByBackendNode.set(ref.backendNodeId!, matches);
+ }
+ if (refsByBackendNode.size === 0) return;
+
+ for (const [frameId, frameSessionId] of iframeSessions) {
+ const sameProcess = frameSessionId === pageSessionId;
+ let tree;
+ try {
+ tree = await services.cdp(
+ "Accessibility.getFullAXTree",
+ sameProcess ? { frameId } : {},
+ frameSessionId,
+ );
+ } catch {
+ continue;
+ }
+ for (const node of tree?.nodes || []) {
+ const backendNodeId = node?.backendDOMNodeId;
+ const matches = refsByBackendNode.get(backendNodeId);
+ if (matches?.length !== 1 || matches[0].frameId) continue;
+ matches[0].frameId = frameId;
+ }
+ }
+}
+
+/** Return whether one advertised locator resolves uniquely to its source ref. */
+export async function validateSnapshotLocator(
+ cdp: CdpAdapter,
+ pageSessionId: string,
+ iframeSessions: Map<string, string>,
+ ref: SnapshotRef,
+): Promise<boolean> {
+ if (
+ !Number.isInteger(ref.backendNodeId) ||
+ typeof ref.loc !== "string" ||
+ ref.loc.length === 0 ||
+ ref.loc === "unstable" ||
+ ref.loc === "ambiguous"
+ ) {
+ return false;
+ }
+
+ let resolved:
+ | { objectId: string; sessionId: string; frameId?: string }
+ | undefined;
+ try {
+ resolved = await resolveElementObjectId(
+ cdp,
+ pageSessionId,
+ new RefMap(),
+ ref.loc.startsWith("loc=") ? ref.loc : `loc=${ref.loc}`,
+ iframeSessions,
+ { strict: true, strictGlobal: true },
+ );
+ const described = await cdp.sendRaw(
+ "DOM.describeNode",
+ { objectId: resolved.objectId, depth: 0 },
+ resolved.sessionId,
+ );
+ return described?.node?.backendNodeId === ref.backendNodeId;
+ } catch {
+ // Invalid, missing, and ambiguous native locators are all unsafe to expose.
+ return false;
+ } finally {
+ if (resolved?.objectId) {
+ await cdp
+ .sendRaw(
+ "Runtime.releaseObject",
+ { objectId: resolved.objectId },
+ resolved.sessionId,
+ )
+ .catch(() => {});
+ }
+ }
+}
+
+/** Replace invalid native stable locators while retaining their short-lived refs. */
+export async function sanitizeSnapshotLocators(
+ result: SnapshotResult,
+ validator: (ref: SnapshotRef) => Promise<boolean>,
+): Promise<SnapshotResult> {
+ if (!Array.isArray(result?.refs)) return result;
+
+ for (const ref of result.refs) {
+ const locator = ref?.loc;
+ if (
+ typeof locator !== "string" ||
+ locator === "unstable" ||
+ locator === "ambiguous"
+ ) {
+ continue;
+ }
+ if (await validator(ref)) continue;
+
+ ref.loc = "unstable";
+ const refId = ref.refId ?? ref.backendNodeId;
+ if (typeof result.content === "string" && refId !== undefined) {
+ result.content = result.content.replaceAll(
+ `ref=${refId}, loc=${locator}`,
+ `ref=${refId}, loc=unstable`,
+ );
+ }
+ }
+ return result;
+}
+
+/** Prepare one native snapshot for the Page API without changing its text shape. */
+export async function preparePageSnapshotResult(
+ services: SnapshotServices,
+ pageSessionId: string,
+ iframeSessions: Map<string, string>,
+ result: SnapshotResult,
+): Promise<SnapshotResult> {
+ await enrichSnapshotRefFrames(
+ services,
+ pageSessionId,
+ iframeSessions,
+ result?.refs || [],
+ );
+ const adapter: CdpAdapter = {
+ sendRaw: (method, params = {}, sessionId) =>
+ services.cdp(method, params, sessionId),
+ };
+ return sanitizeSnapshotLocators(result, (ref) =>
+ validateSnapshotLocator(adapter, pageSessionId, iframeSessions, ref),
+ );
+}
diff --git a/package/ego-browser/src/taskspace-e2e.test.mjs b/package/ego-browser/src/taskspace-e2e.test.mjs
index bee6a1d..2688cc6 100644
--- a/package/ego-browser/src/taskspace-e2e.test.mjs
+++ b/package/ego-browser/src/taskspace-e2e.test.mjs
@@ -271,7 +271,7 @@ test("cli e2e exposes the unified helperContext surface (help present, internals
`
cliLog(JSON.stringify({
helpType: typeof help,
- publicHelp: help("TaskSpace.openPage"),
+ publicHelp: help("TaskSpace.newPage"),
legacyHint: help("click"),
newTabType: typeof newTab,
helperContextType: typeof helperContext,
@@ -284,7 +284,7 @@ test("cli e2e exposes the unified helperContext surface (help present, internals
assert.deepEqual(firstJsonLine(result.stdout), {
helpType: "function",
publicHelp:
- "TaskSpace.openPage\n\nOpen and durably label a new Page. Options: as: Permanent Page label. timeout: Maximum duration in milliseconds.\n\nawait task.openPage(url, { as?, timeout? })",
+ "TaskSpace.newPage\n\nCreate and durably label a blank Page.\n\nawait task.newPage()",
legacyHint:
'Legacy helper hidden from default help: click. Use help("legacy", "click").',
newTabType: "undefined",
diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.md
index 9022094..f90bf6d 100644
--- a/skills/ego-browser/SKILL.md
+++ b/skills/ego-browser/SKILL.md
@@ -16,7 +16,8 @@ Run JavaScript through a heredoc:
```bash
ego-browser nodejs <<'EOF'
const task = await taskSpace("inspect example page");
-const page = await task.openPage("https://example.com");
+const page = await task.newPage();
+await page.goto("https://example.com");
console.log({ taskSpaceId: task.spaceId, page: page.label });
console.log(await page.snapshot());
@@ -27,6 +28,9 @@ The heredoc runs in Node.js with the browser APIs preloaded. Use them directly;
run page JavaScript inside `page.evaluate()`. Do not import Playwright or launch
another browser.
+The Node.js runtime uses ESM. When a script needs local files, load built-ins
+with dynamic imports such as `await import("node:fs/promises")`.
+
Ego-browser deliberately exposes a small custom API. It is not Playwright, even
where method names and options look similar. Use only the TaskSpace, Page,
FileChooser, mouse, and keyboard APIs explicitly listed in this Skill. Do not
@@ -62,14 +66,16 @@ use `help("profiles")` for the exact workflow.
Supported TaskSpace API:
- State: `spaceId`, `name`, `ownership`, `page(label)`, `userPage()`
-- Pages: `await task.pages()`, `await task.tabs()`, `openPage(url, { as?, timeout? })`,
+- Pages: `await task.pages()`, `await task.tabs()`, `newPage()`,
`adopt(page, { as? })`, `release(label)`
- Control: `waitForControl(options)`, `handOff()`, `finish()`, `close()`
- Advanced: `cdp(method, params, options)`
Pages receive permanent labels such as `p1`, `p2`, and `p3`. Prefer these labels
-to custom `{ as }` values. A space manages at most eight Pages; close a temporary
-Page or reuse an existing one when the limit is reached.
+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()`.
`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
@@ -97,7 +103,7 @@ them. Supported Page API:
- Navigation and waits: `goto()`, `waitForURL()`, `waitForSelector()`,
`waitForLoadState()`, `waitForFunction()`, `waitForTimeout()`
- Elements: `click()`, `dblclick()`, `hover()`, `dragAndDrop()`, `fill()`,
- `focus()`, `press()`, `scrollBy()`, `setInputFiles()`,
+ `selectOption()`, `focus()`, `press()`, `setInputFiles()`,
`waitForFileChooser()`, `close()`
- Pointer: `mouse.click()`, `move()`, `down()`, `up()`, `wheel()`
- Keyboard: `keyboard.down()`, `up()`, `press()`, `type()`, `insertText()`,
@@ -121,6 +127,7 @@ console.log(await page.snapshot());
await page.fill("@21", "[email protected]");
await page.click("loc=role:button[name='Sign in']");
+await page.selectOption("#country", "nl");
await page.waitForSelector("loc=css:#account-home");
await page.click("text=Save changes");
```
@@ -144,8 +151,9 @@ interactive ancestor or unique editable descendant; `fill()` and
Snapshot node names are accessibility roles. Use a ref now or `loc=...` to find
the element again. After the page changes, take a new snapshot. When a useful
node has no ref, construct a selector from its role, text, or surrounding
-context. CSS searches nested open shadow roots; role locators also search
-frames when the top-level document has no match.
+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.
### Visual pages: screenshot, mouse, and keyboard
@@ -155,6 +163,7 @@ spreadsheets, maps, and other interfaces that lack useful DOM semantics:
```js
const path = await page.screenshot({ path: "/absolute/path/before.png" });
await page.mouse.click(420, 260);
+await page.mouse.wheel(0, 600);
await page.keyboard.paste("hello\tworld");
console.log({ screenshot: path });
```
@@ -254,6 +263,12 @@ const response = await page.fetch("/api/items", {
});
```
+Save binary responses without converting them to text:
+
+```js
+await page.fetch("/image.png", { saveAs: "/absolute/path/image.png" });
+```
+
Use standard Node.js `fetch()` for background requests that do not need Page
browser semantics.
diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.md
index d2b9024..96bd60d 100644
--- a/skills/ego-browser/references/api.md
+++ b/skills/ego-browser/references/api.md
@@ -29,7 +29,7 @@ For an explicit popup wait, arm it before the action: `const popupPromise = page
| `task.userPage()` | — | Return the tab active at the claim/takeover boundary, when one was captured. |
| `await task.pages()` | — | List the managed Page handles in this space. |
| `await task.tabs()` | — | List managed Pages and unmanaged tabs in this space. |
-| `await task.openPage(url, { as?, timeout? })` | `as` — Permanent Page label.<br>`timeout` — Maximum duration in milliseconds. | Open and durably label a new Page. |
+| `await task.newPage()` | — | Create and durably label a blank Page. |
| `await task.adopt(unmanagedPage, { as? })` | `as` — Permanent Page label. | Bring an unmanaged tab under the Page lifecycle. |
| `await task.release(label)` | — | Stop managing an unknown-origin Page without closing it. |
| `await task.waitForControl({ interval?, timeout? })` | `interval` — Polling interval in milliseconds.<br>`timeout` — Maximum duration in milliseconds. | Wait for Agent control without taking it from the user. |
@@ -40,39 +40,39 @@ 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>`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 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 verify the value. |
-| `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.scrollBy(deltaY, { deltaX?, behavior? })` | `deltaX` — Horizontal CSS-pixel delta.<br>`behavior` (auto, instant, smooth) — Scroll behavior. | Scroll this Page by CSS-pixel deltas. |
-| `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. |
+| `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 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. |
## Page.mouse