Skip to content

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

Bind a Gmail Chat send to its own header, never to a compose window

Emre Sokullu623e50a1ca19
diff --git a/src/chrome/src/agent/adapters.js b/src/chrome/src/agent/adapters.js
index 96ab13efd..b1288dbf6 100644
--- a/src/chrome/src/agent/adapters.js
+++ b/src/chrome/src/agent/adapters.js
@@ -18271,17 +18271,16 @@ export function isPublicComposerRoute(url) {
/**
* True for Google Chat inside Gmail: the /chat/ app, or a #chat/... view
- * opened from mail (a direct message, space or the chat home). Gmail keeps a
- * compose window open across these views; a URL that names one (compose=,
- * in the query or the view's own #…?compose=) is a mail compose.
+ * opened from mail (a direct message, space or the chat home). Gmail keeps
+ * compose= in the URL while any compose window is open, so the URL cannot
+ * say which composer sends; a compose window open over these views is told
+ * apart by its own To/Cc/Bcc rows (content.js).
*/
export function isGmailChatRoute(url) {
try {
const parsed = new URL(url);
- if (parsed.hostname !== 'mail.google.com') return false;
- const viewQuery = parsed.hash.includes('?') ? parsed.hash.slice(parsed.hash.indexOf('?') + 1) : '';
- if (parsed.searchParams.has('compose') || new URLSearchParams(viewQuery).has('compose')) return false;
- return /^\/chat(?:\/|$)/.test(parsed.pathname) || /^#chat(?:[/?]|$)/.test(parsed.hash);
+ return parsed.hostname === 'mail.google.com'
+ && (/^\/chat(?:\/|$)/.test(parsed.pathname) || /^#chat(?:[/?]|$)/.test(parsed.hash));
} catch {
return false;
}
diff --git a/src/chrome/src/content/content.js b/src/chrome/src/content/content.js
index b8fd7e4d7..093f5da32 100644
--- a/src/chrome/src/content/content.js
+++ b/src/chrome/src/content/content.js
@@ -8072,6 +8072,162 @@
};
let gmailComposeRoot = null;
+ // ── Gmail: the message a composer and its Send belong to ─────────────
+ // The To, Cc or Bcc row an element names. The compose window, its
+ // chips and its typed addresses below use it.
+ const roleFromAttribute = (attribute, value) => {
+ const text = compact(value, 120).toLowerCase();
+ if (!text) return '';
+ // A row's or field's label names its role in the user's language,
+ // read by a model; the app's own names below do not.
+ if (attribute === 'aria-label') {
+ const role = _pageReading('message_field', compact(value, 120));
+ return ['to', 'cc', 'bcc'].includes(role) ? role : '';
+ }
+ 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']) {
+ const role = roleFromAttribute(attribute, current.getAttribute?.(attribute));
+ if (role) return role;
+ }
+ if (root && current === root) break;
+ try {
+ const descendantRoles = new Set();
+ for (const marker of current.querySelectorAll?.(
+ 'input[name="to"],input[name="cc"],input[name="bcc"],[aria-label]'
+ ) || []) {
+ const role = roleFromAttribute('name', marker.getAttribute?.('name'))
+ || roleFromAttribute('aria-label', marker.getAttribute?.('aria-label'));
+ if (role) descendantRoles.add(role);
+ }
+ // A nearest row containing one role marker can classify its
+ // chips. A shared ancestor containing multiple rows cannot.
+ if (descendantRoles.size === 1) return [...descendantRoles][0];
+ } catch {}
+ }
+ return '';
+ };
+ const collectGmailRecipients = (root) => {
+ const collected = new Map();
+ if (!root?.querySelectorAll) return collected;
+ for (const el of root.querySelectorAll('[email],[data-hovercard-id],[data-email]')) {
+ if (!visible(el) || editable(el)) continue;
+ if (el === composer || composer.contains?.(el)) continue;
+ const email = [
+ el.getAttribute?.('email'),
+ el.getAttribute?.('data-email'),
+ el.getAttribute?.('data-hovercard-id'),
+ ].map(value => compact(value, 240)).find(value => /@/.test(value)) || '';
+ if (!email) continue;
+ const aliases = new Map();
+ const addAlias = (val) => {
+ const alias = compact(val, 240);
+ const normalized = normalizedIdentity(alias);
+ if (alias && normalized && !aliases.has(normalized)) aliases.set(normalized, alias);
+ const angleMatch = alias.match(/^([^<@]+)<[^>]+>$/);
+ if (angleMatch) {
+ const nameOnly = compact(angleMatch[1], 240);
+ const normName = normalizedIdentity(nameOnly);
+ if (nameOnly && normName && !aliases.has(normName)) aliases.set(normName, nameOnly);
+ }
+ };
+ for (const value of [
+ email,
+ el.getAttribute?.('name'),
+ el.getAttribute?.('aria-label'),
+ el.getAttribute?.('title'),
+ el.innerText,
+ el.textContent,
+ ]) {
+ addAlias(value);
+ }
+ const key = normalizedIdentity(email);
+ if (!key) continue;
+ const role = recipientRole(el, root);
+ if (!role) continue;
+ const recipientKey = `${role}:${key}`;
+ const prior = collected.get(recipientKey) || { identity: email, role, aliases: new Map() };
+ for (const [normalized, alias] of aliases) prior.aliases.set(normalized, alias);
+ collected.set(recipientKey, prior);
+ }
+ return collected;
+ };
+ // Another message's editor: not this composer, not nested with it,
+ // not a search or navigation field and not a To/Cc/Bcc row's field.
+ const otherMessageEditor = editor => editor !== composer && !composer.contains?.(editor)
+ && !editor.contains?.(composer) && !verifiedNavigationEditable(editor)
+ && !editor.matches?.('[name="to"],[name="cc"],[name="bcc"]');
+ // In Gmail a send has recipients only from its composer's own mail
+ // compose window: a popup or full-screen compose is the composer's
+ // dialog (else its form), and an inline thread reply, which has
+ // neither, the nearest ancestor with To/Cc/Bcc chips that stays inside
+ // the page's main region and holds no other window or message editor.
+ // Gmail's own field names, its compose body, a chip in a row or a
+ // field read as a row mark that window; one without them (a chat) is
+ // none.
+ const gmailComposeWindow = (() => {
+ if (!gmailRecipientMode) return null;
+ const recipientRows = root => !!root && (
+ !!root.querySelector?.('[name="to"],[name="cc"],[name="bcc"],input[name="subjectbox"]')
+ || composer.getAttribute?.('g_editable') === 'true'
+ || collectGmailRecipients(root).size > 0
+ || Array.from(root.querySelectorAll?.('input, textarea, [contenteditable="true"], [contenteditable=""]') || [])
+ .slice(0, 40).some(input => visible(input) && input !== composer && !composer.contains?.(input)
+ && !!(roleFromAttribute('name', input.getAttribute?.('name'))
+ || roleFromAttribute('aria-label', input.getAttribute?.('aria-label')))));
+ const explicit = composer.closest?.('[role="dialog"]') || composer.closest?.('form') || null;
+ if (explicit) return recipientRows(explicit) ? explicit : null;
+ let current = composer.parentElement;
+ for (let depth = 0; current && depth < 16; depth += 1, current = current.parentElement) {
+ if (current === document.body || current === document.documentElement
+ || current.matches?.('main,[role="main"]') || current.querySelector?.('[role="dialog"]')
+ || composerCandidates.some(editor => current.contains?.(editor) && otherMessageEditor(editor))) break;
+ if (collectGmailRecipients(current).size > 0) return current;
+ }
+ return null;
+ })();
+ // The control that sends must be this composer's own: the two share an
+ // owner holding no message editor beyond this composer's own window.
+ // A Send the page's layout pairs with another message's composer (a
+ // Chat's Send beside a compose window's body, or the reverse) belongs
+ // to that other message.
+ let gmailSendOwner = null;
+ if (gmailRecipientMode && (tool === 'click' || tool === 'click_ax') && dispatchTarget
+ && dispatchTarget !== composer && !composer.contains?.(dispatchTarget)) {
+ for (let node = composer.parentElement; node; node = node.parentElement) {
+ if (node.contains?.(dispatchTarget)) { gmailSendOwner = node; break; }
+ }
+ }
+ const gmailEditorScope = composer.closest?.('[role="dialog"]') || gmailComposeWindow || composer;
+ const gmailForeignSend = !!gmailSendOwner && composerCandidates.some(editor => gmailSendOwner.contains(editor)
+ && !gmailEditorScope.contains?.(editor) && otherMessageEditor(editor));
+ const gmailMailSend = !!gmailComposeWindow && !gmailForeignSend;
+ // Google Chat inside Gmail is a chat: on a Chat route, a composer in
+ // the page's main region and in no compose window is identified by its
+ // own conversation header, as any chat is (below).
+ const gmailChatRoute = gmailRecipientMode && (() => {
+ try {
+ return location.hostname === 'mail.google.com'
+ && (/^\/chat(?:\/|$)/.test(String(location.pathname || ''))
+ || /^#chat(?:[/?]|$)/.test(String(location.hash || '')));
+ } catch { return false; }
+ })();
+ const gmailChatMain = gmailChatRoute && !gmailComposeWindow && !gmailForeignSend
+ && composer.getAttribute?.('g_editable') !== 'true' && !composer.closest?.('[role="dialog"]')
+ ? composer.closest?.('main,[role="main"]') || null : null;
+ const gmailChatComposer = !!gmailChatMain;
+ // Gmail's recipient sets come from that window alone, on any route.
+ const recipientSets = gmailRecipientMode ? gmailMailSend : params.supportsRecipientSets === true;
const nativeTelegramComposer = /^(?:web|webk|weba|webz|k)\.telegram\.org$/i.test(location.hostname)
&& composer.matches?.('.input-message-input[contenteditable="true"],#editable-message-text[contenteditable="true"][role="textbox"]');
if (nativeLayoutContext?.service === 'whatsapp') {
@@ -8143,112 +8299,11 @@
strongRecipients.push({ identity: context.id, role: 'to' });
observedRecipientCandidates.push({ identity: context.id, role: 'to', aliases: [context.id, context.name,
...(context.alias ? [context.alias, '@' + context.alias] : [])] });
- } else if (gmailRecipientMode) {
- // The To, Cc or Bcc row an element names. Both the chips and the
- // typed addresses below use it.
- const roleFromAttribute = (attribute, value) => {
- const text = compact(value, 120).toLowerCase();
- if (!text) return '';
- // A row's or field's label names its role in the user's language,
- // read by a model; the app's own names below do not.
- if (attribute === 'aria-label') {
- const role = _pageReading('message_field', compact(value, 120));
- return ['to', 'cc', 'bcc'].includes(role) ? role : '';
- }
- 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']) {
- const role = roleFromAttribute(attribute, current.getAttribute?.(attribute));
- if (role) return role;
- }
- if (root && current === root) break;
- try {
- const descendantRoles = new Set();
- for (const marker of current.querySelectorAll?.(
- 'input[name="to"],input[name="cc"],input[name="bcc"],[aria-label]'
- ) || []) {
- const role = roleFromAttribute('name', marker.getAttribute?.('name'))
- || roleFromAttribute('aria-label', marker.getAttribute?.('aria-label'));
- if (role) descendantRoles.add(role);
- }
- // A nearest row containing one role marker can classify its
- // chips. A shared ancestor containing multiple rows cannot.
- if (descendantRoles.size === 1) return [...descendantRoles][0];
- } catch {}
- }
- return '';
- };
- const collectGmailRecipients = (root) => {
- const collected = new Map();
- if (!root?.querySelectorAll) return collected;
- for (const el of root.querySelectorAll('[email],[data-hovercard-id],[data-email]')) {
- if (!visible(el) || editable(el)) continue;
- if (el === composer || composer.contains?.(el)) continue;
- const email = [
- el.getAttribute?.('email'),
- el.getAttribute?.('data-email'),
- el.getAttribute?.('data-hovercard-id'),
- ].map(value => compact(value, 240)).find(value => /@/.test(value)) || '';
- if (!email) continue;
- const aliases = new Map();
- const addAlias = (val) => {
- const alias = compact(val, 240);
- const normalized = normalizedIdentity(alias);
- if (alias && normalized && !aliases.has(normalized)) aliases.set(normalized, alias);
- const angleMatch = alias.match(/^([^<@]+)<[^>]+>$/);
- if (angleMatch) {
- const nameOnly = compact(angleMatch[1], 240);
- const normName = normalizedIdentity(nameOnly);
- if (nameOnly && normName && !aliases.has(normName)) aliases.set(normName, nameOnly);
- }
- };
- for (const value of [
- email,
- el.getAttribute?.('name'),
- el.getAttribute?.('aria-label'),
- el.getAttribute?.('title'),
- el.innerText,
- el.textContent,
- ]) {
- addAlias(value);
- }
- const key = normalizedIdentity(email);
- if (!key) continue;
- const role = recipientRole(el, root);
- if (!role) continue;
- const recipientKey = `${role}:${key}`;
- const prior = collected.get(recipientKey) || { identity: email, role, aliases: new Map() };
- for (const [normalized, alias] of aliases) prior.aliases.set(normalized, alias);
- collected.set(recipientKey, prior);
- }
- return collected;
- };
- // Dialog/popup compose keeps its form root. Inline thread replies are
- // not inside [role=dialog] or form; use the nearest ancestor that
- // already contains role-qualified To/Cc/Bcc chips so thread hovercards
- // without a recipient role cannot pin a send.
- const composeRoot = (() => {
- const explicit = composer.closest?.('[role="dialog"],form') || null;
- if (explicit) return explicit;
- let current = composer.parentElement;
- for (let depth = 0; current && depth < 16; depth += 1, current = current.parentElement) {
- if (current === document.body || current === document.documentElement) break;
- if (collectGmailRecipients(current).size > 0) return current;
- }
- return null;
- })();
- gmailComposeRoot = composeRoot;
- const recipients = collectGmailRecipients(composeRoot);
+ } else if (gmailMailSend) {
+ // A send from the composer's own mail compose window: that window's
+ // To, Cc and Bcc rows are its recipients.
+ gmailComposeRoot = gmailComposeWindow;
+ const recipients = collectGmailRecipients(gmailComposeWindow);
// A recipient that was typed but not yet turned into a chip lives only
// in the To/Cc/Bcc input VALUE β€” there is no [email] attribute to read.
// Without this pass a compose window whose address was just typed
@@ -8297,7 +8352,7 @@
}
}
};
- collectRecipientInputValues(composeRoot);
+ collectRecipientInputValues(gmailComposeWindow);
for (const [recipientKey, recipient] of recipients) {
const emailKey = recipientKey.slice(recipientKey.indexOf(':') + 1);
const identity = recipient.aliases.get(emailKey) || [...recipient.aliases.values()][0] || recipient.identity || '';
@@ -8352,6 +8407,11 @@
}
}
}
+ } else if (gmailRecipientMode && !gmailChatComposer) {
+ // Any other Gmail send identifies no one: a Send the page's layout
+ // pairs with another message's composer, or, outside Google Chat, a
+ // composer in no mail compose window (an inline reply whose chips
+ // name no row). Nothing on the page then says where it goes.
} else if (twitterConversation) {
const headers = Array.from(document.querySelectorAll('[data-testid="dm-conversation-username"]'))
.filter(el => visible(el) && inConversationHeaderBand(el) && !independentScrollableRegion(el, composer));
@@ -8392,7 +8452,7 @@
}
}
} else {
- for (const el of document.querySelectorAll(
+ for (const el of (gmailChatMain || document).querySelectorAll(
'[aria-selected="true"],[aria-current]:not([aria-current="false"])'
)) {
// Search results and navigation rows can also be selected/current, so
@@ -8402,14 +8462,14 @@
if (strongIdentities.length >= 8) break;
}
- for (const el of document.querySelectorAll(
+ for (const el of (gmailChatMain || document).querySelectorAll(
'h1,h2,h3,h4,[role="heading"]'
)) {
addStrongIdentity(el);
if (strongIdentities.length >= 8) break;
}
- if (!strongIdentities.length && params.adapterName === 'generic-messaging'
- && params.supportsRecipientSets !== true) {
+ if (!strongIdentities.length && (gmailChatComposer || (params.adapterName === 'generic-messaging'
+ && params.supportsRecipientSets !== true))) {
// Some conversation headers expose the contact name as a button
// rather than a heading, or (help desks, CRMs) only the contact's
// address as a mailto link or address chip. A shared local
@@ -8516,17 +8576,6 @@
}
}
- // Gmail keeps a mail compose window open across its Chat views. A
- // composer whose own compose window (its dialog, else its form; never
- // a wider region that only contains one) has To/Cc/Bcc rows sends to
- // that recipient set wherever it is open, decided from its structure,
- // when the send comes from that window.
- const gmailComposeWindow = gmailRecipientMode
- ? composer.closest?.('[role="dialog"]') || composer.closest?.('form') : null;
- const recipientSets = params.supportsRecipientSets === true
- || (!!gmailComposeWindow?.querySelector?.('[name="to"],[name="cc"],[name="bcc"]')
- && (!dispatchTarget || gmailComposeWindow.contains?.(dispatchTarget) === true));
-
// The isolated monitor reads this exact local proof synchronously. Its
// closure-only callback never participates in the public message API,
// authorizes an action, or needs the expensive message-history scan.
@@ -8542,7 +8591,10 @@
// field, or an address-bearing chip/link near the composer β€” instead of
// depending on one vendor's markup. This is what makes confirm-then-send
// work globally rather than only on Gmail.
- if (observedRecipientCandidates.length === 0) {
+ // In Gmail only a send from a mail compose window reads further, and
+ // only inside that window: another window's typed addresses or chips
+ // never name this send's recipients.
+ if (observedRecipientCandidates.length === 0 && (!gmailRecipientMode || gmailMailSend)) {
const genericMailRecipientMode = params.adapterName === 'generic-messaging'
&& params.supportsRecipientSets === true;
// A field holds recipients when its labels and names read, in any
@@ -8600,7 +8652,7 @@
}
};
try {
- for (const el of Array.from(document.querySelectorAll(
+ for (const el of Array.from((gmailMailSend ? gmailComposeWindow : document).querySelectorAll(
'input, textarea, [contenteditable="true"], [contenteditable=""]',
)).slice(0, 60)) {
if (!visible(el) || el === composer || composer?.contains?.(el)) continue;
@@ -8617,7 +8669,8 @@
// conversation header), so without one it stays unverified.
if (recipientSets) {
try {
- const chipScope = composer.closest?.('[role="dialog"],form,[role="main"]') || document;
+ const chipScope = (gmailMailSend ? gmailComposeWindow
+ : composer.closest?.('[role="dialog"],form,[role="main"]')) || document;
for (const el of Array.from(chipScope.querySelectorAll(
'[email],[data-email],[data-hovercard-id],a[href^="mailto:" i],input[type="email"]',
)).slice(0, 40)) {
diff --git a/src/firefox/src/agent/adapters.js b/src/firefox/src/agent/adapters.js
index 11de57d38..eb269e0e5 100644
--- a/src/firefox/src/agent/adapters.js
+++ b/src/firefox/src/agent/adapters.js
@@ -18269,17 +18269,16 @@ export function isPublicComposerRoute(url) {
/**
* True for Google Chat inside Gmail: the /chat/ app, or a #chat/... view
- * opened from mail (a direct message, space or the chat home). Gmail keeps a
- * compose window open across these views; a URL that names one (compose=,
- * in the query or the view's own #…?compose=) is a mail compose.
+ * opened from mail (a direct message, space or the chat home). Gmail keeps
+ * compose= in the URL while any compose window is open, so the URL cannot
+ * say which composer sends; a compose window open over these views is told
+ * apart by its own To/Cc/Bcc rows (content.js).
*/
export function isGmailChatRoute(url) {
try {
const parsed = new URL(url);
- if (parsed.hostname !== 'mail.google.com') return false;
- const viewQuery = parsed.hash.includes('?') ? parsed.hash.slice(parsed.hash.indexOf('?') + 1) : '';
- if (parsed.searchParams.has('compose') || new URLSearchParams(viewQuery).has('compose')) return false;
- return /^\/chat(?:\/|$)/.test(parsed.pathname) || /^#chat(?:[/?]|$)/.test(parsed.hash);
+ return parsed.hostname === 'mail.google.com'
+ && (/^\/chat(?:\/|$)/.test(parsed.pathname) || /^#chat(?:[/?]|$)/.test(parsed.hash));
} catch {
return false;
}
diff --git a/src/firefox/src/content/content.js b/src/firefox/src/content/content.js
index c4d4829a2..fbb39bfa8 100644
--- a/src/firefox/src/content/content.js
+++ b/src/firefox/src/content/content.js
@@ -7226,6 +7226,162 @@
};
let gmailComposeRoot = null;
+ // ── Gmail: the message a composer and its Send belong to ─────────────
+ // The To, Cc or Bcc row an element names. The compose window, its
+ // chips and its typed addresses below use it.
+ const roleFromAttribute = (attribute, value) => {
+ const text = compact(value, 120).toLowerCase();
+ if (!text) return '';
+ // A row's or field's label names its role in the user's language,
+ // read by a model; the app's own names below do not.
+ if (attribute === 'aria-label') {
+ const role = _pageReading('message_field', compact(value, 120));
+ return ['to', 'cc', 'bcc'].includes(role) ? role : '';
+ }
+ 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']) {
+ const role = roleFromAttribute(attribute, current.getAttribute?.(attribute));
+ if (role) return role;
+ }
+ if (root && current === root) break;
+ try {
+ const descendantRoles = new Set();
+ for (const marker of current.querySelectorAll?.(
+ 'input[name="to"],input[name="cc"],input[name="bcc"],[aria-label]'
+ ) || []) {
+ const role = roleFromAttribute('name', marker.getAttribute?.('name'))
+ || roleFromAttribute('aria-label', marker.getAttribute?.('aria-label'));
+ if (role) descendantRoles.add(role);
+ }
+ // A nearest row containing one role marker can classify its
+ // chips. A shared ancestor containing multiple rows cannot.
+ if (descendantRoles.size === 1) return [...descendantRoles][0];
+ } catch {}
+ }
+ return '';
+ };
+ const collectGmailRecipients = (root) => {
+ const collected = new Map();
+ if (!root?.querySelectorAll) return collected;
+ for (const el of root.querySelectorAll('[email],[data-hovercard-id],[data-email]')) {
+ if (!visible(el) || editable(el)) continue;
+ if (el === composer || composer.contains?.(el)) continue;
+ const email = [
+ el.getAttribute?.('email'),
+ el.getAttribute?.('data-email'),
+ el.getAttribute?.('data-hovercard-id'),
+ ].map(value => compact(value, 240)).find(value => /@/.test(value)) || '';
+ if (!email) continue;
+ const aliases = new Map();
+ const addAlias = (val) => {
+ const alias = compact(val, 240);
+ const normalized = normalizedIdentity(alias);
+ if (alias && normalized && !aliases.has(normalized)) aliases.set(normalized, alias);
+ const angleMatch = alias.match(/^([^<@]+)<[^>]+>$/);
+ if (angleMatch) {
+ const nameOnly = compact(angleMatch[1], 240);
+ const normName = normalizedIdentity(nameOnly);
+ if (nameOnly && normName && !aliases.has(normName)) aliases.set(normName, nameOnly);
+ }
+ };
+ for (const value of [
+ email,
+ el.getAttribute?.('name'),
+ el.getAttribute?.('aria-label'),
+ el.getAttribute?.('title'),
+ el.innerText,
+ el.textContent,
+ ]) {
+ addAlias(value);
+ }
+ const key = normalizedIdentity(email);
+ if (!key) continue;
+ const role = recipientRole(el, root);
+ if (!role) continue;
+ const recipientKey = `${role}:${key}`;
+ const prior = collected.get(recipientKey) || { identity: email, role, aliases: new Map() };
+ for (const [normalized, alias] of aliases) prior.aliases.set(normalized, alias);
+ collected.set(recipientKey, prior);
+ }
+ return collected;
+ };
+ // Another message's editor: not this composer, not nested with it,
+ // not a search or navigation field and not a To/Cc/Bcc row's field.
+ const otherMessageEditor = editor => editor !== composer && !composer.contains?.(editor)
+ && !editor.contains?.(composer) && !verifiedNavigationEditable(editor)
+ && !editor.matches?.('[name="to"],[name="cc"],[name="bcc"]');
+ // In Gmail a send has recipients only from its composer's own mail
+ // compose window: a popup or full-screen compose is the composer's
+ // dialog (else its form), and an inline thread reply, which has
+ // neither, the nearest ancestor with To/Cc/Bcc chips that stays inside
+ // the page's main region and holds no other window or message editor.
+ // Gmail's own field names, its compose body, a chip in a row or a
+ // field read as a row mark that window; one without them (a chat) is
+ // none.
+ const gmailComposeWindow = (() => {
+ if (!gmailRecipientMode) return null;
+ const recipientRows = root => !!root && (
+ !!root.querySelector?.('[name="to"],[name="cc"],[name="bcc"],input[name="subjectbox"]')
+ || composer.getAttribute?.('g_editable') === 'true'
+ || collectGmailRecipients(root).size > 0
+ || Array.from(root.querySelectorAll?.('input, textarea, [contenteditable="true"], [contenteditable=""]') || [])
+ .slice(0, 40).some(input => visible(input) && input !== composer && !composer.contains?.(input)
+ && !!(roleFromAttribute('name', input.getAttribute?.('name'))
+ || roleFromAttribute('aria-label', input.getAttribute?.('aria-label')))));
+ const explicit = composer.closest?.('[role="dialog"]') || composer.closest?.('form') || null;
+ if (explicit) return recipientRows(explicit) ? explicit : null;
+ let current = composer.parentElement;
+ for (let depth = 0; current && depth < 16; depth += 1, current = current.parentElement) {
+ if (current === document.body || current === document.documentElement
+ || current.matches?.('main,[role="main"]') || current.querySelector?.('[role="dialog"]')
+ || composerCandidates.some(editor => current.contains?.(editor) && otherMessageEditor(editor))) break;
+ if (collectGmailRecipients(current).size > 0) return current;
+ }
+ return null;
+ })();
+ // The control that sends must be this composer's own: the two share an
+ // owner holding no message editor beyond this composer's own window.
+ // A Send the page's layout pairs with another message's composer (a
+ // Chat's Send beside a compose window's body, or the reverse) belongs
+ // to that other message.
+ let gmailSendOwner = null;
+ if (gmailRecipientMode && (tool === 'click' || tool === 'click_ax') && dispatchTarget
+ && dispatchTarget !== composer && !composer.contains?.(dispatchTarget)) {
+ for (let node = composer.parentElement; node; node = node.parentElement) {
+ if (node.contains?.(dispatchTarget)) { gmailSendOwner = node; break; }
+ }
+ }
+ const gmailEditorScope = composer.closest?.('[role="dialog"]') || gmailComposeWindow || composer;
+ const gmailForeignSend = !!gmailSendOwner && composerCandidates.some(editor => gmailSendOwner.contains(editor)
+ && !gmailEditorScope.contains?.(editor) && otherMessageEditor(editor));
+ const gmailMailSend = !!gmailComposeWindow && !gmailForeignSend;
+ // Google Chat inside Gmail is a chat: on a Chat route, a composer in
+ // the page's main region and in no compose window is identified by its
+ // own conversation header, as any chat is (below).
+ const gmailChatRoute = gmailRecipientMode && (() => {
+ try {
+ return location.hostname === 'mail.google.com'
+ && (/^\/chat(?:\/|$)/.test(String(location.pathname || ''))
+ || /^#chat(?:[/?]|$)/.test(String(location.hash || '')));
+ } catch { return false; }
+ })();
+ const gmailChatMain = gmailChatRoute && !gmailComposeWindow && !gmailForeignSend
+ && composer.getAttribute?.('g_editable') !== 'true' && !composer.closest?.('[role="dialog"]')
+ ? composer.closest?.('main,[role="main"]') || null : null;
+ const gmailChatComposer = !!gmailChatMain;
+ // Gmail's recipient sets come from that window alone, on any route.
+ const recipientSets = gmailRecipientMode ? gmailMailSend : params.supportsRecipientSets === true;
const nativeTelegramComposer = /^(?:web|webk|weba|webz|k)\.telegram\.org$/i.test(location.hostname)
&& composer.matches?.('.input-message-input[contenteditable="true"],#editable-message-text[contenteditable="true"][role="textbox"]');
if (nativeLayoutContext?.service === 'whatsapp') {
@@ -7297,112 +7453,11 @@
strongRecipients.push({ identity: context.id, role: 'to' });
observedRecipientCandidates.push({ identity: context.id, role: 'to', aliases: [context.id, context.name,
...(context.alias ? [context.alias, '@' + context.alias] : [])] });
- } else if (gmailRecipientMode) {
- // The To, Cc or Bcc row an element names. Both the chips and the
- // typed addresses below use it.
- const roleFromAttribute = (attribute, value) => {
- const text = compact(value, 120).toLowerCase();
- if (!text) return '';
- // A row's or field's label names its role in the user's language,
- // read by a model; the app's own names below do not.
- if (attribute === 'aria-label') {
- const role = _pageReading('message_field', compact(value, 120));
- return ['to', 'cc', 'bcc'].includes(role) ? role : '';
- }
- 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']) {
- const role = roleFromAttribute(attribute, current.getAttribute?.(attribute));
- if (role) return role;
- }
- if (root && current === root) break;
- try {
- const descendantRoles = new Set();
- for (const marker of current.querySelectorAll?.(
- 'input[name="to"],input[name="cc"],input[name="bcc"],[aria-label]'
- ) || []) {
- const role = roleFromAttribute('name', marker.getAttribute?.('name'))
- || roleFromAttribute('aria-label', marker.getAttribute?.('aria-label'));
- if (role) descendantRoles.add(role);
- }
- // A nearest row containing one role marker can classify its
- // chips. A shared ancestor containing multiple rows cannot.
- if (descendantRoles.size === 1) return [...descendantRoles][0];
- } catch {}
- }
- return '';
- };
- const collectGmailRecipients = (root) => {
- const collected = new Map();
- if (!root?.querySelectorAll) return collected;
- for (const el of root.querySelectorAll('[email],[data-hovercard-id],[data-email]')) {
- if (!visible(el) || editable(el)) continue;
- if (el === composer || composer.contains?.(el)) continue;
- const email = [
- el.getAttribute?.('email'),
- el.getAttribute?.('data-email'),
- el.getAttribute?.('data-hovercard-id'),
- ].map(value => compact(value, 240)).find(value => /@/.test(value)) || '';
- if (!email) continue;
- const aliases = new Map();
- const addAlias = (val) => {
- const alias = compact(val, 240);
- const normalized = normalizedIdentity(alias);
- if (alias && normalized && !aliases.has(normalized)) aliases.set(normalized, alias);
- const angleMatch = alias.match(/^([^<@]+)<[^>]+>$/);
- if (angleMatch) {
- const nameOnly = compact(angleMatch[1], 240);
- const normName = normalizedIdentity(nameOnly);
- if (nameOnly && normName && !aliases.has(normName)) aliases.set(normName, nameOnly);
- }
- };
- for (const value of [
- email,
- el.getAttribute?.('name'),
- el.getAttribute?.('aria-label'),
- el.getAttribute?.('title'),
- el.innerText,
- el.textContent,
- ]) {
- addAlias(value);
- }
- const key = normalizedIdentity(email);
- if (!key) continue;
- const role = recipientRole(el, root);
- if (!role) continue;
- const recipientKey = `${role}:${key}`;
- const prior = collected.get(recipientKey) || { identity: email, role, aliases: new Map() };
- for (const [normalized, alias] of aliases) prior.aliases.set(normalized, alias);
- collected.set(recipientKey, prior);
- }
- return collected;
- };
- // Dialog/popup compose keeps its form root. Inline thread replies are
- // not inside [role=dialog] or form; use the nearest ancestor that
- // already contains role-qualified To/Cc/Bcc chips so thread hovercards
- // without a recipient role cannot pin a send.
- const composeRoot = (() => {
- const explicit = composer.closest?.('[role="dialog"],form') || null;
- if (explicit) return explicit;
- let current = composer.parentElement;
- for (let depth = 0; current && depth < 16; depth += 1, current = current.parentElement) {
- if (current === document.body || current === document.documentElement) break;
- if (collectGmailRecipients(current).size > 0) return current;
- }
- return null;
- })();
- gmailComposeRoot = composeRoot;
- const recipients = collectGmailRecipients(composeRoot);
+ } else if (gmailMailSend) {
+ // A send from the composer's own mail compose window: that window's
+ // To, Cc and Bcc rows are its recipients.
+ gmailComposeRoot = gmailComposeWindow;
+ const recipients = collectGmailRecipients(gmailComposeWindow);
// A typed, uncommitted Gmail address only exists in the visible
// recipient input. Include it so confirmation remains bound to what
// is actually on screen before the UI turns it into a chip.
@@ -7443,7 +7498,7 @@
}
}
};
- collectRecipientInputValues(composeRoot);
+ collectRecipientInputValues(gmailComposeWindow);
for (const [recipientKey, recipient] of recipients) {
const emailKey = recipientKey.slice(recipientKey.indexOf(':') + 1);
const identity = recipient.aliases.get(emailKey) || [...recipient.aliases.values()][0] || recipient.identity || '';
@@ -7498,6 +7553,11 @@
}
}
}
+ } else if (gmailRecipientMode && !gmailChatComposer) {
+ // Any other Gmail send identifies no one: a Send the page's layout
+ // pairs with another message's composer, or, outside Google Chat, a
+ // composer in no mail compose window (an inline reply whose chips
+ // name no row). Nothing on the page then says where it goes.
} else if (twitterConversation) {
const headers = Array.from(document.querySelectorAll('[data-testid="dm-conversation-username"]'))
.filter(el => visible(el) && inConversationHeaderBand(el) && !independentScrollableRegion(el, composer));
@@ -7538,7 +7598,7 @@
}
}
} else {
- for (const el of document.querySelectorAll(
+ for (const el of (gmailChatMain || document).querySelectorAll(
'[aria-selected="true"],[aria-current]:not([aria-current="false"])'
)) {
// Search results and navigation rows can also be selected/current, so
@@ -7548,14 +7608,14 @@
if (strongIdentities.length >= 8) break;
}
- for (const el of document.querySelectorAll(
+ for (const el of (gmailChatMain || document).querySelectorAll(
'h1,h2,h3,h4,[role="heading"]'
)) {
addStrongIdentity(el);
if (strongIdentities.length >= 8) break;
}
- if (!strongIdentities.length && params.adapterName === 'generic-messaging'
- && params.supportsRecipientSets !== true) {
+ if (!strongIdentities.length && (gmailChatComposer || (params.adapterName === 'generic-messaging'
+ && params.supportsRecipientSets !== true))) {
// Some conversation headers expose the contact name as a button
// rather than a heading, or (help desks, CRMs) only the contact's
// address as a mailto link or address chip. A shared local
@@ -7662,17 +7722,6 @@
}
}
- // Gmail keeps a mail compose window open across its Chat views. A
- // composer whose own compose window (its dialog, else its form; never
- // a wider region that only contains one) has To/Cc/Bcc rows sends to
- // that recipient set wherever it is open, decided from its structure,
- // when the send comes from that window.
- const gmailComposeWindow = gmailRecipientMode
- ? composer.closest?.('[role="dialog"]') || composer.closest?.('form') : null;
- const recipientSets = params.supportsRecipientSets === true
- || (!!gmailComposeWindow?.querySelector?.('[name="to"],[name="cc"],[name="bcc"]')
- && (!dispatchTarget || gmailComposeWindow.contains?.(dispatchTarget) === true));
-
// The isolated monitor reads this exact local proof synchronously. Its
// closure-only callback never participates in the public message API,
// authorizes an action, or needs the expensive message-history scan.
@@ -7685,7 +7734,10 @@
// provider-specific adapter. Read only explicit recipient semantics;
// an ordinary contact form's email field must not become a message
// recipient, and a generic chat still requires one header identity.
- if (observedRecipientCandidates.length === 0) {
+ // In Gmail only a send from a mail compose window reads further, and
+ // only inside that window: another window's typed addresses or chips
+ // never name this send's recipients.
+ if (observedRecipientCandidates.length === 0 && (!gmailRecipientMode || gmailMailSend)) {
const genericMailRecipientMode = params.adapterName === 'generic-messaging'
&& params.supportsRecipientSets === true;
// A field holds recipients when its labels and names read, in any
@@ -7740,7 +7792,7 @@
}
};
try {
- for (const el of Array.from(document.querySelectorAll(
+ for (const el of Array.from((gmailMailSend ? gmailComposeWindow : document).querySelectorAll(
'input, textarea, [contenteditable="true"], [contenteditable=""]',
)).slice(0, 60)) {
if (!visible(el) || el === composer || composer?.contains?.(el)) continue;
@@ -7757,7 +7809,8 @@
// conversation header), so without one it stays unverified.
if (recipientSets) {
try {
- const chipScope = composer.closest?.('[role="dialog"],form,[role="main"]') || document;
+ const chipScope = (gmailMailSend ? gmailComposeWindow
+ : composer.closest?.('[role="dialog"],form,[role="main"]')) || document;
for (const el of Array.from(chipScope.querySelectorAll(
'[email],[data-email],[data-hovercard-id],a[href^="mailto:" i],input[type="email"]',
)).slice(0, 40)) {
diff --git a/test/improver-content-recipient.mjs b/test/improver-content-recipient.mjs
index d4667143e..bd9d74032 100644
--- a/test/improver-content-recipient.mjs
+++ b/test/improver-content-recipient.mjs
@@ -57,20 +57,31 @@ const GMAIL_COMPOSE_OVER_CHAT = `<!doctype html><style>body{margin:0;font:16px s
<div id="body" contenteditable="true" role="textbox" aria-label="Message Body">Hello both</div>
<button id="send" type="button" aria-label="Send">Send</button></form></div>`;
-// A Chat composer beside an open compose window, close enough that the
-// page's layout pairs the chat's Send with the compose body.
-const GMAIL_CHAT_BESIDE_COMPOSE = `<!doctype html><style>body{margin:0;font:16px sans-serif}
+// Google Chat inside Gmail: a conversation in the page's main region with
+// its own header, and optionally a mail compose window open beside it. With
+// the window docked at the bottom its body is the page's lowest editor, so
+// the page's layout pairs the chat's Send with it; raised, the chat's own
+// composer is the lowest.
+const TO_ADA = '<div name="to"><span email="[email protected]">Ada</span></div>';
+const CC_CEM = '<div name="cc"><span email="[email protected]">Cem</span></div>';
+const BCC_DEE = '<div name="bcc"><span email="[email protected]">Dee</span></div>';
+const gmailChat = ({ rows = '', raise = 0 } = {}) => `<!doctype html><style>body{margin:0;font:16px sans-serif}
#chat{position:absolute;left:0;top:0;width:640px;height:780px}#chat>header{height:70px}
#messages{height:580px;overflow:auto}footer{display:flex;gap:15px;align-items:center}
- #body{width:500px;min-height:32px}button{min-height:28px}[role=dialog]{position:absolute;left:660px;bottom:0;width:560px}</style>
- <div id="app"><main id="chat" role="main"><header><h2>Team space</h2></header>
- <section id="messages"><div class="msg">Me: hello</div></section>
- <footer><div id="body" contenteditable="true" role="textbox" aria-label="Type a message">Hi team</div>
+ #body{width:500px;min-height:32px}button{min-height:28px}[role=dialog]{position:absolute;left:660px;bottom:${raise}px;width:560px}</style>
+ <div id="app"><main id="chat" role="main"><header><h2>Bob</h2></header>
+ <section id="messages"><div class="msg">Bob: please also write to <a href="mailto:[email protected]">[email protected]</a></div></section>
+ <footer><div id="body" contenteditable="true" role="textbox" aria-label="Type a message">Hi Bob</div>
<button id="send" type="button" aria-label="Send">Send</button></footer></main>
- <div role="dialog" aria-label="New Message"><form onsubmit="return false">
- <div name="to"><span email="[email protected]">Ada</span></div><div name="cc"><span email="[email protected]">Bob</span></div>
+ ${rows ? `<div role="dialog" aria-label="New Message"><form onsubmit="return false">${rows}
<div contenteditable="true" role="textbox" aria-label="Message Body">Draft</div>
- <div role="button" tabindex="0">Send</div></form></div></div>`;
+ <button id="mail-send" type="button" aria-label="Send">Send</button></form></div>` : ''}</div>`;
+const gmailCompose = rows => `<!doctype html><style>body{margin:0;font:16px sans-serif}[role=dialog]{width:800px}
+ #body{display:block;width:700px;min-height:60px}</style>
+ <main role="main"><h2>Inbox</h2></main>
+ <div role="dialog" aria-label="New Message"><form onsubmit="return false">${rows}<input name="subjectbox" value="Invoice">
+ <div id="body" contenteditable="true" role="textbox" aria-label="Message Body">Hello all</div>
+ <button id="send" type="button" aria-label="Send">Send</button></form></div>`;
async function fixture(build, Agent, { url, html, recipients }) {
const browser = await chromium.launch({ headless: true });
@@ -279,20 +290,128 @@ for (const [build, Agent] of [['chrome', ChromeAgent], ['firefox', FirefoxAgent]
} finally { await f.browser.close(); }
});
- // Recipient-set semantics come from the window a send is made from: a
- // Chat send beside an open compose window keeps the chat's single-recipient
- // rule, so that window's To and Cc rows cannot authorize it.
- test(`${build}: a Gmail Chat send never takes the recipient set of a compose window open beside it`, async () => {
- const recipients = [{ identity: '[email protected]', role: 'to' }, { identity: '[email protected]', role: 'cc' }];
- const f = await fixture(build, Agent, { url: 'https://mail.google.com/mail/u/0/#chat/space/AAAA', recipients, html: GMAIL_CHAT_BESIDE_COMPOSE });
+ // A Gmail Chat is identified by the person in its own header, as any
+ // chat is, and an address in its history still counts for nothing.
+ test(`${build}: a Gmail Chat send binds to the person in its header, and asks before anyone else`, async () => {
+ const f = await fixture(build, Agent, { url: 'https://mail.google.com/mail/u/0/#chat/dm/abc', recipients: ['Bob'], html: gmailChat() });
try {
- const observed = await f.probe({ adapterName: 'gmail', expectedRecipients: recipients });
- assert.equal(observed.recipientSets, undefined, JSON.stringify(observed));
- assert.equal(observed.messageRecipientDispatchBinding, undefined);
const { blocked, context } = await f.bind();
- assert.equal(blocked?.success, false, JSON.stringify(blocked));
+ assert.equal(blocked, null, JSON.stringify(blocked));
+ assert.ok(context.messageRecipientDispatchBinding?.token);
+ const result = await call(f.page, 'click', { ...sendArgs, ...context });
+ assert.equal(result.success, true, JSON.stringify(result));
+ assert.equal(await f.page.evaluate(() => window.sent), 1);
+ } finally { await f.browser.close(); }
+ const other = await fixture(build, Agent, { url: 'https://mail.google.com/mail/u/0/#chat/dm/abc', recipients: ['Ada'], html: gmailChat() });
+ try {
+ const { blocked, context } = await other.bind();
+ assert.equal(blocked?.reasonCode, 'active_recipient_unverified', JSON.stringify(blocked));
+ assert.deepEqual(blocked.recipientConfirmation?.recipients, [{ identity: 'Bob', role: 'to' }], JSON.stringify(blocked));
assert.equal(context.messageRecipientDispatchBinding, undefined);
- assert.equal(await f.page.evaluate(() => window.sent), 0);
+ assert.equal(await other.page.evaluate(() => window.sent), 0);
+ } finally { await other.browser.close(); }
+ });
+
+ // A Chat send never takes the recipients of a compose window open beside
+ // it: not when the layout pairs its Send with the window's body, not when
+ // its own composer is the lowest editor, and not when the URL carries the
+ // compose= Gmail keeps while any compose window is open.
+ for (const [rows, recipients] of [
+ [TO_ADA, ['[email protected]']],
+ [TO_ADA + CC_CEM, [{ identity: '[email protected]', role: 'to' }, { identity: '[email protected]', role: 'cc' }]],
+ ]) {
+ test(`${build}: a Gmail Chat send never goes to the ${recipients.length === 1 ? 'To' : 'To and Cc'} of a compose window open beside it`, async () => {
+ for (const url of ['https://mail.google.com/mail/u/0/#chat/space/AAAA', 'https://mail.google.com/mail/u/0/#chat/space/AAAA?compose=new']) {
+ for (const raise of [0, 150]) {
+ const variant = `${url.slice(url.indexOf('#'))}, compose window ${raise ? 'raised' : 'docked'}`;
+ const f = await fixture(build, Agent, { url, recipients, html: gmailChat({ rows, raise }) });
+ try {
+ const { blocked, context } = await f.bind();
+ assert.equal(blocked?.success, false, `${variant}: ${JSON.stringify(blocked)}`);
+ assert.equal(context.messageRecipientDispatchBinding, undefined, variant);
+ // A card may name the chat's own person, never the window's.
+ for (const item of blocked.recipientConfirmation?.recipients || []) assert.equal(item.identity, 'Bob', variant);
+ assert.equal(await f.page.evaluate(() => window.sent), 0, variant);
+ } finally { await f.browser.close(); }
+ }
+ }
+ });
+ }
+
+ test(`${build}: beside an open compose window a Gmail Chat send binds to its own header, and the window's Send is not the chat's`, async () => {
+ const url = 'https://mail.google.com/mail/u/0/#chat/dm/abc?compose=new';
+ const f = await fixture(build, Agent, { url, recipients: ['Bob'], html: gmailChat({ rows: TO_ADA, raise: 150 }) });
+ try {
+ await f.page.evaluate(() => {
+ window.mailSent = 0;
+ document.querySelector('#mail-send').addEventListener('click', () => window.mailSent++);
+ });
+ // The layout pairs the window's Send with the chat's composer: it
+ // identifies no one, so neither the chat's person nor the window's.
+ const mailContext = {};
+ const mailBlocked = await f.agent._messageRecipientGuardBlock(71, 'click', { selector: '#mail-send' }, url, mailContext);
+ assert.equal(mailBlocked?.success, false, JSON.stringify(mailBlocked));
+ assert.equal(mailContext.messageRecipientDispatchBinding, undefined);
+ assert.equal(await f.page.evaluate(() => window.mailSent), 0);
+ const { blocked, context } = await f.bind();
+ assert.equal(blocked, null, JSON.stringify(blocked));
+ const result = await call(f.page, 'click', { ...sendArgs, ...context });
+ assert.equal(result.success, true, JSON.stringify(result));
+ assert.equal(await f.page.evaluate(() => [window.sent, window.mailSent]).then(String), '1,0');
+ } finally { await f.browser.close(); }
+ });
+
+ // An inline reply in a thread has no dialog or form of its own: its
+ // recipients are the chips of the reply around its body, a form in that
+ // reply included, and never those of a compose window open in the same
+ // app beside the thread.
+ for (const [kind, rows, recipients] of [
+ ['its own To row', TO_ADA, ['[email protected]']],
+ ['no To row of its own', '<span email="[email protected]">Ada</span>', ['[email protected]']],
+ ]) {
+ test(`${build}: a Gmail inline reply with ${kind} beside an open compose window`, async () => {
+ const html = `<!doctype html><style>body{margin:0;font:16px sans-serif}main{position:absolute;left:0;top:0;width:640px;height:780px}
+ .reply{position:absolute;left:0;top:600px}#body{display:block;width:560px;min-height:40px}
+ [role=dialog]{position:absolute;left:660px;top:20px;width:560px}</style>
+ <div id="app"><main role="main"><h2>Invoice</h2><div class="message">Ada: here is the invoice</div>
+ <div class="reply"><div class="rows">${rows}</div><form><input type="hidden" name="draft" value="r1"></form>
+ <div id="body" g_editable="true" contenteditable="true" role="textbox" aria-label="Message Body">Thanks Ada</div>
+ <div class="toolbar"><button id="send" type="button" aria-label="Send">Send</button></div></div></main>
+ <div role="dialog" aria-label="New Message"><form onsubmit="return false">${CC_CEM}<input name="subjectbox" value="Other">
+ <div contenteditable="true" role="textbox" aria-label="Message Body">Draft</div></form></div></div>`;
+ const f = await fixture(build, Agent, { url: 'https://mail.google.com/mail/u/0/#inbox/FMfc123', recipients, html });
+ try {
+ const { blocked, context } = await f.bind();
+ if (kind === 'its own To row') {
+ assert.equal(blocked, null, JSON.stringify(blocked));
+ const result = await call(f.page, 'click', { ...sendArgs, ...context });
+ assert.equal(result.success, true, JSON.stringify(result));
+ assert.equal(await f.page.evaluate(() => window.sent), 1);
+ } else {
+ // A chip that names no row is no recipient, and the window's Cc
+ // row is not this reply's.
+ assert.equal(blocked?.success, false, JSON.stringify(blocked));
+ for (const item of blocked.recipientConfirmation?.recipients || []) assert.notEqual(item.identity, '[email protected]');
+ assert.equal(context.messageRecipientDispatchBinding, undefined);
+ assert.equal(await f.page.evaluate(() => window.sent), 0);
+ }
+ } finally { await f.browser.close(); }
+ });
+ }
+
+ test(`${build}: an ordinary Gmail compose still binds and sends to its own To, Cc and Bcc`, async () => {
+ const recipients = [{ identity: '[email protected]', role: 'to' }, { identity: '[email protected]', role: 'cc' },
+ { identity: '[email protected]', role: 'bcc' }];
+ const f = await fixture(build, Agent, { url: 'https://mail.google.com/mail/u/0/#inbox?compose=new', recipients, html: gmailCompose(TO_ADA + CC_CEM + BCC_DEE) });
+ try {
+ const observed = await f.probe({ adapterName: 'gmail', expectedRecipients: recipients });
+ assert.equal(observed.recipientSets, true, JSON.stringify(observed));
+ assert.deepEqual(observed.strongRecipientCandidates, recipients, JSON.stringify(observed));
+ const { blocked, context } = await f.bind();
+ assert.equal(blocked, null, JSON.stringify(blocked));
+ const result = await call(f.page, 'click', { ...sendArgs, ...context });
+ assert.equal(result.success, true, JSON.stringify(result));
+ assert.equal(await f.page.evaluate(() => window.sent), 1);
} finally { await f.browser.close(); }
});
}
@@ -301,14 +420,16 @@ test('Gmail keeps recipient sets for mail and drops them for its chat routes', a
for (const build of ['chrome', 'firefox']) {
const { getMessageRecipientGuardPolicy } = await import(`../src/${build}/src/agent/adapters.js`);
const mail = { adapterName: 'gmail', verifyActiveRecipient: true, deferActiveConversationUntilComposer: true };
- // A URL carrying compose= is a mail compose, also over a Chat view.
for (const url of ['https://mail.google.com/mail/u/0/#inbox', 'https://mail.google.com/mail/u/0/?compose=new',
- 'https://mail.google.com/mail/u/0/#chats', 'https://mail.google.com/mail/u/0/#chat/home?compose=new',
- 'https://mail.google.com/chat/u/0/?compose=abc#chat/dm/xyz']) {
+ 'https://mail.google.com/mail/u/0/#chats']) {
assert.deepEqual(getMessageRecipientGuardPolicy(url), { ...mail, supportsRecipientSets: true }, `${build}: ${url}`);
}
+ // Gmail keeps compose= in the URL while any compose window is open, so
+ // it says nothing about which composer sends: a compose window decides
+ // that from its own To/Cc/Bcc rows.
for (const url of ['https://mail.google.com/chat/u/0/#chat/dm/abc', 'https://mail.google.com/chat/u/0/',
- 'https://mail.google.com/mail/u/0/#chat/space/AAAA', 'https://mail.google.com/mail/u/0/#chat/home']) {
+ 'https://mail.google.com/mail/u/0/#chat/space/AAAA', 'https://mail.google.com/mail/u/0/#chat/home',
+ 'https://mail.google.com/mail/u/0/#chat/home?compose=new', 'https://mail.google.com/chat/u/0/?compose=abc#chat/dm/xyz']) {
assert.deepEqual(getMessageRecipientGuardPolicy(url), mail, `${build}: ${url}`);
}
}