Skip to content

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

fix: monitor subtree replacements and late shadow roots

Barack Sokulluf00527c1792b
diff --git a/docs/page-feedback-monitor.md b/docs/page-feedback-monitor.md
index 58c746453..c3adaf159 100644
--- a/docs/page-feedback-monitor.md
+++ b/docs/page-feedback-monitor.md
@@ -31,8 +31,11 @@ Steer or grant authorization. Enter and Alt+Enter retain their existing behavior
breaks the expectation, including a later click on the same target. Uncertain
effects remain `unknown`; `isTrusted` alone does not establish human origin.
- Meaningful visible content, control state, visibility and geometry changes are
- coalesced. CSS animation and extension decoration are ignored. Open shadow
- roots are observed; inaccessible frames and closed shadow roots retain the
+ coalesced. Visible subtree identity changes invalidate targets even when the
+ replacement has identical text and geometry. CSS animation and extension
+ decoration are ignored. A MAIN-world attachment signal observes new open
+ shadow roots on existing hosts before their initial rendering; shadow-root
+ child-list mutations are also monitored. Inaccessible frames and closed shadow roots retain the
existing browser-access limitations.
- Event payloads contain bounded target identifiers and scroll positions, never
typed keys, field values or selected text. The subsequent normal page read uses
@@ -66,7 +69,8 @@ cancellation remove the monitor and its pending run state.
`npm run test:page-feedback` runs the controller/transport/workflow/cloud/scheduler
regressions and real Chromium/Firefox DOM fixtures. Fixtures exercise trusted
-browser input, same-target intervention, frames, open shadow roots, window and
+browser input, same-target intervention, same-shape subtree replacements, frames,
+late shadow-root attachment and custom-element upgrades, window and
container scrolling, animation noise, cleanup/restart and persisted navigation
notes. Browser extension APIs are mocked in these fixtures; they are not a live
companion-session integration test.
diff --git a/src/chrome/manifest.json b/src/chrome/manifest.json
index a42a5abdb..391079132 100644
--- a/src/chrome/manifest.json
+++ b/src/chrome/manifest.json
@@ -55,7 +55,7 @@
},
{
"matches": ["<all_urls>"],
- "js": ["src/content/captcha-callback-bridge.js"],
+ "js": ["src/content/page-monitor-shadow.js", "src/content/captcha-callback-bridge.js"],
"run_at": "document_start",
"world": "MAIN",
"all_frames": true,
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index 264ec3fe2..fa418a562 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -33024,7 +33024,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
await chrome.scripting.executeScript({
target: { tabId },
world: 'MAIN',
- files: ['src/content/file-picker-guard-page.js'],
+ files: ['src/content/page-monitor-shadow.js', 'src/content/file-picker-guard-page.js'],
});
await chrome.scripting.executeScript({
target: { tabId },
diff --git a/src/chrome/src/content/page-monitor-shadow.js b/src/chrome/src/content/page-monitor-shadow.js
new file mode 100644
index 000000000..c4ab4f6a3
--- /dev/null
+++ b/src/chrome/src/content/page-monitor-shadow.js
@@ -0,0 +1,17 @@
+/** MAIN-world attachment signal; contains no page content or input values. */
+(() => {
+ const descriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'attachShadow');
+ const original = descriptor?.value;
+ if (typeof original !== 'function' || original.__webbrainShadowMonitor) return;
+ function attachShadow(options) {
+ const root = Reflect.apply(original, this, arguments);
+ // Observe before the caller fills the new root. Dormant monitors emit
+ // nothing, and detached hosts are discovered when inserted in the DOM.
+ if (root.mode === 'open' && this.isConnected && document.documentElement?.hasAttribute('data-webbrain-page-revision')) {
+ try { this.dispatchEvent(new Event('webbrain-shadow-root-attached', { bubbles: true, composed: true })); } catch {}
+ }
+ return root;
+ }
+ Object.defineProperty(attachShadow, '__webbrainShadowMonitor', { value: true });
+ try { Object.defineProperty(Element.prototype, 'attachShadow', { ...descriptor, value: attachShadow }); } catch {}
+})();
diff --git a/src/chrome/src/content/page-monitor.js b/src/chrome/src/content/page-monitor.js
index 4bb4ee80f..51cb1713b 100644
--- a/src/chrome/src/content/page-monitor.js
+++ b/src/chrome/src/content/page-monitor.js
@@ -136,27 +136,50 @@
if (ignored(el)) return '';
const shown = visible(el);
const rect = shown ? el.getBoundingClientRect() : {};
- const content = editable(el) ? '' : [...el.childNodes].filter(node => node.nodeType === 3)
+ const content = editable(el) ? '' : [...el.childNodes, ...(el.shadowRoot?.childNodes || [])].filter(node => node.nodeType === 3)
.map(node => node.textContent).join('').slice(0, 200);
- return JSON.stringify([shown, content, el.children.length, el.getAttribute('role'), el.getAttribute('aria-label'),
+ return JSON.stringify([shown, content, el.children.length + (el.shadowRoot?.children.length || 0), el.getAttribute('role'), el.getAttribute('aria-label'),
el.getAttribute('aria-expanded'), el.getAttribute('aria-selected'), el.getAttribute('aria-checked'),
el.getAttribute('aria-disabled'), el.disabled === true, el.readOnly === true, el.checked === true, el.validity?.valid !== false, Math.round((rect.width || 0) / 8), Math.round((rect.height || 0) / 8),
Math.round(((rect.x || 0) + window.scrollX) / 8), Math.round(((rect.y || 0) + window.scrollY) / 8)]);
}
- function seed(root) {
+ function seed(root, budget = { remaining: 600 }) {
const nodes = root.querySelectorAll?.('*') || [];
- for (const el of [...nodes].slice(0, 600)) {
- signatures.set(el, signature(el));
- if (el.shadowRoot) observeRoot(el.shadowRoot);
+ for (const el of nodes) {
+ if (budget.remaining > 0) { budget.remaining--; signatures.set(el, signature(el)); }
+ // Root discovery is cheap and must not share the layout-measurement cap.
+ if (el.shadowRoot && !ignored(el)) observeRoot(el.shadowRoot, budget);
}
}
- function observeRoot(root) {
+ function observeRoot(root, budget) {
if (!root || roots.has(root) || !observer) return;
roots.add(root);
observer.observe(root, { childList: true, subtree: true, characterData: true, attributes: true,
attributeFilter: ['role', 'aria-label', 'aria-expanded', 'aria-selected', 'aria-checked', 'aria-disabled',
'aria-hidden', 'hidden', 'disabled', 'readonly', 'checked', 'selected', 'class', 'style'] });
- seed(root);
+ seed(root, budget);
+ }
+ function subtreeChanged(record, el) {
+ const changedNodes = [...record.addedNodes, ...record.removedNodes];
+ const meaningful = node => {
+ // Text identity is not an interactive target; its content is compared by
+ // the parent's signature, including direct text in a shadow root.
+ if (node.nodeType === 3) return false;
+ if (node.nodeType !== 1 || ignored(node)) return false;
+ if (visible(node) || signatures.get(node)?.startsWith('[true')) return true;
+ return [...node.querySelectorAll('*')].slice(0, 200).some(child => !ignored(child)
+ && (visible(child) || signatures.get(child)?.startsWith('[true')));
+ };
+ if (changedNodes.some(meaningful)) return true;
+ // Removed prepared targets also matter when their old geometry was outside
+ // the bounded signature seed, including targets inside an open shadow root.
+ return [...record.removedNodes].some(node => !ignored(node.nodeType === 1 ? node : el)
+ && [...operations.values()].some(op => {
+ for (let target = op.target; target; target = target.getRootNode?.().host) {
+ if (node === target || node.contains?.(target)) return true;
+ }
+ return false;
+ }));
}
function onMutations(records) {
if (!active) return;
@@ -169,23 +192,29 @@
changes.push({ type: 'layout', target: el });
}
let measured = 0;
+ const seedBudget = { remaining: 600 };
for (const record of changes) {
- const el = record.target.nodeType === 1 ? record.target : record.target.parentElement;
+ const el = record.target.nodeType === 1 ? record.target : record.target.host || record.target.parentElement;
if (ignored(el) || (record.type === 'characterData' && editable(el))) continue;
if (record.type === 'attributes' && ['class', 'style'].includes(record.attributeName)
&& el.getAnimations?.().some(animation => animation.playState === 'running')) continue;
+ if (++measured > 300) break;
+ let identityChanged = record.type === 'shadow' && (visible(el) || signatures.get(el)?.startsWith('[true'));
if (record.type === 'childList') {
+ identityChanged = subtreeChanged(record, el);
for (const node of record.addedNodes) {
- if (node.nodeType !== 1) continue;
- if (node.shadowRoot) observeRoot(node.shadowRoot);
- for (const child of [...node.querySelectorAll('*')].slice(0, 200)) if (child.shadowRoot) observeRoot(child.shadowRoot);
+ if (node.nodeType !== 1 || ignored(node)) continue;
+ if (seedBudget.remaining > 0) { seedBudget.remaining--; signatures.set(node, signature(node)); }
+ seed(node, seedBudget);
+ if (node.shadowRoot) observeRoot(node.shadowRoot, seedBudget);
+ }
+ if ([...record.addedNodes, ...record.removedNodes].every(node => node.nodeType === 1 && ignored(node))) {
+ signatures.set(el, signature(el)); continue;
}
- if ([...record.addedNodes, ...record.removedNodes].every(node => node.nodeType === 1 && ignored(node))) continue;
}
- if (++measured > 300) break;
const next = signature(el), previous = signatures.get(el);
signatures.set(el, next);
- if (next === previous || (!visible(el) && !previous?.startsWith('[true'))) continue;
+ if (!identityChanged && (next === previous || (!visible(el) && !previous?.startsWith('[true')))) continue;
// Attribute the marked input/write's synchronous handlers to that dispatch.
// Later DOM writes stay observable, including writes on the same target.
if (agentTurn && lastUserAt <= agentTurn.userAt) continue;
@@ -211,6 +240,14 @@
active = true; runToken = state.runToken; seq = 0; revision = 0; publishRevision();
observer = new MutationObserver(onMutations);
observeRoot(document);
+ listen(document, 'webbrain-shadow-root-attached', event => {
+ const path = event.composedPath();
+ if (path.some(node => node instanceof Element && ignored(node))) return;
+ const host = elementFor(event), root = host?.shadowRoot;
+ if (!host?.isConnected || !root || roots.has(root)) return;
+ observeRoot(root);
+ onMutations([{ type: 'shadow', target: host }]);
+ });
listen(document, 'webbrain-agent-dom-dispatch', event => {
try {
const guard = JSON.parse(String(event.detail));
diff --git a/src/firefox/manifest.json b/src/firefox/manifest.json
index fb1f2c210..4e9cf68b8 100644
--- a/src/firefox/manifest.json
+++ b/src/firefox/manifest.json
@@ -45,7 +45,7 @@
},
{
"matches": ["<all_urls>"],
- "js": ["src/content/captcha-callback-bridge.js"],
+ "js": ["src/content/page-monitor-shadow.js", "src/content/captcha-callback-bridge.js"],
"run_at": "document_start",
"world": "MAIN",
"all_frames": true,
@@ -131,6 +131,7 @@
"vendor/pdfjs/pdf.worker.mjs",
"src/agent/social-media-downloader.js",
"src/content/file-picker-guard-page.js",
+ "src/content/page-monitor-shadow.js",
"skills/*"
],
"browser_specific_settings": {
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index f598f7c0d..f97bcefae 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -35349,6 +35349,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
async _injectCoreContentScripts(tabId) {
+ await browser.tabs.executeScript(tabId, { file: 'src/content/page-monitor-shadow-loader.js' });
await browser.tabs.executeScript(tabId, { file: 'src/content/page-monitor.js' });
await browser.tabs.executeScript(tabId, {
file: 'src/content/file-picker-guard-loader.js',
diff --git a/src/firefox/src/content/page-monitor-shadow-loader.js b/src/firefox/src/content/page-monitor-shadow-loader.js
new file mode 100644
index 000000000..7b71d7513
--- /dev/null
+++ b/src/firefox/src/content/page-monitor-shadow-loader.js
@@ -0,0 +1,10 @@
+/** Firefox MV2 reinjection fallback; normal document startup uses MAIN world. */
+(() => {
+ try {
+ const script = document.createElement('script');
+ script.src = browser.runtime.getURL('src/content/page-monitor-shadow.js');
+ script.async = false;
+ script.onload = script.onerror = () => script.remove();
+ (document.head || document.documentElement).appendChild(script);
+ } catch {}
+})();
diff --git a/src/firefox/src/content/page-monitor-shadow.js b/src/firefox/src/content/page-monitor-shadow.js
new file mode 100644
index 000000000..c4ab4f6a3
--- /dev/null
+++ b/src/firefox/src/content/page-monitor-shadow.js
@@ -0,0 +1,17 @@
+/** MAIN-world attachment signal; contains no page content or input values. */
+(() => {
+ const descriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'attachShadow');
+ const original = descriptor?.value;
+ if (typeof original !== 'function' || original.__webbrainShadowMonitor) return;
+ function attachShadow(options) {
+ const root = Reflect.apply(original, this, arguments);
+ // Observe before the caller fills the new root. Dormant monitors emit
+ // nothing, and detached hosts are discovered when inserted in the DOM.
+ if (root.mode === 'open' && this.isConnected && document.documentElement?.hasAttribute('data-webbrain-page-revision')) {
+ try { this.dispatchEvent(new Event('webbrain-shadow-root-attached', { bubbles: true, composed: true })); } catch {}
+ }
+ return root;
+ }
+ Object.defineProperty(attachShadow, '__webbrainShadowMonitor', { value: true });
+ try { Object.defineProperty(Element.prototype, 'attachShadow', { ...descriptor, value: attachShadow }); } catch {}
+})();
diff --git a/src/firefox/src/content/page-monitor.js b/src/firefox/src/content/page-monitor.js
index 4bb4ee80f..51cb1713b 100644
--- a/src/firefox/src/content/page-monitor.js
+++ b/src/firefox/src/content/page-monitor.js
@@ -136,27 +136,50 @@
if (ignored(el)) return '';
const shown = visible(el);
const rect = shown ? el.getBoundingClientRect() : {};
- const content = editable(el) ? '' : [...el.childNodes].filter(node => node.nodeType === 3)
+ const content = editable(el) ? '' : [...el.childNodes, ...(el.shadowRoot?.childNodes || [])].filter(node => node.nodeType === 3)
.map(node => node.textContent).join('').slice(0, 200);
- return JSON.stringify([shown, content, el.children.length, el.getAttribute('role'), el.getAttribute('aria-label'),
+ return JSON.stringify([shown, content, el.children.length + (el.shadowRoot?.children.length || 0), el.getAttribute('role'), el.getAttribute('aria-label'),
el.getAttribute('aria-expanded'), el.getAttribute('aria-selected'), el.getAttribute('aria-checked'),
el.getAttribute('aria-disabled'), el.disabled === true, el.readOnly === true, el.checked === true, el.validity?.valid !== false, Math.round((rect.width || 0) / 8), Math.round((rect.height || 0) / 8),
Math.round(((rect.x || 0) + window.scrollX) / 8), Math.round(((rect.y || 0) + window.scrollY) / 8)]);
}
- function seed(root) {
+ function seed(root, budget = { remaining: 600 }) {
const nodes = root.querySelectorAll?.('*') || [];
- for (const el of [...nodes].slice(0, 600)) {
- signatures.set(el, signature(el));
- if (el.shadowRoot) observeRoot(el.shadowRoot);
+ for (const el of nodes) {
+ if (budget.remaining > 0) { budget.remaining--; signatures.set(el, signature(el)); }
+ // Root discovery is cheap and must not share the layout-measurement cap.
+ if (el.shadowRoot && !ignored(el)) observeRoot(el.shadowRoot, budget);
}
}
- function observeRoot(root) {
+ function observeRoot(root, budget) {
if (!root || roots.has(root) || !observer) return;
roots.add(root);
observer.observe(root, { childList: true, subtree: true, characterData: true, attributes: true,
attributeFilter: ['role', 'aria-label', 'aria-expanded', 'aria-selected', 'aria-checked', 'aria-disabled',
'aria-hidden', 'hidden', 'disabled', 'readonly', 'checked', 'selected', 'class', 'style'] });
- seed(root);
+ seed(root, budget);
+ }
+ function subtreeChanged(record, el) {
+ const changedNodes = [...record.addedNodes, ...record.removedNodes];
+ const meaningful = node => {
+ // Text identity is not an interactive target; its content is compared by
+ // the parent's signature, including direct text in a shadow root.
+ if (node.nodeType === 3) return false;
+ if (node.nodeType !== 1 || ignored(node)) return false;
+ if (visible(node) || signatures.get(node)?.startsWith('[true')) return true;
+ return [...node.querySelectorAll('*')].slice(0, 200).some(child => !ignored(child)
+ && (visible(child) || signatures.get(child)?.startsWith('[true')));
+ };
+ if (changedNodes.some(meaningful)) return true;
+ // Removed prepared targets also matter when their old geometry was outside
+ // the bounded signature seed, including targets inside an open shadow root.
+ return [...record.removedNodes].some(node => !ignored(node.nodeType === 1 ? node : el)
+ && [...operations.values()].some(op => {
+ for (let target = op.target; target; target = target.getRootNode?.().host) {
+ if (node === target || node.contains?.(target)) return true;
+ }
+ return false;
+ }));
}
function onMutations(records) {
if (!active) return;
@@ -169,23 +192,29 @@
changes.push({ type: 'layout', target: el });
}
let measured = 0;
+ const seedBudget = { remaining: 600 };
for (const record of changes) {
- const el = record.target.nodeType === 1 ? record.target : record.target.parentElement;
+ const el = record.target.nodeType === 1 ? record.target : record.target.host || record.target.parentElement;
if (ignored(el) || (record.type === 'characterData' && editable(el))) continue;
if (record.type === 'attributes' && ['class', 'style'].includes(record.attributeName)
&& el.getAnimations?.().some(animation => animation.playState === 'running')) continue;
+ if (++measured > 300) break;
+ let identityChanged = record.type === 'shadow' && (visible(el) || signatures.get(el)?.startsWith('[true'));
if (record.type === 'childList') {
+ identityChanged = subtreeChanged(record, el);
for (const node of record.addedNodes) {
- if (node.nodeType !== 1) continue;
- if (node.shadowRoot) observeRoot(node.shadowRoot);
- for (const child of [...node.querySelectorAll('*')].slice(0, 200)) if (child.shadowRoot) observeRoot(child.shadowRoot);
+ if (node.nodeType !== 1 || ignored(node)) continue;
+ if (seedBudget.remaining > 0) { seedBudget.remaining--; signatures.set(node, signature(node)); }
+ seed(node, seedBudget);
+ if (node.shadowRoot) observeRoot(node.shadowRoot, seedBudget);
+ }
+ if ([...record.addedNodes, ...record.removedNodes].every(node => node.nodeType === 1 && ignored(node))) {
+ signatures.set(el, signature(el)); continue;
}
- if ([...record.addedNodes, ...record.removedNodes].every(node => node.nodeType === 1 && ignored(node))) continue;
}
- if (++measured > 300) break;
const next = signature(el), previous = signatures.get(el);
signatures.set(el, next);
- if (next === previous || (!visible(el) && !previous?.startsWith('[true'))) continue;
+ if (!identityChanged && (next === previous || (!visible(el) && !previous?.startsWith('[true')))) continue;
// Attribute the marked input/write's synchronous handlers to that dispatch.
// Later DOM writes stay observable, including writes on the same target.
if (agentTurn && lastUserAt <= agentTurn.userAt) continue;
@@ -211,6 +240,14 @@
active = true; runToken = state.runToken; seq = 0; revision = 0; publishRevision();
observer = new MutationObserver(onMutations);
observeRoot(document);
+ listen(document, 'webbrain-shadow-root-attached', event => {
+ const path = event.composedPath();
+ if (path.some(node => node instanceof Element && ignored(node))) return;
+ const host = elementFor(event), root = host?.shadowRoot;
+ if (!host?.isConnected || !root || roots.has(root)) return;
+ observeRoot(root);
+ onMutations([{ type: 'shadow', target: host }]);
+ });
listen(document, 'webbrain-agent-dom-dispatch', event => {
try {
const guard = JSON.parse(String(event.detail));
diff --git a/test/page-feedback.mjs b/test/page-feedback.mjs
index 22c9bc37e..1e2285260 100644
--- a/test/page-feedback.mjs
+++ b/test/page-feedback.mjs
@@ -414,12 +414,23 @@ for (const build of ['chrome', 'firefox']) {
}
test('shared page monitoring modules stay identical between browser builds', () => {
- for (const file of ['agent/page-feedback.js', 'content/page-monitor.js', 'ui/page-feedback-ui.js']) {
+ for (const file of ['agent/page-feedback.js', 'content/page-monitor.js', 'content/page-monitor-shadow.js', 'ui/page-feedback-ui.js']) {
const read = build => fs.readFileSync(new URL(`../src/${build}/src/${file}`, import.meta.url), 'utf8');
assert.equal(read('chrome'), read('firefox'));
}
});
+test('both manifests signal shadow attachment from MAIN in all monitored frames', () => {
+ for (const build of ['chrome', 'firefox']) {
+ const manifest = JSON.parse(fs.readFileSync(new URL(`../src/${build}/manifest.json`, import.meta.url), 'utf8'));
+ const entry = manifest.content_scripts.find(item => item.js.includes('src/content/page-monitor-shadow.js'));
+ assert.equal(entry.world, 'MAIN');
+ assert.equal(entry.run_at, 'document_start');
+ assert.equal(entry.all_frames, true);
+ assert.equal(entry.match_about_blank, true);
+ }
+});
+
for (const path of ['local', 'memory']) {
for (const intervention of ['preparation', 'handshake', 'none']) {
test(`Chrome ${path} upload honors feedback arriving during ${intervention}`, async () => {
diff --git a/test/page-monitor-ui.mjs b/test/page-monitor-ui.mjs
index ee2e91eda..2f0db4f55 100644
--- a/test/page-monitor-ui.mjs
+++ b/test/page-monitor-ui.mjs
@@ -38,6 +38,7 @@ async function fixture(engine, build, { runToken = 'test-run', siteIsolation = f
params: { runToken: monitorRunToken, ...params }, active: action === 'page_monitor_state' ? monitorEnabled : undefined,
runToken: monitorRunToken }, {}, value => { window.lastMonitorResponse = value; }));
});
+ await context.addInitScript({ content: read(build, 'content/page-monitor-shadow.js') });
await context.addInitScript({ content: read(build, 'content/page-monitor.js') });
const page = await context.newPage();
await page.goto('https://monitor.test/start');
@@ -297,9 +298,11 @@ for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) {
feedback = [];
const decoration = document.createElement('div'); decoration.dataset.webbrainUi = 'indicator';
decoration.textContent = 'Agent decoration'; document.body.appendChild(decoration);
+ const root = decoration.attachShadow({ mode: 'open' }); root.innerHTML = '<span>Shadow decoration</span>';
window.animationUpdates = setInterval(() => {
document.getElementById('moving').style.transform = `translateX(${Math.random() * 10}px)`;
decoration.textContent = String(Math.random());
+ root.querySelector('span').textContent = String(Math.random());
}, 10);
});
await page.waitForTimeout(400);
@@ -331,6 +334,71 @@ for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) {
} finally { await browser.close(); }
});
+ test(`${build}: same-shape subtree replacements invalidate prepared actions`, async () => {
+ const { browser, page } = await fixture(engine, build);
+ try {
+ await page.evaluate(() => {
+ const region = document.createElement('div'); region.id = 'rerender';
+ region.style.cssText = 'width:200px;height:50px';
+ region.innerHTML = '<div><button id="replace-target" style="width:100px;height:30px">Old</button></div>';
+ document.body.prepend(region);
+ });
+ for (const label of ['New', 'New']) {
+ await page.evaluate(() => { monitorEnabled = false; deliver('page_monitor_state'); monitorEnabled = true; deliver('page_monitor_state'); });
+ await page.waitForTimeout(200);
+ const result = await page.evaluate(async label => {
+ feedback = [];
+ const region = document.getElementById('rerender'), oldTarget = document.getElementById('replace-target');
+ const before = region.getBoundingClientRect();
+ const fence = document.documentElement.getAttribute('data-webbrain-page-revision');
+ const finish = __wbPageMonitor.beginContentAction('click', { selector: '#replace-target', _bidiPrepare: true });
+ region.innerHTML = `<div><button id="replace-target" style="width:100px;height:30px">${label}</button></div>`;
+ await Promise.resolve();
+ let code;
+ try { __wbPageMonitor.beforeLocalDispatch(); } catch (error) { code = error.code; }
+ finally { finish(); }
+ const after = region.getBoundingClientRect();
+ return { code, disconnected: !oldTarget.isConnected, sameSize: before.width === after.width && before.height === after.height,
+ revised: fence !== document.documentElement.getAttribute('data-webbrain-page-revision') };
+ }, label);
+ assert.deepEqual(result, { code: 'page_feedback_pending', disconnected: true, sameSize: true, revised: true });
+ await page.waitForFunction(() => feedback.some(event => event.kind === 'dom'));
+ }
+ } finally { await browser.close(); }
+ });
+
+ test(`${build}: upgrading an existing host observes its newly attached shadow root`, async () => {
+ const { browser, page } = await fixture(engine, build);
+ try {
+ await page.evaluate(() => {
+ const host = document.createElement('wb-late-shadow'); host.id = 'late-shadow';
+ host.style.cssText = 'display:block;width:200px;height:50px'; document.body.prepend(host);
+ monitorEnabled = false; deliver('page_monitor_state'); monitorEnabled = true; deliver('page_monitor_state');
+ });
+ await page.waitForTimeout(200);
+ const result = await page.evaluate(async () => {
+ feedback = [];
+ const finish = __wbPageMonitor.beginContentAction('click', { selector: '#agent', _bidiPrepare: true });
+ customElements.define('wb-late-shadow', class extends HTMLElement {
+ constructor() { super(); this.attachShadow({ mode: 'open' }).innerHTML = '<button id="late-target">Before</button>'; }
+ });
+ await Promise.resolve();
+ try { __wbPageMonitor.beforeLocalDispatch(); return null; }
+ catch (error) { return error.code; }
+ finally { finish(); }
+ });
+ assert.equal(result, 'page_feedback_pending');
+ await page.waitForFunction(() => feedback.some(event => event.kind === 'dom'));
+ await page.evaluate(() => { feedback = []; document.getElementById('late-shadow').shadowRoot.querySelector('button').textContent = 'After'; });
+ await page.waitForFunction(() => feedback.some(event => event.kind === 'dom' && event.target === 'button#late-target'));
+ await page.evaluate(() => { feedback = []; document.getElementById('late-shadow').shadowRoot.innerHTML = '<button id="late-target">After</button>'; });
+ await page.waitForFunction(() => feedback.some(event => event.kind === 'dom'));
+ await page.evaluate(() => { monitorEnabled = false; deliver('page_monitor_state'); feedback = []; document.getElementById('late-shadow').shadowRoot.querySelector('button').textContent = 'Stopped'; });
+ await page.waitForTimeout(200);
+ assert.equal((await page.evaluate(() => feedback)).length, 0);
+ } finally { await browser.close(); }
+ });
+
test(`${build}: marked synchronous DOM writes suppress their own effects and retain later edits`, async () => {
const { browser, page } = await fixture(engine, build);
try {