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): add frame-aware subtree snapshots

JackWang45038fc04101
diff --git a/docs/native-bindings-api.md b/docs/native-bindings-api.md
index 3e9022f..92b6e5e 100644
--- a/docs/native-bindings-api.md
+++ b/docs/native-bindings-api.md
@@ -334,6 +334,11 @@ const snapshot = await ego.snapshot({
console.log(snapshot.content);
console.log(snapshot.refs);
+
+const subtree = await ego.snapshot({
+ scope: 'subtree',
+ root: snapshot.refs[0].backendNodeId,
+});
```
Arguments:
@@ -348,6 +353,10 @@ Supported options:
scope:
'full_page' Capture the full page. This is the default.
'only_within_viewport' Capture only the viewport.
+ 'subtree' Capture the node identified by root and its descendants.
+
+root: number
+ backendNodeId from a previous snapshot ref. Required only for subtree scope.
includeActionMarks: boolean
Include action markers in the textual snapshot.
@@ -362,6 +371,12 @@ maxResultLength: number
Maximum result content length. Zero or omitted means unlimited.
```
+In Ego Lite 0.5.0.19, subtree scope requires launching the browser with
+`--enable-features=SnapshotSubtree`. Do not use `PageSnapshotSubtree`.
+This version matches `root` by `backendNodeId` across all frames, although that
+identifier is only frame-local. If the same value occurs in multiple frames,
+the call fails with an ambiguity error instead of selecting an arbitrary node.
+
Result:
```js
diff --git a/package/ego-browser/README.md b/package/ego-browser/README.md
index aac30a9..28c1386 100644
--- a/package/ego-browser/README.md
+++ b/package/ego-browser/README.md
@@ -90,7 +90,7 @@ existing scripts.
## Design constraints
- 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 })`.
+- Snapshot helpers use the browser runtime contract: `ego.snapshot({ scope, root, includeActionMarks, includeStableLocator })`; the Page API resolves a subtree `root` from a Page-scoped snapshot ref before invoking it.
- Page selectors search the top document first. Input actions search frames
when the top document has no match usable for that action, then require one
usable frame match.
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
index ef53d07..52c3b97 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
@@ -15,6 +15,7 @@ import { pageJavaScriptDialogHandlingCase } from "./page-dialogs.mjs";
import { pageMediaPlaybackCase } from "./page-media-playback.mjs";
import { pageScrolledScreenshotCase } from "./page-screenshot.mjs";
import { pageSnapshotLocatorCase } from "./page-snapshot-locators.mjs";
+import { pageSnapshotSubtreeCase } from "./page-snapshot-subtree.mjs";
import { pageShadowDomCase } from "./page-shadow-dom.mjs";
import { pageTextLocatorCase } from "./page-text-locators.mjs";
import { pageSelectorCompatibilityCase } from "./page-selector-compatibility.mjs";
@@ -103,6 +104,7 @@ export const e2eCases = [
{ name: "Page media playback", body: pageMediaPlaybackCase },
{ name: "Page scrolled screenshot", body: pageScrolledScreenshotCase },
{ name: "Page snapshot locator quality", body: pageSnapshotLocatorCase },
+ { name: "Page snapshot subtree", body: pageSnapshotSubtreeCase },
{ name: "Page open Shadow DOM locators", body: pageShadowDomCase },
{ name: "Page text locators", body: pageTextLocatorCase },
{
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-download.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-download.mjs
index 76bf3ba..7f03832 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-download.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-download.mjs
@@ -217,9 +217,7 @@ export function pagePdfViewerDownloadCase() {
let viewerSnapshot = "";
let viewerToolbar;
while (Date.now() <= viewerDeadline) {
- viewerSnapshot = await preview.snapshot({
- scope: "only_within_viewport",
- });
+ viewerSnapshot = await preview.snapshot({ scope: "full_page" });
viewerToolbar = viewerSnapshot.match(
/ container\\n button "([^"]+)"\\n svg_root\\n button "([^"]+)"\\n svg_root\\n button "([^"]+)"\\n svg_root\\n button "([^"]+)"/
);
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-snapshot-subtree.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-snapshot-subtree.mjs
new file mode 100644
index 0000000..3287cb4
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-snapshot-subtree.mjs
@@ -0,0 +1,401 @@
+export function pageSnapshotSubtreeCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const page = await newPageAt(task, baseUrl + "/?workflow=page-snapshot-subtree");
+
+ // Ego Lite 0.5.0.19 identifies subtree roots by backendNodeId alone. Those
+ // ids are only frame-local, so keep this positive-path fixture single-frame.
+ await page.evaluate(
+ "document.querySelectorAll('iframe').forEach((frame) => frame.remove())"
+ );
+
+ const fullSnapshot = await page.snapshot({ scope: "full_page" });
+ const rootLine = fullSnapshot
+ .split("\\n")
+ .find((line) => line.includes("Increment counter"));
+ const rootMatch = rootLine && rootLine.match(/\\[ref=([0-9]+)/);
+ assert(rootMatch, "full snapshot exposes the subtree root ref");
+ const root = "@" + rootMatch[1];
+
+ const subtree = await page.snapshot({ scope: "subtree", root });
+ assertIncludes(subtree, "Increment counter", "subtree includes its root");
+ assertIncludes(subtree, "Click counter", "subtree includes descendants");
+ assert(
+ !subtree.includes("Helper e2e fixture"),
+ "subtree excludes the page heading sibling"
+ );
+ assert(
+ !subtree.includes("Duplicate action"),
+ "subtree excludes button siblings"
+ );
+
+ await page.click(root);
+ assertEqual(
+ await page.evaluate("window.__fixtureState.clicks"),
+ 1,
+ "a ref returned by the subtree remains actionable"
+ );
+
+ await assertRejects(
+ () => page.snapshot({ scope: "subtree" }),
+ "subtree scope requires root",
+ "subtree rejects a missing root"
+ );
+ await assertRejects(
+ () => page.snapshot({ scope: "full_page", root }),
+ "root is only supported when scope is subtree",
+ "non-subtree scopes reject root"
+ );
+ await assertRejects(
+ () => page.snapshot({ scope: "subtree", root: "css:#click-button" }),
+ "root must be a snapshot ref",
+ "subtree rejects selectors as roots"
+ );
+ await page.goto(baseUrl + "/nav-target");
+ await assertRejects(
+ () => page.snapshot({ scope: "subtree", root }),
+ "ref",
+ "navigation invalidates a stale subtree root ref"
+ );
+
+ await page.close();
+
+ async function assertDeferredIframeSubtree(mode, frameLabel) {
+ const framePage = await newPageAt(
+ task,
+ baseUrl + "/snapshot-subtree-frame-host?mode=" + mode
+ );
+ const actionName = "Run " + frameLabel + " subtree action";
+ const frameMarker = frameLabel + " subtree content";
+
+ await framePage.waitForSelector(
+ 'loc=role:button[name="' + actionName + '"]',
+ { state: "visible" }
+ );
+
+ const initial = await framePage.snapshot();
+ assertIncludes(
+ initial,
+ "Snapshot iframe host",
+ frameLabel + " host is visible in the default snapshot"
+ );
+ assert(
+ !initial.includes(frameMarker),
+ frameLabel + " contents are deferred in the default snapshot"
+ );
+ const iframeLine = initial
+ .split("\\n")
+ .find((line) => line.trimStart().startsWith("iframe "));
+ const iframeMatch = iframeLine && iframeLine.match(/\\[ref=([0-9]+)/);
+ assert(iframeMatch, frameLabel + " iframe exposes a subtree root ref");
+ const iframeRoot = "@" + iframeMatch[1];
+
+ const frameSubtree = await framePage.snapshot({
+ scope: "subtree",
+ root: iframeRoot,
+ });
+ assert(
+ frameSubtree
+ .split("\\n")
+ .some((line) => line.trimStart().startsWith("iframe ")),
+ frameLabel + " subtree retains the iframe root: " + frameSubtree
+ );
+ assertIncludes(
+ frameSubtree,
+ frameMarker,
+ frameLabel + " subtree includes the deferred frame contents"
+ );
+ assert(
+ !frameSubtree.includes("Host sibling marker"),
+ frameLabel + " subtree excludes host siblings"
+ );
+ const actionLine = frameSubtree
+ .split("\\n")
+ .find((line) => line.includes(actionName));
+ const actionMatch = actionLine && actionLine.match(/\\[ref=([0-9]+)/);
+ assert(actionLine, frameLabel + " subtree includes its action");
+ if (mode === "same-origin") {
+ assert(
+ actionMatch,
+ frameLabel + " subtree returns an actionable ref: " + frameSubtree
+ );
+ }
+
+ await framePage.click(
+ actionMatch
+ ? "@" + actionMatch[1]
+ : 'loc=role:button[name="' + actionName + '"]'
+ );
+ assertIncludes(
+ await framePage.snapshot({ scope: "full_page" }),
+ frameLabel + " clicked",
+ frameLabel + " expanded subtree remains actionable"
+ );
+ await framePage.close();
+ }
+
+ await assertDeferredIframeSubtree("same-origin", "Same-origin iframe");
+ await assertDeferredIframeSubtree("cross-origin", "Cross-origin OOPIF");
+
+ const lazyRun = "lazy-" + Date.now();
+ const lazyPage = await newPageAt(
+ task,
+ baseUrl +
+ "/snapshot-subtree-frame-host?mode=same-origin&lazy=true&run=" +
+ lazyRun
+ );
+ const lazyInitial = await lazyPage.snapshot();
+ assert(
+ !lazyInitial.includes("Deferred snapshot subtree frame"),
+ "an offscreen native lazy iframe is absent from the initial viewport snapshot"
+ );
+ assertEqual(
+ (await (await fetch(
+ baseUrl + "/snapshot-subtree-frame-state?run=" + lazyRun
+ )).json()).requests,
+ 0,
+ "the offscreen loading=lazy iframe has not been requested"
+ );
+ await lazyPage.evaluate(
+ "document.querySelector('#snapshot-subtree-frame').scrollIntoView()"
+ );
+ await lazyPage.waitForSelector(
+ 'loc=role:button[name="Run Same-origin iframe subtree action"]',
+ { state: "visible" }
+ );
+ assertEqual(
+ (await (await fetch(
+ baseUrl + "/snapshot-subtree-frame-state?run=" + lazyRun
+ )).json()).requests,
+ 1,
+ "scrolling the lazy iframe into view loads it once"
+ );
+ const lazyVisible = await lazyPage.snapshot();
+ assert(
+ !lazyVisible.includes("Same-origin iframe subtree content"),
+ "the loaded lazy iframe remains collapsed in a viewport snapshot"
+ );
+ const lazyIframeLine = lazyVisible
+ .split("\\n")
+ .find((line) => line.trimStart().startsWith("iframe "));
+ const lazyIframeMatch =
+ lazyIframeLine && lazyIframeLine.match(/\\[ref=([0-9]+)/);
+ assert(lazyIframeMatch, "the visible lazy iframe exposes a subtree root ref");
+ assertIncludes(
+ await lazyPage.snapshot({
+ scope: "subtree",
+ root: "@" + lazyIframeMatch[1],
+ }),
+ "Same-origin iframe subtree content",
+ "the lazy iframe subtree expands after loading"
+ );
+ await lazyPage.close();
+
+ const siblingPage = await newPageAt(
+ task,
+ baseUrl +
+ "/snapshot-subtree-frame-host?mode=same-origin&layout=siblings"
+ );
+ await siblingPage.waitForSelector(
+ 'loc=role:button[name="Run First sibling iframe subtree action"]',
+ { state: "visible" }
+ );
+ await siblingPage.waitForSelector(
+ 'loc=role:button[name="Run Second sibling iframe subtree action"]',
+ { state: "visible" }
+ );
+ const siblingInitial = await siblingPage.snapshot();
+ const siblingRoots = siblingInitial
+ .split("\\n")
+ .filter((line) => line.trimStart().startsWith("iframe "))
+ .map((line) => line.match(/\\[ref=([0-9]+)/))
+ .filter(Boolean)
+ .map((match) => "@" + match[1]);
+ assertEqual(siblingRoots.length, 2, "both sibling iframe roots are visible");
+ assert(
+ !siblingInitial.includes("First sibling iframe subtree content") &&
+ !siblingInitial.includes("Second sibling iframe subtree content"),
+ "the default snapshot collapses both sibling iframe subtrees"
+ );
+ const firstSibling = await siblingPage.snapshot({
+ scope: "subtree",
+ root: siblingRoots[0],
+ });
+ assertIncludes(
+ firstSibling,
+ "First sibling iframe subtree content",
+ "the first sibling root expands only its own frame"
+ );
+ assert(
+ !firstSibling.includes("Second sibling iframe subtree content"),
+ "the first sibling subtree excludes the second sibling"
+ );
+ // No full snapshot in between: a subtree snapshot must keep the other
+ // iframe root from the earlier viewport snapshot usable.
+ const secondSibling = await siblingPage.snapshot({
+ scope: "subtree",
+ root: siblingRoots[1],
+ });
+ assertIncludes(
+ secondSibling,
+ "Second sibling iframe subtree content",
+ "the second sibling root expands only its own frame"
+ );
+ assert(
+ !secondSibling.includes("First sibling iframe subtree content"),
+ "the second sibling subtree excludes the first sibling"
+ );
+ const firstActionLine = firstSibling
+ .split("\\n")
+ .find((line) =>
+ line.includes("Run First sibling iframe subtree action")
+ );
+ const firstActionMatch =
+ firstActionLine && firstActionLine.match(/\\[ref=([0-9]+)/);
+ assert(firstActionMatch, "the first sibling action has a ref");
+ await siblingPage.click("@" + firstActionMatch[1]);
+ const siblingAfterClick = await siblingPage.snapshot();
+ const siblingRootsAfterClick = siblingAfterClick
+ .split("\\n")
+ .filter((line) => line.trimStart().startsWith("iframe "))
+ .map((line) => line.match(/\\[ref=([0-9]+)/))
+ .filter(Boolean)
+ .map((match) => "@" + match[1]);
+ assertEqual(
+ siblingRootsAfterClick.length,
+ 2,
+ "both sibling iframe roots stay visible after the click"
+ );
+ assertIncludes(
+ await siblingPage.snapshot({
+ scope: "subtree",
+ root: siblingRootsAfterClick[0],
+ }),
+ "First sibling iframe clicked",
+ "the first sibling ref acts in the correct frame"
+ );
+ assertIncludes(
+ await siblingPage.snapshot({
+ scope: "subtree",
+ root: siblingRootsAfterClick[1],
+ }),
+ "Second sibling iframe idle",
+ "the second sibling frame remains unchanged"
+ );
+ await siblingPage.close();
+
+ const nestedPage = await newPageAt(
+ task,
+ baseUrl + "/snapshot-subtree-frame-host?mode=same-origin&layout=nested"
+ );
+ await nestedPage.waitForSelector(
+ 'loc=role:button[name="Run Nested inner iframe subtree action"]',
+ { state: "visible" }
+ );
+ const nestedInitial = await nestedPage.snapshot();
+ assert(
+ !nestedInitial.includes("Nested outer iframe subtree content") &&
+ !nestedInitial.includes("Nested inner iframe subtree content"),
+ "the default snapshot collapses the complete nested iframe tree"
+ );
+ const outerLine = nestedInitial
+ .split("\\n")
+ .find((line) => line.trimStart().startsWith("iframe "));
+ const outerMatch = outerLine && outerLine.match(/\\[ref=([0-9]+)/);
+ assert(outerMatch, "the outer iframe exposes a subtree root ref");
+ const outerSubtree = await nestedPage.snapshot({
+ scope: "subtree",
+ root: "@" + outerMatch[1],
+ });
+ assertIncludes(
+ outerSubtree,
+ "Nested outer iframe subtree content",
+ "the outer subtree includes its own content"
+ );
+ assertIncludes(
+ outerSubtree,
+ "Nested inner iframe subtree content",
+ "the outer subtree includes its nested iframe content"
+ );
+ const nestedIframeLines = outerSubtree
+ .split("\\n")
+ .filter((line) => line.trimStart().startsWith("iframe "));
+ const innerMatch =
+ nestedIframeLines[1] && nestedIframeLines[1].match(/\\[ref=([0-9]+)/);
+ assert(innerMatch, "the expanded outer subtree exposes the inner iframe ref");
+ const innerSubtree = await nestedPage.snapshot({
+ scope: "subtree",
+ root: "@" + innerMatch[1],
+ });
+ assertIncludes(
+ innerSubtree,
+ "Nested inner iframe subtree content",
+ "the nested iframe root expands its own content"
+ );
+ assert(
+ !innerSubtree.includes("Nested outer iframe subtree content"),
+ "the nested iframe subtree excludes its outer frame ancestor"
+ );
+ await nestedPage.close();
+
+ const replacedPage = await newPageAt(
+ task,
+ baseUrl + "/snapshot-subtree-frame-host?mode=same-origin"
+ );
+ await replacedPage.waitForSelector(
+ 'loc=role:button[name="Run Same-origin iframe subtree action"]',
+ { state: "visible" }
+ );
+ const beforeReplacement = await replacedPage.snapshot();
+ const oldFrameLine = beforeReplacement
+ .split("\\n")
+ .find((line) => line.trimStart().startsWith("iframe "));
+ const oldFrameMatch =
+ oldFrameLine && oldFrameLine.match(/\\[ref=([0-9]+)/);
+ assert(oldFrameMatch, "the original iframe exposes a root ref");
+ const originalSubtree = await replacedPage.snapshot({
+ scope: "subtree",
+ root: "@" + oldFrameMatch[1],
+ });
+ const oldActionLine = originalSubtree
+ .split("\\n")
+ .find((line) => line.includes("Run Same-origin iframe subtree action"));
+ const oldActionMatch =
+ oldActionLine && oldActionLine.match(/\\[ref=([0-9]+)/);
+ assert(oldActionMatch, "the original iframe action exposes a ref");
+ await replacedPage.evaluate(() => {
+ const previous = document.querySelector("#snapshot-subtree-frame");
+ const replacement = document.createElement("iframe");
+ replacement.id = "snapshot-subtree-frame";
+ replacement.title = "Replacement subtree frame";
+ replacement.src =
+ "/snapshot-subtree-frame-content?mode=same-origin&frame=replacement";
+ previous.replaceWith(replacement);
+ });
+ await replacedPage.waitForSelector(
+ 'loc=role:button[name="Run Replacement iframe subtree action"]',
+ { state: "visible" }
+ );
+ await assertRejects(
+ () => replacedPage.click("@" + oldActionMatch[1]),
+ "Stale ref",
+ "an iframe replacement invalidates its former descendant refs"
+ );
+ const afterReplacement = await replacedPage.snapshot();
+ const replacementLine = afterReplacement
+ .split("\\n")
+ .find((line) => line.trimStart().startsWith("iframe "));
+ const replacementMatch =
+ replacementLine && replacementLine.match(/\\[ref=([0-9]+)/);
+ assert(replacementMatch, "the replacement iframe exposes a fresh root ref");
+ assertIncludes(
+ await replacedPage.snapshot({
+ scope: "subtree",
+ root: "@" + replacementMatch[1],
+ }),
+ "Replacement iframe subtree content",
+ "a fresh snapshot expands the replacement iframe"
+ );
+ await replacedPage.close();
+ `;
+}
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 000ff99..fe93329 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
@@ -261,13 +261,16 @@ export function snapshotWorkflowCase() {
await first.click(firstRef);
assertEqual(await first.evaluate("window.__fixtureState.clicks"), 1, "the first snapshot ref acts on Page A");
assertEqual(await second.evaluate("window.__fixtureState.clicks"), 0, "the Page A ref does not affect Page B");
- await second.click(secondRef);
+ const refreshedSecondRef = refFor(await second.snapshot());
+ assertEqual(refreshedSecondRef, secondRef, "a fresh Page B snapshot can reuse the native ref id");
+ await second.click(refreshedSecondRef);
assertEqual(await second.evaluate("window.__fixtureState.clicks"), 1, "the second snapshot ref acts on Page B");
+ const navigationRef = refFor(await first.snapshot());
await first.goto(baseUrl + "/nav-target?workflow=snapshot-navigation");
await assertRejects(
- () => first.click(firstRef),
- "Unknown ref",
+ () => first.click(navigationRef),
+ "Stale ref",
"navigation invalidates refs from the previous document"
);
diff --git a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
index feb50f0..bc2d8f9 100644
--- a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
@@ -20,6 +20,7 @@ export async function startFixtureServer(taskName) {
new URL("./fixtures/openai-gpt-4-system-card.pdf", import.meta.url),
);
let crossSiteBaseUrl = "";
+ const snapshotFrameRequests = new Map();
const fixtureServer = createServer((req, res) => {
const url = new URL(req.url || "/", "http://127.0.0.1");
if (url.pathname === "/healthz") {
@@ -206,6 +207,126 @@ export async function startFixtureServer(taskName) {
res.end();
return;
}
+ if (url.pathname === "/snapshot-subtree-frame-state") {
+ const run = url.searchParams.get("run") || "";
+ res.writeHead(200, {
+ "content-type": "application/json",
+ "cache-control": "no-store",
+ });
+ res.end(
+ JSON.stringify({ requests: snapshotFrameRequests.get(run) || 0 }),
+ );
+ return;
+ }
+ if (url.pathname === "/snapshot-subtree-frame-content") {
+ const mode =
+ url.searchParams.get("mode") === "cross-origin"
+ ? "cross-origin"
+ : "same-origin";
+ const requestedFrame = url.searchParams.get("frame") || "";
+ const frameLabels = {
+ first: "First sibling iframe",
+ second: "Second sibling iframe",
+ "nested-outer": "Nested outer iframe",
+ "nested-inner": "Nested inner iframe",
+ replacement: "Replacement iframe",
+ };
+ const frameLabel =
+ frameLabels[requestedFrame] ||
+ (mode === "cross-origin" ? "Cross-origin OOPIF" : "Same-origin iframe");
+ const run = url.searchParams.get("run") || "";
+ if (run) {
+ snapshotFrameRequests.set(
+ run,
+ (snapshotFrameRequests.get(run) || 0) + 1,
+ );
+ }
+ const nestedFrame =
+ requestedFrame === "nested-outer"
+ ? `<iframe
+ id="nested-subtree-frame"
+ title="Nested subtree frame"
+ src="/snapshot-subtree-frame-content?mode=same-origin&frame=nested-inner"
+ ></iframe>`
+ : "";
+ res.writeHead(200, {
+ "content-type": "text/html",
+ "cache-control": "no-store",
+ });
+ res.end(`<!doctype html>
+ <html>
+ <head><title>${frameLabel} subtree fixture</title></head>
+ <body>
+ <main>
+ <h1>${frameLabel} subtree content</h1>
+ <button id="subtree-action" type="button" aria-label="Run ${frameLabel} subtree action">
+ Run frame action
+ </button>
+ <p id="subtree-status">${frameLabel} idle</p>
+ ${nestedFrame}
+ </main>
+ <script>
+ document.querySelector("#subtree-action").addEventListener("click", () => {
+ document.querySelector("#subtree-status").textContent =
+ ${JSON.stringify(frameLabel)} + " clicked";
+ });
+ </script>
+ </body>
+ </html>`);
+ return;
+ }
+ if (url.pathname === "/snapshot-subtree-frame-host") {
+ const mode =
+ url.searchParams.get("mode") === "cross-origin"
+ ? "cross-origin"
+ : "same-origin";
+ const layout = ["siblings", "nested"].includes(
+ url.searchParams.get("layout"),
+ )
+ ? url.searchParams.get("layout")
+ : "single";
+ const run = url.searchParams.get("run") || "";
+ const lazy = url.searchParams.get("lazy") === "true";
+ const frameUrl = (frame) => {
+ const origin = mode === "cross-origin" ? crossSiteBaseUrl : "";
+ const params = new URLSearchParams({ mode });
+ if (frame) params.set("frame", frame);
+ if (run) params.set("run", run);
+ return `${origin}/snapshot-subtree-frame-content?${params}`;
+ };
+ const frameMarkup =
+ layout === "siblings"
+ ? `<iframe
+ id="snapshot-subtree-frame-first"
+ title="First sibling subtree frame"
+ src="${frameUrl("first")}"
+ ></iframe>
+ <iframe
+ id="snapshot-subtree-frame-second"
+ title="Second sibling subtree frame"
+ src="${frameUrl("second")}"
+ ></iframe>`
+ : `<iframe
+ id="snapshot-subtree-frame"
+ title="Deferred snapshot subtree frame"
+ ${lazy ? 'loading="lazy"' : ""}
+ src="${frameUrl(layout === "nested" ? "nested-outer" : "")}"
+ ></iframe>`;
+ res.writeHead(200, { "content-type": "text/html" });
+ res.end(`<!doctype html>
+ <html>
+ <head><title>Snapshot iframe host</title></head>
+ <body>
+ <main>
+ <h1>Snapshot iframe host</h1>
+ <p>Host sibling marker</p>
+ ${lazy ? '<div style="height: 12000px">Lazy frame spacer</div>' : ""}
+ ${frameMarkup}
+ </main>
+ </body>
+ </html>`);
+ return;
+ }
if (url.pathname === "/frame.html") {
res.writeHead(200, { "content-type": "text/html" });
res.end(pageHtml("frame", { iframeUrl: null }));
diff --git a/package/ego-browser/src/driver/observe.test.mjs b/package/ego-browser/src/driver/observe.test.mjs
index 116da01..af5a7df 100644
--- a/package/ego-browser/src/driver/observe.test.mjs
+++ b/package/ego-browser/src/driver/observe.test.mjs
@@ -8,7 +8,11 @@ import {
browserCdp,
invalidateSession,
} from "../../dist/src/browser-runtime.js";
-import { captureScreenshot, snapshot } from "../../dist/src/driver/observe.js";
+import {
+ captureScreenshot,
+ snapshot,
+ snapshotText,
+} from "../../dist/src/driver/observe.js";
import { setOverrides } from "../../dist/src/state.js";
function withCdpRuntime(fn) {
@@ -104,6 +108,35 @@ test("snapshot compacts the native result before returning it", async () => {
}
});
+test("snapshotText forwards a subtree root to the native snapshot", async () => {
+ const previous = globalThis.ego;
+ const calls = [];
+ globalThis.ego = {
+ async snapshot(options) {
+ calls.push(options);
+ return { content: "button [ref=21]", refs: [] };
+ },
+ };
+
+ try {
+ assert.equal(
+ await snapshotText({ scope: "subtree", root: 21 }),
+ "button [ref=21]",
+ );
+ assert.deepEqual(calls, [
+ {
+ scope: "subtree",
+ root: 21,
+ includeActionMarks: true,
+ includeStableLocator: true,
+ },
+ ]);
+ } finally {
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ }
+});
+
test("captureScreenshot skips page metric JavaScript while a native dialog is pending", async () => {
const writes = [];
const restore = setOverrides({
diff --git a/package/ego-browser/src/driver/observe.ts b/package/ego-browser/src/driver/observe.ts
index b2cbf62..41556c7 100644
--- a/package/ego-browser/src/driver/observe.ts
+++ b/package/ego-browser/src/driver/observe.ts
@@ -22,7 +22,8 @@ import {
} from "../ref-state.js";
export type SnapshotOptions = {
- scope?: "only_within_viewport" | "full_page";
+ scope?: "only_within_viewport" | "full_page" | "subtree";
+ root?: number;
includeActionMarks?: boolean;
includeStableLocator?: boolean;
};
@@ -64,12 +65,13 @@ export const snapshotRaw = snapshot;
/**
* Return snapshot content with agent-friendly defaults.
- * @param {{scope?: "only_within_viewport"|"full_page", includeActionMarks?: boolean, includeStableLocator?: boolean}} [options]
+ * @param {{scope?: "only_within_viewport"|"full_page"|"subtree", root?: number, includeActionMarks?: boolean, includeStableLocator?: boolean}} [options]
* @returns {Promise<string>}
*/
export async function snapshotText(options: SnapshotOptions = {}) {
const result = await snapshot({
scope: options.scope ?? "full_page",
+ ...(options.root === undefined ? {} : { root: options.root }),
includeActionMarks: options.includeActionMarks ?? true,
includeStableLocator: options.includeStableLocator ?? true,
});
diff --git a/package/ego-browser/src/element-resolver.test.mjs b/package/ego-browser/src/element-resolver.test.mjs
index b32f9d2..da6708d 100644
--- a/package/ego-browser/src/element-resolver.test.mjs
+++ b/package/ego-browser/src/element-resolver.test.mjs
@@ -95,6 +95,200 @@ test("stale backend node still falls back to role/name lookup", async () => {
);
});
+test("iframe refs recover frame provenance before resolving a colliding backend node", async () => {
+ const refMap = new RefMap();
+ refMap.addWithFrame(
+ "4729",
+ 21,
+ "option",
+ "Upload",
+ undefined,
+ undefined,
+ "unknown",
+ );
+ const cdp = new FakeCDP(async (method, params, sessionId) => {
+ if (method === "Accessibility.getFullAXTree") {
+ if (sessionId === "session:picker") {
+ return {
+ nodes: [
+ {
+ role: { value: "option" },
+ name: { value: "Upload" },
+ backendDOMNodeId: 21,
+ },
+ ],
+ };
+ }
+ if (sessionId === "session:page" && !params.frameId) {
+ return {
+ nodes: [
+ {
+ role: { value: "button" },
+ name: { value: "Close" },
+ backendDOMNodeId: 21,
+ },
+ ],
+ };
+ }
+ return { nodes: [] };
+ }
+ if (method === "DOM.resolveNode") {
+ return {
+ object: {
+ objectId:
+ sessionId === "session:picker"
+ ? "picker-upload-option"
+ : "wrong-page-node",
+ },
+ };
+ }
+ return {};
+ });
+
+ const resolved = await resolveElementObjectId(
+ cdp,
+ "session:page",
+ refMap,
+ "@4729",
+ new Map([
+ ["frame:picker", "session:picker"],
+ ["frame:other", "session:other"],
+ ]),
+ );
+
+ assert.deepEqual(resolved, {
+ objectId: "picker-upload-option",
+ sessionId: "session:picker",
+ frameId: "frame:picker",
+ });
+});
+
+test("main-page ref provenance skips frame recovery", async () => {
+ const refMap = new RefMap();
+ refMap.addWithFrame(
+ "73",
+ 100,
+ "button",
+ "Save",
+ undefined,
+ undefined,
+ "page",
+ );
+ const cdp = new FakeCDP(async (method, _params, sessionId) => {
+ if (method === "Accessibility.getFullAXTree") {
+ throw new Error("main-page refs must not scan frame AX trees");
+ }
+ if (method === "DOM.resolveNode") {
+ assert.equal(sessionId, "session:page");
+ return { object: { objectId: "page-save-button" } };
+ }
+ return {};
+ });
+
+ assert.deepEqual(
+ await resolveElementObjectId(
+ cdp,
+ "session:page",
+ refMap,
+ "@73",
+ new Map([["frame:detached", "session:detached"]]),
+ ),
+ { objectId: "page-save-button", sessionId: "session:page" },
+ );
+});
+
+test("unknown frame provenance recovers by backend id after the accessible name changes", async () => {
+ const refMap = new RefMap();
+ refMap.addWithFrame(
+ "73",
+ 100,
+ "button",
+ "Save",
+ undefined,
+ undefined,
+ "unknown",
+ );
+ const cdp = new FakeCDP(async (method, _params, sessionId) => {
+ if (method === "Accessibility.getFullAXTree") {
+ return sessionId === "session:frame"
+ ? {
+ nodes: [
+ {
+ role: { value: "button" },
+ name: { value: "Saving…" },
+ backendDOMNodeId: 100,
+ },
+ ],
+ }
+ : { nodes: [] };
+ }
+ if (method === "DOM.resolveNode") {
+ assert.equal(sessionId, "session:frame");
+ return { object: { objectId: "frame-save-button" } };
+ }
+ return {};
+ });
+
+ assert.deepEqual(
+ await resolveElementObjectId(
+ cdp,
+ "session:page",
+ refMap,
+ "@73",
+ new Map([["frame:child", "session:frame"]]),
+ ),
+ {
+ objectId: "frame-save-button",
+ sessionId: "session:frame",
+ frameId: "frame:child",
+ },
+ );
+});
+
+test("unknown frame provenance falls back to the main document when no frame owns the node", async () => {
+ const refMap = new RefMap();
+ refMap.addWithFrame(
+ "74",
+ 100,
+ "button",
+ "Save",
+ undefined,
+ undefined,
+ "unknown",
+ );
+ const cdp = new FakeCDP(async (method, _params, sessionId) => {
+ if (method === "Accessibility.getFullAXTree") {
+ return sessionId === "session:page"
+ ? {
+ nodes: [
+ {
+ role: { value: "button" },
+ name: { value: "Save" },
+ backendDOMNodeId: 100,
+ },
+ ],
+ }
+ : { nodes: [] };
+ }
+ if (method === "DOM.resolveNode") {
+ assert.equal(sessionId, "session:page");
+ return { object: { objectId: "page-save-button" } };
+ }
+ return {};
+ });
+
+ assert.deepEqual(
+ await resolveElementObjectId(
+ cdp,
+ "session:page",
+ refMap,
+ "@74",
+ new Map([["frame:child", "session:frame"]]),
+ ),
+ { objectId: "page-save-button", sessionId: "session:page" },
+ );
+});
+
test("role locator with degenerate box model throws transient", async () => {
const cdp = new FakeCDP(async (method) => {
if (method === "Accessibility.getFullAXTree") {
@@ -1067,3 +1261,96 @@ test("strict global role validation rejects a hidden duplicate", async () => {
},
);
});
+
+test("a stale ref refuses an ambiguous role/name recovery", async () => {
+ // The ref points at a row that left the DOM. Role and name are all that is
+ // left to identify it, and they no longer single one element out, so the
+ // recovery must fail instead of acting on whichever row comes first.
+ const refMap = new RefMap();
+ refMap.add("23", 13, "button", "Delete");
+ const cdp = new FakeCDP(async (method, params) => {
+ if (method === "DOM.resolveNode") {
+ if (params.backendNodeId === 13) {
+ throw new Error("Could not find node with given id");
+ }
+ return { object: { objectId: `obj-${params.backendNodeId}` } };
+ }
+ if (method === "Accessibility.getFullAXTree") {
+ return {
+ nodes: [
+ {
+ role: { value: "button" },
+ name: { value: "Delete" },
+ backendDOMNodeId: 11,
+ },
+ {
+ role: { value: "button" },
+ name: { value: "Delete" },
+ backendDOMNodeId: 12,
+ },
+ ],
+ };
+ }
+ return {};
+ });
+
+ const error = await resolveElementObjectId(
+ cdp,
+ "session:page",
+ refMap,
+ "@23",
+ new Map(),
+ { strict: true },
+ ).then(
+ () => undefined,
+ (thrown) => thrown,
+ );
+
+ assert.ok(error instanceof ElementResolutionError);
+ assert.equal(error.kind, "permanent");
+ assert.match(error.message, /matched 2 elements/);
+ assert.ok(
+ !cdp.calls.some(
+ ([method, params]) =>
+ method === "DOM.resolveNode" && params.backendNodeId !== 13,
+ ),
+ "an ambiguous recovery must not resolve some other node",
+ );
+});
+
+test("a stale ref still recovers when role and name identify one element", async () => {
+ // The legitimate case the fallback exists for: a re-render replaced the node
+ // but exactly one element still carries that role and name.
+ const refMap = new RefMap();
+ refMap.add("23", 13, "button", "Save");
+ const cdp = new FakeCDP(async (method, params) => {
+ if (method === "DOM.resolveNode") {
+ if (params.backendNodeId === 13) {
+ throw new Error("Could not find node with given id");
+ }
+ return { object: { objectId: `obj-${params.backendNodeId}` } };
+ }
+ if (method === "Accessibility.getFullAXTree") {
+ return {
+ nodes: [
+ {
+ role: { value: "button" },
+ name: { value: "Save" },
+ backendDOMNodeId: 99,
+ },
+ ],
+ };
+ }
+ return {};
+ });
+
+ const resolved = await resolveElementObjectId(
+ cdp,
+ "session:page",
+ refMap,
+ "@23",
+ new Map(),
+ { strict: true },
+ );
+ assert.equal(resolved.objectId, "obj-99");
+});
diff --git a/package/ego-browser/src/element-resolver.ts b/package/ego-browser/src/element-resolver.ts
index 737dcca..4aff124 100644
--- a/package/ego-browser/src/element-resolver.ts
+++ b/package/ego-browser/src/element-resolver.ts
@@ -151,6 +151,15 @@ export async function resolveElementObjectId(
if (!entry) {
throw new ElementResolutionError(`Unknown ref: ${refId}`, "transient");
}
+ if (entry.frameProvenance === "unknown") {
+ return resolveRefObjectIdWithRecoveredFrame(
+ cdp,
+ sessionId,
+ iframeSessions,
+ refId,
+ entry,
+ );
+ }
const effectiveSessionId = resolveFrameSession(
entry.frameId,
sessionId,
@@ -254,6 +263,134 @@ export async function resolveElementObjectId(
);
}
+async function resolveRefObjectIdWithRecoveredFrame(
+ cdp,
+ sessionId: string,
+ iframeSessions,
+ refId: string,
+ entry,
+): Promise<{ objectId: string; sessionId: string; frameId?: string }> {
+ const allContexts = pageContexts(sessionId, iframeSessions);
+ const frameContexts = allContexts.slice(1);
+ // Unknown provenance means the snapshot placed this ref under an iframe, so
+ // frames are searched first. The main document remains a fallback in case
+ // the snapshot text misattributed a page-owned node to a frame.
+ let matches = await collectBackendNodeMatches(
+ cdp,
+ frameContexts,
+ entry.backendNodeId,
+ );
+ if (matches.size === 0) {
+ matches = await collectBackendNodeMatches(
+ cdp,
+ allContexts.slice(0, 1),
+ entry.backendNodeId,
+ );
+ }
+
+ let match;
+ if (matches.size === 1) {
+ match = [...matches.values()][0];
+ } else if (matches.size > 1) {
+ const semanticMatches = [...matches.values()].filter(
+ (candidate) =>
+ candidate.role === normalizeRole(entry.role) &&
+ candidate.name === entry.name,
+ );
+ if (semanticMatches.length === 1) {
+ match = semanticMatches[0];
+ } else {
+ throw new ElementResolutionError(
+ `Ref @${refId} matched ${matches.size} frame contexts because its frame provenance is missing`,
+ "permanent",
+ );
+ }
+ } else {
+ // strictGlobal resolves before findUniqueRoleMatch consults actionability,
+ // so passing it here would only imply a filter that never runs. Ambiguity
+ // across the whole page is the answer this recovery path wants anyway.
+ match = await findUniqueRoleMatch(
+ cdp,
+ allContexts,
+ entry.role,
+ entry.name,
+ `ref @${refId}`,
+ { strictGlobal: true },
+ );
+ }
+
+ const result = await send(
+ cdp,
+ "DOM.resolveNode",
+ {
+ backendNodeId: match.backendNodeId,
+ objectGroup: "ego-browser",
+ },
+ match.sessionId,
+ );
+ const objectId = result.object?.objectId;
+ if (!objectId) {
+ throw new ElementResolutionError(
+ `No objectId for ref @${refId}`,
+ "permanent",
+ );
+ }
+ const frameId = match.frameId || match.ownerFrameId;
+ return {
+ objectId,
+ sessionId: match.sessionId,
+ ...(frameId ? { frameId } : {}),
+ };
+}
+
+type BackendNodeMatch = {
+ backendNodeId: number;
+ sessionId: string;
+ frameId?: string;
+ role: string;
+ name: string;
+};
+
+async function collectBackendNodeMatches(
+ cdp,
+ contexts: PageRuntimeContext[],
+ backendNodeId: number,
+): Promise<Map<string, BackendNodeMatch>> {
+ const matches = new Map<string, BackendNodeMatch>();
+ if (contexts.length === 0) return matches;
+ const trees = await Promise.allSettled(
+ contexts.map(async (context) => ({
+ context,
+ result: await send(
+ cdp,
+ "Accessibility.getFullAXTree",
+ context.frameId ? { frameId: context.frameId } : {},
+ context.sessionId,
+ ),
+ })),
+ );
+ for (const tree of trees) {
+ if (tree.status !== "fulfilled") continue;
+ const { context, result } = tree.value;
+ for (const node of result.nodes || []) {
+ if (node.ignored || node.backendDOMNodeId !== backendNodeId) continue;
+ const frameId = context.ownerFrameId || context.frameId;
+ const key = `${context.sessionId}\u0000${node.backendDOMNodeId}`;
+ const existing = matches.get(key);
+ if (!existing || (!existing.frameId && frameId)) {
+ matches.set(key, {
+ backendNodeId: node.backendDOMNodeId,
+ sessionId: context.sessionId,
+ role: normalizeRole(extractAxString(node.role)),
+ name: extractAxString(node.name),
+ ...(frameId ? { frameId } : {}),
+ });
+ }
+ }
+ }
+ return matches;
+}
+
/**
* Validate many native snapshot locators together. DOM locator counts are
* queried once per execution context, matching nodes are described in
@@ -1447,36 +1584,37 @@ async function findBackendNodeIdByRoleName(
params,
effectiveSessionId,
);
- const nthIndex = nth ?? 0;
- let matchCount = 0;
- for (const node of result.nodes || []) {
- if (node.ignored) {
- continue;
- }
- if (
- normalizeRole(extractAxString(node.role)) !== normalizeRole(role) ||
- extractAxString(node.name) !== name
- ) {
- continue;
- }
- if (matchCount === nthIndex) {
- if (
- node.backendDOMNodeId === undefined ||
- node.backendDOMNodeId === null
- ) {
- throw new ElementResolutionError(
- `AX node has no backendDOMNodeId for role=${role} name=${name}`,
- "permanent",
- );
- }
- return node.backendDOMNodeId;
- }
- matchCount += 1;
- }
- throw new ElementResolutionError(
- `Could not locate element with role=${role} name=${name}`,
- "transient",
+ const matches = (result.nodes || []).filter(
+ (node) =>
+ !node.ignored &&
+ normalizeRole(extractAxString(node.role)) === normalizeRole(role) &&
+ extractAxString(node.name) === name,
);
+ // This is a recovery path: the ref's backend node is gone, so role and name
+ // are the only identity left. They do not distinguish repeated labels, so an
+ // ambiguous result must fail loudly instead of silently acting on whichever
+ // node happens to come first. A ref that recorded an explicit nth already
+ // carries the disambiguator and keeps indexing.
+ if (nth === undefined && matches.length > 1) {
+ throw new ElementResolutionError(
+ `Stale ref for role=${role} name=${name} matched ${matches.length} elements after its node was replaced; take a new snapshot`,
+ "permanent",
+ );
+ }
+ const node = matches[nth ?? 0];
+ if (!node) {
+ throw new ElementResolutionError(
+ `Could not locate element with role=${role} name=${name}`,
+ "transient",
+ );
+ }
+ if (node.backendDOMNodeId === undefined || node.backendDOMNodeId === null) {
+ throw new ElementResolutionError(
+ `AX node has no backendDOMNodeId for role=${role} name=${name}`,
+ "permanent",
+ );
+ }
+ return node.backendDOMNodeId;
}
async function findUniqueBackendNodeIdByRoleName(cdp, sessionId, role, name) {
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 962d84c..a6d92c7 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -2015,6 +2015,34 @@ test("snapshot defaults to the viewport, reports its source, and validates optio
includeStableLocator: true,
});
+ assert.match(
+ await page.snapshot({ scope: "subtree", root: "@21" }),
+ /snapshot:https:\/\/example\.test\/before/,
+ );
+ assert.deepEqual(fixture.snapshotOptions.at(-1), {
+ scope: "subtree",
+ root: 21,
+ includeActionMarks: true,
+ includeStableLocator: true,
+ });
+
+ await assert.rejects(
+ () => page.snapshot({ scope: "subtree" }),
+ /page\.snapshot subtree scope requires root to be a snapshot ref such as @21/,
+ );
+ await assert.rejects(
+ () => page.snapshot({ scope: "full_page", root: "@21" }),
+ /page\.snapshot root is only supported when scope is subtree/,
+ );
+ await assert.rejects(
+ () => page.snapshot({ scope: "subtree", root: "css:#target" }),
+ /page\.snapshot root must be a snapshot ref such as @21/,
+ );
+ await assert.rejects(
+ () => page.snapshot({ scope: "subtree", root: "@999" }),
+ /Unknown ref: @999/,
+ );
+
await assert.rejects(
() => page.snapshot({ diff: true }),
/page\.snapshot received unknown option: diff/,
@@ -2022,6 +2050,213 @@ test("snapshot defaults to the viewport, reports its source, and validates optio
});
});
+test("a viewport snapshot preserves previously registered deferred iframe refs", async () => {
+ await withFixture(async (fixture) => {
+ const snapshotFixture = async () => ({
+ content: [
+ "root",
+ ' heading "Host"',
+ " iframe [ref=11]",
+ " root",
+ ' button "Hidden frame action" [ref=21]',
+ ].join("\n"),
+ refs: [
+ { refId: 11, backendNodeId: 11, role: "iframe" },
+ { refId: 21, backendNodeId: 21, role: "button" },
+ ],
+ });
+ const task = taskForRound(fixture, "round-a", {
+ snapshot: snapshotFixture,
+ });
+ const page = await openTestPage(task, "https://example.test/iframe-host");
+ await page.snapshot({ scope: "full_page" });
+ assert.equal(
+ fixture.services.pageRefs.forTarget(page.targetId).get("21")
+ .backendNodeId,
+ 21,
+ "the full snapshot initially advertises the iframe descendant",
+ );
+
+ const snapshot = await page.snapshot();
+
+ assert.match(snapshot, /iframe \[ref=11\]/);
+ assert.doesNotMatch(snapshot, /Hidden frame action/);
+ assert.equal(
+ fixture.services.pageRefs.forTarget(page.targetId).get("11")
+ .backendNodeId,
+ 11,
+ );
+ assert.equal(
+ fixture.services.pageRefs.forTarget(page.targetId).get("21")
+ .backendNodeId,
+ 21,
+ "a partial viewport snapshot must not invalidate an omitted ref",
+ );
+ assert.equal(
+ fixture.services.pageRefs.isInvalidated(page.targetId, "21"),
+ false,
+ );
+ });
+});
+
+test("a subtree snapshot preserves refs outside the observed subtree", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a", {
+ async snapshot(options) {
+ if (options.scope === "full_page") {
+ return {
+ content: [
+ "root",
+ ' button "First" [ref=21]',
+ ' button "Second" [ref=22]',
+ ].join("\n"),
+ refs: [
+ { refId: 21, backendNodeId: 21, role: "button", name: "First" },
+ { refId: 22, backendNodeId: 22, role: "button", name: "Second" },
+ ],
+ };
+ }
+ return {
+ content: ['button "First" [ref=21]'].join("\n"),
+ refs: [
+ { refId: 21, backendNodeId: 21, role: "button", name: "First" },
+ ],
+ };
+ },
+ });
+ const page = await openTestPage(task, "https://example.test/two-actions");
+ await page.snapshot({ scope: "full_page" });
+
+ await page.snapshot({ scope: "subtree", root: "@21" });
+
+ assert.equal(
+ fixture.services.pageRefs.forTarget(page.targetId).get("22")
+ .backendNodeId,
+ 22,
+ );
+ assert.equal(
+ fixture.services.pageRefs.isInvalidated(page.targetId, "22"),
+ false,
+ );
+ });
+});
+
+test("a subtree snapshot inherits the root ref frame provenance", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a", {
+ async ensureFrameSessions() {
+ return new Map([["frame-child", "session:target-1"]]);
+ },
+ async snapshot(options) {
+ if (options.scope === "full_page") {
+ return {
+ content: [
+ "root",
+ " iframe [ref=11]",
+ " root",
+ ' button "Frame root" [ref=21]',
+ ].join("\n"),
+ refs: [
+ { refId: 11, backendNodeId: 11, role: "iframe" },
+ {
+ refId: 21,
+ backendNodeId: 21,
+ role: "button",
+ name: "Frame root",
+ },
+ ],
+ };
+ }
+ return {
+ content: [
+ 'button "Frame root" [ref=21]',
+ ' link "Frame child" [ref=22]',
+ ].join("\n"),
+ refs: [
+ {
+ refId: 21,
+ backendNodeId: 21,
+ role: "button",
+ name: "Frame root",
+ },
+ {
+ refId: 22,
+ backendNodeId: 22,
+ role: "link",
+ name: "Frame child",
+ },
+ ],
+ };
+ },
+ });
+ const page = await openTestPage(task, "https://example.test/frame");
+ await page.snapshot({ scope: "full_page" });
+
+ await page.snapshot({ scope: "subtree", root: "@21" });
+
+ assert.deepEqual(
+ fixture.services.pageRefs.forTarget(page.targetId).get("22"),
+ {
+ backendNodeId: 22,
+ role: "link",
+ name: "Frame child",
+ nth: undefined,
+ frameId: "frame-child",
+ frameProvenance: "frame",
+ },
+ );
+ });
+});
+
+test("Page evaluate makes prior snapshot refs stale until a new snapshot", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/iframe-host");
+ await page.snapshot({ scope: "full_page" });
+ await page.evaluate("document.body.replaceChildren()");
+ const snapshotsBefore = fixture.calls.filter(
+ ([kind]) => kind === "snapshot",
+ ).length;
+
+ await assert.rejects(
+ () => page.click("@21"),
+ /Stale ref: @21; take a new snapshot/,
+ );
+ assert.equal(
+ fixture.calls.filter(([kind]) => kind === "snapshot").length,
+ snapshotsBefore,
+ "a stale ref must not be silently remapped by an automatic snapshot",
+ );
+
+ await page.snapshot({ scope: "full_page" });
+ await page.click("@21");
+ });
+});
+
+test("subtree snapshot resolves its root in the addressed Page", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const first = await openTestPage(task, "https://example.test/first");
+ const second = await openTestPage(task, "https://example.test/second");
+
+ await first.snapshot();
+ await second.snapshot();
+ assert.equal(fixture.activeTarget(), "target-2");
+
+ assert.match(
+ await first.snapshot({ scope: "subtree", root: "ref=21" }),
+ /\[p1 .*space "research"\(7\).*\]\nsnapshot:https:\/\/example\.test\/first/,
+ );
+ assert.equal(fixture.activeTarget(), "target-1");
+ assert.deepEqual(fixture.snapshotOptions.at(-1), {
+ scope: "subtree",
+ root: 21,
+ includeActionMarks: true,
+ includeStableLocator: true,
+ });
+ });
+});
+
test("metadata reads stay target-scoped while evaluate and screenshot activate their Page", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
@@ -2673,7 +2908,7 @@ test("a no-dialog response keeps current snapshot refs", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
const page = await openTestPage(task, "https://example.test/dialog");
- await page.snapshot();
+ await page.snapshot({ scope: "full_page" });
assert.equal(
fixture.services.pageRefs.forTarget(page.targetId).get("21")
diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.ts
index 402b1f8..70d9db0 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -96,7 +96,11 @@ import {
type PageOrigin,
} from "./page-ledger.js";
import { PageRefRegistry } from "./page-ref-registry.js";
-import { preparePageSnapshotResult } from "./snapshot-result.js";
+import {
+ deferIframeSnapshotSubtrees,
+ preparePageSnapshotResult,
+ retainSnapshotRefsInContent,
+} from "./snapshot-result.js";
import {
clearSpacePageNotices,
forgetPageNotice,
@@ -145,7 +149,9 @@ type PageGotoOptions = {
type PageReloadOptions = Pick<PageGotoOptions, "timeout" | "waitUntil">;
-type PageSnapshotOptions = SnapshotOptions;
+type PageSnapshotOptions = Omit<SnapshotOptions, "root"> & {
+ root?: string;
+};
type PageScreenshotOptions = Omit<CaptureScreenshotOptions, "full"> & {
path?: string;
@@ -1582,15 +1588,72 @@ class Page {
async snapshot(options: PageSnapshotOptions = {}): Promise<string> {
validatePublicApiOptions("Page.snapshot", options);
+ const rootRefId =
+ options.scope === "subtree" && options.root !== undefined
+ ? parseRef(options.root)
+ : undefined;
+ if (options.scope === "subtree" && options.root === undefined) {
+ throw pageSnapshotOptionsError(
+ "page.snapshot subtree scope requires root to be a snapshot ref such as @21",
+ );
+ }
+ if (options.scope !== "subtree" && options.root !== undefined) {
+ throw pageSnapshotOptionsError(
+ "page.snapshot root is only supported when scope is subtree",
+ );
+ }
+ if (options.root !== undefined && !rootRefId) {
+ throw pageSnapshotOptionsError(
+ "page.snapshot root must be a snapshot ref such as @21",
+ );
+ }
const page = await this.#resolve();
return this.#services.gate.withPage(page, async ({ sessionId }) => {
await this.#activate(page.targetId);
+ let root: number | undefined;
+ let rootContext:
+ | {
+ frameId?: string;
+ frameProvenance?: "page" | "frame" | "unknown";
+ }
+ | undefined;
+ if (rootRefId) {
+ const refs = await this.#refMapForAction(
+ page,
+ sessionId,
+ options.root!,
+ );
+ const entry = refs.get(rootRefId);
+ if (!entry) {
+ throw new ElementResolutionError(
+ `Unknown ref: ${options.root}`,
+ "permanent",
+ );
+ }
+ root = entry.backendNodeId;
+ rootContext = {
+ ...(entry.frameId ? { frameId: entry.frameId } : {}),
+ ...(entry.frameProvenance
+ ? { frameProvenance: entry.frameProvenance }
+ : {}),
+ };
+ }
+ const { root: _root, ...snapshotOptions } = options;
+ const snapshotScope = options.scope ?? "only_within_viewport";
const result = await this.#services.snapshot({
- ...options,
- scope: options.scope ?? "only_within_viewport",
+ ...snapshotOptions,
+ ...(root === undefined ? {} : { root }),
+ scope: snapshotScope,
includeActionMarks: options.includeActionMarks ?? true,
includeStableLocator: options.includeStableLocator ?? true,
});
+ if (
+ snapshotScope === "only_within_viewport" &&
+ typeof result?.content === "string"
+ ) {
+ result.content = deferIframeSnapshotSubtrees(result.content);
+ retainSnapshotRefsInContent(result);
+ }
const iframeSessions =
Array.isArray(result?.refs) && result.refs.length > 0
? await this.#services.ensureFrameSessions(page.targetId)
@@ -1600,8 +1663,13 @@ class Page {
sessionId,
iframeSessions,
result,
+ rootContext,
);
- this.#services.pageRefs.replace(page.targetId, result?.refs || []);
+ if (snapshotScope === "full_page") {
+ this.#services.pageRefs.replace(page.targetId, result?.refs || []);
+ } else {
+ this.#services.pageRefs.merge(page.targetId, result?.refs || []);
+ }
const content = result?.content || "";
const header = await this.#snapshotHeader(page);
return `${header}\n${content}`;
@@ -1889,7 +1957,7 @@ class Page {
} finally {
// The predicate may mutate the DOM, so snapshot refs are no longer
// guaranteed to identify the same elements.
- this.#services.pageRefs.clear(page.targetId);
+ this.#services.pageRefs.invalidate(page.targetId);
}
throw waitForFunctionTimeoutError(
this.spaceId,
@@ -1962,7 +2030,7 @@ class Page {
} finally {
// Raw CDP can navigate or mutate the document, so existing refs are no
// longer safe even when the command looked observational.
- this.#services.pageRefs.clear(page.targetId);
+ this.#services.pageRefs.invalidate(page.targetId);
}
});
}
@@ -2001,7 +2069,7 @@ class Page {
try {
await waitForLoadStateInPage(this.#services, sessionId, state, options);
} finally {
- this.#services.pageRefs.clear(page.targetId);
+ this.#services.pageRefs.invalidate(page.targetId);
}
});
}
@@ -2409,7 +2477,7 @@ class Page {
throw error;
}
} finally {
- if (activate) this.#services.pageRefs.clear(page.targetId);
+ if (activate) this.#services.pageRefs.invalidate(page.targetId);
}
});
}
@@ -2507,7 +2575,7 @@ class Page {
);
// A handled dialog resumes its callback and may mutate the DOM. A
// no-dialog response leaves the page untouched, so its refs stay valid.
- this.#services.pageRefs.clear(page.targetId);
+ this.#services.pageRefs.invalidate(page.targetId);
return true;
} catch (error) {
if (isNoJavaScriptDialogError(error)) return false;
@@ -2525,7 +2593,7 @@ class Page {
try {
return await operation(sessionId);
} finally {
- this.#services.pageRefs.clear(page.targetId);
+ this.#services.pageRefs.invalidate(page.targetId);
}
});
}
@@ -2617,7 +2685,7 @@ class Page {
};
} finally {
await fileChooserGuard?.dispose();
- this.#services.pageRefs.clear(page.targetId);
+ this.#services.pageRefs.invalidate(page.targetId);
}
});
}
@@ -2627,6 +2695,18 @@ class Page {
sessionId: string,
...selectors: string[]
): Promise<RefMap> {
+ for (const selector of selectors) {
+ const refId = parseRef(selector);
+ if (
+ refId &&
+ this.#services.pageRefs.isInvalidated(page.targetId, refId)
+ ) {
+ throw new ElementResolutionError(
+ `Stale ref: @${refId}; take a new snapshot`,
+ "permanent",
+ );
+ }
+ }
let refs = this.#services.pageRefs.forTarget(page.targetId);
const missingRef = selectors.some((selector) => {
const refId = parseRef(selector);
@@ -2679,6 +2759,11 @@ class Page {
}
}
+function pageSnapshotOptionsError(message: string): TypeError {
+ const signature = publicApiEntry("Page.snapshot")?.signature;
+ return new TypeError(`${message}. Expected: ${signature}`);
+}
+
function snapshotSourceHeader(input: {
currentLabel: string;
currentTargetId: string;
diff --git a/package/ego-browser/src/page-ref-registry.test.mjs b/package/ego-browser/src/page-ref-registry.test.mjs
index 3097cd0..1ffaa67 100644
--- a/package/ego-browser/src/page-ref-registry.test.mjs
+++ b/package/ego-browser/src/page-ref-registry.test.mjs
@@ -9,6 +9,7 @@ test("Page refs preserve native frame provenance and an explicit ref id", () =>
refId: 901,
backendNodeId: 21,
frameId: "frame-target",
+ frameProvenance: "frame",
role: "button",
name: "Run iframe action",
},
@@ -20,6 +21,7 @@ test("Page refs preserve native frame provenance and an explicit ref id", () =>
name: "Run iframe action",
nth: undefined,
frameId: "frame-target",
+ frameProvenance: "frame",
});
assert.equal(
refs.get("21"),
@@ -27,3 +29,80 @@ test("Page refs preserve native frame provenance and an explicit ref id", () =>
"a renderer-local backend node id must not replace the printed ref id",
);
});
+
+test("invalidated Page refs stay stale until an explicit snapshot replaces them", () => {
+ const registry = new PageRefRegistry();
+ registry.replace("page-target", [
+ { refId: 21, backendNodeId: 21, role: "button", name: "Old action" },
+ { refId: 22, backendNodeId: 22, role: "button", name: "Removed action" },
+ ]);
+
+ registry.invalidate("page-target");
+
+ assert.equal(registry.forTarget("page-target").get("21"), undefined);
+ assert.equal(registry.isInvalidated("page-target", "21"), true);
+
+ registry.replace("page-target", [
+ { refId: 21, backendNodeId: 42, role: "button", name: "New action" },
+ ]);
+
+ assert.equal(registry.isInvalidated("page-target", "21"), false);
+ assert.equal(
+ registry.isInvalidated("page-target", "22"),
+ true,
+ "an explicit snapshot only revives refs that it advertises",
+ );
+ assert.equal(registry.forTarget("page-target").get("21").backendNodeId, 42);
+});
+
+test("partial snapshots merge refs without invalidating omitted targets", () => {
+ const registry = new PageRefRegistry();
+ registry.replace("page-target", [
+ { refId: 21, backendNodeId: 21, role: "button", name: "First" },
+ { refId: 22, backendNodeId: 22, role: "button", name: "Second" },
+ ]);
+
+ registry.merge("page-target", [
+ { refId: 21, backendNodeId: 42, role: "button", name: "Updated" },
+ ]);
+
+ assert.equal(registry.forTarget("page-target").get("21").backendNodeId, 42);
+ assert.equal(registry.forTarget("page-target").get("22").backendNodeId, 22);
+ assert.equal(registry.isInvalidated("page-target", "22"), false);
+});
+
+test("partial snapshots revive only the invalidated refs they advertise", () => {
+ const registry = new PageRefRegistry();
+ registry.replace("page-target", [
+ { refId: 21, backendNodeId: 21, role: "button", name: "First" },
+ { refId: 22, backendNodeId: 22, role: "button", name: "Second" },
+ ]);
+ registry.invalidate("page-target");
+
+ registry.merge("page-target", [
+ { refId: 21, backendNodeId: 42, role: "button", name: "Updated" },
+ ]);
+
+ assert.equal(registry.forTarget("page-target").get("21").backendNodeId, 42);
+ assert.equal(registry.isInvalidated("page-target", "21"), false);
+ assert.equal(registry.forTarget("page-target").get("22"), undefined);
+ assert.equal(registry.isInvalidated("page-target", "22"), true);
+});
+
+test("stale ref tombstones stay bounded for long-lived pages", () => {
+ const registry = new PageRefRegistry();
+ registry.replace(
+ "page-target",
+ Array.from({ length: 10_001 }, (_, index) => ({
+ refId: index + 1,
+ backendNodeId: index + 1,
+ role: "button",
+ name: `Action ${index + 1}`,
+ })),
+ );
+
+ registry.invalidate("page-target");
+
+ assert.equal(registry.isInvalidated("page-target", "1"), false);
+ assert.equal(registry.isInvalidated("page-target", "10001"), true);
+});
diff --git a/package/ego-browser/src/page-ref-registry.ts b/package/ego-browser/src/page-ref-registry.ts
index 182e5c7..ace271e 100644
--- a/package/ego-browser/src/page-ref-registry.ts
+++ b/package/ego-browser/src/page-ref-registry.ts
@@ -1,9 +1,12 @@
import { RefMap } from "./ref-map.js";
+const MAX_INVALIDATED_REFS_PER_TARGET = 10_000;
+
type SnapshotRef = {
refId?: string | number;
backendNodeId?: number;
frameId?: string;
+ frameProvenance?: "page" | "frame" | "unknown";
role?: string;
name?: string;
};
@@ -14,6 +17,7 @@ type SnapshotRef = {
*/
export class PageRefRegistry {
readonly #targets = new Map<string, RefMap>();
+ readonly #invalidated = new Map<string, Set<string>>();
forTarget(targetId: string): RefMap {
assertTargetId(targetId);
@@ -27,6 +31,10 @@ export class PageRefRegistry {
replace(targetId: string, snapshotRefs: SnapshotRef[] = []): RefMap {
assertTargetId(targetId);
+ const invalidated = new Set(this.#invalidated.get(targetId) || []);
+ for (const refId of this.#targets.get(targetId)?.map.keys() || []) {
+ addInvalidatedRef(invalidated, refId);
+ }
const refs = new RefMap();
for (const ref of snapshotRefs) {
if (
@@ -37,22 +45,73 @@ export class PageRefRegistry {
) {
continue;
}
+ const refId = String(ref.refId ?? ref.backendNodeId);
refs.addWithFrame(
- String(ref.refId ?? ref.backendNodeId),
+ refId,
ref.backendNodeId,
ref.role,
ref.name,
undefined,
ref.frameId,
+ ref.frameProvenance,
);
+ invalidated.delete(refId);
}
this.#targets.set(targetId, refs);
+ if (invalidated.size > 0) this.#invalidated.set(targetId, invalidated);
+ else this.#invalidated.delete(targetId);
return refs;
}
+ merge(targetId: string, snapshotRefs: SnapshotRef[] = []): RefMap {
+ assertTargetId(targetId);
+ const refs = this.forTarget(targetId);
+ const invalidated = new Set(this.#invalidated.get(targetId) || []);
+ for (const ref of snapshotRefs) {
+ if (
+ !ref ||
+ typeof ref !== "object" ||
+ ref.backendNodeId === undefined ||
+ ref.backendNodeId === null
+ ) {
+ continue;
+ }
+ const refId = String(ref.refId ?? ref.backendNodeId);
+ refs.addWithFrame(
+ refId,
+ ref.backendNodeId,
+ ref.role,
+ ref.name,
+ undefined,
+ ref.frameId,
+ ref.frameProvenance,
+ );
+ invalidated.delete(refId);
+ }
+ if (invalidated.size > 0) this.#invalidated.set(targetId, invalidated);
+ else this.#invalidated.delete(targetId);
+ return refs;
+ }
+
+ invalidate(targetId: string): void {
+ assertTargetId(targetId);
+ const invalidated = this.#invalidated.get(targetId) ?? new Set<string>();
+ for (const refId of this.#targets.get(targetId)?.map.keys() || []) {
+ addInvalidatedRef(invalidated, refId);
+ }
+ this.#targets.delete(targetId);
+ if (invalidated.size > 0) this.#invalidated.set(targetId, invalidated);
+ }
+
+ isInvalidated(targetId: string, refId: string): boolean {
+ assertTargetId(targetId);
+ return this.#invalidated.get(targetId)?.has(refId) ?? false;
+ }
+
clear(targetId: string): void {
assertTargetId(targetId);
this.#targets.delete(targetId);
+ this.#invalidated.delete(targetId);
}
}
@@ -61,3 +120,11 @@ function assertTargetId(targetId: string): void {
throw new TypeError("PageRefRegistry requires a non-empty targetId");
}
}
+
+function addInvalidatedRef(invalidated: Set<string>, refId: string): void {
+ invalidated.delete(refId);
+ invalidated.add(refId);
+ if (invalidated.size <= MAX_INVALIDATED_REFS_PER_TARGET) return;
+ const oldest = invalidated.values().next().value;
+ if (oldest !== undefined) invalidated.delete(oldest);
+}
diff --git a/package/ego-browser/src/public-api-schema.test.mjs b/package/ego-browser/src/public-api-schema.test.mjs
index c985d32..799bce9 100644
--- a/package/ego-browser/src/public-api-schema.test.mjs
+++ b/package/ego-browser/src/public-api-schema.test.mjs
@@ -70,6 +70,10 @@ test("schema-driven option validation rejects unknown and invalid fields", () =>
path: "/tmp/image.png",
scale: "css",
});
+ validatePublicApiOptions("Page.snapshot", {
+ scope: "subtree",
+ root: "@21",
+ });
validatePublicApiOptions("TaskSpace.finish", { keep: [] });
validatePublicApiOptions("TaskSpace.finish", { keep: ["p2"] });
validatePublicApiOptions("TaskSpace.finish", { keep: "all" });
@@ -109,6 +113,10 @@ test("schema-driven option validation rejects unknown and invalid fields", () =>
() => validatePublicApiOptions("Page.goto", { waitUntil: "interactive" }),
/waitUntil must be one of commit, domcontentloaded, load, networkidle/,
);
+ assert.throws(
+ () => validatePublicApiOptions("Page.snapshot", { root: 21 }),
+ /root must be a non-empty string/,
+ );
assert.throws(
() => validatePublicApiOptions("Page.waitForFunction", { polling: 0 }),
/polling must be a positive number of milliseconds/,
@@ -153,6 +161,11 @@ test("the generated reference contains signatures and option descriptions", () =
markdown,
/`await page\.reload\(\{ timeout\?, waitUntil\? \}\)`/,
);
+ assert.match(
+ markdown,
+ /`await page\.snapshot\(\{ scope\?, root\?, includeActionMarks\?, includeStableLocator\? \}\)`/,
+ );
+ assert.match(markdown, /`root`.*snapshot ref/);
assert.match(
markdown,
/`await page\.selectOption\(selector, valueOrValues, \{ timeout\? \}\)`/,
diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.ts
index e458da4..d94a40d 100644
--- a/package/ego-browser/src/public-api-schema.ts
+++ b/package/ego-browser/src/public-api-schema.ts
@@ -233,14 +233,18 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
{
name: "Page.snapshot",
signature:
- "await page.snapshot({ scope?, includeActionMarks?, includeStableLocator? })",
+ "await page.snapshot({ scope?, root?, includeActionMarks?, includeStableLocator? })",
summary:
- "Return a semantic snapshot of the current viewport with Page provenance.",
+ "Return a semantic snapshot of the current viewport, full Page, or one snapshot-ref subtree with Page provenance.",
options: {
scope: option(
"string",
- "Snapshot scope; defaults to only_within_viewport.",
- ["full_page", "only_within_viewport"],
+ "Snapshot scope; defaults to only_within_viewport, which keeps iframe roots but defers their descendants. Use subtree with an iframe root ref to inspect that frame.",
+ ["full_page", "only_within_viewport", "subtree"],
+ ),
+ root: option(
+ "nonEmptyString",
+ "Latest Page snapshot ref such as @21; required only when scope is subtree.",
),
includeActionMarks: option("boolean", "Include action marks."),
includeStableLocator: option("boolean", "Include stable locators."),
diff --git a/package/ego-browser/src/ref-map.ts b/package/ego-browser/src/ref-map.ts
index 0453bc0..5e9125a 100644
--- a/package/ego-browser/src/ref-map.ts
+++ b/package/ego-browser/src/ref-map.ts
@@ -16,6 +16,7 @@ export class RefMap {
name,
nth = undefined,
frameId = undefined,
+ frameProvenance = undefined,
) {
this.map.set(refId, {
backendNodeId,
@@ -23,6 +24,7 @@ export class RefMap {
name,
nth,
frameId,
+ ...(frameProvenance ? { frameProvenance } : {}),
});
}
diff --git a/package/ego-browser/src/snapshot-result.test.mjs b/package/ego-browser/src/snapshot-result.test.mjs
index 2e6aaa9..14f8fb1 100644
--- a/package/ego-browser/src/snapshot-result.test.mjs
+++ b/package/ego-browser/src/snapshot-result.test.mjs
@@ -4,6 +4,7 @@ import assert from "node:assert/strict";
import {
compactSnapshotContent,
compactSnapshotResult,
+ deferIframeSnapshotSubtrees,
preparePageSnapshotResult,
sanitizeSnapshotLocators,
validateSnapshotLocator,
@@ -107,6 +108,46 @@ test("snapshot compaction omits unusable locator statuses from refs", () => {
assert.equal(result.refs[2].loc, "css:#save");
});
+test("viewport snapshots defer iframe descendants while preserving frame roots and siblings", () => {
+ const content = [
+ "root",
+ ' heading "Host"',
+ " iframe [ref=4]",
+ " root",
+ ' button "Inside same-origin frame" [ref=5]',
+ ' text "Host sibling"',
+ " iframe [ref=6]",
+ " root",
+ " iframe [ref=7]",
+ " root",
+ ' textbox "Inside nested OOPIF" [ref=8]',
+ ' text "iframe is literal text, not a frame node"',
+ ].join("\n");
+
+ assert.equal(
+ deferIframeSnapshotSubtrees(content),
+ [
+ "root",
+ ' heading "Host"',
+ " iframe [ref=4]",
+ ' text "Host sibling"',
+ " iframe [ref=6]",
+ ' text "iframe is literal text, not a frame node"',
+ ].join("\n"),
+ );
+});
+
+test("iframe deferral preserves non-tree output and trailing newlines", () => {
+ assert.equal(
+ deferIframeSnapshotSubtrees("snapshot unavailable"),
+ "snapshot unavailable",
+ );
+ assert.equal(
+ deferIframeSnapshotSubtrees("root\n iframe [ref=4]\n root\n"),
+ "root\n iframe [ref=4]\n",
+ );
+});
+
test("snapshot locator validation batches DOM queries and object cleanup", async () => {
const calls = [];
const services = {
@@ -395,7 +436,6 @@ test("Page snapshots preserve native ref provenance", async () => {
},
],
};
- const expected = structuredClone(result.refs);
const services = {
async cdp(_method, _params, sessionId) {
if (sessionId === "session:oopif") {
@@ -420,5 +460,197 @@ test("Page snapshots preserve native ref provenance", async () => {
result,
);
- assert.deepEqual(result.refs, expected);
+ assert.deepEqual(result.refs, [
+ {
+ refId: 1,
+ backendNodeId: 6,
+ role: "textbox",
+ name: "",
+ frameProvenance: "page",
+ },
+ {
+ refId: 17,
+ backendNodeId: 6,
+ role: "textbox",
+ name: "",
+ frameId: "frame-oopif",
+ frameProvenance: "frame",
+ },
+ ]);
+});
+
+test("Page snapshots backfill missing frame provenance from a unique locator", async () => {
+ const result = {
+ content: [
+ "iframe [ref=12]",
+ "root",
+ ' button "Run iframe action" [ref=21, loc=role:button[name="Run iframe action"]]',
+ ].join("\n"),
+ refs: [
+ {
+ refId: 21,
+ backendNodeId: 21,
+ role: "button",
+ name: "Run iframe action",
+ loc: 'role:button[name="Run iframe action"]',
+ },
+ ],
+ };
+ const services = {
+ async cdp(method, params, sessionId) {
+ assert.equal(method, "Accessibility.getFullAXTree");
+ if (sessionId === "session:page" && params.frameId === "frame-same") {
+ return {
+ nodes: [
+ {
+ backendDOMNodeId: 21,
+ ignored: false,
+ role: { value: "button" },
+ name: { value: "Run iframe action" },
+ },
+ ],
+ };
+ }
+ return { nodes: [] };
+ },
+ };
+
+ await preparePageSnapshotResult(
+ services,
+ "session:page",
+ new Map([
+ ["frame-same", "session:page"],
+ ["frame-oopif", "session:oopif"],
+ ]),
+ result,
+ );
+
+ assert.equal(result.refs[0].frameId, "frame-same");
+ assert.equal(result.refs[0].frameProvenance, "frame");
+});
+
+test("Page snapshots do not invent frame provenance for an ambiguous backend node", async () => {
+ const result = {
+ content: [
+ "iframe [ref=12]",
+ "root",
+ ' button "Duplicate action" [ref=21, loc=role:button[name="Duplicate action"]]',
+ ].join("\n"),
+ refs: [
+ {
+ refId: 21,
+ backendNodeId: 21,
+ role: "button",
+ name: "Duplicate action",
+ loc: 'role:button[name="Duplicate action"]',
+ },
+ ],
+ };
+ const services = {
+ async cdp(method, params, sessionId) {
+ assert.equal(method, "Accessibility.getFullAXTree");
+ const isFirstFrame =
+ sessionId === "session:page" && params.frameId === "frame-first";
+ const isSecondFrame = sessionId === "session:second";
+ return isFirstFrame || isSecondFrame
+ ? {
+ nodes: [
+ {
+ backendDOMNodeId: 21,
+ ignored: false,
+ role: { value: "button" },
+ name: { value: "Duplicate action" },
+ },
+ ],
+ }
+ : { nodes: [] };
+ },
+ };
+
+ await preparePageSnapshotResult(
+ services,
+ "session:page",
+ new Map([
+ ["frame-first", "session:page"],
+ ["frame-second", "session:second"],
+ ]),
+ result,
+ );
+
+ assert.equal(result.refs[0].frameId, undefined);
+ assert.equal(result.refs[0].frameProvenance, "unknown");
+});
+
+test("iframe deferral keeps a frame that advertises no ref expandable", () => {
+ // Deferring an iframe with no ref would hide its descendants with no root to
+ // pass back through subtree scope, so that frame stays inline.
+ const content = [
+ "root",
+ " iframe",
+ " root",
+ ' button "Unreachable without a ref" [ref=5]',
+ " iframe [ref=6]",
+ " root",
+ ' button "Reachable via @6" [ref=7]',
+ ].join("\n");
+
+ assert.equal(
+ deferIframeSnapshotSubtrees(content),
+ [
+ "root",
+ " iframe",
+ " root",
+ ' button "Unreachable without a ref" [ref=5]',
+ " iframe [ref=6]",
+ ].join("\n"),
+ );
+});
+
+test("frame provenance ignores a ref token inside an accessible name", async () => {
+ const result = {
+ content: [
+ "root",
+ ' link "See [ref=3] in the spec" [ref=3]',
+ " iframe [ref=12]",
+ " root",
+ ' link "See [ref=3] in the spec" [ref=42]',
+ ].join("\n"),
+ refs: [
+ {
+ refId: 3,
+ backendNodeId: 3,
+ role: "link",
+ name: "See [ref=3] in the spec",
+ },
+ {
+ refId: 42,
+ backendNodeId: 42,
+ role: "link",
+ name: "See [ref=3] in the spec",
+ },
+ ],
+ };
+
+ await preparePageSnapshotResult(
+ {
+ async cdp() {
+ return { nodes: [] };
+ },
+ },
+ "session:page",
+ new Map([["frame-child", "session:page"]]),
+ result,
+ );
+
+ assert.equal(
+ result.refs[0].frameProvenance,
+ "page",
+ "the page-owned ref must not be re-homed by a quoted ref token",
+ );
+ assert.equal(
+ result.refs[1].frameProvenance,
+ "frame",
+ "the frame-owned ref must still be recognised as a frame descendant",
+ );
+ assert.equal(result.refs[1].frameId, "frame-child");
});
diff --git a/package/ego-browser/src/snapshot-result.ts b/package/ego-browser/src/snapshot-result.ts
index 2a2ce91..16cf3f5 100644
--- a/package/ego-browser/src/snapshot-result.ts
+++ b/package/ego-browser/src/snapshot-result.ts
@@ -3,6 +3,7 @@ import { validateLocatorBackendNodes } from "./element-resolver.js";
type SnapshotRef = {
backendNodeId?: number;
frameId?: string;
+ frameProvenance?: "page" | "frame" | "unknown";
loc?: string;
name?: string;
refId?: number | string;
@@ -35,6 +36,11 @@ type SnapshotServices = {
): Promise<any>;
};
+type SnapshotFrameContext = {
+ frameId?: string;
+ frameProvenance?: "page" | "frame" | "unknown";
+};
+
/**
* Remove redundant native snapshot wrappers without changing semantic nodes.
*
@@ -84,6 +90,62 @@ export function compactSnapshotResult(result: SnapshotResult): SnapshotResult {
return result;
}
+/** Keep iframe roots visible while deferring their descendants in viewport snapshots. */
+export function deferIframeSnapshotSubtrees(content: string): string {
+ if (typeof content !== "string" || content.length === 0) return content;
+ if (!content.split(/\r?\n/).some((line) => line.trim() === "root")) {
+ return content;
+ }
+
+ const newline = content.includes("\r\n") ? "\r\n" : "\n";
+ const trailingNewline = content.endsWith(newline);
+ const lines = content.split(/\r?\n/);
+ if (trailingNewline) lines.pop();
+
+ const output: string[] = [];
+ let deferredIndent: number | undefined;
+ for (const line of lines) {
+ const text = line.trim();
+ if (!text) {
+ if (deferredIndent === undefined) output.push(line);
+ continue;
+ }
+
+ const indent = line.length - line.trimStart().length;
+ if (deferredIndent !== undefined && indent > deferredIndent) continue;
+ deferredIndent = undefined;
+ output.push(line);
+ // Deferring is only safe when the iframe advertises a ref, because that ref
+ // is the caller's only way back into the subtree. An unreferenced iframe
+ // keeps its descendants inline rather than hiding them irrecoverably.
+ if (/^iframe(?:\s|$)/.test(text) && snapshotLineRefId(line) !== undefined) {
+ deferredIndent = indent;
+ }
+ }
+
+ return output.join(newline) + (trailingNewline ? newline : "");
+}
+
+/** Keep only refs still advertised by the final rendered snapshot text. */
+export function retainSnapshotRefsInContent(
+ result: SnapshotResult,
+): SnapshotResult {
+ if (!Array.isArray(result?.refs) || typeof result.content !== "string") {
+ return result;
+ }
+
+ const visibleRefIds = new Set<string>();
+ for (const line of result.content.split(/\r?\n/)) {
+ const refId = snapshotLineRefId(line);
+ if (refId !== undefined) visibleRefIds.add(refId);
+ }
+ result.refs = result.refs.filter((ref) => {
+ const refId = ref.refId ?? ref.backendNodeId;
+ return refId !== undefined && visibleRefIds.has(String(refId));
+ });
+ return result;
+}
+
function compactSnapshotNode(node: SnapshotTreeNode): SnapshotTreeNode[] {
const text = omitUnusableLocatorStatus(node.text);
const children = node.children.flatMap(compactSnapshotNode);
@@ -108,6 +170,17 @@ function omitUnusableLocatorStatus(text: string): string {
: `${text.slice(0, metadataIndex)}${compacted}`;
}
+/**
+ * Read the ref id a snapshot line advertises. Quote-aware, so a `[ref=` that
+ * appears inside an accessible name is never mistaken for the line's metadata.
+ */
+function snapshotLineRefId(line: string): string | undefined {
+ const metadataIndex = findSnapshotMetadataStart(line);
+ if (metadataIndex < 0) return undefined;
+ const match = line.slice(metadataIndex).match(/^\[ref=([^,\]]+)/);
+ return match ? match[1] : undefined;
+}
+
function findSnapshotMetadataStart(text: string): number {
let quoted = false;
let escaped = false;
@@ -256,12 +329,17 @@ export async function preparePageSnapshotResult(
pageSessionId: string,
iframeSessions: Map<string, string>,
result: SnapshotResult,
+ rootContext: SnapshotFrameContext = {},
): Promise<SnapshotResult> {
const adapter: CdpAdapter = {
sendRaw: (method, params = {}, sessionId) =>
services.cdp(method, params, sessionId),
};
const refs = result?.refs || [];
+ const descendantRefIds =
+ typeof result?.content === "string"
+ ? iframeDescendantRefIds(result.content)
+ : new Set<string>();
const validIndexes = await validateLocatorBackendNodes(
adapter,
pageSessionId,
@@ -269,9 +347,128 @@ export async function preparePageSnapshotResult(
snapshotLocatorCandidates(refs),
);
const validRefs = new Set(refs.filter((_, index) => validIndexes.has(index)));
+ await backfillSnapshotFrameIds(
+ adapter,
+ pageSessionId,
+ iframeSessions,
+ result,
+ descendantRefIds,
+ );
+ for (const ref of refs) {
+ const refId = ref.refId ?? ref.backendNodeId;
+ if (ref.frameId) {
+ ref.frameProvenance = "frame";
+ } else if (refId !== undefined && descendantRefIds.has(String(refId))) {
+ ref.frameProvenance = "unknown";
+ } else if (rootContext.frameId) {
+ ref.frameId = rootContext.frameId;
+ ref.frameProvenance = "frame";
+ } else {
+ // A subtree root with frame provenance always carries a frameId, so the
+ // remaining cases are a page-owned root or one whose frame is unknown.
+ ref.frameProvenance = rootContext.frameProvenance ?? "page";
+ }
+ }
return sanitizeSnapshotLocators(result, async (ref) => validRefs.has(ref));
}
+async function backfillSnapshotFrameIds(
+ cdp: CdpAdapter,
+ pageSessionId: string,
+ iframeSessions: Map<string, string>,
+ result: SnapshotResult,
+ descendantRefIds: Set<string>,
+): Promise<void> {
+ if (iframeSessions.size === 0 || typeof result.content !== "string") return;
+
+ const missing = (result.refs || []).filter((ref) => {
+ const refId = ref.refId ?? ref.backendNodeId;
+ return (
+ !ref.frameId && refId !== undefined && descendantRefIds.has(String(refId))
+ );
+ });
+ if (missing.length === 0) return;
+
+ const frameIds = [...iframeSessions.keys()];
+ // One frame admits no ambiguity to resolve, and the refs that most need a
+ // frame here are the ones with no usable locator to validate against.
+ if (frameIds.length === 1) {
+ for (const ref of missing) ref.frameId = frameIds[0];
+ return;
+ }
+
+ const owners = new Map<number, { frameId: string; ref: SnapshotRef }>();
+ const candidates: Array<{
+ index: number;
+ locator: string;
+ backendNodeId: number;
+ frameId: string;
+ }> = [];
+ for (const ref of missing) {
+ const base = snapshotLocatorCandidates([ref])[0];
+ if (!base) continue;
+ for (const frameId of frameIds) {
+ const index = candidates.length;
+ candidates.push({ ...base, index, frameId });
+ owners.set(index, { frameId, ref });
+ }
+ }
+
+ const valid = await validateLocatorBackendNodes(
+ cdp,
+ pageSessionId,
+ iframeSessions,
+ candidates,
+ );
+ const matches = new Map<SnapshotRef, Set<string>>();
+ for (const index of valid) {
+ const owner = owners.get(index);
+ if (!owner) continue;
+ const frameMatches = matches.get(owner.ref) ?? new Set<string>();
+ frameMatches.add(owner.frameId);
+ matches.set(owner.ref, frameMatches);
+ }
+ for (const [ref, frameMatches] of matches) {
+ if (frameMatches.size === 1) ref.frameId = [...frameMatches][0];
+ }
+}
+
+function iframeDescendantRefIds(content: string): Set<string> {
+ const refs = new Set<string>();
+ let iframeIndent: number | undefined;
+ let frameRootIndent: number | undefined;
+ for (const line of content.split(/\r?\n/)) {
+ const text = line.trim();
+ if (!text) continue;
+ const indent = line.length - line.trimStart().length;
+ const startsIframe = /^iframe(?:\s|$)/.test(text);
+
+ if (iframeIndent === undefined) {
+ if (startsIframe) iframeIndent = indent;
+ continue;
+ }
+
+ if (frameRootIndent === undefined) {
+ if (/^root(?:\s|$)/.test(text) && indent >= iframeIndent) {
+ frameRootIndent = indent;
+ } else if (indent <= iframeIndent) {
+ iframeIndent = startsIframe ? indent : undefined;
+ }
+ continue;
+ }
+
+ if (indent <= frameRootIndent) {
+ iframeIndent = startsIframe ? indent : undefined;
+ frameRootIndent = undefined;
+ continue;
+ }
+
+ const refId = snapshotLineRefId(line);
+ if (refId !== undefined) refs.add(refId);
+ }
+ return refs;
+}
+
function snapshotLocatorCandidates(refs: SnapshotRef[]) {
return refs.flatMap((ref, index) => {
if (
diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.md
index 8bd7548..cafe59f 100644
--- a/skills/ego-browser/SKILL.md
+++ b/skills/ego-browser/SKILL.md
@@ -163,6 +163,18 @@ captures the current moment; it does not wait for the page to become stable.
`page.snapshot()` captures the current viewport. For content outside it, use
`page.snapshot({ scope: "full_page" })`.
+The default viewport snapshot keeps each `iframe` root but defers its nested
+tree. To inspect a frame, reuse the ref printed on that `iframe` line:
+
+```js
+console.log(await page.snapshot({ scope: "subtree", root: "@12" }));
+```
+
+For cross-process frames, readable subtree content may not include action refs.
+Use a unique `loc=role:` or `loc=css:` selector when an inner action has no ref.
+If subtree reports a duplicate backend node id across frames, use
+`page.snapshot({ scope: "full_page" })`; the runtime refuses to guess.
+
`waitForLoadState()` defaults to `load`. `waitForFunction()` follows the
Playwright argument order; pass `undefined` before options when there is no Page
argument:
@@ -221,6 +233,13 @@ 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.
+Snapshot refs are intentionally invalidated after input actions,
+`page.evaluate()`, `page.cdp()`, `page.waitForFunction()`,
+`page.waitForLoadState()`, and successful dialog handling because any of them
+can change the document. Take a new snapshot before using another ref; use a
+stable `loc=...` selector when several actions must run without an intervening
+snapshot.
+
Select options by value, visible label, or zero-based index. A string matches
either value or label; pass an array for a multiple select:
diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.md
index 1418667..98c30a7 100644
--- a/skills/ego-browser/references/api.md
+++ b/skills/ego-browser/references/api.md
@@ -51,7 +51,7 @@ Selectors accept refs, Ego locators, XPath, and raw CSS. A small compatibility s
| `page.targetId` | — | Internal browser target identifier for advanced Target-domain CDP only. |
| `await page.goto(url, { referer?, timeout?, waitUntil? })` | `referer` — HTTP Referer header for the navigation.<br>`timeout` — Maximum duration in milliseconds.<br>`waitUntil` (commit, domcontentloaded, load, networkidle) — Completion state; defaults to load. networkidle requires 500ms without network activity. | Navigate this Page in place. Timeout errors report whether the new document committed, plus its URL and readyState when available. |
| `await page.reload({ timeout?, waitUntil? })` | `timeout` — Maximum duration in milliseconds.<br>`waitUntil` (commit, domcontentloaded, load, networkidle) — Completion state; defaults to load. networkidle requires 500ms without network activity. | Reload this Page and wait for the selected navigation state. |
-| `await page.snapshot({ scope?, includeActionMarks?, includeStableLocator? })` | `scope` (full_page, only_within_viewport) — Snapshot scope; defaults to only_within_viewport.<br>`includeActionMarks` — Include action marks.<br>`includeStableLocator` — Include stable locators. | Return a semantic snapshot of the current viewport with Page provenance. |
+| `await page.snapshot({ scope?, root?, includeActionMarks?, includeStableLocator? })` | `scope` (full_page, only_within_viewport, subtree) — Snapshot scope; defaults to only_within_viewport, which keeps iframe roots but defers their descendants. Use subtree with an iframe root ref to inspect that frame.<br>`root` — Latest Page snapshot ref such as @21; required only when scope is subtree.<br>`includeActionMarks` — Include action marks.<br>`includeStableLocator` — Include stable locators. | Return a semantic snapshot of the current viewport, full Page, or one snapshot-ref subtree with Page provenance. |
| `await page.screenshot({ path?, fullPage?, clip?, scale?, raw? })` | `path` — Output path; missing parent directories are created.<br>`fullPage` — Capture the full scrollable page.<br>`clip` — CSS-pixel clipping rectangle.<br>`scale` (css) — Output scale mode; css uses CSS-pixel sizing and is the default.<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(urlMatcher, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for an exact URL, Playwright-style glob, RegExp, or synchronous predicate receiving a URL object. |