Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
fix: verify Discord sends without name identity
Emre Sokulluef5bc3c95802
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex 999b2e1c6..a2cf03e85 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -23022,6 +23022,18 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout ddispatchedSession = { ...pending, pendingOutbound: null };this.chatSessions.set(tabId, dispatchedSession);this._persist(tabId);+ } else if (dispatch?.noDispatch !== true+ && (dispatch?.dispatched === true || dispatch?.success === true)+ && dispatchedSession.pendingOutbound) {+ dispatchedSession = {+ ...dispatchedSession,+ pendingOutbound: {+ ...dispatchedSession.pendingOutbound,+ dispatchedAt: new Date().toISOString(),+ },+ };+ this.chatSessions.set(tabId, dispatchedSession);+ try { await this._persistNow(tabId); } catch {}}const after = await this._readChatObservation(tabId);@@ -23057,15 +23069,16 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dmessage.direction === 'outgoing'&& message.text === decision.text&& !previouslySeenIds.has(message.id)- )) && verifiedState.session.pendingOutbound === null;+ )) || verifiedState.pendingDeliveryVerified === true;+ const deliveryVerified = outgoingVerified && verifiedState.session.pendingOutbound === null;return {...this._chatObservationResult(after, verifiedState),- success: outgoingVerified,- sent: outgoingVerified,+ success: deliveryVerified,+ sent: deliveryVerified,dispatched: dispatch?.dispatched === true || dispatch?.success === true,- deliveryVerified: outgoingVerified,- verificationRequired: !outgoingVerified,- ...(outgoingVerified ? {} : {+ deliveryVerified,+ verificationRequired: !deliveryVerified,+ ...(deliveryVerified ? {} : {outcomeUnknown: dispatch?.dispatched !== false && dispatch?.noDispatch !== true,error: 'The composer action completed without a new matching outgoing bubble. Do not retry until chat_observe confirms the result.',}),diff --git a/src/chrome/src/agent/chat-workflow.js b/src/chrome/src/agent/chat-workflow.jsindex 74476fbdd..94100618c 100644--- a/src/chrome/src/agent/chat-workflow.js+++ b/src/chrome/src/agent/chat-workflow.js@@ -244,6 +244,9 @@ export function normalizeChatSession(value, now = Date.now()) {? { replyAnchor: bounded(source.pendingOutbound.replyAnchor, MAX_ID) }: {}),attemptedAt: bounded(source.pendingOutbound.attemptedAt, 80),+ ...(bounded(source.pendingOutbound.dispatchedAt, 80)+ ? { dispatchedAt: bounded(source.pendingOutbound.dispatchedAt, 80) }+ : {}),}: null;return {@@ -330,8 +333,10 @@ export function advanceChatSession(value, rawSnapshot, now = Date.now()) {const newMessages = snapshot.messages.filter(message => !known.has(message.id));const newIncoming = newMessages.filter(message => message.direction === 'incoming');const newOutgoing = newMessages.filter(message => message.direction === 'outgoing');+ const pendingDiscordDelivery = discordPendingDeliveryMatch(session.pendingOutbound, snapshot, newMessages);const outgoingKeys = new Set(session.sentMessageKeys);for (const key of outgoingMessageKeys(snapshot)) outgoingKeys.add(key);+ if (pendingDiscordDelivery && session.pendingOutbound) outgoingKeys.add(session.pendingOutbound.key);if (snapshot.userInput?.required) {events.push({ type: 'user_input_required', ...snapshot.userInput });@@ -353,6 +358,12 @@ export function advanceChatSession(value, rawSnapshot, now = Date.now()) {events.push({ type: 'counterparty_replied', messages: newIncoming.slice(-MAX_NEW_MESSAGES).map(message => message.id) });} else if (newOutgoing.length) {events.push({ type: 'outgoing_verified', messages: newOutgoing.slice(-MAX_NEW_MESSAGES).map(message => message.id) });+ } else if (pendingDiscordDelivery) {+ events.push({+ type: 'outgoing_verified',+ messages: [pendingDiscordDelivery.id],+ evidence: 'discord_pending_delivery',+ });} else if (snapshot.agentConnected === true && session.state === 'waiting_for_transfer') {events.push({ type: 'agent_connected' });} else if (events.length === 0) {@@ -370,6 +381,7 @@ export function advanceChatSession(value, rawSnapshot, now = Date.now()) {const matchedPending = session.pendingOutbound&& (visibleOutgoingKeys.has(session.pendingOutbound.key)|| newOutgoing.some(message => canonicalChatText(message.text) === canonicalChatText(session.pendingOutbound.text))+ || !!pendingDiscordDelivery|| (!session.pendingOutbound.replyAnchor&& session.pendingOutbound.key === legacyMessageKey(snapshot.threadKey, session.pendingOutbound.text)));const clearUserInput = events.some(event => event.type === 'user_input_cleared');@@ -405,6 +417,7 @@ export function advanceChatSession(value, rawSnapshot, now = Date.now()) {return {session,snapshot,+ pendingDeliveryVerified: !!pendingDiscordDelivery,events,newMessages: newMessages.slice(-MAX_NEW_MESSAGES),newMessagesTruncated: newMessages.length > MAX_NEW_MESSAGES,@@ -485,6 +498,29 @@ export function markChatSendPending(value, decision, now = Date.now()) {};}+function discordPendingDeliveryMatch(pending, snapshot, newMessages) {+ if (!pending || !snapshot.threadKey.startsWith('dom:discord:')+ || pending.threadKey !== snapshot.threadKey+ || snapshot.composer.available !== true || snapshot.composer.empty !== true+ || !pending.dispatchedAt) return null;+ const dispatchedAt = Date.parse(pending.dispatchedAt);+ const observedAt = Date.parse(snapshot.observedAt);+ if (!Number.isFinite(dispatchedAt) || !Number.isFinite(observedAt)+ || observedAt < dispatchedAt - 5_000 || observedAt - dispatchedAt > 120_000) return null;+ const matchingMessages = newMessages.filter(message => (+ canonicalChatText(message.text) === canonicalChatText(pending.text)+ ));+ // Discord default avatars and server nicknames do not identify an author.+ // Correlate delivery only after a persisted successful dispatch, with one+ // fresh exact-text bubble and an empty composer; leave its direction unchanged.+ if (matchingMessages.length !== 1 || matchingMessages[0].direction !== 'unknown') return null;+ const [candidate] = matchingMessages;+ const messageAt = Date.parse(candidate.timestamp || '');+ if (!Number.isFinite(messageAt)+ || messageAt < dispatchedAt - 5_000 || messageAt > observedAt + 5_000) return null;+ return candidate;+}+export function serializeChatSession(value, now = Date.now()) {return normalizeChatSession(value, now);}diff --git a/src/chrome/src/content/chat-observation.js b/src/chrome/src/content/chat-observation.jsindex cd1127bbc..e584bf22e 100644--- a/src/chrome/src/content/chat-observation.js+++ b/src/chrome/src/content/chat-observation.js@@ -267,6 +267,14 @@} catch { return ''; }};+ const discordDefaultAvatar = (node) => {+ try {+ const url = new URL(attribute(node, 'src'), window.location.href);+ return (url.hostname === 'cdn.discordapp.com' && /^\/embed\/avatars\/\d+\.png$/.test(url.pathname))+ || (url.origin === window.location.origin && /^\/assets\/embed\/avatars\/\d+\.png$/.test(url.pathname));+ } catch { return false; }+ };+const discordMessageText = (content) => {const read = (node) => {if (node?.nodeType === 3) return node.nodeValue || '';@@ -324,10 +332,9 @@const collectDiscordMessages = (channel) => {const account = query(document, '[class*="accountPopoutButtonWrapper"]')[0]?.parentElement;- const ownAvatarId = discordAvatarUserId(query(account, 'img[src*="/avatars/"]')[0]);- const ownNames = new Set(query(account, '[class*="panelTitle"],[class*="hovered"]')- .map(node => canonicalText(node.textContent))- .filter(Boolean));+ const ownAvatar = query(account, 'img[src*="/avatars/"]')[0];+ const ownAvatarId = discordAvatarUserId(ownAvatar);+ const ownUsesDefaultAvatar = discordDefaultAvatar(ownAvatar);const rows = query(channel.transcript, '[role="article"][data-list-item-id]');const messages = [];let previousAuthor = '';@@ -354,7 +361,7 @@const avatarId = discordAvatarUserId(avatar);let direction = 'unknown';if (ownAvatarId && avatarId) direction = ownAvatarId === avatarId ? 'outgoing' : 'incoming';- else if (author && ownNames.size) direction = ownNames.has(canonicalText(author)) ? 'outgoing' : 'incoming';+ else if (ownUsesDefaultAvatar && avatarId) direction = 'incoming';else if (!username) direction = previousDirection;previousAuthor = author;previousDirection = direction;diff --git a/src/chrome/src/content/content.js b/src/chrome/src/content/content.jsindex 68ad2eddf..7d7862acd 100644--- a/src/chrome/src/content/content.js+++ b/src/chrome/src/content/content.js@@ -5920,14 +5920,14 @@|| _composedClosestElement(control, 'form')) return false;const menu = _composedClosestElement(control, '[role="menu"]');if (menu) {- const menuActions = {- 'guild-header-popout-settings': 'Server Settings',- 'guild-header-popout-create-channel': 'Create Channel',- 'guild-header-popout-create-category': 'Create Category',- };+ const menuActionIds = new Set([+ 'guild-header-popout-settings',+ 'guild-header-popout-create-channel',+ 'guild-header-popout-create-category',+ ]);return menu.id === 'guild-header-popout'&& control.getAttribute('role') === 'menuitem'- && menuActions[control.id] === label;+ && menuActionIds.has(control.id);}const nav = _composedClosestElement(control, 'nav,[role="navigation"]');if (!nav || !/\(server\)$/.test(compact(nav.getAttribute('aria-label')))) return false;diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex 7a2a3b067..2006f4f47 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -20765,6 +20765,18 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout ddispatchedSession = { ...pending, pendingOutbound: null };this.chatSessions.set(tabId, dispatchedSession);this._persist(tabId);+ } else if (dispatch?.noDispatch !== true+ && (dispatch?.dispatched === true || dispatch?.success === true)+ && dispatchedSession.pendingOutbound) {+ dispatchedSession = {+ ...dispatchedSession,+ pendingOutbound: {+ ...dispatchedSession.pendingOutbound,+ dispatchedAt: new Date().toISOString(),+ },+ };+ this.chatSessions.set(tabId, dispatchedSession);+ try { await this._persistNow(tabId); } catch {}}const after = await this._readChatObservation(tabId);@@ -20800,15 +20812,16 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dmessage.direction === 'outgoing'&& message.text === decision.text&& !previouslySeenIds.has(message.id)- )) && verifiedState.session.pendingOutbound === null;+ )) || verifiedState.pendingDeliveryVerified === true;+ const deliveryVerified = outgoingVerified && verifiedState.session.pendingOutbound === null;return {...this._chatObservationResult(after, verifiedState),- success: outgoingVerified,- sent: outgoingVerified,+ success: deliveryVerified,+ sent: deliveryVerified,dispatched: dispatch?.dispatched === true || dispatch?.success === true,- deliveryVerified: outgoingVerified,- verificationRequired: !outgoingVerified,- ...(outgoingVerified ? {} : {+ deliveryVerified,+ verificationRequired: !deliveryVerified,+ ...(deliveryVerified ? {} : {outcomeUnknown: dispatch?.dispatched !== false && dispatch?.noDispatch !== true,error: 'The composer action completed without a new matching outgoing bubble. Do not retry until chat_observe confirms the result.',}),diff --git a/src/firefox/src/agent/chat-workflow.js b/src/firefox/src/agent/chat-workflow.jsindex 74476fbdd..94100618c 100644--- a/src/firefox/src/agent/chat-workflow.js+++ b/src/firefox/src/agent/chat-workflow.js@@ -244,6 +244,9 @@ export function normalizeChatSession(value, now = Date.now()) {? { replyAnchor: bounded(source.pendingOutbound.replyAnchor, MAX_ID) }: {}),attemptedAt: bounded(source.pendingOutbound.attemptedAt, 80),+ ...(bounded(source.pendingOutbound.dispatchedAt, 80)+ ? { dispatchedAt: bounded(source.pendingOutbound.dispatchedAt, 80) }+ : {}),}: null;return {@@ -330,8 +333,10 @@ export function advanceChatSession(value, rawSnapshot, now = Date.now()) {const newMessages = snapshot.messages.filter(message => !known.has(message.id));const newIncoming = newMessages.filter(message => message.direction === 'incoming');const newOutgoing = newMessages.filter(message => message.direction === 'outgoing');+ const pendingDiscordDelivery = discordPendingDeliveryMatch(session.pendingOutbound, snapshot, newMessages);const outgoingKeys = new Set(session.sentMessageKeys);for (const key of outgoingMessageKeys(snapshot)) outgoingKeys.add(key);+ if (pendingDiscordDelivery && session.pendingOutbound) outgoingKeys.add(session.pendingOutbound.key);if (snapshot.userInput?.required) {events.push({ type: 'user_input_required', ...snapshot.userInput });@@ -353,6 +358,12 @@ export function advanceChatSession(value, rawSnapshot, now = Date.now()) {events.push({ type: 'counterparty_replied', messages: newIncoming.slice(-MAX_NEW_MESSAGES).map(message => message.id) });} else if (newOutgoing.length) {events.push({ type: 'outgoing_verified', messages: newOutgoing.slice(-MAX_NEW_MESSAGES).map(message => message.id) });+ } else if (pendingDiscordDelivery) {+ events.push({+ type: 'outgoing_verified',+ messages: [pendingDiscordDelivery.id],+ evidence: 'discord_pending_delivery',+ });} else if (snapshot.agentConnected === true && session.state === 'waiting_for_transfer') {events.push({ type: 'agent_connected' });} else if (events.length === 0) {@@ -370,6 +381,7 @@ export function advanceChatSession(value, rawSnapshot, now = Date.now()) {const matchedPending = session.pendingOutbound&& (visibleOutgoingKeys.has(session.pendingOutbound.key)|| newOutgoing.some(message => canonicalChatText(message.text) === canonicalChatText(session.pendingOutbound.text))+ || !!pendingDiscordDelivery|| (!session.pendingOutbound.replyAnchor&& session.pendingOutbound.key === legacyMessageKey(snapshot.threadKey, session.pendingOutbound.text)));const clearUserInput = events.some(event => event.type === 'user_input_cleared');@@ -405,6 +417,7 @@ export function advanceChatSession(value, rawSnapshot, now = Date.now()) {return {session,snapshot,+ pendingDeliveryVerified: !!pendingDiscordDelivery,events,newMessages: newMessages.slice(-MAX_NEW_MESSAGES),newMessagesTruncated: newMessages.length > MAX_NEW_MESSAGES,@@ -485,6 +498,29 @@ export function markChatSendPending(value, decision, now = Date.now()) {};}+function discordPendingDeliveryMatch(pending, snapshot, newMessages) {+ if (!pending || !snapshot.threadKey.startsWith('dom:discord:')+ || pending.threadKey !== snapshot.threadKey+ || snapshot.composer.available !== true || snapshot.composer.empty !== true+ || !pending.dispatchedAt) return null;+ const dispatchedAt = Date.parse(pending.dispatchedAt);+ const observedAt = Date.parse(snapshot.observedAt);+ if (!Number.isFinite(dispatchedAt) || !Number.isFinite(observedAt)+ || observedAt < dispatchedAt - 5_000 || observedAt - dispatchedAt > 120_000) return null;+ const matchingMessages = newMessages.filter(message => (+ canonicalChatText(message.text) === canonicalChatText(pending.text)+ ));+ // Discord default avatars and server nicknames do not identify an author.+ // Correlate delivery only after a persisted successful dispatch, with one+ // fresh exact-text bubble and an empty composer; leave its direction unchanged.+ if (matchingMessages.length !== 1 || matchingMessages[0].direction !== 'unknown') return null;+ const [candidate] = matchingMessages;+ const messageAt = Date.parse(candidate.timestamp || '');+ if (!Number.isFinite(messageAt)+ || messageAt < dispatchedAt - 5_000 || messageAt > observedAt + 5_000) return null;+ return candidate;+}+export function serializeChatSession(value, now = Date.now()) {return normalizeChatSession(value, now);}diff --git a/src/firefox/src/content/chat-observation.js b/src/firefox/src/content/chat-observation.jsindex cd1127bbc..e584bf22e 100644--- a/src/firefox/src/content/chat-observation.js+++ b/src/firefox/src/content/chat-observation.js@@ -267,6 +267,14 @@} catch { return ''; }};+ const discordDefaultAvatar = (node) => {+ try {+ const url = new URL(attribute(node, 'src'), window.location.href);+ return (url.hostname === 'cdn.discordapp.com' && /^\/embed\/avatars\/\d+\.png$/.test(url.pathname))+ || (url.origin === window.location.origin && /^\/assets\/embed\/avatars\/\d+\.png$/.test(url.pathname));+ } catch { return false; }+ };+const discordMessageText = (content) => {const read = (node) => {if (node?.nodeType === 3) return node.nodeValue || '';@@ -324,10 +332,9 @@const collectDiscordMessages = (channel) => {const account = query(document, '[class*="accountPopoutButtonWrapper"]')[0]?.parentElement;- const ownAvatarId = discordAvatarUserId(query(account, 'img[src*="/avatars/"]')[0]);- const ownNames = new Set(query(account, '[class*="panelTitle"],[class*="hovered"]')- .map(node => canonicalText(node.textContent))- .filter(Boolean));+ const ownAvatar = query(account, 'img[src*="/avatars/"]')[0];+ const ownAvatarId = discordAvatarUserId(ownAvatar);+ const ownUsesDefaultAvatar = discordDefaultAvatar(ownAvatar);const rows = query(channel.transcript, '[role="article"][data-list-item-id]');const messages = [];let previousAuthor = '';@@ -354,7 +361,7 @@const avatarId = discordAvatarUserId(avatar);let direction = 'unknown';if (ownAvatarId && avatarId) direction = ownAvatarId === avatarId ? 'outgoing' : 'incoming';- else if (author && ownNames.size) direction = ownNames.has(canonicalText(author)) ? 'outgoing' : 'incoming';+ else if (ownUsesDefaultAvatar && avatarId) direction = 'incoming';else if (!username) direction = previousDirection;previousAuthor = author;previousDirection = direction;diff --git a/src/firefox/src/content/content.js b/src/firefox/src/content/content.jsindex cd731f603..960b331ee 100644--- a/src/firefox/src/content/content.js+++ b/src/firefox/src/content/content.js@@ -4998,14 +4998,14 @@|| _composedClosestElement(control, 'form')) return false;const menu = _composedClosestElement(control, '[role="menu"]');if (menu) {- const menuActions = {- 'guild-header-popout-settings': 'Server Settings',- 'guild-header-popout-create-channel': 'Create Channel',- 'guild-header-popout-create-category': 'Create Category',- };+ const menuActionIds = new Set([+ 'guild-header-popout-settings',+ 'guild-header-popout-create-channel',+ 'guild-header-popout-create-category',+ ]);return menu.id === 'guild-header-popout'&& control.getAttribute('role') === 'menuitem'- && menuActions[control.id] === label;+ && menuActionIds.has(control.id);}const nav = _composedClosestElement(control, 'nav,[role="navigation"]');if (!nav || !/\(server\)$/.test(compact(nav.getAttribute('aria-label')))) return false;diff --git a/test/discord-guard.mjs b/test/discord-guard.mjsindex 7d985a149..d1f434d24 100644--- a/test/discord-guard.mjs+++ b/test/discord-guard.mjs@@ -101,6 +101,14 @@ for (const [kind, engine, AgentClass, policy] of [try {for(const id of ['settings','create-channel','create-category']) assert.equal(await guard('click',{selector:`#guild-header-popout-${id}`}),null);assert.equal((await guard('click',{selector:'#unknown'}))?.noDispatch,true);+ await page.locator('#guild-header-popout-settings').evaluate(el=>el.textContent='Paramètres du serveur');+ await page.locator('#guild-header-popout-create-channel').evaluate(el=>el.textContent='Kanal erstellen');+ await page.locator('#guild-header-popout-create-category').evaluate(el=>el.textContent='Kategori oluştur');+ for(const id of ['settings','create-channel','create-category']) {+ const selector=`#guild-header-popout-${id}`;+ assert.equal((await probe('click',{selector})).nonMessagingTarget,true,`${id} accepts translated labels by structural ID`);+ assert.equal(await guard('click',{selector}),null);+ }await page.locator('#guild-header-popout-settings').evaluate(el=>el.textContent='Send invitation');assert.notEqual((await probe('click',{selector:'#guild-header-popout-settings'})).nonMessagingTarget,true);} finally {await page.close();}@@ -206,30 +214,41 @@ for (const [kind, engine, AgentClass, policy] of [await page.locator('#profile-avatar').evaluate(el=>el.setAttribute('src','/assets/embed/avatars/3.png'));await page.locator('#message .contents img').evaluate(el=>el.setAttribute('src','/assets/embed/avatars/3.png'));const defaultAvatars=await observe();- assert.equal(defaultAvatars.messages[0].direction,'incoming','a shared Discord default avatar does not make a different author outgoing');+ assert.equal(defaultAvatars.messages[0].direction,'unknown','shared Discord default avatars do not identify message authors');let advanced=advanceChatSession(createChatSession({threadKey:result.threadKey}),defaultAvatars);await page.locator('#wave').evaluate(el=>el.textContent='Changed hover action');const afterHover=await observe();- assert.deepEqual(afterHover.messages,result.messages,'message actions do not alter observed content');+ assert.deepEqual(afterHover.messages.map(item=>item.text),result.messages.map(item=>item.text),'message actions do not alter observed content');+ assert.equal(afterHover.messages[0].direction,'unknown','default-avatar direction stays unresolved after hover');advanced=advanceChatSession(advanced.session,afterHover);assert.deepEqual(advanced.newMessages,[],'hover does not create a new message');+ const attemptedAt=new Date(Date.now()-1000).toISOString();await page.locator('[data-list-id=chat-messages]').evaluate(el=>el.insertAdjacentHTML('beforeend',`<li><div role="article" data-list-item-id="chat-messages___chat-messages-456-1002"><div class="contents">- <img src="/assets/embed/avatars/3.png"><h3><span id="message-username-1002"><span data-text="WebBrain">WebBrain</span></span><time id="message-timestamp-1002" datetime="2026-09-29T01:01:00.000Z"></time></h3>+ <img src="/assets/embed/avatars/3.png"><h3><span id="message-username-1002"><span data-text="WebBrain">WebBrain</span></span><time id="message-timestamp-1002" datetime="${new Date().toISOString()}"></time></h3><div id="message-content-1002">My answer</div></div></div></li><li><div role="article" data-list-item-id="chat-messages___chat-messages-999-1003"><div id="message-content-1003">Wrong channel</div></div></li><li><div role="article" class="isSystemMessage_fixture" data-list-item-id="chat-messages___chat-messages-456-1004"><div id="message-content-1004">A member joined</div></div></li>`));+ const afterDraft=await observe();+ const pending=markChatSendPending(advanced.session,{+ ok:true,messageKey:'test-pending',threadKey:result.threadKey,text:'My answer',attemptedAt,+ },Date.parse(attemptedAt));+ const dispatchedPending={...pending,pendingOutbound:{...pending.pendingOutbound,dispatchedAt:attemptedAt}};+ const blockedByDraft=advanceChatSession(dispatchedPending,afterDraft);+ assert.equal(blockedByDraft.pendingDeliveryVerified,false,'an uncleared composer draft is not delivery evidence');+ assert.ok(blockedByDraft.session.pendingOutbound,'uncertain sends stay pending when the composer is not empty');+ await page.locator('#composer').evaluate(el=>el.textContent='');const afterSend=await observe();assert.deepEqual(afterSend.messages.map(item=>item.id),['discord:456:1001','discord:456:1002']);- assert.equal(afterSend.messages[1].direction,'outgoing');- const pending=markChatSendPending(advanced.session,{- ok:true,messageKey:'test-pending',threadKey:result.threadKey,text:'My answer',- });- advanced=advanceChatSession(pending,afterSend);- assert.equal(advanced.newMessages[0].direction,'outgoing');+ assert.equal(afterSend.messages[1].direction,'unknown','nickname equality never asserts message authorship');+ const withoutDispatchEvidence=advanceChatSession(pending,afterSend,Date.parse(afterSend.observedAt));+ assert.equal(withoutDispatchEvidence.pendingDeliveryVerified,false,'an ordinary observation cannot infer Discord message authorship');+ advanced=advanceChatSession(dispatchedPending,afterSend,Date.parse(afterSend.observedAt));+ assert.equal(advanced.newMessages[0].direction,'unknown','transaction evidence does not overwrite the message author direction');assert.equal(advanced.session.state,'we_responded');assert.equal(advanced.session.pendingOutbound,null,'self-authored default-avatar message clears pending send');+ assert.equal(advanced.pendingDeliveryVerified,true,'the unique fresh exact-text bubble and empty composer verify this pending send');await page.locator('[data-list-id=chat-messages]').evaluate(el=>el.insertAdjacentHTML('beforeend',`<li><div role="article" data-list-item-id="chat-messages___chat-messages-456-1005">@@ -244,7 +263,7 @@ for (const [kind, engine, AgentClass, policy] of [assert.equal(advanced.nextAction,'reply');await page.locator('[data-list-id=chat-messages]').evaluate(el=>el.insertAdjacentHTML('beforeend',`<li><div role="article" data-list-item-id="chat-messages___chat-messages-456-1006"><div class="contents">- <img src="/assets/embed/avatars/3.png"><h3><span id="message-username-1006"><span data-text="Ficsit">Ficsit</span></span><time id="message-timestamp-1006" datetime="2026-09-29T01:03:00.000Z"></time></h3>+ <img src="https://cdn.discordapp.com/avatars/22/other.webp?size=160"><h3><span id="message-username-1006"><span data-text="Ficsit">Ficsit</span></span><time id="message-timestamp-1006" datetime="2026-09-29T01:03:00.000Z"></time></h3><div id="message-content-1006"></div></div><div id="message-accessories-1006"><div class="attachment_fixture"><img width="64" height="64" alt="support-error.png" src="/assets/support-error.png"></div><div role="img" aria-label="Sticker, Wave" style="display:block;width:24px;height:24px"></div><div class="embedTitle_fixture">Build error report</div><div class="embedDescription_fixture">Setup fails on startup</div></div></div></li>`));const afterAttachment=await observe();@@ -254,6 +273,12 @@ for (const [kind, engine, AgentClass, policy] of [advanced=advanceChatSession(advanced.session,afterAttachment);assert.deepEqual(advanced.newMessages.map(item=>item.id),['discord:456:1006']);assert.equal(advanced.nextAction,'reply');+ await page.locator('[data-list-id=chat-messages]').evaluate(el=>el.insertAdjacentHTML('beforeend',`+ <li><div role="article" data-list-item-id="chat-messages___chat-messages-456-1007"><div class="contents">+ <img src="/assets/embed/avatars/3.png"><h3><span id="message-username-1007"><span data-text="WebBrain">WebBrain</span></span><time id="message-timestamp-1007" datetime="${new Date().toISOString()}"></time></h3>+ <div id="message-content-1007">A member with the same display name</div></div></div></li>`));+ const collidingNickname=await observe();+ assert.equal(collidingNickname.messages.at(-1).direction,'unknown','a member sharing the account display name is not called outgoing');await page.locator('[data-list-id=chat-messages]').evaluate(el=>el.replaceChildren());assert.equal((await observe()).success,true);await page.locator('#channel').evaluate(el=>el.setAttribute('href','/channels/123/999'));diff --git a/test/run.js b/test/run.jsindex ec9bd3582..8902f381a 100644--- a/test/run.js+++ b/test/run.js@@ -6925,6 +6925,45 @@ test('chat workflow state survives worker restart and is durable before dispatch});assert.equal(sent.deliveryVerified, true, `${AgentClass.name}: durable send did not verify delivery`);assert.equal(sender.chatSessions.get(tabId)?.pendingOutbound, null, `${AgentClass.name}: pending send remained after verification`);++ const discordThreadKey = 'dom:discord:123:456';+ const discordSender = new AgentClass({});+ discordSender.conversations.set(tabId, [{ role: 'system', content: 'system' }]);+ discordSender.conversationIds.set(tabId, `conversation-discord-${index}`);+ discordSender._persist = () => {};+ discordSender._persistNow = async () => true;+ discordSender._messageRecipientGuardBlock = async () => null;+ const discordBefore = {+ ...baseSnapshot,+ threadKey: discordThreadKey,+ url: 'https://discord.com/channels/123/456',+ observedAt: new Date().toISOString(),+ };+ let discordAfter;+ const discordObservations = [discordBefore];+ discordSender._readChatObservation = async () => discordObservations.shift() || discordAfter;+ discordSender.executeTool = async () => {+ const observedAt = new Date().toISOString();+ discordAfter = {+ ...discordBefore,+ observedAt,+ messages: [{+ id: `discord:456:${index}`,+ direction: 'unknown',+ text: 'Send once with a default avatar.',+ timestamp: observedAt,+ }],+ };+ return { success: true, dispatched: true };+ };+ const discordSent = await discordSender._sendChatWorkflow(tabId, {+ thread_key: discordThreadKey,+ composer_ref: `composer-${index}`,+ text: 'Send once with a default avatar.',+ });+ assert.equal(discordSent.deliveryVerified, true, `${AgentClass.name}: exact fresh Discord bubble and empty composer did not verify the pending send`);+ assert.equal(discordSent.chatWorkflow.newMessages[0].direction, 'unknown', `${AgentClass.name}: delivery verification must not claim the Discord message author`);+ assert.equal(discordSender.chatSessions.get(tabId)?.pendingOutbound, null, `${AgentClass.name}: default-avatar Discord send remained pending`);}} finally {if (previousChrome === undefined) delete globalThis.chrome;