The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): a re-attach page that already holds the reply keeps one bubble
Teknium5cd94853baec
diff --git a/apps/desktop/e2e/core/oracle.ts b/apps/desktop/e2e/core/oracle.tsindex 72ef37c1c95..277575fe643 100644--- a/apps/desktop/e2e/core/oracle.ts+++ b/apps/desktop/e2e/core/oracle.ts@@ -75,6 +75,34 @@ export async function installDuplicateSampler(page: Page): Promise<void> {// "x|y": x has been seen above y. A later frame with y above x is a flip.const above = new Set<string>()let scheduled = false+ // The last few bubble layouts (newest bubbles: id = markers), so a red+ // says which rows drew the copy and what the view showed just before.+ const timeline: { at: number; route: string; layout: string[] }[] = []+ let lastLayout = ''++ const seen = (text: string) => {+ const flat = text.replace(/\s+/g, ' ')++ return flat.length > 600 ? `${flat.slice(0, 150)} … ${flat.slice(-450)}` : flat+ }++ const recordLayout = (viewport: HTMLElement) => {+ const layout = (+ [+ ...viewport.querySelectorAll('[data-slot="aui_user-message-root"], [data-slot="aui_assistant-message-root"]')+ ] as HTMLElement[]+ )+ .slice(-6)+ .map(el => `${el.getAttribute('data-message-id') ?? '?'}=${[...new Set(el.innerText.match(re) ?? [])].join('+')}`)++ const key = `${location.hash}|${layout.join('|')}`++ if (key !== lastLayout) {+ lastLayout = key+ timeline.push({ at: Math.round(performance.now()), route: location.hash, layout })+ timeline.splice(0, Math.max(0, timeline.length - 8))+ }+ }const orderViolation = (detail: string, text: string) => {if (w.__coreSampler.order.length < 20) {@@ -82,7 +110,8 @@ export async function installDuplicateSampler(page: Page): Promise<void> {detail,at: Math.round(performance.now()),route: location.hash,- text: text.replace(/\s+/g, ' ').slice(0, 600)+ text: seen(text),+ ...(w.__coreSampler.order.length === 0 ? { timeline: [...timeline] } : {})})}}@@ -98,6 +127,7 @@ export async function installDuplicateSampler(page: Page): Promise<void> {const text = viewport.innerTextw.__coreSampler.samples+++ recordLayout(viewport)const counts = new Map<string, number>()for (const match of text.match(re) ?? []) {@@ -143,7 +173,8 @@ export async function installDuplicateSampler(page: Page): Promise<void> {at: Math.round(performance.now()),route: location.hash,bubbles,- text: text.replace(/\s+/g, ' ').slice(0, 600)+ text: seen(text),+ ...(w.__coreSampler.violations.length === 0 ? { timeline: [...timeline] } : {})})}}diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/committed-reply.test.ts b/apps/desktop/src/app/session/hooks/use-session-actions/committed-reply.test.tsnew file mode 100644index 00000000000..4f407727d4f--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-session-actions/committed-reply.test.ts@@ -0,0 +1,62 @@+import { describe, expect, it } from 'vitest'++import { type ChatMessage, chatMessageText } from '@/lib/chat-messages'++import { overlayConcurrentMessageChanges } from './utils'++const tool = { type: 'tool-call', toolCallId: 'call-1', toolName: 'terminal', args: {}, argsText: '{}', result: 'ok' }++const live = (answer: string): ChatMessage =>+ ({+ id: 'assistant-stream-1-3',+ role: 'assistant',+ pending: true,+ parts: [{ type: 'text', text: '\n\nA6i steered narration' }, tool, { type: 'text', text: `\n\n${answer}` }]+ }) as ChatMessage++const steer: ChatMessage = { id: 'user-1-steer', role: 'user', parts: [{ type: 'text', text: 'change course' }] }++// The switch-back REST page as history folds it: the turn's narration, its+// tool and its stored final reply in one bubble under the narration's row.+const committedPage = (prompt: string): ChatMessage[] => [+ { id: '18-user', role: 'user', rowId: 18, parts: [{ type: 'text', text: prompt }] } as ChatMessage,+ {+ id: '19-assistant',+ role: 'assistant',+ rowId: 19,+ parts: [+ { type: 'text', text: 'A6i steered narration', sourceRowId: 19 },+ tool,+ { type: 'text', text: 'A6 steered answer', sourceRowId: 21 }+ ]+ } as ChatMessage+]++const assistants = (messages: ChatMessage[]) =>+ messages.filter(message => message.role === 'assistant').map(message => [message.id, chatMessageText(message)])++describe('a re-attach page that commits the reply before its completion', () => {+ // Steer, switch away, switch back: the turn stores its final row while the+ // REST read is in flight, and that page resolves before message.complete+ // reaches the still-pending live row (the e2e "steer then re-attach" step).+ it('keeps the live row in the committed bubble’s place instead of beside it', () => {+ const baseline = [steer, live('A6 ')]+ const current = [steer, live('A6 steered answer')]++ const overlaid = overlayConcurrentMessageChanges(committedPage('change course'), baseline, current)++ expect(assistants(overlaid)).toEqual([['assistant-stream-1-3', chatMessageText(current[1])]])+ expect(overlaid.map(message => message.id)).toEqual(['18-user', 'assistant-stream-1-3'])+ })++ // A page whose newest prompt is not the live row's own is an earlier turn:+ // a new reply that happens to open with the same words is not that answer.+ it('leaves a page reply that follows another prompt alone', () => {+ const baseline = [steer, live('A6 ')]+ const current = [steer, live('A6 steered')]++ const overlaid = overlayConcurrentMessageChanges(committedPage('an earlier prompt'), baseline, current)++ expect(assistants(overlaid).map(([id]) => id)).toEqual(['19-assistant', 'assistant-stream-1-3'])+ })+})diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/committed-reply.ts b/apps/desktop/src/app/session/hooks/use-session-actions/committed-reply.tsnew file mode 100644index 00000000000..b71b4f27af2--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-session-actions/committed-reply.ts@@ -0,0 +1,90 @@+import { textWithoutReferenceLines } from '@/components/assistant-ui/reference-kinds'+import { type ChatMessage, chatMessageText } from '@/lib/chat-messages'+import { isLiveTailReplyId } from '@/lib/spoken-reply'++/**+ * True when `next` is a pure forward extension of the previous *answer* text.+ * Empty previous answer never accepts a dump as an extension — that is how the+ * mid-turn inflight flat dump used to sandwich structured rows (#76444).+ */+export function isStrictAnswerTextExtension(next: string, previous: string): boolean {+ const n = next.trim()+ const p = previous.trim()++ if (!p || !n) {+ return false+ }++ return n.startsWith(p)+}++/** A folded tool-turn bubble's answer: its text after the last tool call. */+export function replyAfterLastTool(message: ChatMessage): string {+ const lastTool = message.parts.findLastIndex(part => part.type === 'tool-call')++ return chatMessageText({ ...message, parts: message.parts.slice(lastTool + 1) })+}++const spokenText = (message: ChatMessage) =>+ message.parts+ .flatMap(part => (part.type === 'text' ? [part.text] : []))+ .join(' ')+ .replace(/\s+/g, ' ')++/**+ * Whether a committed bubble already holds the reply a stale live snapshot was+ * streaming. History folds a tool turn's narration, tools and answer into one+ * bubble while the snapshot carries the turn's whole text, so compare the+ * bubble's text with whitespace collapsed. The bubble must end in a reply: a+ * mid-turn commit ends on a tool call and the turn is still running.+ */+export function committedReplyCovers(message: ChatMessage, snapshot: string): boolean {+ return (+ Boolean(replyAfterLastTool(message).trim()) &&+ isStrictAnswerTextExtension(spokenText(message), snapshot.replace(/\s+/g, ' '))+ )+}++const promptText = (message: ChatMessage | undefined) =>+ message ? textWithoutReferenceLines(chatMessageText(message)).trim() : ''++/**+ * Where a transcript page already commits a still-streaming live reply, or -1.+ *+ * A re-attach reads the persisted page over REST while the turn's events ride+ * the socket, so the page can carry the turn's final row before its+ * `message.complete` reaches the live row. Placing the live row beside that+ * bubble paints the reply twice until the completion lands. The live row keeps+ * the turn: its late deltas and the completion still find it by id, while a+ * dropped live row would be re-seeded by the next delta. So it takes the+ * committed bubble's place. `committedNew` admits only page bubbles that are+ * new since the baseline and not themselves live, and the bubble must follow+ * the live row's own prompt and end in a reply covering the live text.+ */+export function pageReplyCommittingLiveRow(+ page: ChatMessage[],+ committedNew: (message: ChatMessage) => boolean,+ live: ChatMessage,+ liveMessages: ChatMessage[]+): number {+ if (live.role !== 'assistant' || live.pending !== true || live.error || !isLiveTailReplyId(live.id)) {+ return -1+ }++ const ownPrompt = liveMessages.slice(0, liveMessages.indexOf(live)).findLast(message => message.role === 'user')+ const pagePrompt = page.findLastIndex(message => message.role === 'user')++ if (pagePrompt < 0 || !promptText(ownPrompt) || promptText(ownPrompt) !== promptText(page[pagePrompt])) {+ return -1+ }++ const snapshot = spokenText(live)++ return page.findIndex(+ (message, index) =>+ index > pagePrompt &&+ message.role === 'assistant' &&+ committedNew(message) &&+ committedReplyCovers(message, snapshot)+ )+}diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.tsindex 511010ee004..e0a4bb426fd 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts@@ -70,6 +70,12 @@ import type { SessionCreateResponse, SessionInfo, SessionResumeResult, SessionRuimport type { ClientSessionState } from '../../../types'+import {+ committedReplyCovers,+ isStrictAnswerTextExtension,+ pageReplyCommittingLiveRow,+ replyAfterLastTool+} from './committed-reply'import {acknowledgedTranscriptBoundary,conflictingTranscriptIdentity,@@ -110,45 +116,6 @@ function isLiveTailRow(message: ChatMessage): boolean {return message.pending === true || isLiveTailReplyId(message.id) || message.interim === true}-/**- * True when `next` is a pure forward extension of the previous *answer* text.- * Empty previous answer never accepts a dump as an extension — that is how the- * mid-turn inflight flat dump used to sandwich structured rows (#76444).- */-export function isStrictAnswerTextExtension(next: string, previous: string): boolean {- const n = next.trim()- const p = previous.trim()-- if (!p || !n) {- return false- }-- return n.startsWith(p)-}--/**- * Whether a committed bubble already holds the reply a stale live snapshot was- * streaming. History folds a tool turn's narration, tools and answer into one- * bubble while the snapshot carries the turn's whole text, so compare the- * bubble's text with whitespace collapsed. The bubble must end in a reply: a- * mid-turn commit ends on a tool call and the turn is still running.- */-function committedReplyCovers(message: ChatMessage, snapshot: string): boolean {- const text = message.parts- .flatMap(part => (part.type === 'text' ? [part.text] : []))- .join(' ')- .replace(/\s+/g, ' ')-- return Boolean(replyAfterLastTool(message).trim()) && isStrictAnswerTextExtension(text, snapshot.replace(/\s+/g, ' '))-}--/** A folded tool-turn bubble's answer: its text after the last tool call. */-function replyAfterLastTool(message: ChatMessage): string {- const lastTool = message.parts.findLastIndex(part => part.type === 'tool-call')-- return chatMessageText({ ...message, parts: message.parts.slice(lastTool + 1) })-}-/*** Carry the durable row id and reactions from a same-turn `previous` row onto* `next` when it lacks them — reactions are keyed by row id, so they travel@@ -1711,6 +1678,8 @@ export function overlayConcurrentMessageChanges()}+ const committedNewRow = (message: ChatMessage) => !baselineById.has(message.id) && !isLiveTailRow(message)+const representedOnPage = (current: ChatMessage): boolean =>// The page can still carry the row's older streaming copy by id when it// was composed from the baseline; the committed row replaces both.@@ -1771,6 +1740,18 @@ export function overlayConcurrentMessageChanges(continue}+ // The page caught this turn's reply committed before its completion+ // reached the live row: the live row takes that bubble's place.+ const committedIndex = pageReplyCommittingLiveRow(overlaid, committedNewRow, current, currentMessages)++ if (committedIndex >= 0) {+ nextIndexById.set(current.id, committedIndex)+ overlaid[committedIndex] = current+ changed = true++ continue+ }+nextIndexById.set(current.id, overlaid.length)overlaid.push(current)changed = true