Skip to content

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

fix(chat): land review fixes on top of the Copilot workflow review

Codex release-state testcfec1e1bdcbf
diff --git a/src/chrome/src/agent/chat-workflow.js b/src/chrome/src/agent/chat-workflow.js
index 470cb2bd3..ac91aac8f 100644
--- a/src/chrome/src/agent/chat-workflow.js
+++ b/src/chrome/src/agent/chat-workflow.js
@@ -174,8 +174,11 @@ export function normalizeChatSnapshot(value, now = Date.now()) {
for (const raw of (Array.isArray(source.messages) ? source.messages : [])) {
const provisionalText = canonicalChatText(raw?.text ?? raw?.content ?? raw?.message);
const provisionalDirection = normalizeDirection(raw?.direction ?? raw?.authorRole ?? raw?.role);
- const occurrence = seenOccurrences.get(`${provisionalDirection}\u001f${provisionalText}`) || 0;
- seenOccurrences.set(`${provisionalDirection}\u001f${provisionalText}`, occurrence + 1);
+ const counted = seenOccurrences.get(`${provisionalDirection}\u001f${provisionalText}`) || 0;
+ seenOccurrences.set(`${provisionalDirection}\u001f${provisionalText}`, counted + 1);
+ // An observation that numbered its own messages before its own truncation
+ // is authoritative; such a source must number every message it reports.
+ const occurrence = Number.isInteger(raw?.occurrence) && raw.occurrence >= 0 ? raw.occurrence : counted;
const message = normalizeChatMessage(raw, { threadKey, occurrence });
if (message && !messageIds.has(message.id)) {
messageIds.add(message.id);
@@ -352,8 +355,13 @@ export function advanceChatSession(value, rawSnapshot, now = Date.now()) {
let nextState = session.state;
for (const event of events) nextState = transitionChatState(nextState, event);
const visibleOutgoingKeys = outgoingMessageKeys(snapshot);
+ // The anchored key is recomputed from DOM order, so a counterparty message
+ // that renders after a send could move our anchor and the key never matches,
+ // stranding the pending record. A newly visible outgoing bubble carrying the
+ // pending text is the same proof of delivery without depending on the anchor.
const matchedPending = session.pendingOutbound
&& (visibleOutgoingKeys.has(session.pendingOutbound.key)
+ || newOutgoing.some(message => canonicalChatText(message.text) === canonicalChatText(session.pendingOutbound.text))
|| (!session.pendingOutbound.replyAnchor
&& session.pendingOutbound.key === legacyMessageKey(snapshot.threadKey, session.pendingOutbound.text)));
const clearUserInput = events.some(event => event.type === 'user_input_cleared');
diff --git a/src/chrome/src/content/chat-observation.js b/src/chrome/src/content/chat-observation.js
index 7cfa3a281..db5c74048 100644
--- a/src/chrome/src/content/chat-observation.js
+++ b/src/chrome/src/content/chat-observation.js
@@ -65,6 +65,13 @@
.join('\n')
.slice(0, MAX_TEXT);
+ // Mirrors the kernel's canonical form so the fallback ordinal below groups
+ // exactly the bubbles the kernel would otherwise give the same id.
+ const canonicalText = (value) => {
+ const text = normalizeText(value);
+ try { return text.normalize('NFKC').toLocaleLowerCase(); } catch { return text.toLowerCase(); }
+ };
+
const attribute = (node, name) => compact(node?.getAttribute?.(name), 1000);
const visible = (node) => {
@@ -271,12 +278,31 @@
}
}
+ // A bubble the page does not identify is identified positionally, so the
+ // ordinal has to be assigned over the whole transcript rather than over
+ // the retained tail. Numbering after the cap restarts at 0 as older
+ // bubbles age out, which lets a genuinely new duplicate collapse onto an
+ // id the session has already seen and never surface as a delta.
+ const occurrences = new Map();
+ for (const item of selected) {
+ const key = [
+ item.direction,
+ canonicalText(item.text),
+ canonicalText(item.author),
+ item.timestamp,
+ ].join('\u001f');
+ const seen = occurrences.get(key) || 0;
+ occurrences.set(key, seen + 1);
+ item.occurrence = seen;
+ }
+
// The kernel keeps the last MAX_ITEMS entries, so the newest bubbles β€”
// not the oldest β€” must survive the cap in a long conversation.
return selected.slice(-MAX_ITEMS).map(item => ({
...(item.id ? { id: item.id } : {}),
direction: item.direction,
text: item.text,
+ occurrence: item.occurrence,
...(item.author ? { author: item.author } : {}),
...(item.timestamp ? { timestamp: item.timestamp } : {}),
}));
diff --git a/src/firefox/src/agent/chat-workflow.js b/src/firefox/src/agent/chat-workflow.js
index 470cb2bd3..ac91aac8f 100644
--- a/src/firefox/src/agent/chat-workflow.js
+++ b/src/firefox/src/agent/chat-workflow.js
@@ -174,8 +174,11 @@ export function normalizeChatSnapshot(value, now = Date.now()) {
for (const raw of (Array.isArray(source.messages) ? source.messages : [])) {
const provisionalText = canonicalChatText(raw?.text ?? raw?.content ?? raw?.message);
const provisionalDirection = normalizeDirection(raw?.direction ?? raw?.authorRole ?? raw?.role);
- const occurrence = seenOccurrences.get(`${provisionalDirection}\u001f${provisionalText}`) || 0;
- seenOccurrences.set(`${provisionalDirection}\u001f${provisionalText}`, occurrence + 1);
+ const counted = seenOccurrences.get(`${provisionalDirection}\u001f${provisionalText}`) || 0;
+ seenOccurrences.set(`${provisionalDirection}\u001f${provisionalText}`, counted + 1);
+ // An observation that numbered its own messages before its own truncation
+ // is authoritative; such a source must number every message it reports.
+ const occurrence = Number.isInteger(raw?.occurrence) && raw.occurrence >= 0 ? raw.occurrence : counted;
const message = normalizeChatMessage(raw, { threadKey, occurrence });
if (message && !messageIds.has(message.id)) {
messageIds.add(message.id);
@@ -352,8 +355,13 @@ export function advanceChatSession(value, rawSnapshot, now = Date.now()) {
let nextState = session.state;
for (const event of events) nextState = transitionChatState(nextState, event);
const visibleOutgoingKeys = outgoingMessageKeys(snapshot);
+ // The anchored key is recomputed from DOM order, so a counterparty message
+ // that renders after a send could move our anchor and the key never matches,
+ // stranding the pending record. A newly visible outgoing bubble carrying the
+ // pending text is the same proof of delivery without depending on the anchor.
const matchedPending = session.pendingOutbound
&& (visibleOutgoingKeys.has(session.pendingOutbound.key)
+ || newOutgoing.some(message => canonicalChatText(message.text) === canonicalChatText(session.pendingOutbound.text))
|| (!session.pendingOutbound.replyAnchor
&& session.pendingOutbound.key === legacyMessageKey(snapshot.threadKey, session.pendingOutbound.text)));
const clearUserInput = events.some(event => event.type === 'user_input_cleared');
diff --git a/src/firefox/src/content/chat-observation.js b/src/firefox/src/content/chat-observation.js
index 7cfa3a281..db5c74048 100644
--- a/src/firefox/src/content/chat-observation.js
+++ b/src/firefox/src/content/chat-observation.js
@@ -65,6 +65,13 @@
.join('\n')
.slice(0, MAX_TEXT);
+ // Mirrors the kernel's canonical form so the fallback ordinal below groups
+ // exactly the bubbles the kernel would otherwise give the same id.
+ const canonicalText = (value) => {
+ const text = normalizeText(value);
+ try { return text.normalize('NFKC').toLocaleLowerCase(); } catch { return text.toLowerCase(); }
+ };
+
const attribute = (node, name) => compact(node?.getAttribute?.(name), 1000);
const visible = (node) => {
@@ -271,12 +278,31 @@
}
}
+ // A bubble the page does not identify is identified positionally, so the
+ // ordinal has to be assigned over the whole transcript rather than over
+ // the retained tail. Numbering after the cap restarts at 0 as older
+ // bubbles age out, which lets a genuinely new duplicate collapse onto an
+ // id the session has already seen and never surface as a delta.
+ const occurrences = new Map();
+ for (const item of selected) {
+ const key = [
+ item.direction,
+ canonicalText(item.text),
+ canonicalText(item.author),
+ item.timestamp,
+ ].join('\u001f');
+ const seen = occurrences.get(key) || 0;
+ occurrences.set(key, seen + 1);
+ item.occurrence = seen;
+ }
+
// The kernel keeps the last MAX_ITEMS entries, so the newest bubbles β€”
// not the oldest β€” must survive the cap in a long conversation.
return selected.slice(-MAX_ITEMS).map(item => ({
...(item.id ? { id: item.id } : {}),
direction: item.direction,
text: item.text,
+ occurrence: item.occurrence,
...(item.author ? { author: item.author } : {}),
...(item.timestamp ? { timestamp: item.timestamp } : {}),
}));
diff --git a/test/run.js b/test/run.js
index b2d07335b..797d4e112 100644
--- a/test/run.js
+++ b/test/run.js
@@ -5973,6 +5973,38 @@ test('long-running chat workflow tracks deltas, safe states, and idempotent send
assert.equal(sent.session.pendingOutbound, null);
assert.equal(sent.newMessages.length, 1);
+ // A support message that renders above our own bubble moves the anchor the
+ // pending key was built from, so the recomputed key never matches. Delivery
+ // is still proven by the new outgoing bubble itself carrying the pending
+ // text, so the pending record must not survive.
+ const anchorMoved = workflow.advanceChatSession(
+ pending,
+ {
+ threadId: 'case-42',
+ composer: { available: true, empty: true },
+ messages: [
+ { id: 'in-0', direction: 'incoming', author: 'Support', text: 'One moment.' },
+ { id: 'out-1', direction: 'outgoing', text: decision.text },
+ ],
+ },
+ Date.parse('2026-09-05T01:02:00Z'),
+ );
+ assert.equal(
+ anchorMoved.session.pendingOutbound,
+ null,
+ 'a verified send was left pending because a counterparty message moved its reply anchor',
+ );
+ assert.equal(
+ workflow.decideChatSend(
+ anchorMoved.session,
+ anchorMoved.snapshot,
+ 'A follow-up question.',
+ Date.parse('2026-09-05T01:02:10Z'),
+ ).ok,
+ true,
+ 'a stranded pending record must not block the next send',
+ );
+
const duplicate = workflow.decideChatSend(sent.session, sent.snapshot, decision.text);
assert.equal(duplicate.ok, false);
assert.equal(duplicate.duplicate, true);
@@ -6126,6 +6158,42 @@ test('long-running chat workflow tracks deltas, safe states, and idempotent send
);
assert.equal(largeDelta.newMessages.length, 20, 'chat workflow delta must remain bounded independently of transcript retention');
assert.equal(largeDelta.newMessages[0].id, 'delta-5');
+
+ // Unidentified duplicates are numbered positionally. Numbering only the
+ // retained window would restart at 0 as older bubbles age out, so a new
+ // duplicate would normalize onto an already-seen id and never surface.
+ const untitled = count => Array.from({ length: count }, () => ({ direction: 'incoming', text: 'Are you still there?' }));
+ const overCap = workflow.normalizeChatSnapshot({ threadId: 'case-42', messages: untitled(205) });
+ assert.equal(overCap.messages.length, 200, 'transcript retention cap changed');
+ assert.equal(
+ new Set(overCap.messages.map(message => message.id)).size,
+ 200,
+ 'duplicate untitled messages collapsed onto shared ids past the retention cap',
+ );
+ const grown = workflow.normalizeChatSnapshot({ threadId: 'case-42', messages: untitled(206) });
+ assert.equal(
+ grown.messages.filter(message => !overCap.messages.some(item => item.id === message.id)).length,
+ 1,
+ 'a new untitled duplicate past the retention cap produced no delta',
+ );
+ // An observation that numbered its own messages before its own truncation
+ // is authoritative, so the ordinal survives a transcript the kernel never
+ // saw in full.
+ const preNumbered = workflow.normalizeChatSnapshot({
+ threadId: 'case-42',
+ messages: [
+ { direction: 'incoming', text: 'Are you still there?', occurrence: 41 },
+ { direction: 'incoming', text: 'Are you still there?', occurrence: 42 },
+ ],
+ });
+ assert.deepEqual(
+ preNumbered.messages.map(message => message.id),
+ [
+ workflow.stableChatMessageId({ threadKey: 'case-42', direction: 'incoming', text: 'Are you still there?', occurrence: 41 }),
+ workflow.stableChatMessageId({ threadKey: 'case-42', direction: 'incoming', text: 'Are you still there?', occurrence: 42 }),
+ ],
+ 'an observer-assigned message ordinal was discarded',
+ );
}
});
@@ -7183,6 +7251,29 @@ test('chat observation returns a current-thread snapshot without treating messag
}),
);
+ // The observer caps the transcript it reports, so it β€” not the kernel β€” is
+ // the last layer that can see a duplicate that falls outside the cap. It has
+ // to number those duplicates before truncating, or the numbering restarts at
+ // 0 as older bubbles age out.
+ const capped = makeDom();
+ for (let index = 0; index < 205; index += 1) {
+ capped.main.appendChild(capped.makeElement('article', {
+ 'data-message-direction': 'incoming',
+ 'data-message-author': 'Support',
+ }, 'Are you still there?'));
+ }
+ vm.runInNewContext(chromeSource, capped.context);
+ const cappedSnapshot = capped.context.window.__wb_observe_chat_dom({
+ probe: { success: true, composerAvailable: true, composerRef: 'composer_ref' },
+ });
+ const cappedDuplicates = cappedSnapshot.messages.filter(message => message.text === 'Are you still there?');
+ assert.equal(cappedDuplicates.length, 200, 'observer transcript cap changed');
+ assert.deepEqual(
+ [cappedDuplicates[0].occurrence, cappedDuplicates.at(-1).occurrence],
+ [5, 204],
+ 'the observer numbered unidentified duplicates after its own cap instead of before it',
+ );
+
const firefox = makeDom();
vm.runInNewContext(firefoxSource, firefox.context);
const firefoxSnapshot = firefox.context.window.__wb_observe_chat_dom({