Skip to content

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

fix(agent): enforce distinct recipient clarification matching and scope

Emre Sokullu9ddeecae36f6
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index a266a6041..2c7660d85 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -43,7 +43,7 @@ import {
workflowControlLabelIsRequested,
workflowRequiredRowsAreProcessed,
} from './adapter-workflow-evidence.js';
-import { answerNamesIdentity, messageTargetMatchesObservedIdentities, normalizeMessageTarget, normalizeRecipientIdentity } from './message-recipient-guard.js';
+import { answerNamesAllObservedRecipients, answerNamesIdentity, messageTargetMatchesObservedIdentities, normalizeMessageTarget, normalizeRecipientIdentity } from './message-recipient-guard.js';
import {
fetchUrl,
executeHttpSkillTool,
@@ -17842,8 +17842,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// Offered to the next clarify only. The model chooses what it asks, so a
// pending authorization must not survive into an unrelated question.
// Staged only when the plan already permits messaging.
- guard.pendingRecipientAuthorization = messagingPermitted
- && observedRecipientCandidates.length > 0;
+ // Associate with an explicit recipient-change clarification when a target
+ // was already authorized, or a recipient clarification when missing.
+ guard.pendingRecipientAuthorization = messagingPermitted && observedRecipientCandidates.length > 0
+ ? (target ? 'recipient_change' : true)
+ : false;
}
return {
@@ -17865,6 +17868,22 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
};
}
+ _isRecipientClarification(context, pendingType = 'message_recipient') {
+ if (!context || typeof context !== 'object') return false;
+ const purpose = String(context.purpose || '').trim();
+ if (pendingType === 'recipient_change') {
+ if (purpose === 'recipient_change') return true;
+ const text = [context.question, context.reason].filter(Boolean).join(' ').toLowerCase();
+ return /(change|switch|different|instead|update|replace).*(recipient|conversation|contact|send to|person|address)/i.test(text)
+ || /(recipient|conversation|contact).*(change|switch|different)/i.test(text)
+ || /(send|deliver).*(to .* instead|to someone else)/i.test(text)
+ || /(send|reply).*(instead of)/i.test(text);
+ }
+ if (purpose === 'message_recipient' || purpose === 'recipient_change') return true;
+ const text = [context.question, context.reason].filter(Boolean).join(' ').toLowerCase();
+ return /(recipient|who (is|to|should|are)|send (the |this )?(message|email|draft) to|message (to|for)|deliver to|email to|draft to|authorize.*conversation)/i.test(text);
+ }
+
/**
* Bind a user's clarify answer to a recipient the content probe observed.
*
@@ -17876,10 +17895,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
* and an answer matching no candidate or only a subset of observed
* candidates authorizes nothing. When multiple recipients are observed on
* the page (e.g. Reply all), the answer must explicitly authorize the full
- * observed recipient set. A recipient answer may only bind under a plan
- * that already permits messaging (requiresSubmission=true and requiresStateChange=true).
+ * observed recipient set with distinct non-overlapping answer spans.
+ * A recipient answer may only bind under a plan that already permits
+ * messaging (requiresSubmission=true and requiresStateChange=true) and must
+ * match the specific clarification purpose or question.
*/
- _bindClarifiedMessageRecipient(tabId, answer, source = 'user') {
+ _bindClarifiedMessageRecipient(tabId, answer, source = 'user', clarifyContext = null) {
const guard = this._planExecutionGuards.get(tabId);
if (!guard) return false;
// Read and clear together. The consent the guard staged belongs to exactly
@@ -17889,22 +17910,28 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// consent from remaining parked for an unrelated later clarify to pick up.
const messagingPermitted = guard.requiresSubmission === true
&& guard.requiresStateChange === true;
- const pending = guard.pendingRecipientAuthorization === true && messagingPermitted;
+ const pending = !!guard.pendingRecipientAuthorization && messagingPermitted;
+ const pendingType = typeof guard.pendingRecipientAuthorization === 'string'
+ ? guard.pendingRecipientAuthorization
+ : (pending ? 'message_recipient' : null);
const observed = Array.isArray(guard.observedRecipientCandidates)
? guard.observedRecipientCandidates
: [];
guard.pendingRecipientAuthorization = false;
guard.observedRecipientCandidates = null;
- if (!pending || observed.length === 0) return false;
+ if (!pending || !pendingType || observed.length === 0) return false;
if (!answer || source === 'timeout' || source === 'auto') return false;
+ if (pendingType === 'recipient_change') {
+ if (!clarifyContext || !this._isRecipientClarification(clarifyContext, 'recipient_change')) {
+ return false;
+ }
+ } else if (clarifyContext && !this._isRecipientClarification(clarifyContext, 'message_recipient')) {
+ return false;
+ }
const normalizedAnswer = normalizeRecipientIdentity(answer);
if (!normalizedAnswer) return false;
- const matched = observed.filter(candidate => answerNamesIdentity(
- normalizedAnswer,
- normalizeRecipientIdentity(candidate?.identity),
- ));
- if (matched.length === 0 || matched.length !== observed.length) return false;
- const target = normalizeMessageTarget({ target_kind: 'named', recipients: matched });
+ if (!answerNamesAllObservedRecipients(normalizedAnswer, observed)) return false;
+ const target = normalizeMessageTarget({ target_kind: 'named', recipients: observed });
if (!target) return false;
guard.messaging = target;
return true;
@@ -26085,7 +26112,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
? args.options.map(s => String(s).slice(0, 200)).filter(Boolean).slice(0, 4)
: [];
const reason = args?.reason ? String(args.reason).slice(0, 300) : null;
- const purpose = args?.purpose === 'research_escalation' ? 'research_escalation' : null;
+ const purpose = args?.purpose === 'research_escalation'
+ ? 'research_escalation'
+ : (args?.purpose === 'recipient_change'
+ ? 'recipient_change'
+ : (args?.purpose === 'message_recipient' ? 'message_recipient' : null));
const isResearchEscalation = purpose === 'research_escalation';
const requireExplicitAnswer = isResearchEscalation || args?.require_explicit_answer === true;
const researchRequest = isResearchEscalation ? normalizeResearchRequest(args?.research_request) : '';
@@ -26187,7 +26218,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (tabPending.size === 0) this._pendingClarifications.delete(tabId);
if (response && response.cancelled) {
- this._bindClarifiedMessageRecipient(tabId, '', 'cancelled');
+ this._bindClarifiedMessageRecipient(tabId, '', 'cancelled', { question, options, reason, purpose });
return { success: false, cancelled: true, reason: response.reason || 'clarify cancelled' };
}
const answer = String(response?.answer || '').trim();
@@ -26201,7 +26232,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// nothing, matching how research escalation treats those sources below.
// Every clarification outcome (human answer, timeout, auto) must consume
// the staged recipient consent so a later unrelated clarify does not inherit it.
- this._bindClarifiedMessageRecipient(tabId, answer, source);
+ this._bindClarifiedMessageRecipient(tabId, answer, source, { question, options, reason, purpose });
const explicitResearchApproval = isResearchEscalation
&& source !== 'timeout'
&& source !== 'auto'
diff --git a/src/chrome/src/agent/message-recipient-guard.js b/src/chrome/src/agent/message-recipient-guard.js
index 66a65ecf7..d72ae26a6 100644
--- a/src/chrome/src/agent/message-recipient-guard.js
+++ b/src/chrome/src/agent/message-recipient-guard.js
@@ -58,6 +58,28 @@ export function recipientMatchesObservedIdentity(recipient, observedIdentity) {
const IDENTITY_WORD_CHAR = /[\p{L}\p{N}]/u;
+/**
+ * Return all start/end spans where normalizedIdentity occurs in normalizedAnswer
+ * at word boundaries, or as an exact full-string match for short identities (< 3 chars).
+ */
+export function findCandidateAnswerSpans(normalizedAnswer, normalizedIdentity) {
+ const answer = normalizeRecipientIdentity(normalizedAnswer);
+ const identity = normalizeRecipientIdentity(normalizedIdentity);
+ if (!identity || !answer) return [];
+ if (identity.length < 3) {
+ return answer === identity ? [{ start: 0, end: answer.length }] : [];
+ }
+ const spans = [];
+ for (let at = answer.indexOf(identity); at >= 0; at = answer.indexOf(identity, at + 1)) {
+ const before = at > 0 ? answer[at - 1] : '';
+ const after = answer[at + identity.length] || '';
+ if (!IDENTITY_WORD_CHAR.test(before) && !IDENTITY_WORD_CHAR.test(after)) {
+ spans.push({ start: at, end: at + identity.length });
+ }
+ }
+ return spans;
+}
+
/**
* Does the user's answer actually name this identity, rather than merely
* containing its letters?
@@ -65,20 +87,56 @@ const IDENTITY_WORD_CHAR = /[\p{L}\p{N}]/u;
* A bare substring test authorizes on accidents: the observed display name
* "Ann" is inside "I cannot decide". Requiring the match to sit against a
* non-alphanumeric neighbour or a string edge keeps an incidental fragment
- * from standing in for the user naming someone. Scripts written without word
- * separators fall back to exact equality, which fails closed rather than
- * guessing where a name ends.
+ * from standing in for the user naming someone. Identities shorter than 3
+ * characters accept exact equality to authorize short names without loose
+ * substring false positives.
*/
export function answerNamesIdentity(normalizedAnswer, normalizedIdentity) {
- const answer = String(normalizedAnswer || '');
- const identity = String(normalizedIdentity || '');
- if (identity.length < 3 || !answer) return false;
- for (let at = answer.indexOf(identity); at >= 0; at = answer.indexOf(identity, at + 1)) {
- const before = at > 0 ? answer[at - 1] : '';
- const after = answer[at + identity.length] || '';
- if (!IDENTITY_WORD_CHAR.test(before) && !IDENTITY_WORD_CHAR.test(after)) return true;
+ return findCandidateAnswerSpans(normalizedAnswer, normalizedIdentity).length > 0;
+}
+
+/**
+ * Verify that each observed recipient identity is matched by a distinct,
+ * non-overlapping span in the user's answer.
+ *
+ * When one observed identity is a boundary-delimited prefix of another
+ * (e.g. "Ann" and "Ann Smith", or "[email protected]" and "[email protected]"),
+ * a single mention must not satisfy both candidates. A distinct span is
+ * required for each observed recipient identity.
+ */
+export function answerNamesAllObservedRecipients(normalizedAnswer, observedCandidates) {
+ const answer = normalizeRecipientIdentity(normalizedAnswer);
+ if (!answer || !Array.isArray(observedCandidates) || observedCandidates.length === 0) {
+ return false;
}
- return false;
+ const uniqueIdentities = [...new Set(
+ observedCandidates
+ .map(c => normalizeRecipientIdentity(typeof c === 'string' ? c : (c?.identity ?? c?.recipient)))
+ .filter(Boolean)
+ )];
+ if (uniqueIdentities.length === 0) return false;
+
+ const candidateSpans = [];
+ for (const identity of uniqueIdentities) {
+ const spans = findCandidateAnswerSpans(answer, identity);
+ if (spans.length === 0) return false;
+ candidateSpans.push(spans);
+ }
+
+ function search(index, usedSpans) {
+ if (index >= candidateSpans.length) return true;
+ for (const span of candidateSpans[index]) {
+ const overlaps = usedSpans.some(used => !(span.end <= used.start || used.end <= span.start));
+ if (!overlaps) {
+ usedSpans.push(span);
+ if (search(index + 1, usedSpans)) return true;
+ usedSpans.pop();
+ }
+ }
+ return false;
+ }
+
+ return search(0, []);
}
export function messageTargetMatchesObservedIdentities(target, candidates) {
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index 4a2bc24be..e5d694e52 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -42,7 +42,7 @@ import {
workflowControlLabelIsRequested,
workflowRequiredRowsAreProcessed,
} from './adapter-workflow-evidence.js';
-import { answerNamesIdentity, messageTargetMatchesObservedIdentities, normalizeMessageTarget, normalizeRecipientIdentity } from './message-recipient-guard.js';
+import { answerNamesAllObservedRecipients, answerNamesIdentity, messageTargetMatchesObservedIdentities, normalizeMessageTarget, normalizeRecipientIdentity } from './message-recipient-guard.js';
import {
fetchUrl,
executeHttpSkillTool,
@@ -15595,8 +15595,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// Offered to the next clarify only. The model chooses what it asks, so a
// pending authorization must not survive into an unrelated question.
// Staged only when the plan already permits messaging.
- guard.pendingRecipientAuthorization = messagingPermitted
- && observedRecipientCandidates.length > 0;
+ // Associate with an explicit recipient-change clarification when a target
+ // was already authorized, or a recipient clarification when missing.
+ guard.pendingRecipientAuthorization = messagingPermitted && observedRecipientCandidates.length > 0
+ ? (target ? 'recipient_change' : true)
+ : false;
}
return {
@@ -15618,6 +15621,22 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
};
}
+ _isRecipientClarification(context, pendingType = 'message_recipient') {
+ if (!context || typeof context !== 'object') return false;
+ const purpose = String(context.purpose || '').trim();
+ if (pendingType === 'recipient_change') {
+ if (purpose === 'recipient_change') return true;
+ const text = [context.question, context.reason].filter(Boolean).join(' ').toLowerCase();
+ return /(change|switch|different|instead|update|replace).*(recipient|conversation|contact|send to|person|address)/i.test(text)
+ || /(recipient|conversation|contact).*(change|switch|different)/i.test(text)
+ || /(send|deliver).*(to .* instead|to someone else)/i.test(text)
+ || /(send|reply).*(instead of)/i.test(text);
+ }
+ if (purpose === 'message_recipient' || purpose === 'recipient_change') return true;
+ const text = [context.question, context.reason].filter(Boolean).join(' ').toLowerCase();
+ return /(recipient|who (is|to|should|are)|send (the |this )?(message|email|draft) to|message (to|for)|deliver to|email to|draft to|authorize.*conversation)/i.test(text);
+ }
+
/**
* Bind a user's clarify answer to a recipient the content probe observed.
*
@@ -15629,10 +15648,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
* and an answer matching no candidate or only a subset of observed
* candidates authorizes nothing. When multiple recipients are observed on
* the page (e.g. Reply all), the answer must explicitly authorize the full
- * observed recipient set. A recipient answer may only bind under a plan
- * that already permits messaging (requiresSubmission=true and requiresStateChange=true).
+ * observed recipient set with distinct non-overlapping answer spans.
+ * A recipient answer may only bind under a plan that already permits
+ * messaging (requiresSubmission=true and requiresStateChange=true) and must
+ * match the specific clarification purpose or question.
*/
- _bindClarifiedMessageRecipient(tabId, answer, source = 'user') {
+ _bindClarifiedMessageRecipient(tabId, answer, source = 'user', clarifyContext = null) {
const guard = this._planExecutionGuards.get(tabId);
if (!guard) return false;
// Read and clear together. The consent the guard staged belongs to exactly
@@ -15642,22 +15663,28 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// consent from remaining parked for an unrelated later clarify to pick up.
const messagingPermitted = guard.requiresSubmission === true
&& guard.requiresStateChange === true;
- const pending = guard.pendingRecipientAuthorization === true && messagingPermitted;
+ const pending = !!guard.pendingRecipientAuthorization && messagingPermitted;
+ const pendingType = typeof guard.pendingRecipientAuthorization === 'string'
+ ? guard.pendingRecipientAuthorization
+ : (pending ? 'message_recipient' : null);
const observed = Array.isArray(guard.observedRecipientCandidates)
? guard.observedRecipientCandidates
: [];
guard.pendingRecipientAuthorization = false;
guard.observedRecipientCandidates = null;
- if (!pending || observed.length === 0) return false;
+ if (!pending || !pendingType || observed.length === 0) return false;
if (!answer || source === 'timeout' || source === 'auto') return false;
+ if (pendingType === 'recipient_change') {
+ if (!clarifyContext || !this._isRecipientClarification(clarifyContext, 'recipient_change')) {
+ return false;
+ }
+ } else if (clarifyContext && !this._isRecipientClarification(clarifyContext, 'message_recipient')) {
+ return false;
+ }
const normalizedAnswer = normalizeRecipientIdentity(answer);
if (!normalizedAnswer) return false;
- const matched = observed.filter(candidate => answerNamesIdentity(
- normalizedAnswer,
- normalizeRecipientIdentity(candidate?.identity),
- ));
- if (matched.length === 0 || matched.length !== observed.length) return false;
- const target = normalizeMessageTarget({ target_kind: 'named', recipients: matched });
+ if (!answerNamesAllObservedRecipients(normalizedAnswer, observed)) return false;
+ const target = normalizeMessageTarget({ target_kind: 'named', recipients: observed });
if (!target) return false;
guard.messaging = target;
return true;
@@ -22849,7 +22876,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
? args.options.map(s => String(s).slice(0, 200)).filter(Boolean).slice(0, 4)
: [];
const reason = args?.reason ? String(args.reason).slice(0, 300) : null;
- const purpose = args?.purpose === 'research_escalation' ? 'research_escalation' : null;
+ const purpose = args?.purpose === 'research_escalation'
+ ? 'research_escalation'
+ : (args?.purpose === 'recipient_change'
+ ? 'recipient_change'
+ : (args?.purpose === 'message_recipient' ? 'message_recipient' : null));
const isResearchEscalation = purpose === 'research_escalation';
const requireExplicitAnswer = isResearchEscalation || args?.require_explicit_answer === true;
const researchRequest = isResearchEscalation ? normalizeResearchRequest(args?.research_request) : '';
@@ -22951,7 +22982,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (tabPending.size === 0) this._pendingClarifications.delete(tabId);
if (response && response.cancelled) {
- this._bindClarifiedMessageRecipient(tabId, '', 'cancelled');
+ this._bindClarifiedMessageRecipient(tabId, '', 'cancelled', { question, options, reason, purpose });
return { success: false, cancelled: true, reason: response.reason || 'clarify cancelled' };
}
const answer = String(response?.answer || '').trim();
@@ -22965,7 +22996,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// nothing, matching how research escalation treats those sources below.
// Every clarification outcome (human answer, timeout, auto) must consume
// the staged recipient consent so a later unrelated clarify does not inherit it.
- this._bindClarifiedMessageRecipient(tabId, answer, source);
+ this._bindClarifiedMessageRecipient(tabId, answer, source, { question, options, reason, purpose });
const explicitResearchApproval = isResearchEscalation
&& source !== 'timeout'
&& source !== 'auto'
diff --git a/src/firefox/src/agent/message-recipient-guard.js b/src/firefox/src/agent/message-recipient-guard.js
index 66a65ecf7..d72ae26a6 100644
--- a/src/firefox/src/agent/message-recipient-guard.js
+++ b/src/firefox/src/agent/message-recipient-guard.js
@@ -58,6 +58,28 @@ export function recipientMatchesObservedIdentity(recipient, observedIdentity) {
const IDENTITY_WORD_CHAR = /[\p{L}\p{N}]/u;
+/**
+ * Return all start/end spans where normalizedIdentity occurs in normalizedAnswer
+ * at word boundaries, or as an exact full-string match for short identities (< 3 chars).
+ */
+export function findCandidateAnswerSpans(normalizedAnswer, normalizedIdentity) {
+ const answer = normalizeRecipientIdentity(normalizedAnswer);
+ const identity = normalizeRecipientIdentity(normalizedIdentity);
+ if (!identity || !answer) return [];
+ if (identity.length < 3) {
+ return answer === identity ? [{ start: 0, end: answer.length }] : [];
+ }
+ const spans = [];
+ for (let at = answer.indexOf(identity); at >= 0; at = answer.indexOf(identity, at + 1)) {
+ const before = at > 0 ? answer[at - 1] : '';
+ const after = answer[at + identity.length] || '';
+ if (!IDENTITY_WORD_CHAR.test(before) && !IDENTITY_WORD_CHAR.test(after)) {
+ spans.push({ start: at, end: at + identity.length });
+ }
+ }
+ return spans;
+}
+
/**
* Does the user's answer actually name this identity, rather than merely
* containing its letters?
@@ -65,20 +87,56 @@ const IDENTITY_WORD_CHAR = /[\p{L}\p{N}]/u;
* A bare substring test authorizes on accidents: the observed display name
* "Ann" is inside "I cannot decide". Requiring the match to sit against a
* non-alphanumeric neighbour or a string edge keeps an incidental fragment
- * from standing in for the user naming someone. Scripts written without word
- * separators fall back to exact equality, which fails closed rather than
- * guessing where a name ends.
+ * from standing in for the user naming someone. Identities shorter than 3
+ * characters accept exact equality to authorize short names without loose
+ * substring false positives.
*/
export function answerNamesIdentity(normalizedAnswer, normalizedIdentity) {
- const answer = String(normalizedAnswer || '');
- const identity = String(normalizedIdentity || '');
- if (identity.length < 3 || !answer) return false;
- for (let at = answer.indexOf(identity); at >= 0; at = answer.indexOf(identity, at + 1)) {
- const before = at > 0 ? answer[at - 1] : '';
- const after = answer[at + identity.length] || '';
- if (!IDENTITY_WORD_CHAR.test(before) && !IDENTITY_WORD_CHAR.test(after)) return true;
+ return findCandidateAnswerSpans(normalizedAnswer, normalizedIdentity).length > 0;
+}
+
+/**
+ * Verify that each observed recipient identity is matched by a distinct,
+ * non-overlapping span in the user's answer.
+ *
+ * When one observed identity is a boundary-delimited prefix of another
+ * (e.g. "Ann" and "Ann Smith", or "[email protected]" and "[email protected]"),
+ * a single mention must not satisfy both candidates. A distinct span is
+ * required for each observed recipient identity.
+ */
+export function answerNamesAllObservedRecipients(normalizedAnswer, observedCandidates) {
+ const answer = normalizeRecipientIdentity(normalizedAnswer);
+ if (!answer || !Array.isArray(observedCandidates) || observedCandidates.length === 0) {
+ return false;
}
- return false;
+ const uniqueIdentities = [...new Set(
+ observedCandidates
+ .map(c => normalizeRecipientIdentity(typeof c === 'string' ? c : (c?.identity ?? c?.recipient)))
+ .filter(Boolean)
+ )];
+ if (uniqueIdentities.length === 0) return false;
+
+ const candidateSpans = [];
+ for (const identity of uniqueIdentities) {
+ const spans = findCandidateAnswerSpans(answer, identity);
+ if (spans.length === 0) return false;
+ candidateSpans.push(spans);
+ }
+
+ function search(index, usedSpans) {
+ if (index >= candidateSpans.length) return true;
+ for (const span of candidateSpans[index]) {
+ const overlaps = usedSpans.some(used => !(span.end <= used.start || used.end <= span.start));
+ if (!overlaps) {
+ usedSpans.push(span);
+ if (search(index + 1, usedSpans)) return true;
+ usedSpans.pop();
+ }
+ }
+ return false;
+ }
+
+ return search(0, []);
}
export function messageTargetMatchesObservedIdentities(target, candidates) {
diff --git a/test/run.js b/test/run.js
index 00f38dfd9..132f2e557 100644
--- a/test/run.js
+++ b/test/run.js
@@ -4642,6 +4642,26 @@ test('direct-message recipient guard uses structured intent and exact active ide
assert.equal(helper.recipientMatchesObservedIdentity('Team', 'Team-Sales'), false);
assert.equal(helper.recipientMatchesObservedIdentity('Alice', 'Search results for Alice'), false);
assert.equal(helper.recipientMatchesObservedIdentity('Alice', 'Malice'), false);
+ assert.equal(helper.answerNamesIdentity('Li', 'Li'), true);
+ assert.equal(helper.answerNamesIdentity('Lisa', 'Li'), false);
+ assert.equal(helper.answerNamesIdentity('王', '王'), true);
+ assert.equal(helper.answerNamesIdentity('王小明', '王'), false);
+ assert.equal(helper.answerNamesAllObservedRecipients(
+ 'Send to Ann Smith',
+ [{ identity: 'Ann' }, { identity: 'Ann Smith' }],
+ ), false, 'a single mention must not satisfy both a prefix candidate and full name');
+ assert.equal(helper.answerNamesAllObservedRecipients(
+ 'Send to Ann and Ann Smith',
+ [{ identity: 'Ann' }, { identity: 'Ann Smith' }],
+ ), true, 'distinct mentions for both candidates must succeed');
+ assert.equal(helper.answerNamesAllObservedRecipients(
+ [{ identity: '[email protected]' }, { identity: '[email protected]' }],
+ ), false, 'a single mention must not satisfy both .co and .co.uk');
+ assert.equal(helper.answerNamesAllObservedRecipients(
+ [{ identity: '[email protected]' }, { identity: '[email protected]' }],
+ ), true, 'distinct mentions for both domain variants must succeed');
assert.equal(helper.messageTargetMatchesObservedIdentities(
{ target_kind: 'named', recipients: ['迷你世界皓宸'] },
['迷你世界皓宸'],
@@ -5167,6 +5187,100 @@ test('direct-message recipient guard uses structured intent and exact active ide
true,
`${label}: a short identity the user actually named was rejected`,
);
+
+ // Short identities (< 3 chars) require exact full-string match to avoid substring false positives.
+ agent._planExecutionGuards.set(tabId, clarifyGuardState([{ identity: 'Li', role: 'to' }]));
+ assert.equal(
+ agent._bindClarifiedMessageRecipient(tabId, 'Lisa'),
+ false,
+ `${label}: a prefix matching a short identity authorized the recipient`,
+ );
+ agent._planExecutionGuards.set(tabId, clarifyGuardState([{ identity: 'Li', role: 'to' }]));
+ assert.equal(
+ agent._bindClarifiedMessageRecipient(tabId, 'Li'),
+ true,
+ `${label}: an exact match for a short identity was rejected`,
+ );
+
+ // Multi-recipient prefix collision resolution: non-overlapping distinct spans are required.
+ agent._planExecutionGuards.set(tabId, clarifyGuardState([
+ { identity: 'Ann', role: 'to' },
+ { identity: 'Ann Smith', role: 'to' },
+ ]));
+ assert.equal(
+ agent._bindClarifiedMessageRecipient(tabId, 'Send to Ann Smith'),
+ false,
+ `${label}: a single mention satisfied both prefix candidate and full name in agent binding`,
+ );
+ agent._planExecutionGuards.set(tabId, clarifyGuardState([
+ { identity: 'Ann', role: 'to' },
+ { identity: 'Ann Smith', role: 'to' },
+ ]));
+ assert.equal(
+ agent._bindClarifiedMessageRecipient(tabId, 'Send to Ann and Ann Smith'),
+ true,
+ `${label}: distinct mentions for prefix and full name were rejected`,
+ );
+
+ // Clarification context validation: unrelated clarify question must not authorize recipient,
+ // and must consume the staged consent.
+ agent._planExecutionGuards.set(tabId, clarifyGuardState([{ identity: '[email protected]', role: 'to' }]));
+ assert.equal(
+ agent._bindClarifiedMessageRecipient(tabId, '[email protected]', 'user', {
+ question: 'Should I book the flight to New York?',
+ }),
+ false,
+ `${label}: unrelated clarify question authorized a send target`,
+ );
+ assert.equal(agent._planExecutionGuards.get(tabId)?.pendingRecipientAuthorization, false,
+ `${label}: unrelated clarify left pendingRecipientAuthorization true`);
+ assert.equal(agent._planExecutionGuards.get(tabId)?.observedRecipientCandidates, null,
+ `${label}: unrelated clarify left observedRecipientCandidates intact`);
+
+ // Valid message_recipient clarification context authorizes candidate.
+ agent._planExecutionGuards.set(tabId, clarifyGuardState([{ identity: '[email protected]', role: 'to' }]));
+ assert.equal(
+ agent._bindClarifiedMessageRecipient(tabId, '[email protected]', 'user', {
+ question: 'Who should I send the message to?',
+ purpose: 'message_recipient',
+ }),
+ true,
+ `${label}: valid recipient clarification context was rejected`,
+ );
+
+ // Recipient-change clarification check: when a target was already set, an explicit
+ // recipient_change context is required.
+ const recipientChangeGuardState = (candidates) => ({
+ messaging: { target_kind: 'named', recipients: [{ identity: '[email protected]', role: 'to' }] },
+ requiresSubmission: true,
+ requiresStateChange: true,
+ pendingRecipientAuthorization: 'recipient_change',
+ observedRecipientCandidates: candidates,
+ });
+
+ agent._planExecutionGuards.set(tabId, recipientChangeGuardState([{ identity: '[email protected]', role: 'to' }]));
+ assert.equal(
+ agent._bindClarifiedMessageRecipient(tabId, '[email protected]', 'user', {
+ question: 'Who should I send the message to?',
+ purpose: 'message_recipient',
+ }),
+ false,
+ `${label}: standard recipient clarification authorized a recipient change`,
+ );
+
+ agent._planExecutionGuards.set(tabId, recipientChangeGuardState([{ identity: '[email protected]', role: 'to' }]));
+ assert.equal(
+ agent._bindClarifiedMessageRecipient(tabId, '[email protected]', 'user', {
+ question: 'Do you want to switch recipient to Alice instead?',
+ purpose: 'recipient_change',
+ }),
+ true,
+ `${label}: explicit recipient change clarification was rejected`,
+ );
+ assert.deepEqual(agent._planExecutionGuards.get(tabId)?.messaging, {
+ target_kind: 'named',
+ recipients: [{ identity: '[email protected]', role: 'to' }],
+ }, `${label}: recipient change did not update target`);
}
});