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): flag content outside the viewport in default snapshots

Zhuowei Wang6419f1ac62ec
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 9533a81..8683704 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
@@ -19,6 +19,7 @@ import {
pageDefaultScreenshotPathSecondRunCase,
} from "./page-default-screenshot-path.mjs";
import { pageSnapshotLocatorCase } from "./page-snapshot-locators.mjs";
+import { pageSnapshotViewportOverflowCase } from "./page-snapshot-viewport-overflow.mjs";
import {
pageSnapshotIframeViewportCase,
pageSnapshotLazyIframeCase,
@@ -146,6 +147,10 @@ export const e2eCases = [
body: pageSnapshotIframeViewportCase,
},
{ name: "Page snapshot subtree", body: pageSnapshotSubtreeCase },
+ {
+ name: "Page snapshot viewport overflow hint",
+ body: pageSnapshotViewportOverflowCase,
+ },
{
name: "Page ref identity across partial snapshots",
body: pageRefIdentityCase,
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-snapshot-viewport-overflow.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-snapshot-viewport-overflow.mjs
new file mode 100644
index 0000000..09baf25
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-snapshot-viewport-overflow.mjs
@@ -0,0 +1,47 @@
+export function pageSnapshotViewportOverflowCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const page = await newPageAt(task, baseUrl + "/snapshot-viewport-overflow");
+ const hintLine = (text) =>
+ text.split("\\n").find((line) => line.startsWith("[more content "));
+
+ await page.click('text="Submit"');
+ await page.waitForFunction(() => document.body.innerText.includes("RESULT-OK"));
+ const metrics = await page.evaluate(() => ({
+ innerHeight,
+ scrollY,
+ resultTop: Math.round(
+ document.querySelector("#out [role=status]").getBoundingClientRect().top
+ ),
+ }));
+ assert(
+ metrics.resultTop >= metrics.innerHeight,
+ "fixture keeps the result below the fold: " + JSON.stringify(metrics)
+ );
+
+ const viewport = await page.snapshot();
+ assert(!viewport.includes("RESULT-OK"), "the viewport snapshot omits the offscreen result");
+ const below = hintLine(viewport);
+ assert(below, "the viewport snapshot ends with an overflow hint");
+ assertIncludes(below, "more content below the viewport", "the hint points below");
+ assertIncludes(below, "scrollY=0", "the hint reports the scroll position");
+ assertIncludes(below, 'snapshot({ scope: "full_page" })', "the hint names the full_page scope");
+ assertEqual(viewport.split("\\n").at(-1), below, "the hint is the last snapshot line");
+
+ const full = await page.snapshot({ scope: "full_page" });
+ assertIncludes(full, "RESULT-OK ticket T-1234", "the full_page snapshot includes the result");
+ assert(!hintLine(full), "the full_page snapshot carries no overflow hint");
+
+ await page.evaluate(() => window.scrollTo(0, document.documentElement.scrollHeight));
+ const scrolled = await page.snapshot();
+ assertIncludes(scrolled, "RESULT-OK ticket T-1234", "scrolling brings the result into the viewport snapshot");
+ assertIncludes(hintLine(scrolled) || "", "more content above the viewport", "the hint flips to above after scrolling to the bottom");
+
+ await page.goto(baseUrl + "/download-entry");
+ const fits = await page.snapshot();
+ assertIncludes(fits, "Preview report", "the short page snapshot has its content");
+ assert(!hintLine(fits), "a page that fits the viewport gets no overflow hint");
+
+ await page.close();
+ `;
+}
diff --git a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
index 27be181..c088396 100644
--- a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
@@ -349,6 +349,38 @@ export async function startFixtureServer(taskName) {
</html>`);
return;
}
+ if (url.pathname === "/snapshot-viewport-overflow") {
+ // Mirrors the CITRO-4285 repro: the button sits at the bottom edge of the
+ // viewport, so the result it reveals lands just below the fold.
+ res.writeHead(200, { "content-type": "text/html" });
+ res.end(`<!doctype html>
+ <html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <title>snapshot viewport overflow</title>
+ <style>
+ body { margin: 0; font: 16px sans-serif; }
+ #spacer { height: calc(100vh - 40px); background: #eef; }
+ #out { margin-top: 60px; }
+ </style>
+ </head>
+ <body>
+ <div id="spacer">Spacer</div>
+ <button id="go">Submit</button>
+ <div id="out"></div>
+ <script>
+ document.getElementById("go").addEventListener("click", () => {
+ const out = document.getElementById("out");
+ out.innerHTML = '<p role="status">Checking…</p>';
+ setTimeout(() => {
+ out.innerHTML = '<div role="status">RESULT-OK ticket T-1234</div>';
+ }, 300);
+ });
+ </script>
+ </body>
+ </html>`);
+ return;
+ }
if (url.pathname === "/nav-target") {
res.writeHead(200, { "content-type": "text/html" });
res.end(pageHtml("nav-target"));
diff --git a/package/ego-browser/skill-body/SKILL.md b/package/ego-browser/skill-body/SKILL.md
index 32a72e9..ae53194 100644
--- a/package/ego-browser/skill-body/SKILL.md
+++ b/package/ego-browser/skill-body/SKILL.md
@@ -251,7 +251,13 @@ Wait for the expected result: use `waitForURL()` for navigation,
state. Avoid fixed delays when an observable condition exists. A snapshot
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" })`.
+`page.snapshot({ scope: "full_page" })`. When the document scrolls past the
+viewport, a viewport snapshot ends with a line such as
+`[more content below the viewport: scrollY=0, viewport 778 / page 880 px; ...]`;
+nodes outside the viewport are omitted, not missing from the page. When the
+expected result may appear below the fold (for example after clicking a button
+near the bottom edge), scroll first or snapshot with `full_page` before
+concluding that the result did not appear.
The default viewport snapshot includes visible iframe content returned by the
browser. To focus on a frame's subtree, reuse the ref printed on its `iframe`
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 9d27027..09bc6f0 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -74,6 +74,7 @@ function createFixture(rootDir) {
let timeoutNextLifecycleEvaluate = false;
let timeoutNextUrlEvaluate = false;
let waitFunctionResults = [];
+ let viewportMetrics = { viewportHeight: 600, scrollY: 0, pageHeight: 600 };
let fetchFailure = null;
let nowMs = 1_000;
const pageEvents = new Map();
@@ -325,6 +326,9 @@ function createFixture(rootDir) {
result: { type: "number", value: elementPresent ? 1 : 0 },
};
}
+ if (params.expression.includes("viewportHeight")) {
+ return { result: { type: "object", value: viewportMetrics } };
+ }
if (params.expression.includes("innerWidth")) {
return {
result: {
@@ -804,6 +808,9 @@ function createFixture(rootDir) {
openPopupOnNextClick(url) {
popupOnNextClick = url;
},
+ setViewportMetrics(metrics) {
+ viewportMetrics = metrics;
+ },
openFileChooserOnNextClick(options = {}) {
fileChooserOnNextClick = {
backendNodeId: options.backendNodeId ?? 71,
@@ -2138,6 +2145,90 @@ test("snapshot defaults to the viewport, reports its source, and validates optio
});
});
+test("a viewport snapshot reports content outside the viewport", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/overflow");
+ const lastLine = (text) => text.split("\n").at(-1);
+
+ fixture.setViewportMetrics({
+ viewportHeight: 778,
+ scrollY: 0,
+ pageHeight: 880,
+ });
+ assert.equal(
+ lastLine(await page.snapshot()),
+ '[more content below the viewport: scrollY=0, viewport 778 / page 880 px; scroll or use snapshot({ scope: "full_page" })]',
+ );
+
+ fixture.setViewportMetrics({
+ viewportHeight: 778,
+ scrollY: 102,
+ pageHeight: 880,
+ });
+ assert.match(
+ lastLine(await page.snapshot()),
+ /^\[more content above the viewport: scrollY=102, viewport 778 \/ page 880 px;/,
+ );
+
+ fixture.setViewportMetrics({
+ viewportHeight: 778,
+ scrollY: 50,
+ pageHeight: 1600,
+ });
+ assert.match(
+ lastLine(await page.snapshot({ scope: "only_within_viewport" })),
+ /^\[more content above and below the viewport: scrollY=50, viewport 778 \/ page 1600 px;/,
+ );
+
+ for (const scope of ["full_page", "subtree"]) {
+ const calls = fixture.calls.length;
+ const text = await page.snapshot(
+ scope === "subtree" ? { scope, root: "@21" } : { scope },
+ );
+ assert.doesNotMatch(text, /more content/);
+ assert(
+ !fixture.calls
+ .slice(calls)
+ .some(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Runtime.evaluate" &&
+ params.expression.includes("viewportHeight"),
+ ),
+ `${scope} snapshot must not read viewport metrics`,
+ );
+ }
+ });
+});
+
+test("a viewport snapshot stays silent when the document fits the viewport", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/fits");
+
+ for (const metrics of [
+ { viewportHeight: 600, scrollY: 0, pageHeight: 600 },
+ { viewportHeight: 600, scrollY: 0, pageHeight: 400 },
+ { viewportHeight: 600, scrollY: 0.5, pageHeight: 600.75 },
+ ]) {
+ fixture.setViewportMetrics(metrics);
+ assert.equal(
+ (await page.snapshot()).split("\n").at(-1),
+ "snapshot:https://example.test/fits",
+ `no hint for ${JSON.stringify(metrics)}`,
+ );
+ }
+
+ fixture.setViewportMetrics("complete");
+ assert.equal(
+ (await page.snapshot()).split("\n").at(-1),
+ "snapshot:https://example.test/fits",
+ "an unreadable metrics result degrades to no hint",
+ );
+ });
+});
+
test("viewport snapshots preserve native iframe contents and refs", async () => {
for (const options of [{}, { scope: "only_within_viewport" }]) {
await withFixture(async (fixture) => {
diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.ts
index d4ffb12..ccdc589 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -1762,10 +1762,43 @@ class Page {
);
const content = result?.content || "";
const header = await this.#snapshotHeader(page);
- return `${header}\n${content}`;
+ const overflow =
+ snapshotScope === "only_within_viewport"
+ ? await this.#viewportOverflowHint(sessionId)
+ : "";
+ if (!overflow) return `${header}\n${content}`;
+ // The native content ends with a newline; keep the hint directly below
+ // the last node instead of after a blank line.
+ return `${header}\n${content.replace(/\n+$/, "")}\n${overflow}`;
});
}
+ /**
+ * One trailing line for a viewport snapshot when the document scrolls past
+ * the viewport. The native viewport snapshot silently omits offscreen nodes,
+ * so without this line an agent cannot tell "no result yet" from "the result
+ * is below the fold". Any failure to read the metrics (pending dialog, lost
+ * frame, slow page) degrades to no hint rather than a failed snapshot.
+ */
+ async #viewportOverflowHint(sessionId: string): Promise<string> {
+ if (this.#services.pendingDialog(sessionId)) return "";
+ let metrics: ViewportMetrics | undefined;
+ try {
+ metrics = await evaluateInSession<ViewportMetrics>(
+ this.#services,
+ sessionId,
+ VIEWPORT_METRICS_EXPRESSION,
+ false,
+ undefined,
+ VIEWPORT_METRICS_TIMEOUT_MS,
+ VIEWPORT_METRICS_TIMEOUT_MS,
+ );
+ } catch {
+ return "";
+ }
+ return viewportOverflowHint(metrics);
+ }
+
async url(): Promise<string> {
return this.#evaluate("location.href", false);
}
@@ -2984,6 +3017,47 @@ class Page {
}
}
+type ViewportMetrics = {
+ viewportHeight: number;
+ scrollY: number;
+ pageHeight: number;
+};
+
+const VIEWPORT_METRICS_TIMEOUT_MS = 2_000;
+
+// Keep the field names distinct from page.info() so test doubles and log
+// readers can tell the two reads apart.
+const VIEWPORT_METRICS_EXPRESSION =
+ "({viewportHeight:innerHeight,scrollY:scrollY,pageHeight:document.documentElement.scrollHeight})";
+
+/**
+ * Describe scrollable content outside the viewport, or return "" when the
+ * viewport already shows the whole document. Sub-pixel differences from
+ * fractional layout are ignored so a page that fits never gets a hint.
+ */
+export function viewportOverflowHint(metrics: unknown): string {
+ if (!metrics || typeof metrics !== "object") return "";
+ const { viewportHeight, scrollY, pageHeight } = metrics as Record<
+ string,
+ unknown
+ >;
+ if (
+ !Number.isFinite(viewportHeight) ||
+ !Number.isFinite(scrollY) ||
+ !Number.isFinite(pageHeight)
+ ) {
+ return "";
+ }
+ const top = Math.round(scrollY as number);
+ const viewport = Math.round(viewportHeight as number);
+ const page = Math.round(pageHeight as number);
+ const above = top > 1;
+ const below = page - (top + viewport) > 1;
+ if (!above && !below) return "";
+ const where = above && below ? "above and below" : above ? "above" : "below";
+ return `[more content ${where} the viewport: scrollY=${top}, viewport ${viewport} / page ${page} px; scroll or use snapshot({ scope: "full_page" })]`;
+}
+
function pageSnapshotOptionsError(message: string): TypeError {
const signature = publicApiEntry("Page.snapshot")?.signature;
return new TypeError(`${message}. Expected: ${signature}`);