Open-source AI browser agent for Chrome and Firefox (monorepo) ðŸ§
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
fix: allow verified LinkedIn navigation through recipient guard
release-verification8c8a968d605b
diff --git a/src/chrome/src/content/content.js b/src/chrome/src/content/content.jsindex 8a53fe287..280486754 100644--- a/src/chrome/src/content/content.js+++ b/src/chrome/src/content/content.js@@ -1337,6 +1337,20 @@};}+ // Shared by click dispatch and its recipient-safety preflight. In+ // particular, navigation links must participate in text-match ambiguity.+ function _clickTextCandidates(scope) {+ const selectors = [+ 'a', 'button', '[role="button"]', '[role="link"]', '[role="tab"]', '[role="menuitem"]',+ 'input:not([type="hidden"])', 'textarea', 'select', 'input[type="button"]',+ 'input[type="submit"]', 'summary', 'label', '[onclick]', '[data-action]',+ ..._siteInteractiveSelectors(),+ ].join(', ');+ return Array.from(scope.querySelectorAll(selectors))+ .map(e => ({ e, txt: _siteInteractionText(e).toLowerCase() }))+ .filter(candidate => candidate.txt);+ }+let _lastClickIdent = null;/**@@ -1372,13 +1386,6 @@if (params.text) {const needle = params.text.toLowerCase();const explicit = params.textMatch || '';- // Include inputs/select/textarea so we can match by placeholder, value, or aria-label- const sels = [- 'a', 'button', '[role="button"]', '[role="link"]', '[role="tab"]', '[role="menuitem"]',- 'input:not([type="hidden"])', 'textarea', 'select', 'input[type="button"]',- 'input[type="submit"]', 'summary', 'label', '[onclick]', '[data-action]',- ..._siteInteractiveSelectors(),- ].join(', ');// Modal scoping: if a topmost modal/dialog is open, restrict the search// to elements inside it. Without this, click({text: "Create"}) can land// on a background button (GitHub's "Create new tag" dialog over the@@ -1386,11 +1393,7 @@// what queryInteractive() already does for index-based clicks.const _modalRoot = _findTopmostModal();const _scope = _modalRoot || document;- const all = Array.from(_scope.querySelectorAll(sels));- const normalized = all.map(e => ({- e,- txt: _siteInteractionText(e).toLowerCase(),- })).filter(x => !!x.txt);+ const normalized = _clickTextCandidates(_scope);// Build label→input map so we can match label text and resolve to associated inputconst labelMap = new Map();@@ -1447,11 +1450,7 @@if (actionDeadlineExpired()) return deadlineFailure();window.scrollBy(0, Math.round(window.innerHeight * 0.7));const _retryScope = _findTopmostModal() || document;- const allRetry = Array.from(_retryScope.querySelectorAll(sels));- const normRetry = allRetry.map(e => ({- e,- txt: _siteInteractionText(e).toLowerCase(),- })).filter(x => !!x.txt);+ const normRetry = _clickTextCandidates(_retryScope);for (const m of modes) {if (m === 'exact') matches = normRetry.filter(x => x.txt === needle);else if (m === 'prefix') matches = normRetry.filter(x => x.txt.startsWith(needle));@@ -4900,20 +4899,32 @@if (refId && typeof window.__wb_ax_lookup === 'function') target = window.__wb_ax_lookup(refId);targetResolved = !!target;} else if (tool === 'click') {- if (typeof args.selector === 'string' && args.selector) {- try { target = document.querySelector(args.selector); } catch {}+ // Match dispatch precedence, modal scope, candidate text and match+ // mode. A supplied selector must not approve a different text click.+ if (typeof args.text === 'string' && args.text) {+ const needle = args.text.toLowerCase();+ const scope = _findTopmostModal() || document;+ const candidates = _clickTextCandidates(scope);+ const modes = args.textMatch ? [args.textMatch] : ['exact', 'prefix', 'contains'];+ for (const mode of modes) {+ let matches = candidates.filter(({ txt }) => mode === 'exact' ? txt === needle+ : mode === 'prefix' ? txt.startsWith(needle)+ : mode === 'contains' ? txt.includes(needle) : false);+ // Dispatch prefers the sole interactive match over passive labels.+ // Multiple interactive matches must still stop at this match tier.+ if (matches.length > 1) {+ const interactiveMatches = matches.filter(({ e }) => _isInteractive(e));+ if (interactiveMatches.length === 1) matches = interactiveMatches;+ }+ if (matches.length === 1) target = _resolveInteractiveAncestor(matches[0].e);+ if (matches.length) break;+ }+ } else if (typeof args.selector === 'string' && args.selector) {+ target = safeIndexedQuerySelector(args.selector, args.matchIndex).element;} else if (Number.isInteger(args.index) && args.index >= 0) {target = queryInteractiveForToolIndex()[args.index] || null;} else if (Number.isFinite(args.x) && Number.isFinite(args.y)) {target = document.elementFromPoint(args.x, args.y);- } else if (typeof args.text === 'string' && args.text.trim()) {- const needle = compact(args.text).toLocaleLowerCase();- const matches = Array.from(document.querySelectorAll(- 'button,[role="button"],input[type="submit"],input[type="button"],[data-action]'- )).filter((el) => compact(- el.innerText || el.value || el.getAttribute?.('aria-label') || el.getAttribute?.('title')- ).toLocaleLowerCase() === needle);- if (matches.length === 1) target = matches[0];}targetResolved = !!target;}@@ -5023,6 +5034,33 @@&& railRect.right <= composerRect.left + 64;};+ const verifiedLinkedInNavigation = (clicked) => {+ if (params.adapterName !== 'linkedin' || !clicked) return false;+ const link = clicked.closest?.('a[href]');+ if (!link || !visible(link) || !link.closest?.('nav,[role="navigation"]')) return false;+ // A navigation-looking descendant of a composer/action is not a+ // navigation escape hatch. Keep actual sends and modal controls on+ // the existing recipient-verification path.+ if (clicked.closest?.('button,[role="button"],input,select,textarea,[contenteditable]:not([contenteditable="false"]),[onclick],[data-action]')+ || link.closest?.('form,dialog,[role="dialog"],[role="alertdialog"]')+ || link.hasAttribute?.('download')+ || (link.getAttribute?.('role') && link.getAttribute('role') !== 'link')) return false;+ try {+ const href = String(link.getAttribute('href') || '').trim();+ if (!href || href.startsWith('#')) return false;+ const destination = new URL(href, document.baseURI);+ // Only the site's top-level navigation destinations are known not+ // to send. Arbitrary action URLs and conversation controls stay+ // inconclusive, even when their visible label says Home or Jobs.+ return /^https?:$/.test(destination.protocol)+ && destination.origin === location.origin+ && /^(?:www\.)?linkedin\.com$/.test(destination.hostname)+ && /^\/(?:feed|jobs|mynetwork|messaging|notifications)\/?$/.test(destination.pathname);+ } catch {+ return false;+ }+ };+let composer = null;let messageSend = null;if (observationOnly) {@@ -5059,9 +5097,13 @@return { success: true, messageSend: null, conclusive: false, identityCandidates: [] };}const control = target.closest?.('button,[role="button"],input[type="submit"],input[type="button"],[data-action]') || target;- if (!visible(control)) {+ const modal = _findTopmostBlockingModal();+ if (!visible(control) || (modal && !_isComposedAncestor(modal, target))) {return { success: true, messageSend: null, conclusive: false, identityCandidates: [] };}+ if (verifiedLinkedInNavigation(target)) {+ return { success: true, messageSend: false, conclusive: true, navigation: true, identityCandidates: [] };+ }composer = layoutComposer;if (!composer) {const actionLabel = compact(diff --git a/src/firefox/src/content/content.js b/src/firefox/src/content/content.jsindex b62dfb582..56db9c317 100644--- a/src/firefox/src/content/content.js+++ b/src/firefox/src/content/content.js@@ -1277,6 +1277,54 @@return { element: matches[requested] || null, matchCount: matches.length, matchIndex: requested };}+ // Shared by click dispatch and its recipient-safety preflight. Keep the+ // Firefox option visibility and input-label rules identical in both paths.+ function _clickTextCandidates(scope) {+ const sels = [+ 'a', 'button', '[role="button"]', '[role="link"]', '[role="tab"]', '[role="menuitem"]',+ '[role="option"]', '[role="menuitemradio"]', '[role="menuitemcheckbox"]', '[role="treeitem"]',+ 'input:not([type="hidden"])', 'textarea', 'select', 'input[type="button"]',+ 'input[type="submit"]', 'summary', 'label', '[onclick]', '[data-action]',+ ..._siteInteractiveSelectors(),+ ].join(', ');+ // Candidate filter: listbox/menu option roles are often kept mounted but+ // hidden while a custom select is collapsed or virtualized (Radix/MUI/+ // React-Select). Drop hidden ones so click({text}) can't match — and+ // falsely "succeed" on — an invisible option; the open-listbox fallback+ // still surfaces them when the control is actually open. Shared by the+ // primary pass AND the auto-scroll retry below so they can't diverge.+ const _keepCandidate = (el) => {+ const role = (el.getAttribute && el.getAttribute('role')) || '';+ if (role !== 'option' && role !== 'menuitemradio' && role !== 'menuitemcheckbox' && role !== 'treeitem') return true;+ try {+ const r = el.getBoundingClientRect();+ if (r.width < 1 || r.height < 1) return false;+ const s = window.getComputedStyle(el);+ if (s.visibility === 'hidden' || s.display === 'none' || parseFloat(s.opacity) === 0) return false;+ if (el.closest('[aria-hidden="true"],[hidden]')) return false;+ return true;+ } catch (e) { return false; }+ };+ // A text field's `value` is content the user typed, NOT a click label.+ // Matching on it makes click({text}) resolve to the field you just filled+ // (e.g. a combobox/filter box whose value now equals the needle) instead+ // of the menu option bearing the same text — the "click succeeds but+ // nothing happens, model loops forever" bug. Only treat `value` as a label+ // for button-like inputs; non-input elements with .value (<select>) keep it.+ const _valIsLabel = (el) => {+ if (el.tagName === 'TEXTAREA') return false;+ if (el.tagName !== 'INPUT') return true;+ const t = (el.getAttribute('type') || 'text').toLowerCase();+ return t === 'button' || t === 'submit' || t === 'reset';+ };+ const _normTxt = (el) => {+ const siteText = _isSiteInteractive(el) ? _siteInteractionText(el) : '';+ return (siteText || el.innerText || (_valIsLabel(el) ? el.value : '') || el.placeholder || el.ariaLabel || '').trim().toLowerCase();+ };+ const all = Array.from(scope.querySelectorAll(sels)).filter(_keepCandidate);+ return all.map(e => ({ e, txt: _normTxt(e) })).filter(x => !!x.txt);+ }+let _lastClickIdent = null;let _lastEditableTarget = null;@@ -1599,14 +1647,6 @@if (params.text) {const needle = params.text.toLowerCase();const explicit = params.textMatch || '';- // Include inputs/select/textarea so we can match by placeholder, value, or aria-label- const sels = [- 'a', 'button', '[role="button"]', '[role="link"]', '[role="tab"]', '[role="menuitem"]',- '[role="option"]', '[role="menuitemradio"]', '[role="menuitemcheckbox"]', '[role="treeitem"]',- 'input:not([type="hidden"])', 'textarea', 'select', 'input[type="button"]',- 'input[type="submit"]', 'summary', 'label', '[onclick]', '[data-action]',- ..._siteInteractiveSelectors(),- ].join(', ');// Modal scoping: if a topmost modal/dialog is open, restrict the search// to elements inside it. Prevents the classic failure where the model// types "Publish release" and the resolver clicks the dimmed Publish@@ -1615,42 +1655,7 @@// reachable via coordinate clicks.const _modalRoot = _findTopmostModal();const _scope = _modalRoot || document;- // Candidate filter: listbox/menu option roles are often kept mounted but- // hidden while a custom select is collapsed or virtualized (Radix/MUI/- // React-Select). Drop hidden ones so click({text}) can't match — and- // falsely "succeed" on — an invisible option; the open-listbox fallback- // still surfaces them when the control is actually open. Shared by the- // primary pass AND the auto-scroll retry below so they can't diverge.- const _keepCandidate = (el) => {- const role = (el.getAttribute && el.getAttribute('role')) || '';- if (role !== 'option' && role !== 'menuitemradio' && role !== 'menuitemcheckbox' && role !== 'treeitem') return true;- try {- const r = el.getBoundingClientRect();- if (r.width < 1 || r.height < 1) return false;- const s = window.getComputedStyle(el);- if (s.visibility === 'hidden' || s.display === 'none' || parseFloat(s.opacity) === 0) return false;- if (el.closest('[aria-hidden="true"],[hidden]')) return false;- return true;- } catch (e) { return false; }- };- // A text field's `value` is content the user typed, NOT a click label.- // Matching on it makes click({text}) resolve to the field you just filled- // (e.g. a combobox/filter box whose value now equals the needle) instead- // of the menu option bearing the same text — the "click succeeds but- // nothing happens, model loops forever" bug. Only treat `value` as a label- // for button-like inputs; non-input elements with .value (<select>) keep it.- const _valIsLabel = (el) => {- if (el.tagName === 'TEXTAREA') return false;- if (el.tagName !== 'INPUT') return true;- const t = (el.getAttribute('type') || 'text').toLowerCase();- return t === 'button' || t === 'submit' || t === 'reset';- };- const _normTxt = (el) => {- const siteText = _isSiteInteractive(el) ? _siteInteractionText(el) : '';- return (siteText || el.innerText || (_valIsLabel(el) ? el.value : '') || el.placeholder || el.ariaLabel || '').trim().toLowerCase();- };- const all = Array.from(_scope.querySelectorAll(sels)).filter(_keepCandidate);- const normalized = all.map(e => ({ e, txt: _normTxt(e) })).filter(x => !!x.txt);+ const normalized = _clickTextCandidates(_scope);// Build label→input map so we can match label text and resolve to associated inputconst labelMap = new Map();@@ -1710,8 +1715,7 @@// Re-query after scroll. Re-resolve the modal root in case the// dialog opened/closed during scroll.const _retryScope = _findTopmostModal() || document;- const allRetry = Array.from(_retryScope.querySelectorAll(sels)).filter(_keepCandidate);- const normRetry = allRetry.map(e => ({ e, txt: _normTxt(e) })).filter(x => !!x.txt);+ const normRetry = _clickTextCandidates(_retryScope);for (const m of modes) {if (m === 'exact') matches = normRetry.filter(x => x.txt === needle);else if (m === 'prefix') matches = normRetry.filter(x => x.txt.startsWith(needle));@@ -4060,20 +4064,32 @@if (refId && typeof window.__wb_ax_lookup === 'function') target = window.__wb_ax_lookup(refId);targetResolved = !!target;} else if (tool === 'click') {- if (typeof args.selector === 'string' && args.selector) {- try { target = document.querySelector(args.selector); } catch {}+ // Match dispatch precedence, modal scope, candidate text and match+ // mode. A supplied selector must not approve a different text click.+ if (typeof args.text === 'string' && args.text) {+ const needle = args.text.toLowerCase();+ const scope = _findTopmostModal() || document;+ const candidates = _clickTextCandidates(scope);+ const modes = args.textMatch ? [args.textMatch] : ['exact', 'prefix', 'contains'];+ for (const mode of modes) {+ let matches = candidates.filter(({ txt }) => mode === 'exact' ? txt === needle+ : mode === 'prefix' ? txt.startsWith(needle)+ : mode === 'contains' ? txt.includes(needle) : false);+ // Dispatch prefers the sole interactive match over passive labels.+ // Multiple interactive matches must still stop at this match tier.+ if (matches.length > 1) {+ const interactiveMatches = matches.filter(({ e }) => _isInteractive(e));+ if (interactiveMatches.length === 1) matches = interactiveMatches;+ }+ if (matches.length === 1) target = _resolveInteractiveAncestor(matches[0].e);+ if (matches.length) break;+ }+ } else if (typeof args.selector === 'string' && args.selector) {+ target = safeIndexedQuerySelector(args.selector, args.matchIndex).element;} else if (Number.isInteger(args.index) && args.index >= 0) {target = queryInteractiveForToolIndex()[args.index] || null;} else if (Number.isFinite(args.x) && Number.isFinite(args.y)) {target = document.elementFromPoint(args.x, args.y);- } else if (typeof args.text === 'string' && args.text.trim()) {- const needle = compact(args.text).toLocaleLowerCase();- const matches = Array.from(document.querySelectorAll(- 'button,[role="button"],input[type="submit"],input[type="button"],[data-action]'- )).filter((el) => compact(- el.innerText || el.value || el.getAttribute?.('aria-label') || el.getAttribute?.('title')- ).toLocaleLowerCase() === needle);- if (matches.length === 1) target = matches[0];}targetResolved = !!target;}@@ -4183,6 +4199,33 @@&& railRect.right <= composerRect.left + 64;};+ const verifiedLinkedInNavigation = (clicked) => {+ if (params.adapterName !== 'linkedin' || !clicked) return false;+ const link = clicked.closest?.('a[href]');+ if (!link || !visible(link) || !link.closest?.('nav,[role="navigation"]')) return false;+ // A navigation-looking descendant of a composer/action is not a+ // navigation escape hatch. Keep actual sends and modal controls on+ // the existing recipient-verification path.+ if (clicked.closest?.('button,[role="button"],input,select,textarea,[contenteditable]:not([contenteditable="false"]),[onclick],[data-action]')+ || link.closest?.('form,dialog,[role="dialog"],[role="alertdialog"]')+ || link.hasAttribute?.('download')+ || (link.getAttribute?.('role') && link.getAttribute('role') !== 'link')) return false;+ try {+ const href = String(link.getAttribute('href') || '').trim();+ if (!href || href.startsWith('#')) return false;+ const destination = new URL(href, document.baseURI);+ // Only the site's top-level navigation destinations are known not+ // to send. Arbitrary action URLs and conversation controls stay+ // inconclusive, even when their visible label says Home or Jobs.+ return /^https?:$/.test(destination.protocol)+ && destination.origin === location.origin+ && /^(?:www\.)?linkedin\.com$/.test(destination.hostname)+ && /^\/(?:feed|jobs|mynetwork|messaging|notifications)\/?$/.test(destination.pathname);+ } catch {+ return false;+ }+ };+let composer = null;let messageSend = null;if (observationOnly) {@@ -4219,9 +4262,13 @@return { success: true, messageSend: null, conclusive: false, identityCandidates: [] };}const control = target.closest?.('button,[role="button"],input[type="submit"],input[type="button"],[data-action]') || target;- if (!visible(control)) {+ const modal = _findTopmostBlockingModal();+ if (!visible(control) || (modal && !_isComposedAncestor(modal, target))) {return { success: true, messageSend: null, conclusive: false, identityCandidates: [] };}+ if (verifiedLinkedInNavigation(target)) {+ return { success: true, messageSend: false, conclusive: true, navigation: true, identityCandidates: [] };+ }composer = layoutComposer;if (!composer) {const actionLabel = compact(diff --git a/test/fixtures/message-recipient-navigation.mjs b/test/fixtures/message-recipient-navigation.mjsnew file mode 100644index 000000000..8423f1cb3--- /dev/null+++ b/test/fixtures/message-recipient-navigation.mjs@@ -0,0 +1,189 @@+import { strict as assert } from 'node:assert';++export function registerMessageRecipientNavigationFixtures({+ test, firefoxTest, setupContentHtml, call, Agent, FirefoxAgent,+}) {+ for (const [kind, register, AgentClass] of [+ ['chrome', test, Agent],+ ['firefox', firefoxTest, FirefoxAgent],+ ]) {+ const setup = async (page) => {+ // Keep the real origin and URL parsing without contacting LinkedIn.+ await page.route('**/*', route => route.fulfill({ contentType: 'text/html', body: '<!doctype html>' }));+ await page.goto('https://www.linkedin.com/feed/');+ await setupContentHtml(page, `<!doctype html>+ <style>+ body { margin: 0; font: 16px sans-serif; }+ nav { display: flex; gap: 30px; padding: 20px; }+ a, button { display: inline-block; padding: 8px; }+ #chat { position: fixed; right: 20px; bottom: 20px; width: 360px; }+ #body { width: 260px; height: 60px; }+ #chat h2 { position: fixed; right: 200px; top: 80px; margin: 0; }+ </style>+ <nav aria-label="Primary">+ <a id="home" class="destination" href="/feed/">Home</a>+ <a id="jobs" class="destination" href="/jobs/"><span id="jobs-label">Jobs</span></a>+ <a id="messaging" href="/messaging/">Messaging</a>+ </nav>+ <form id="chat" hidden>+ <h2>Alice</h2><textarea id="body">Hello Alice</textarea><button id="send" type="button">Send</button>+ </form>`, kind);+ await page.evaluate(() => {+ window.fixtureClicks = [];+ document.addEventListener('click', event => {+ const target = event.target.closest('a,button');+ if (target) { event.preventDefault(); window.fixtureClicks.push(target.id); }+ });+ });+ const agent = new AgentClass({ getActive: () => ({ supportsVision: false }) });+ agent._messageRecipientContentProbe = (_, params) => call(page, 'probe_message_recipient_guard', params);+ const guard = (tool, args) => agent._messageRecipientGuardBlock(1, tool, args, page.url());+ const probe = (tool, args) => call(page, 'probe_message_recipient_guard', { tool, args, adapterName: 'linkedin' });+ return { agent, guard, probe };+ };++ register(`${kind}: LinkedIn Home and Jobs navigate with closed and open message composers (#2999)`, async (page) => {+ const { guard, probe } = await setup(page);+ for (const open of [false, true]) {+ await page.evaluate(open => { document.querySelector('#chat').hidden = !open; }, open);+ const ref = await page.evaluate(() => window.__wb_ax_ref(document.querySelector('#jobs-label')));+ for (const [tool, args, expected] of [+ ['click', { text: 'Jobs', textMatch: 'exact' }, 'jobs'],+ ['click', { text: 'Home' }, 'home'],+ ['click_ax', { ref_id: ref }, 'jobs'],+ ['click', { selector: '.destination', matchIndex: 1 }, 'jobs'],+ ['click', { text: 'Messag', textMatch: 'prefix' }, 'messaging'],+ ]) {+ const result = await probe(tool, args);+ assert.equal(result.conclusive, true, JSON.stringify(result));+ assert.equal(result.messageSend, false);+ assert.equal(await guard(tool, args), null);+ const clicked = await call(page, tool, args);+ assert.equal(clicked.success, true, JSON.stringify(clicked));+ assert.equal(await page.evaluate(() => window.fixtureClicks.at(-1)), expected);+ }+ }+ });++ register(`${kind}: LinkedIn recipient guard rejects ambiguous navigation and action lookalikes`, async (page) => {+ const { guard } = await setup(page);+ for (const href of ['#', 'javascript:void(0)', 'https://example.com/jobs/', '/messaging/compose/', '/messaging/send/']) {+ await page.locator('#jobs').evaluate((el, href) => el.setAttribute('href', href), href);+ assert.equal((await guard('click', { text: 'Jobs' }))?.noDispatch, true, href);+ }+ await page.locator('#jobs').evaluate(el => el.setAttribute('href', '/jobs/'));+ for (const [attribute, value] of [['role', 'button'], ['data-action', 'send'], ['onclick', 'void(0)'], ['download', 'jobs']]) {+ await page.locator('#jobs').evaluate((el, [name, value]) => el.setAttribute(name, value), [attribute, value]);+ assert.equal((await guard('click', { text: 'Jobs' }))?.noDispatch, true, attribute);+ await page.locator('#jobs').evaluate((el, name) => el.removeAttribute(name), attribute);+ }+ await page.evaluate(() => {+ document.querySelector('#chat').hidden = false;+ document.querySelector('#send').textContent = 'Jobs';+ });+ assert.equal((await guard('click', { text: 'Jobs' }))?.noDispatch, true, 'duplicate action label');+ // Text wins over selector at dispatch; matchIndex must also agree with+ // dispatch rather than accidentally approving the first selector match.+ await page.locator('#send').evaluate(el => { el.textContent = 'Send'; el.classList.add('destination'); });+ assert.equal((await guard('click', { text: 'Send', selector: '#jobs' }))?.noDispatch, true);+ assert.equal((await guard('click', { selector: '.destination', matchIndex: 2 }))?.noDispatch, true);+ assert.equal((await guard('click_ax', { ref_id: 'ref_missing' }))?.noDispatch, true);+ assert.deepEqual(await page.evaluate(() => window.fixtureClicks), []);+ });++ register(`${kind}: LinkedIn recipient guard disambiguates passive labels like click dispatch`, async (page) => {+ const { agent, guard } = await setup(page);+ await page.evaluate(() => {+ document.querySelector('#chat').hidden = false;+ document.querySelector('#send').insertAdjacentHTML('beforebegin', '<label for="send">Send</label>');+ });+ agent._planExecutionGuards.set(1, { messaging: { target_kind: 'named', recipients: ['Alice'] } });+ for (const args of [+ { text: 'Send', textMatch: 'exact' },+ { text: 'Sen', textMatch: 'prefix' },+ { text: 'end', textMatch: 'contains' },+ { text: 'Send' },+ ]) {+ const execution = {};+ assert.equal(await agent._messageRecipientGuardBlock(1, 'click', args, page.url(), execution), null);+ assert.equal(execution.messageRecipientGuardRequired, true);+ assert.ok(execution.messageRecipientDispatchBinding?.token);+ const clicked = await call(page, 'click', { ...args, ...execution });+ assert.equal(clicked.success, true, JSON.stringify(clicked));+ assert.equal(await page.evaluate(() => window.fixtureClicks.at(-1)), 'send');+ }+ await page.locator('#send').evaluate(el => el.insertAdjacentHTML('afterend', '<button type="button">Send</button>'));+ assert.equal((await guard('click', { text: 'Send' }))?.noDispatch, true, 'two interactive matches must remain ambiguous');+ assert.deepEqual(await page.evaluate(() => window.fixtureClicks), ['send', 'send', 'send', 'send']);+ });++ register(`${kind}: LinkedIn recipient guard accepts shadow controls inside the active modal`, async (page) => {+ const { agent, guard } = await setup(page);+ const ref = await page.evaluate(() => {+ const chat = document.querySelector('#chat');+ chat.hidden = false;+ const modal = document.createElement('div');+ modal.id = 'modal';+ modal.setAttribute('role', 'dialog');+ modal.setAttribute('aria-modal', 'true');+ modal.style.cssText = 'position:fixed;inset:0;background:white';+ document.body.append(modal);+ modal.append(chat);+ const host = document.createElement('span');+ host.id = 'send-host';+ document.querySelector('#send').replaceWith(host);+ const shadow = host.attachShadow({ mode: 'open' });+ shadow.innerHTML = '<button id="shadow-send" type="button" style="padding:8px">Send</button>';+ const send = shadow.querySelector('button');+ send.addEventListener('click', event => {+ event.preventDefault();+ window.fixtureClicks.push(send.id);+ });+ // This is exactly the distinction that ordinary contains() misses.+ if (modal.contains(send)) throw new Error('fixture target must cross a shadow boundary');+ return window.__wb_ax_ref(send);+ });+ agent._planExecutionGuards.set(1, { messaging: { target_kind: 'named', recipients: ['Alice'] } });+ const args = { ref_id: ref };+ const execution = {};+ assert.equal(await agent._messageRecipientGuardBlock(1, 'click_ax', args, page.url(), execution), null);+ assert.equal(execution.messageRecipientGuardRequired, true);+ assert.ok(execution.messageRecipientDispatchBinding?.token);+ const clicked = await call(page, 'click_ax', { ...args, ...execution });+ assert.equal(clicked.success, true, JSON.stringify(clicked));+ assert.deepEqual(await page.evaluate(() => window.fixtureClicks), ['shadow-send']);+ // Moving the same host outside the modal must not grant background access.+ await page.locator('#send-host').evaluate(host => document.body.append(host));+ assert.equal((await guard('click_ax', args))?.noDispatch, true);+ assert.deepEqual(await page.evaluate(() => window.fixtureClicks), ['shadow-send']);+ });++ register(`${kind}: LinkedIn navigation respects modal scope and preserves send authorization`, async (page) => {+ const { agent, guard, probe } = await setup(page);+ await page.evaluate(() => {+ document.querySelector('#chat').hidden = false;+ document.body.insertAdjacentHTML('beforeend', '<div id="modal" role="dialog" aria-modal="true" style="position:fixed;inset:80px;background:white"><button>Jobs</button></div>');+ });+ assert.equal((await guard('click', { text: 'Jobs' }))?.noDispatch, true, 'modal text must not resolve background link');+ assert.equal((await guard('click', { selector: '#jobs' }))?.noDispatch, true, 'background selector must not bypass modal');+ await page.locator('#modal').evaluate(el => el.remove());+ const send = await probe('click', { text: 'Send' });+ assert.equal(send.messageSend, true, JSON.stringify(send));+ assert.deepEqual(send.strongIdentityCandidates, ['Alice']);+ assert.equal((await guard('click', { text: 'Send' }))?.noDispatch, true, 'missing recipient');+ agent._planExecutionGuards.set(1, { messaging: { target_kind: 'named', recipients: ['Bob'] } });+ assert.equal((await guard('click', { text: 'Send' }))?.noDispatch, true, 'wrong recipient');+ agent._planExecutionGuards.set(1, { messaging: { target_kind: 'named', recipients: ['Alice'] } });+ const execution = {};+ assert.equal(await agent._messageRecipientGuardBlock(1, 'click', { text: 'Send' }, page.url(), execution), null);+ assert.equal(execution.messageRecipientGuardRequired, true);+ assert.ok(execution.messageRecipientDispatchBinding?.token);+ // A verified navigation classification must never permit replaying a+ // send binding after the action or conversation changed.+ await page.locator('#chat h2').evaluate(el => { el.textContent = 'Bob'; });+ const stale = await call(page, 'consume_message_recipient_dispatch_binding', execution);+ assert.equal(stale.noDispatch, true);+ assert.deepEqual(await page.evaluate(() => window.fixtureClicks), []);+ });+ }+}diff --git a/test/fixtures/run.mjs b/test/fixtures/run.mjsindex 2d05de44b..cca815095 100644--- a/test/fixtures/run.mjs+++ b/test/fixtures/run.mjs@@ -24,6 +24,7 @@ import {getSelectionShortcutLocalization,} from '../../src/chrome/src/selection-shortcut-i18n.js';import { registerRichTextToolbarFixtures } from './rich-text-toolbar.mjs';+import { registerMessageRecipientNavigationFixtures } from './message-recipient-navigation.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));@@ -4656,6 +4657,8 @@ test('Firefox: type_text rejects disabled indexed text input fallback', async (p});+registerMessageRecipientNavigationFixtures({ test, firefoxTest, setupContentHtml, call, Agent, FirefoxAgent });+registerRichTextToolbarFixtures({test,setupContentHtml,diff --git a/test/run.js b/test/run.jsindex bd84ddba9..5c7a91f5e 100644--- a/test/run.js+++ b/test/run.js@@ -6925,7 +6925,7 @@ test('direct-message recipient probe accepts only a unique active-thread headerquerySelector: (selector) => selector === '#conversation-row' ? conversationRow : null,querySelectorAll: (selector) => {if (selector === 'textarea,[contenteditable="true"],[role="textbox"]') return [composer, searchBox, alternateComposer];- if (selector.startsWith('button,')) return [sendButton, customSendControl, distantControl, conversationRowMenu];+ if (selector.startsWith('a, button,')) return [sendButton, customSendControl, distantControl, conversationRowMenu];if (selector.startsWith('[aria-selected')) return [];if (selector.startsWith('h1,')) return [searchedName, activeHeader, conversationMessageHeading];if (selector.startsWith('[data-testid')) return [];@@ -6953,7 +6953,20 @@ test('direct-message recipient probe accepts only a unique active-thread header}),_deepActiveElement: () => activeElement,};- const probe = vm.runInNewContext(`(${source.slice(start, end)})`, context);+ const candidatesStart = source.indexOf(' function _clickTextCandidates(');+ const candidatesEnd = source.indexOf('\n\n let _lastClickIdent', candidatesStart);+ Object.assign(context, {+ _siteInteractiveSelectors: () => [],+ _siteInteractionText: el => (el.innerText || el.value || '').trim(),+ _isSiteInteractive: () => false,+ _findTopmostModal: () => null,+ _findTopmostBlockingModal: () => null,+ _resolveInteractiveAncestor: el => el,+ safeIndexedQuerySelector: selector => ({ element: document.querySelector(selector) }),+ });+ const probe = vm.runInNewContext(+ `${source.slice(candidatesStart, candidatesEnd)}; (${source.slice(start, end)})`, context,+ );const observationResult = probe({ tool: 'observe_active_conversation', args: {} });const enterResult = probe({ tool: 'press_keys', args: { key: 'Enter' } });const fieldSubmitResult = probe({@@ -6992,7 +7005,7 @@ test('direct-message recipient probe accepts only a unique active-thread headerconst conversationAxResult = probe({ tool: 'click_ax', args: { ref_id: 'conversation-row-label' } });const conversationMenuResult = probe({ tool: 'click', args: { text: 'More' } });const conversationMenuLeafResult = probe({ tool: 'click_ax', args: { ref_id: 'conversation-row-menu-leaf' } });- const unresolvedClickResult = probe({ tool: 'click', args: { text: 'Sen' } });+ const unresolvedClickResult = probe({ tool: 'click', args: { text: 'Sen', textMatch: 'exact' } });activeElement = composer;const gmailAliceChip = element('Alice', {left: 430, right: 620, top: 610, bottom: 650, width: 190, height: 40,