Skip to content

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

fix: restore Gmail recipient checks and preserve email reservations

Barack Sokullu98b71138c0db
diff --git a/package-lock.json b/package-lock.json
index 8a48c9bc8..87c48675d 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "webbrain",
- "version": "40.4.1",
+ "version": "40.4.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "webbrain",
- "version": "40.4.1",
+ "version": "40.4.2",
"license": "GPL-3.0-or-later",
"devDependencies": {
"c8": "^12.0.0",
diff --git a/package.json b/package.json
index 917484255..015e04995 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "webbrain",
- "version": "40.4.1",
+ "version": "40.4.2",
"description": "Open-source AI browser agent — chat with pages, automate tasks, multi-provider LLM support.",
"private": true,
"type": "module",
diff --git a/src/chrome/ARCHITECTURE.md b/src/chrome/ARCHITECTURE.md
index a602c2f9c..30f2b0b37 100644
--- a/src/chrome/ARCHITECTURE.md
+++ b/src/chrome/ARCHITECTURE.md
@@ -1,6 +1,6 @@
# WebBrain Chrome/Edge Extension — Architecture
-> Version 40.4.1 · Manifest V3 · Service Worker background
+> Version 40.4.2 · Manifest V3 · Service Worker background
## High-Level Overview
diff --git a/src/chrome/manifest.json b/src/chrome/manifest.json
index 43af9c275..0a50e1601 100644
--- a/src/chrome/manifest.json
+++ b/src/chrome/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "WebBrain",
- "version": "40.4.1",
+ "version": "40.4.2",
"description": "Open-source AI browser agent — chat with pages, automate tasks, multi-provider LLM support.",
"permissions": [
"sidePanel",
diff --git a/src/chrome/src/agent/bot-memory.js b/src/chrome/src/agent/bot-memory.js
index cf69846d1..e7c952b80 100644
--- a/src/chrome/src/agent/bot-memory.js
+++ b/src/chrome/src/agent/bot-memory.js
@@ -193,6 +193,26 @@ export function observeMemoryPageInPage(args = {}) {
const credential = sensitive(fieldFacts);
const label = clip(safeText(element?.getAttribute?.('aria-label') || element?.innerText || element?.getAttribute?.('title') || ''), 512);
const form = element?.form || element?.closest?.('form');
+ // Gmail saves compose edits as owner drafts. They are not delivery actions
+ // and must not reserve the email's one-send memory entry. This fact comes
+ // from the isolated DOM observer, never model arguments or quoted page text.
+ const gmailDraftField = (() => {
+ if (!element || credential || location.hostname !== 'mail.google.com'
+ || !/^\/mail\//.test(location.pathname)) return false;
+ const dialog = element.closest?.('[role="dialog"]');
+ if (!dialog) return false;
+ const visible = field => {
+ if (!field?.isConnected || field.closest?.('[aria-hidden="true"]')) return false;
+ const rect = field.getBoundingClientRect();
+ const style = getComputedStyle(field);
+ return rect.width > 0 && rect.height > 0
+ && style.display !== 'none' && style.visibility !== 'hidden';
+ };
+ const subject = dialog.querySelector('input[name="subjectbox"]');
+ const bodies = Array.from(dialog.querySelectorAll('[role="textbox"][contenteditable="true"]')).filter(visible);
+ if (!visible(subject) || bodies.length !== 1 || !visible(element)) return false;
+ return element === bodies[0] || element.matches('input[name="subjectbox"],input[name="to"],input[name="cc"],input[name="bcc"]');
+ })();
let scope = form || element;
const draftSelector = 'textarea,[contenteditable=true],input:not([type=hidden]):not([type=submit]):not([type=button]):not([type=reset]):not([type=file]):not([type=checkbox]):not([type=radio])';
let draftFields = [];
@@ -243,6 +263,7 @@ export function observeMemoryPageInPage(args = {}) {
identifiers,
elementFacts: { found: !!element, tag: clip(element?.tagName || '', 30), ...fieldFacts, type, name,
role: clip(element?.getAttribute?.('role') || '', 60), label, credential,
+ ...(gmailDraftField ? { gmailDraftField: true } : {}),
href: clip(element?.href || element?.closest?.('a')?.href || '', 4096),
formMethod: clip(form?.method || '', 20), formAction: clip(form?.action || '', 4096),
draftText: clip(safeText(drafts.join('\n')), 2048), nearbyText: clip(safeText(scope?.innerText), 2048) },
@@ -390,6 +411,17 @@ export class BotMemorySession {
if (await this.canBootstrapNavigation(tabId, name, args)) return { allowed: true, readOnly: true, bootstrapNavigation: true };
const observation = await this.observation(tabId, name, args);
if (!observation.url || !observation.targets.length) return { allowed: false, reason: 'Observe the target page before acting.' };
+ if (name === 'set_field' && (args?.submit === false || args?.submit === undefined)
+ && !detectedSubmit && !consequentialSubmit
+ && observation.elementFacts?.found === true && observation.elementFacts.gmailDraftField === true
+ && observation.elementFacts.credential !== true) {
+ let gmailCompose = false;
+ try {
+ const url = new URL(observation.url);
+ gmailCompose = url.protocol === 'https:' && url.hostname === 'mail.google.com' && /^\/mail\//.test(url.pathname);
+ } catch {}
+ if (gmailCompose) return { allowed: true, readOnly: true, draftOnly: true };
+ }
if ((name === 'click' || consequentialSubmit) && observation.elementFacts?.found !== true) {
return { allowed: false, reason: 'The action target could not be resolved. Read the page and choose an observed control.' };
}
diff --git a/src/chrome/src/content/content.js b/src/chrome/src/content/content.js
index 40491b123..60b8050ec 100644
--- a/src/chrome/src/content/content.js
+++ b/src/chrome/src/content/content.js
@@ -7750,25 +7750,28 @@
observedRecipientCandidates.push({ identity: context.id, role: 'to', aliases: [context.id, context.name,
...(context.alias ? [context.alias, '@' + context.alias] : [])] });
} else if (gmailRecipientMode) {
- const recipientRole = (el, root = null) => {
- const roleFromAttribute = (attribute, value) => {
- const text = compact(value, 120).toLowerCase();
- if (!text) return '';
- if (attribute === 'aria-label') {
- if (/^(?:bcc|blind\s+carbon\s+copy)(?:$|\s*[:,-]\s*)/.test(text)) return 'bcc';
- if (/^(?:cc|carbon\s+copy)(?:$|\s*[:,-]\s*)/.test(text)) return 'cc';
- if (/^to(?:$|\s*[:,-]\s*)/.test(text)) return 'to';
- return '';
- }
- if (attribute === 'name') {
- return /^(?:to|cc|bcc)$/.test(text) ? text : '';
- }
- const tokens = text.split(/[^a-z]+/).filter(Boolean);
- if (tokens.includes('bcc')) return 'bcc';
- if (tokens.includes('cc')) return 'cc';
- if (tokens.length === 1 && tokens[0] === 'to') return 'to';
+ // Chips and not-yet-committed address fields must use the same role
+ // parser. Keep it in their shared scope: a visible Subject/To input
+ // must not turn the entire recipient probe into a ReferenceError.
+ const roleFromAttribute = (attribute, value) => {
+ const text = compact(value, 120).toLowerCase();
+ if (!text) return '';
+ if (attribute === 'aria-label') {
+ if (/^(?:bcc|blind\s+carbon\s+copy)(?:$|\s*[:,-]\s*)/.test(text)) return 'bcc';
+ if (/^(?:cc|carbon\s+copy)(?:$|\s*[:,-]\s*)/.test(text)) return 'cc';
+ if (/^to(?:$|\s*[:,-]\s*)/.test(text)) return 'to';
return '';
- };
+ }
+ if (attribute === 'name') {
+ return /^(?:to|cc|bcc)$/.test(text) ? text : '';
+ }
+ const tokens = text.split(/[^a-z]+/).filter(Boolean);
+ if (tokens.includes('bcc')) return 'bcc';
+ if (tokens.includes('cc')) return 'cc';
+ if (tokens.length === 1 && tokens[0] === 'to') return 'to';
+ return '';
+ };
+ const recipientRole = (el, root = null) => {
let current = el;
for (let depth = 0; current && depth < 7; depth++, current = current.parentElement) {
for (const attribute of ['data-recipient-type', 'data-type', 'name', 'aria-label']) {
diff --git a/src/chrome/src/ui/settings.js b/src/chrome/src/ui/settings.js
index 29a52c59b..6e20ad071 100644
--- a/src/chrome/src/ui/settings.js
+++ b/src/chrome/src/ui/settings.js
@@ -92,7 +92,7 @@ const SUBSCRIPTION_GUIDE_PRODUCTS = Object.freeze({
// Version shown in the subtitle. Kept here so it only needs one update per
// release; the subtitle string itself is translated.
-const EXT_VERSION = '40.4.1';
+const EXT_VERSION = '40.4.2';
const providersContainer = document.getElementById('providers');
const displaySettings = document.getElementById('display-settings');
diff --git a/src/firefox/ARCHITECTURE.md b/src/firefox/ARCHITECTURE.md
index 019d136f5..3000ef90e 100644
--- a/src/firefox/ARCHITECTURE.md
+++ b/src/firefox/ARCHITECTURE.md
@@ -1,6 +1,6 @@
# WebBrain Firefox Extension — Architecture
-> Version 40.4.1 · Manifest V2 · Background Page
+> Version 40.4.2 · Manifest V2 · Background Page
## How Firefox Differs from Chrome
diff --git a/src/firefox/manifest.json b/src/firefox/manifest.json
index e7a3f7ccd..a8b6a3150 100644
--- a/src/firefox/manifest.json
+++ b/src/firefox/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 2,
"name": "WebBrain",
- "version": "40.4.1",
+ "version": "40.4.2",
"description": "Open-source AI browser agent — chat with pages, automate tasks, multi-provider LLM support.",
"permissions": [
"activeTab",
diff --git a/src/firefox/src/agent/bot-memory.js b/src/firefox/src/agent/bot-memory.js
index cf69846d1..e7c952b80 100644
--- a/src/firefox/src/agent/bot-memory.js
+++ b/src/firefox/src/agent/bot-memory.js
@@ -193,6 +193,26 @@ export function observeMemoryPageInPage(args = {}) {
const credential = sensitive(fieldFacts);
const label = clip(safeText(element?.getAttribute?.('aria-label') || element?.innerText || element?.getAttribute?.('title') || ''), 512);
const form = element?.form || element?.closest?.('form');
+ // Gmail saves compose edits as owner drafts. They are not delivery actions
+ // and must not reserve the email's one-send memory entry. This fact comes
+ // from the isolated DOM observer, never model arguments or quoted page text.
+ const gmailDraftField = (() => {
+ if (!element || credential || location.hostname !== 'mail.google.com'
+ || !/^\/mail\//.test(location.pathname)) return false;
+ const dialog = element.closest?.('[role="dialog"]');
+ if (!dialog) return false;
+ const visible = field => {
+ if (!field?.isConnected || field.closest?.('[aria-hidden="true"]')) return false;
+ const rect = field.getBoundingClientRect();
+ const style = getComputedStyle(field);
+ return rect.width > 0 && rect.height > 0
+ && style.display !== 'none' && style.visibility !== 'hidden';
+ };
+ const subject = dialog.querySelector('input[name="subjectbox"]');
+ const bodies = Array.from(dialog.querySelectorAll('[role="textbox"][contenteditable="true"]')).filter(visible);
+ if (!visible(subject) || bodies.length !== 1 || !visible(element)) return false;
+ return element === bodies[0] || element.matches('input[name="subjectbox"],input[name="to"],input[name="cc"],input[name="bcc"]');
+ })();
let scope = form || element;
const draftSelector = 'textarea,[contenteditable=true],input:not([type=hidden]):not([type=submit]):not([type=button]):not([type=reset]):not([type=file]):not([type=checkbox]):not([type=radio])';
let draftFields = [];
@@ -243,6 +263,7 @@ export function observeMemoryPageInPage(args = {}) {
identifiers,
elementFacts: { found: !!element, tag: clip(element?.tagName || '', 30), ...fieldFacts, type, name,
role: clip(element?.getAttribute?.('role') || '', 60), label, credential,
+ ...(gmailDraftField ? { gmailDraftField: true } : {}),
href: clip(element?.href || element?.closest?.('a')?.href || '', 4096),
formMethod: clip(form?.method || '', 20), formAction: clip(form?.action || '', 4096),
draftText: clip(safeText(drafts.join('\n')), 2048), nearbyText: clip(safeText(scope?.innerText), 2048) },
@@ -390,6 +411,17 @@ export class BotMemorySession {
if (await this.canBootstrapNavigation(tabId, name, args)) return { allowed: true, readOnly: true, bootstrapNavigation: true };
const observation = await this.observation(tabId, name, args);
if (!observation.url || !observation.targets.length) return { allowed: false, reason: 'Observe the target page before acting.' };
+ if (name === 'set_field' && (args?.submit === false || args?.submit === undefined)
+ && !detectedSubmit && !consequentialSubmit
+ && observation.elementFacts?.found === true && observation.elementFacts.gmailDraftField === true
+ && observation.elementFacts.credential !== true) {
+ let gmailCompose = false;
+ try {
+ const url = new URL(observation.url);
+ gmailCompose = url.protocol === 'https:' && url.hostname === 'mail.google.com' && /^\/mail\//.test(url.pathname);
+ } catch {}
+ if (gmailCompose) return { allowed: true, readOnly: true, draftOnly: true };
+ }
if ((name === 'click' || consequentialSubmit) && observation.elementFacts?.found !== true) {
return { allowed: false, reason: 'The action target could not be resolved. Read the page and choose an observed control.' };
}
diff --git a/src/firefox/src/content/content.js b/src/firefox/src/content/content.js
index af8b7e83c..bd32403ca 100644
--- a/src/firefox/src/content/content.js
+++ b/src/firefox/src/content/content.js
@@ -6851,25 +6851,28 @@
observedRecipientCandidates.push({ identity: context.id, role: 'to', aliases: [context.id, context.name,
...(context.alias ? [context.alias, '@' + context.alias] : [])] });
} else if (gmailRecipientMode) {
- const recipientRole = (el, root = null) => {
- const roleFromAttribute = (attribute, value) => {
- const text = compact(value, 120).toLowerCase();
- if (!text) return '';
- if (attribute === 'aria-label') {
- if (/^(?:bcc|blind\s+carbon\s+copy)(?:$|\s*[:,-]\s*)/.test(text)) return 'bcc';
- if (/^(?:cc|carbon\s+copy)(?:$|\s*[:,-]\s*)/.test(text)) return 'cc';
- if (/^to(?:$|\s*[:,-]\s*)/.test(text)) return 'to';
- return '';
- }
- if (attribute === 'name') {
- return /^(?:to|cc|bcc)$/.test(text) ? text : '';
- }
- const tokens = text.split(/[^a-z]+/).filter(Boolean);
- if (tokens.includes('bcc')) return 'bcc';
- if (tokens.includes('cc')) return 'cc';
- if (tokens.length === 1 && tokens[0] === 'to') return 'to';
+ // Chips and not-yet-committed address fields must use the same role
+ // parser. Keep it in their shared scope: a visible Subject/To input
+ // must not turn the entire recipient probe into a ReferenceError.
+ const roleFromAttribute = (attribute, value) => {
+ const text = compact(value, 120).toLowerCase();
+ if (!text) return '';
+ if (attribute === 'aria-label') {
+ if (/^(?:bcc|blind\s+carbon\s+copy)(?:$|\s*[:,-]\s*)/.test(text)) return 'bcc';
+ if (/^(?:cc|carbon\s+copy)(?:$|\s*[:,-]\s*)/.test(text)) return 'cc';
+ if (/^to(?:$|\s*[:,-]\s*)/.test(text)) return 'to';
return '';
- };
+ }
+ if (attribute === 'name') {
+ return /^(?:to|cc|bcc)$/.test(text) ? text : '';
+ }
+ const tokens = text.split(/[^a-z]+/).filter(Boolean);
+ if (tokens.includes('bcc')) return 'bcc';
+ if (tokens.includes('cc')) return 'cc';
+ if (tokens.length === 1 && tokens[0] === 'to') return 'to';
+ return '';
+ };
+ const recipientRole = (el, root = null) => {
let current = el;
for (let depth = 0; current && depth < 7; depth++, current = current.parentElement) {
for (const attribute of ['data-recipient-type', 'data-type', 'name', 'aria-label']) {
diff --git a/src/firefox/src/ui/settings.js b/src/firefox/src/ui/settings.js
index 25d77fe71..5c5d8a424 100644
--- a/src/firefox/src/ui/settings.js
+++ b/src/firefox/src/ui/settings.js
@@ -84,7 +84,7 @@ const SUBSCRIPTION_GUIDE_PRODUCTS = Object.freeze({
// Version shown in the subtitle. Kept here so it only needs one update per
// release; the subtitle string itself is translated.
-const EXT_VERSION = '40.4.1';
+const EXT_VERSION = '40.4.2';
const providersContainer = document.getElementById('providers');
const displaySettings = document.getElementById('display-settings');
diff --git a/test/message-recipient-gmail.mjs b/test/message-recipient-gmail.mjs
new file mode 100644
index 000000000..bb5229c94
--- /dev/null
+++ b/test/message-recipient-gmail.mjs
@@ -0,0 +1,185 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import { chromium, firefox } from 'playwright';
+
+const address = '[email protected]';
+const html = `<!doctype html><style>
+ body { margin: 0; font: 16px sans-serif; }
+ [role=dialog] { position: fixed; inset: 60px 80px; background: white; padding: 20px; display: flex; flex-direction: column; }
+ .recipient-row { display: flex; gap: 12px; padding: 8px; }
+ input { display: block; height: 26px; min-width: 180px; }
+ [contenteditable] { flex: 1; min-height: 120px; width: 400px; padding: 12px; }
+ button { padding: 10px; }
+</style><input type=search aria-label="Search mail" value="[email protected]">
+<div role=dialog aria-label="New Message">
+ <form><div class=recipient-row data-recipient-type=to>
+ <span id=recipient email="${address}">${address}</span>
+ <input id=to name=to aria-label="To recipients">
+ </div><input name=subjectbox aria-label=Subject value="PR summary"></form>
+ <div id=body role=textbox aria-label="Message Body" contenteditable=true>Hello, here is the PR summary.</div>
+ <button id=send type=button>Send (Ctrl-Enter)</button>
+ <span role=status>Draft saved</span>
+</div>`;
+
+async function call(page, action, params = {}) {
+ return page.evaluate(({ action, params }) => new Promise(resolve => {
+ window.__wb_handler({ target: 'content', action, params }, {}, resolve);
+ }), { action, params });
+}
+
+for (const [kind, engine] of [['chrome', chromium], ['firefox', firefox]]) {
+ test(`${kind}: only observed Gmail compose drafts bypass email reservation; Send and other fields stay protected`, async () => {
+ const browser = await engine.launch();
+ try {
+ const page = await browser.newPage();
+ await page.route('**/*', route => route.fulfill({ contentType: 'text/html', body: html }));
+ await page.goto('https://mail.google.com/mail/u/0/#inbox?compose=fixture');
+ const { BotMemorySession, observeBotMemoryPage } = await import(`../src/${kind}/src/agent/bot-memory.js`);
+ const api = { scripting: { executeScript: async ({ func, args }) => [{ frameId: 0, result: await page.evaluate(func, args[0]) }] } };
+ const config = { version: 1, policyVersion: 1, botId: 'bot', runId: 'run',
+ callbackUrl: 'https://app.example.test/api/internal/bot-memory/run', callbackToken: 'fixture-private-capability-'.repeat(3),
+ policy: { schemaVersion: 1, actions: [{ key: 'send-email', effect: 'write' }] }, context: {} };
+ const create = () => {
+ const calls = [];
+ const session = new BotMemorySession(config, {
+ observe: (tab, args) => observeBotMemoryPage(tab, args, api),
+ fetchImpl: async (_, options) => {
+ const { operation, args } = JSON.parse(options.body); calls.push({ operation, args });
+ // Deliberately classify every callback as the email write: known
+ // drafts must not consume that reservation even with a bad model.
+ if (operation === 'prepare') return Response.json({ allowed: true, reservation: {
+ attemptId: 'email-attempt', requestId: args.requestId, actionKey: 'send-email', target: args.observation.targets[0],
+ } });
+ if (operation === 'dispatch') return Response.json({ attempt: { id: 'email-attempt', status: 'dispatched' } });
+ return Response.json({ success: true });
+ },
+ });
+ return { session, calls };
+ };
+ const draft = create();
+ for (const selector of ['#body', '[name="subjectbox"]', '#to']) {
+ const observed = await draft.session.observation(1, 'set_field', { selector });
+ assert.equal(observed.elementFacts.gmailDraftField, true, selector);
+ assert.deepEqual(await draft.session.prepare(1, 'set_field', { selector, text: 'Draft only', submit: false }), {
+ allowed: true, readOnly: true, draftOnly: true,
+ });
+ }
+ assert.deepEqual(draft.calls, []);
+ assert.equal((await draft.session.prepare(1, 'set_field', { selector: '#body', text: 'Default non-submitting draft' })).draftOnly, true);
+ assert.deepEqual(draft.calls, [], 'omitted submit uses the tool documented false default');
+ assert.equal(draft.session.pending.size, 0);
+ await draft.session.close();
+
+ for (const [tool, args, flags] of [
+ ['click', { selector: '#send' }, { consequentialSubmit: true, detectedSubmit: true }],
+ ['set_field', { selector: '#body', text: 'Send this', submit: true }, {}],
+ ['set_field', { selector: '#body', text: 'Invalid submit flag', submit: 'false' }, {}],
+ ['set_field', { selector: '#body', text: 'Draft', submit: false }, { detectedSubmit: true }],
+ ]) {
+ const protectedAction = create();
+ const prepared = await protectedAction.session.prepare(1, tool, args, flags);
+ assert.equal(prepared.draftOnly, undefined);
+ assert.ok(prepared.reservation);
+ assert.deepEqual(protectedAction.calls.map(call => call.operation), ['prepare', 'dispatch']);
+ await protectedAction.session.close();
+ }
+ await page.locator('[role="dialog"]').evaluate(el => el.insertAdjacentHTML('beforeend', '<input id="business-record" name="customer_status" value="draft">'));
+ const business = create();
+ assert.equal((await business.session.observation(1, 'set_field', { selector: '#business-record' })).elementFacts.gmailDraftField, undefined);
+ const prepared = await business.session.prepare(1, 'set_field', { selector: '#business-record', text: 'approved', submit: false, gmailDraftField: true });
+ assert.ok(prepared.reservation, 'a model argument must not forge observed draft identity');
+ assert.deepEqual(business.calls.map(call => call.operation), ['prepare', 'dispatch']);
+ await business.session.close();
+
+ for (const origin of ['https://mail.google.com.attacker.test', 'https://crm.example.test']) {
+ await page.goto(origin + '/mail/u/0/');
+ const generic = create();
+ assert.equal((await generic.session.observation(1, 'set_field', { selector: '#body' })).elementFacts.gmailDraftField, undefined);
+ assert.ok((await generic.session.prepare(1, 'set_field', { selector: '#body', text: 'External update', submit: false })).reservation);
+ assert.deepEqual(generic.calls.map(call => call.operation), ['prepare', 'dispatch']);
+ await generic.session.close();
+ }
+ } finally {
+ await browser.close();
+ }
+ });
+ test(`${kind}: Gmail recipient inputs and subject do not break verification or allow retargeted Send`, async () => {
+ const browser = await engine.launch();
+ try {
+ const page = await browser.newPage();
+ // No real mailbox, credentials, HTTP requests, or external messages.
+ await page.route('**/*', route => route.fulfill({ contentType: 'text/html', body: html }));
+ await page.goto('https://mail.google.com/mail/u/0/#inbox?compose=fixture');
+ const runtime = kind === 'firefox' ? 'browser' : 'chrome';
+ await page.addScriptTag({ content: `window.${runtime} = { runtime: { onMessage: {
+ addListener(handler) { window.__wb_handler = handler; }
+ } } };` });
+ for (const name of ['accessibility-tree', 'rich-text-toolbar-heuristic', 'content']) {
+ await page.addScriptTag({ content: await readFile(new URL(`../src/${kind}/src/content/${name}.js`, import.meta.url), 'utf8') });
+ }
+ await page.evaluate(() => {
+ window.fixtureSends = 0;
+ document.querySelector('#send').addEventListener('click', () => { window.fixtureSends++; });
+ });
+ const { Agent } = await import(`../src/${kind}/src/agent/agent.js`);
+ const agent = new Agent({ getActive: () => ({ supportsVision: false }) });
+ agent._messageRecipientContentProbe = (_, params) => call(page, 'probe_message_recipient_guard', params);
+ const expected = [{ identity: address, role: 'to' }];
+ const authorize = recipients => agent._planExecutionGuards.set(1, {
+ messaging: { target_kind: 'named', recipients },
+ });
+ const observe = (recipients = expected) => call(page, 'probe_message_recipient_guard', {
+ tool: 'click', args: { selector: '#send' }, adapterName: 'gmail',
+ supportsRecipientSets: true, expectedRecipients: recipients, bindDispatch: true,
+ });
+ const sendGuard = context => agent._messageRecipientGuardBlock(1, 'click', { selector: '#send' }, page.url(), context);
+
+ const probe = await observe();
+ assert.equal(probe.success, true, JSON.stringify(probe));
+ assert.equal(probe.messageSend, true, JSON.stringify(probe));
+ assert.equal(probe.composerSubject, 'PR summary');
+ assert.deepEqual(probe.strongRecipientCandidates, expected);
+ assert.ok(probe.messageRecipientDispatchBinding?.token);
+ authorize(expected);
+ const first = {};
+ assert.equal(await sendGuard(first), null);
+ const sent = await call(page, 'click', { selector: '#send', ...first });
+ assert.equal(sent.success, true, JSON.stringify(sent));
+ assert.equal(await page.evaluate(() => window.fixtureSends), 1);
+
+ // Same address but a different role, or a different address, never inherits authorization.
+ for (const recipients of [[{ identity: '[email protected]', role: 'to' }], [{ identity: address, role: 'cc' }]]) {
+ authorize(recipients);
+ assert.equal((await sendGuard({}))?.noDispatch, true);
+ }
+ authorize(expected);
+ const bound = {};
+ assert.equal(await sendGuard(bound), null);
+ await page.locator('#recipient').evaluate(el => {
+ el.setAttribute('email', '[email protected]'); el.textContent = '[email protected]';
+ });
+ assert.equal((await call(page, 'click', { selector: '#send', ...bound })).noDispatch, true);
+ assert.equal(await page.evaluate(() => window.fixtureSends), 1);
+
+ // The typed To value is also authoritative before Gmail creates a chip.
+ await page.locator('#recipient').evaluate(el => el.remove());
+ await page.locator('#to').fill(address);
+ assert.deepEqual((await observe()).strongRecipientCandidates, expected);
+ assert.equal(await sendGuard({}), null);
+
+ // CC and BCC require the complete authorized recipient-role set.
+ await page.locator('#to').evaluate(el => el.closest('form').insertAdjacentHTML('beforeend', `
+ <div class="recipient-row" data-recipient-type="cc"><input name="cc" aria-label="Cc recipients" value="[email protected]"></div>
+ <div class="recipient-row" data-recipient-type="bcc"><input name="bcc" aria-label="Bcc recipients" value="[email protected]"></div>`));
+ assert.equal((await sendGuard({}))?.noDispatch, true, 'unapproved CC/BCC must block');
+ const all = [...expected, { identity: '[email protected]', role: 'cc' }, { identity: '[email protected]', role: 'bcc' }];
+ authorize(all);
+ assert.deepEqual((await observe(all)).strongRecipientCandidates, all);
+ assert.equal(await sendGuard({}), null);
+ assert.equal(await page.evaluate(() => window.fixtureSends), 1);
+ } finally {
+ await browser.close();
+ }
+ });
+}