Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠

fix: expose layered surfaces alongside page text

Barack Sokulluae246492a6b8
diff --git a/src/chrome/src/agent/read-page-window.js b/src/chrome/src/agent/read-page-window.js
index af9d70136..ab2a6c6c3 100644
--- a/src/chrome/src/agent/read-page-window.js
+++ b/src/chrome/src/agent/read-page-window.js
@@ -109,6 +109,7 @@ function compactCoreResult(result) {
accessState: result.accessState,
accessGateEvidence: result.accessGateEvidence,
...(pageGate ? { pageGate } : {}),
+ ...(Array.isArray(result.visibleLayers) ? { visibleLayers: result.visibleLayers.slice(0, 4) } : {}),
auxiliaryContentTruncated: true,
}, result.text);
}
diff --git a/src/chrome/src/agent/tools.js b/src/chrome/src/agent/tools.js
index c176eab01..ebe062e6f 100644
--- a/src/chrome/src/agent/tools.js
+++ b/src/chrome/src/agent/tools.js
@@ -189,7 +189,7 @@ export const AGENT_TOOLS = [
type: 'function',
function: {
name: 'read_page',
- description: 'Read the current page as a bounded PROSE window β€” title, URL, visible text, links, and forms. LEGACY read path; prefer get_accessibility_tree for UI tasks. Use read_page only for long-form text content (articles, READMEs, documentation). While `hasMore:true`, either spread the exact returned `continuationArgs` fields into the next call as top-level arguments or pass that exact object as `continuationArgs`; it carries `offset:nextOffset`, `limit`, and extraction options such as `includeChrome`. Never wrap it again or modify it. Do not scroll and reread the same document prefix. RESULT SHAPE: `text`, `originalLength`, `textOffset`, `textLimit`, `returnedLength`, `textTruncated`, `hasMore`, `nextOffset`, and `continuationArgs` describe the tool-output window. `truncationReason:"tool_output_window"` is a context-window boundary, never evidence of a paywall. `accessState:"blocked_by_page_gate"` plus `accessGateEvidence:"pageGate"` is the structured access-block signal; `accessState:"no_blocking_page_gate"` means tool truncation must not be described as an access restriction. `pageGate`, when present, describes the rendered blocking surface; `textSource` identifies the article selector or bounded pre-gate/gate text; `isArticlePage` reports article markup. NOTE: PDF tabs auto-redirect to read_pdf because Chrome\'s PDF viewer is a chrome-extension:// page that content scripts cannot scrape.',
+ description: 'Read the current page as a bounded PROSE window β€” title, URL, visible text, links, and forms. LEGACY read path; prefer get_accessibility_tree for UI tasks. Use read_page only for long-form text content (articles, READMEs, documentation). While `hasMore:true`, either spread the exact returned `continuationArgs` fields into the next call as top-level arguments or pass that exact object as `continuationArgs`; it carries `offset:nextOffset`, `limit`, and extraction options such as `includeChrome`. Never wrap it again or modify it. Do not scroll and reread the same document prefix. RESULT SHAPE: `text`, `originalLength`, `textOffset`, `textLimit`, `returnedLength`, `textTruncated`, `hasMore`, `nextOffset`, and `continuationArgs` describe the tool-output window. `truncationReason:"tool_output_window"` is a context-window boundary, never evidence of a paywall. `accessState:"blocked_by_page_gate"` plus `accessGateEvidence:"pageGate"` is the structured access-block signal; `accessState:"no_blocking_page_gate"` means tool truncation must not be described as an access restriction. `pageGate`, when present, describes the rendered blocking surface; `textSource` identifies the article selector or bounded pre-gate/gate text; `isArticlePage` reports article markup. `visibleLayers` lists rendered dialogs, toolbars, and docked surfaces with viewport bounds while `text` keeps the underlying page prose. NOTE: PDF tabs auto-redirect to read_pdf because Chrome\'s PDF viewer is a chrome-extension:// page that content scripts cannot scrape.',
parameters: {
type: 'object',
properties: {
diff --git a/src/chrome/src/cdp/cdp-client.js b/src/chrome/src/cdp/cdp-client.js
index 8d8eeb221..c4b968926 100644
--- a/src/chrome/src/cdp/cdp-client.js
+++ b/src/chrome/src/cdp/cdp-client.js
@@ -3368,6 +3368,54 @@ export class CDPClient {
}
return blocks.join('\\n\\n').trim();
};
+ const getVisibleLayers = () => {
+ const selectors = [
+ 'header', 'nav', '[role="banner"]', '[role="navigation"]',
+ '[role="toolbar"]', '[class*="toolbar" i]',
+ '[role="dialog"]', '[role="alertdialog"]', '[aria-modal="true"]',
+ 'dialog[open]', '.modal.show', '[class*="DialogContent"]', '[class*="ModalContent"]',
+ '[data-overlay]', '[class*="overlay" i]', '[class*="popover" i]', '[class*="drawer" i]',
+ ].join(',');
+ const layers = [];
+ let candidates = [];
+ try { candidates = Array.from(document.querySelectorAll(selectors)); } catch (e) { return []; }
+ const dialogSelector = '[role="dialog"],[role="alertdialog"],[aria-modal="true"],dialog[open],.modal.show,[class*="DialogContent"],[class*="ModalContent"]';
+ // Preserve the active dialog even when the page has many fixed nav items.
+ candidates.sort((a, b) => Number(b.matches(dialogSelector)) - Number(a.matches(dialogSelector)));
+ for (const el of candidates) {
+ if (layers.length >= 4) break;
+ try {
+ if (!gateElementIsRendered(el)) continue;
+ const style = getComputedStyle(el);
+ if (!['fixed', 'sticky', 'absolute'].includes(style.position) && !(el.tagName === 'DIALOG' && el.open)) continue;
+ const r = el.getBoundingClientRect();
+ const left = Math.max(0, r.left), right = Math.min(window.innerWidth, r.right);
+ const top = Math.max(0, r.top), bottom = Math.min(window.innerHeight, r.bottom);
+ if (right - left < 10 || bottom - top < 10) continue;
+ if (layers.some(layer => layer.element.contains(el) || el.contains(layer.element))) continue;
+ const text = String(el.innerText || el.getAttribute('aria-label') || '')
+ .replace(/\\s+/g, ' ').trim().slice(0, 240);
+ if (!text) continue;
+ const points = [
+ [(left + right) / 2, (top + bottom) / 2],
+ [left + (right - left) * 0.2, top + (bottom - top) * 0.2],
+ [right - (right - left) * 0.2, bottom - (bottom - top) * 0.2],
+ ];
+ if (!points.some(([x, y]) => {
+ const hit = document.elementFromPoint(x, y);
+ return hit === el || el.contains(hit);
+ })) continue;
+ layers.push({
+ element: el,
+ role: el.getAttribute('role') || el.tagName.toLowerCase(),
+ text,
+ position: style.position,
+ rect: { x: Math.round(r.x), y: Math.round(r.y), w: Math.round(r.width), h: Math.round(r.height) },
+ });
+ } catch (e) { /* ignore malformed or changing page surfaces */ }
+ }
+ return layers.map(({ element, ...layer }) => layer);
+ };
const stripChrome = (root) => {
if (includeChrome || !root) return root;
let clone;
@@ -3423,6 +3471,7 @@ export class CDPClient {
textSource,
isArticlePage,
includeChrome,
+ visibleLayers: blockedAuxiliaryContent ? [] : getVisibleLayers(),
links: blockedAuxiliaryContent ? [] : Array.from(document.querySelectorAll('a[href]')).slice(0, 100).map(a => ({
text: a.innerText.trim().slice(0, 100),
href: a.href,
diff --git a/src/chrome/src/content/content.js b/src/chrome/src/content/content.js
index 50667e479..21f14df47 100644
--- a/src/chrome/src/content/content.js
+++ b/src/chrome/src/content/content.js
@@ -194,6 +194,7 @@
title: document.title,
description: document.querySelector('meta[name="description"]')?.content || '',
text: getPageText(),
+ visibleLayers: getVisibleLayers(),
media: getPageMediaSummary(),
activeElement: getActiveEditableSummary(),
links: Array.from(document.querySelectorAll('a[href]')).slice(0, 100).map(a => ({
@@ -3278,6 +3279,55 @@
return blocks.join('\n\n').trim();
}
+ function getVisibleLayers() {
+ const selectors = [
+ 'header', 'nav', '[role="banner"]', '[role="navigation"]',
+ '[role="toolbar"]', '[class*="toolbar" i]',
+ '[role="dialog"]', '[role="alertdialog"]', '[aria-modal="true"]',
+ 'dialog[open]', '.modal.show', '[class*="DialogContent"]', '[class*="ModalContent"]',
+ '[data-overlay]', '[class*="overlay" i]', '[class*="popover" i]', '[class*="drawer" i]',
+ ].join(',');
+ const layers = [];
+ let candidates = [];
+ try { candidates = Array.from(document.querySelectorAll(selectors)); } catch { return []; }
+ const dialogSelector = '[role="dialog"],[role="alertdialog"],[aria-modal="true"],dialog[open],.modal.show,[class*="DialogContent"],[class*="ModalContent"]';
+ // Preserve the active dialog even when the page has many fixed nav items.
+ candidates.sort((a, b) => Number(b.matches(dialogSelector)) - Number(a.matches(dialogSelector)));
+ for (const el of candidates) {
+ if (layers.length >= 4) break;
+ try {
+ if (!gateElementIsRendered(el)) continue;
+ const style = getComputedStyle(el);
+ if (!['fixed', 'sticky', 'absolute'].includes(style.position) && !(el.tagName === 'DIALOG' && el.open)) continue;
+ const r = el.getBoundingClientRect();
+ const left = Math.max(0, r.left), right = Math.min(window.innerWidth, r.right);
+ const top = Math.max(0, r.top), bottom = Math.min(window.innerHeight, r.bottom);
+ if (right - left < 10 || bottom - top < 10) continue;
+ if (layers.some(layer => layer.element.contains(el) || el.contains(layer.element))) continue;
+ const text = String(el.innerText || el.getAttribute('aria-label') || '')
+ .replace(/\s+/g, ' ').trim().slice(0, 240);
+ if (!text) continue;
+ const points = [
+ [(left + right) / 2, (top + bottom) / 2],
+ [left + (right - left) * 0.2, top + (bottom - top) * 0.2],
+ [right - (right - left) * 0.2, bottom - (bottom - top) * 0.2],
+ ];
+ if (!points.some(([x, y]) => {
+ const hit = document.elementFromPoint(x, y);
+ return hit === el || el.contains(hit);
+ })) continue;
+ layers.push({
+ element: el,
+ role: el.getAttribute('role') || el.tagName.toLowerCase(),
+ text,
+ position: style.position,
+ rect: { x: Math.round(r.x), y: Math.round(r.y), w: Math.round(r.width), h: Math.round(r.height) },
+ });
+ } catch { /* ignore malformed or changing page surfaces */ }
+ }
+ return layers.map(({ element, ...layer }) => layer);
+ }
+
function getPageInfoFull(params) {
// `includeChrome:true` opts out of nav/footer/aside stripping. Default
// false because the original behaviour (full body.innerText) bloated
@@ -3421,6 +3471,7 @@
textSource,
isArticlePage,
includeChrome,
+ visibleLayers: blockedAuxiliaryContent ? [] : getVisibleLayers(),
media: blockedAuxiliaryContent
? { videoCount: 0, imageCount: 0, videos: [], images: [] }
: getPageMediaSummary(),
diff --git a/src/firefox/src/agent/read-page-window.js b/src/firefox/src/agent/read-page-window.js
index af9d70136..ab2a6c6c3 100644
--- a/src/firefox/src/agent/read-page-window.js
+++ b/src/firefox/src/agent/read-page-window.js
@@ -109,6 +109,7 @@ function compactCoreResult(result) {
accessState: result.accessState,
accessGateEvidence: result.accessGateEvidence,
...(pageGate ? { pageGate } : {}),
+ ...(Array.isArray(result.visibleLayers) ? { visibleLayers: result.visibleLayers.slice(0, 4) } : {}),
auxiliaryContentTruncated: true,
}, result.text);
}
diff --git a/src/firefox/src/agent/tools.js b/src/firefox/src/agent/tools.js
index 09484f7de..07d5f1bec 100644
--- a/src/firefox/src/agent/tools.js
+++ b/src/firefox/src/agent/tools.js
@@ -189,7 +189,7 @@ export const AGENT_TOOLS = [
type: 'function',
function: {
name: 'read_page',
- description: 'Read the current page as a bounded PROSE window β€” title, URL, visible text, links, and forms. LEGACY read path; prefer get_accessibility_tree for UI tasks. Use read_page only for long-form text content (articles, READMEs, documentation). While `hasMore:true`, either spread the exact returned `continuationArgs` fields into the next call as top-level arguments or pass that exact object as `continuationArgs`; it carries `offset:nextOffset`, `limit`, and extraction options such as `includeChrome`. Never wrap it again or modify it. Do not scroll and reread the same document prefix. RESULT SHAPE: `text`, `originalLength`, `textOffset`, `textLimit`, `returnedLength`, `textTruncated`, `hasMore`, `nextOffset`, and `continuationArgs` describe the tool-output window. `truncationReason:"tool_output_window"` is a context-window boundary, never evidence of a paywall. `accessState:"blocked_by_page_gate"` plus `accessGateEvidence:"pageGate"` is the structured access-block signal; `accessState:"no_blocking_page_gate"` means tool truncation must not be described as an access restriction. `pageGate`, when present, describes the rendered blocking surface; `textSource` identifies the article selector or bounded pre-gate/gate text; `isArticlePage` reports article markup. NOTE: PDF tabs auto-redirect to read_pdf because Firefox\'s built-in viewer is a privileged page that content scripts cannot scrape.',
+ description: 'Read the current page as a bounded PROSE window β€” title, URL, visible text, links, and forms. LEGACY read path; prefer get_accessibility_tree for UI tasks. Use read_page only for long-form text content (articles, READMEs, documentation). While `hasMore:true`, either spread the exact returned `continuationArgs` fields into the next call as top-level arguments or pass that exact object as `continuationArgs`; it carries `offset:nextOffset`, `limit`, and extraction options such as `includeChrome`. Never wrap it again or modify it. Do not scroll and reread the same document prefix. RESULT SHAPE: `text`, `originalLength`, `textOffset`, `textLimit`, `returnedLength`, `textTruncated`, `hasMore`, `nextOffset`, and `continuationArgs` describe the tool-output window. `truncationReason:"tool_output_window"` is a context-window boundary, never evidence of a paywall. `accessState:"blocked_by_page_gate"` plus `accessGateEvidence:"pageGate"` is the structured access-block signal; `accessState:"no_blocking_page_gate"` means tool truncation must not be described as an access restriction. `pageGate`, when present, describes the rendered blocking surface; `textSource` identifies the article selector or bounded pre-gate/gate text; `isArticlePage` reports article markup. `visibleLayers` lists rendered dialogs, toolbars, and docked surfaces with viewport bounds while `text` keeps the underlying page prose. NOTE: PDF tabs auto-redirect to read_pdf because Firefox\'s built-in viewer is a privileged page that content scripts cannot scrape.',
parameters: {
type: 'object',
properties: {
diff --git a/src/firefox/src/content/content.js b/src/firefox/src/content/content.js
index 0291ba6ca..ed00a3446 100644
--- a/src/firefox/src/content/content.js
+++ b/src/firefox/src/content/content.js
@@ -166,6 +166,55 @@
return blocks.join('\n\n').trim();
}
+ function getVisibleLayers() {
+ const selectors = [
+ 'header', 'nav', '[role="banner"]', '[role="navigation"]',
+ '[role="toolbar"]', '[class*="toolbar" i]',
+ '[role="dialog"]', '[role="alertdialog"]', '[aria-modal="true"]',
+ 'dialog[open]', '.modal.show', '[class*="DialogContent"]', '[class*="ModalContent"]',
+ '[data-overlay]', '[class*="overlay" i]', '[class*="popover" i]', '[class*="drawer" i]',
+ ].join(',');
+ const layers = [];
+ let candidates = [];
+ try { candidates = Array.from(document.querySelectorAll(selectors)); } catch { return []; }
+ const dialogSelector = '[role="dialog"],[role="alertdialog"],[aria-modal="true"],dialog[open],.modal.show,[class*="DialogContent"],[class*="ModalContent"]';
+ // Preserve the active dialog even when the page has many fixed nav items.
+ candidates.sort((a, b) => Number(b.matches(dialogSelector)) - Number(a.matches(dialogSelector)));
+ for (const el of candidates) {
+ if (layers.length >= 4) break;
+ try {
+ if (!gateElementIsRendered(el)) continue;
+ const style = getComputedStyle(el);
+ if (!['fixed', 'sticky', 'absolute'].includes(style.position) && !(el.tagName === 'DIALOG' && el.open)) continue;
+ const r = el.getBoundingClientRect();
+ const left = Math.max(0, r.left), right = Math.min(window.innerWidth, r.right);
+ const top = Math.max(0, r.top), bottom = Math.min(window.innerHeight, r.bottom);
+ if (right - left < 10 || bottom - top < 10) continue;
+ if (layers.some(layer => layer.element.contains(el) || el.contains(layer.element))) continue;
+ const text = String(el.innerText || el.getAttribute('aria-label') || '')
+ .replace(/\s+/g, ' ').trim().slice(0, 240);
+ if (!text) continue;
+ const points = [
+ [(left + right) / 2, (top + bottom) / 2],
+ [left + (right - left) * 0.2, top + (bottom - top) * 0.2],
+ [right - (right - left) * 0.2, bottom - (bottom - top) * 0.2],
+ ];
+ if (!points.some(([x, y]) => {
+ const hit = document.elementFromPoint(x, y);
+ return hit === el || el.contains(hit);
+ })) continue;
+ layers.push({
+ element: el,
+ role: el.getAttribute('role') || el.tagName.toLowerCase(),
+ text,
+ position: style.position,
+ rect: { x: Math.round(r.x), y: Math.round(r.y), w: Math.round(r.width), h: Math.round(r.height) },
+ });
+ } catch { /* ignore malformed or changing page surfaces */ }
+ }
+ return layers.map(({ element, ...layer }) => layer);
+ }
+
/**
* Extract readable text content from the page.
*
@@ -349,6 +398,7 @@
textSource: t.textSource,
isArticlePage: t.isArticlePage,
includeChrome: !!(params && params.includeChrome),
+ visibleLayers: blockedAuxiliaryContent ? [] : getVisibleLayers(),
media: blockedAuxiliaryContent
? { videoCount: 0, imageCount: 0, videos: [], images: [] }
: getPageMediaSummary(),
@@ -401,6 +451,7 @@
textSource: t.textSource,
isArticlePage: t.isArticlePage,
includeChrome: !!(params && params.includeChrome),
+ visibleLayers: blockedAuxiliaryContent ? [] : getVisibleLayers(),
media: blockedAuxiliaryContent
? { videoCount: 0, imageCount: 0, videos: [], images: [] }
: getPageMediaSummary(),
diff --git a/test/fixtures/run.mjs b/test/fixtures/run.mjs
index 34fcdb021..adbf3b6ab 100644
--- a/test/fixtures/run.mjs
+++ b/test/fixtures/run.mjs
@@ -18,6 +18,14 @@ import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { Agent } from '../../src/chrome/src/agent/agent.js';
import { Agent as FirefoxAgent } from '../../src/firefox/src/agent/agent.js';
+import {
+ applyReadPageWindow as applyChromeReadPageWindow,
+ fitReadPageWindowResult as fitChromeReadPageWindowResult,
+} from '../../src/chrome/src/agent/read-page-window.js';
+import {
+ applyReadPageWindow as applyFirefoxReadPageWindow,
+ fitReadPageWindowResult as fitFirefoxReadPageWindowResult,
+} from '../../src/firefox/src/agent/read-page-window.js';
import { CDPClient, cdpClient } from '../../src/chrome/src/cdp/cdp-client.js';
import {
SELECTION_SHORTCUT_LOCALES,
@@ -1090,6 +1098,107 @@ for (const [label, browserKind] of [['Chrome', 'chrome'], ['Firefox', 'firefox']
});
}
+const layeredReadingHtml = `<!doctype html>
+ <style>
+ body { margin: 0; }
+ header { position: fixed; top: 0; width: 100%; height: 40px; z-index: 5; background: white; }
+ article { padding: 70px 20px 20px; }
+ #read-target { position: absolute; left: 70px; top: 130px; width: 100px; height: 36px; }
+ [role="dialog"] { position: fixed; left: 50px; top: 100px; width: 240px; height: 120px; z-index: 20; background: white; }
+ [role="toolbar"] { position: fixed; right: 0; bottom: 0; width: 160px; height: 40px; z-index: 10; background: white; }
+ </style>
+ <header>Pinned navigation</header>
+ <article>
+ <button id="read-target">Read target</button>
+ <p>${'UNDERLYING_ARTICLE_TEXT describes the public inventory and its normal display. '.repeat(8)}</p>
+ <table><tr><th>Item</th><th>Count</th></tr><tr><td>Widget</td><td>42</td></tr></table>
+ </article>
+ <div role="dialog" aria-label="Open filters">Open filters dialog <button>Close filters</button></div>
+ <div data-overlay style="position:absolute;left:330px;top:120px;width:140px;height:60px;z-index:11;background:white">Floating panel</div>
+ <div role="toolbar">Floating tools</div>
+ <div role="dialog" style="display:none">Hidden dialog</div>`;
+
+function assertLayeredPageInfo(result, label) {
+ if (result?.pageGate || !result?.text?.includes('UNDERLYING_ARTICLE_TEXT')) {
+ throw new Error(`${label}: underlying article was lost: ${JSON.stringify(result)}`);
+ }
+ const layers = result.visibleLayers || [];
+ if (!layers.some(layer => layer.role === 'dialog' && layer.text.includes('Open filters dialog'))
+ || !layers.some(layer => layer.role === 'toolbar' && layer.text.includes('Floating tools'))
+ || !layers.some(layer => layer.role === 'header' && layer.text.includes('Pinned navigation'))
+ || !layers.some(layer => layer.role === 'div' && layer.position === 'absolute' && layer.text.includes('Floating panel'))
+ || layers.some(layer => layer.text.includes('Hidden dialog'))
+ || layers.some(layer => !Number.isFinite(layer.rect?.x) || !Number.isFinite(layer.rect?.y))) {
+ throw new Error(`${label}: visible layer context is incomplete: ${JSON.stringify(layers)}`);
+ }
+}
+
+async function assertLayeredContentReading(page, browserKind) {
+ await setupContentHtml(page, layeredReadingHtml, browserKind);
+ const overlapsTarget = await page.evaluate(() => {
+ const r = document.getElementById('read-target').getBoundingClientRect();
+ return !!document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2)?.closest('[role="dialog"]');
+ });
+ if (!overlapsTarget) throw new Error(`${browserKind}: fixture dialog does not cover the target`);
+ const pageInfo = await call(page, 'get_page_info_cdp', {});
+ assertLayeredPageInfo(pageInfo, browserKind);
+ const basicPageInfo = await call(page, 'get_page_info', {});
+ if (!basicPageInfo?.visibleLayers?.some(layer => layer.role === 'dialog' && layer.text.includes('Open filters dialog'))) {
+ throw new Error(`${browserKind}: basic page info omitted the dialog: ${JSON.stringify(basicPageInfo?.visibleLayers)}`);
+ }
+ const tables = await call(page, 'extract_data', { type: 'tables' });
+ if (tables?.[0]?.rows?.[1]?.join('|') !== 'Widget|42') {
+ throw new Error(`${browserKind}: underlying table data was lost: ${JSON.stringify(tables)}`);
+ }
+ const tree = await call(page, 'get_accessibility_tree', { filter: 'all', maxDepth: 8, maxChars: 20000 });
+ if (!/button "Read target" \[ref_\d+\][^\n]*occluded=true/.test(tree?.pageContent || '')) {
+ throw new Error(`${browserKind}: accessibility tree did not mark the covered target: ${tree?.pageContent}`);
+ }
+ await page.evaluate(() => {
+ const dialog = document.querySelector('[role="dialog"]');
+ for (let i = 0; i < 5; i++) {
+ const nav = document.createElement('nav');
+ nav.textContent = `Floating navigation ${i}`;
+ nav.style.cssText = `position:fixed;left:0;top:${390 + i * 42}px;width:180px;height:32px;background:white`;
+ document.body.insertBefore(nav, dialog);
+ }
+ });
+ const crowded = await call(page, 'get_page_info_cdp', {});
+ if (crowded.visibleLayers?.length > 4
+ || !crowded.visibleLayers?.some(layer => layer.role === 'dialog' && layer.text.includes('Open filters dialog'))) {
+ throw new Error(`${browserKind}: dialog was displaced by navigation layers: ${JSON.stringify(crowded.visibleLayers)}`);
+ }
+}
+
+test('Chrome: layered page read keeps underlying data and visible surfaces', page =>
+ assertLayeredContentReading(page, 'chrome'));
+firefoxTest('Firefox: layered page read keeps underlying data and visible surfaces', page =>
+ assertLayeredContentReading(page, 'firefox'));
+
+test('Chrome CDP mirror: layered page read keeps underlying data and visible surfaces', async (page) => {
+ await page.setContent(layeredReadingHtml);
+ assertLayeredPageInfo(await readThroughCdpMirror(page), 'CDP mirror');
+});
+
+test('read_page windows keep layer context when oversized output is compacted', async () => {
+ for (const [label, applyWindow, fitWindow] of [
+ ['chrome', applyChromeReadPageWindow, fitChromeReadPageWindowResult],
+ ['firefox', applyFirefoxReadPageWindow, fitFirefoxReadPageWindowResult],
+ ]) {
+ const raw = {
+ url: 'https://example.test/article',
+ title: 'Layered article',
+ text: 'Article text. '.repeat(500),
+ visibleLayers: [{ role: 'dialog', text: 'Open filters dialog', position: 'fixed', rect: { x: 50, y: 100, w: 240, h: 120 } }],
+ links: Array.from({ length: 100 }, (_, i) => ({ text: `Link ${i}`, href: `https://example.test/${i}` })),
+ };
+ const fitted = fitWindow(applyWindow(raw, { limit: 6000 }), 1200);
+ if (JSON.stringify(fitted).length > 1200 || fitted.visibleLayers?.[0]?.text !== 'Open filters dialog') {
+ throw new Error(`${label}: bounded read lost the visible layer: ${JSON.stringify(fitted)}`);
+ }
+ }
+});
+
test('Chrome CDP mirror suppresses a blocking Athletic article body', async (page) => {
await page.goto(fixtureUrl('athletic-subscription-overlay.html'));
const result = await readThroughCdpMirror(page);