The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): settle an identical reply onto its sealed interim instead of painting it twice
jiangkoumo1409d3877c50
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/collapse-duplicate-final.ts b/apps/desktop/src/app/session/hooks/use-message-stream/collapse-duplicate-final.tsindex cdb03b0163b..b9573668260 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/collapse-duplicate-final.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/collapse-duplicate-final.ts@@ -54,3 +54,88 @@ export function collapseDuplicateFinalAfterToolInterim(return { keptId: prior.id, messages: next }}++/**+ * Index of a sealed, text-only interim earlier in this occurrence that already+ * carries exactly the turn's final reply — `-1` when there is none.+ *+ * `message.interim` seals the segment the agent produced (a tool-call round's+ * commentary, or a verify-on-stop candidate). When the client has no live+ * bubble to seal at that moment — a superseded attempt's frames cleared the+ * stream, a reconnect dropped the deltas — the interim materializes its OWN+ * bubble from the text. The turn then streams that same text again and+ * completes, and the reply is on screen twice: the sealed interim (no footer)+ * above the settled bubble (with footer), while the store holds one row+ * (#123801).+ *+ * Byte-identical text is the discriminator: a second real segment never repeats+ * the reply verbatim, so an interim whose text IS the final text is this turn's+ * reply, not another segment. Tool-call parts disqualify it — that interim owns+ * rows the transcript must keep. Only the nearest sealed interim is considered+ * (the loop stops at the first one): anything further back is an earlier+ * segment of the turn.+ */+export function identicalInterimSiblingIndex(+ messages: ChatMessage[],+ boundaryIndex: number,+ finalText: string,+ excludeIndex = -1+): number {+ if (!finalText) {+ return -1+ }++ for (let index = messages.length - 1; index > boundaryIndex; index -= 1) {+ if (index === excludeIndex) {+ continue+ }++ const message = messages[index]++ if (message.role !== 'assistant' || message.hidden || message.interim !== true) {+ continue+ }++ if (message.parts.some(part => part.type === 'tool-call')) {+ return -1+ }++ return chatMessageText(message).trim() === finalText ? index : -1+ }++ return -1+}++/** The identical interim survives (it IS this reply); the live twin is dropped. */+export function collapseDuplicateFinalOntoIdenticalInterim(+ messages: ChatMessage[],+ streamIndex: number,+ interimIndex: number,+ options: {+ completeMessage: (message: ChatMessage) => ChatMessage+ finalText: string+ hasFailure: boolean+ }+): DuplicateFinalCollapse | null {+ if (streamIndex < 0 || interimIndex < 0 || options.hasFailure || !options.finalText) {+ return null+ }++ const live = messages[streamIndex]+ const interim = messages[interimIndex]++ if (!live || !interim || chatMessageText(live).trim() !== options.finalText) {+ return null+ }++ const next = messages.slice()+ next[interimIndex] = options.completeMessage(+ withUniqueToolCallIdsWithinMessage({+ ...interim,+ parts: [...interim.parts, ...live.parts.filter(part => part.type !== 'text')]+ })+ )+ next.splice(streamIndex, 1)++ return { keptId: interim.id, messages: next }+}diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts b/apps/desktop/src/app/session/hooks/use-message-stream/index.tsindex 1db0674c8e9..032f01b9cd2 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/index.ts@@ -36,7 +36,12 @@ import { broadcastTranscriptChanged } from '@/store/transcript-sync'import type { ClientSessionState } from '../../../types'-import { collapseDuplicateFinalAfterToolInterim, type DuplicateFinalCollapse } from './collapse-duplicate-final'+import {+ collapseDuplicateFinalAfterToolInterim,+ collapseDuplicateFinalOntoIdenticalInterim,+ type DuplicateFinalCollapse,+ identicalInterimSiblingIndex+} from './collapse-duplicate-final'import { useGatewayEventHandler } from './gateway-event'import { handleServerRequest as dispatchServerRequest } from './gateway-event/server-requests'import { extendInterruptedReply } from './interrupted-reply'@@ -862,13 +867,26 @@ export function useMessageStream({let collapsed: DuplicateFinalCollapse | null = null+ const hasFailure = Boolean(failure) || Boolean(completionError)++ // A sealed text-only interim carrying exactly this reply IS the reply+ // (#123801) — see identicalInterimSiblingIndex. Settling it keeps one+ // bubble for the one stored row instead of painting the text twice.+ const identicalInterimIndex = identicalInterimSiblingIndex(prev, lastUserIndex, finalText, streamIndex)+if (streamIndex >= 0) {- collapsed = collapseDuplicateFinalAfterToolInterim(prev, streamIndex, {- completeMessage,- finalText,- hasFailure: Boolean(failure) || Boolean(completionError),- interimBoundaryPending- })+ collapsed =+ collapseDuplicateFinalAfterToolInterim(prev, streamIndex, {+ completeMessage,+ finalText,+ hasFailure,+ interimBoundaryPending+ }) ??+ collapseDuplicateFinalOntoIdenticalInterim(prev, streamIndex, identicalInterimIndex, {+ completeMessage,+ finalText,+ hasFailure+ })nextMessages = collapsed?.messages ?? settleAt(streamIndex)} else {const fallbackIndex = prev.findLastIndex(@@ -968,6 +986,10 @@ export function useMessageStream({// force an append of a duplicate bubble (#74560). This also// closes the non-previewed tool-call gap from #63679.nextMessages = settleAt(index)+ } else if (identicalInterimIndex >= 0) {+ // The reply is already on screen as the sealed interim: settle it+ // instead of appending the same text a second time (#123801).+ nextMessages = settleAt(identicalInterimIndex)} else if (finalText) {nextMessages = [...prev, newAssistantFromCompletion()]}@@ -988,6 +1010,8 @@ export function useMessageStream({if (sealed?.interim === true && chatMessageText(sealed).trim() === finalText) {nextMessages = settleAt(sealedIndex)+ } else if (identicalInterimIndex >= 0) {+ nextMessages = settleAt(identicalInterimIndex)} else if (finalText) {nextMessages = [...prev, newAssistantFromCompletion()]}diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/interim-redelivery-duplicate.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/interim-redelivery-duplicate.test.tsxnew file mode 100644index 00000000000..bc952206b70--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-message-stream/interim-redelivery-duplicate.test.tsx@@ -0,0 +1,112 @@+import { act, cleanup } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'++import type { ClientSessionState } from '@/app/types'+import { chatMessageText } from '@/lib/chat-messages'++import { type MessageStreamHarness, renderMessageStream } from './test-harness'+import { STREAM_DELTA_FLUSH_MS } from './utils'++// A turn whose reply was sealed as an interim BEFORE the client had it on+// screen (the interim materialized its own bubble because a superseded+// attempt's frames had cleared the live stream) paints the reply twice on+// current main: the sealed interim above, and the settled bubble the same text+// streams into below — while the store holds one row (#123801).+//+// No user prompt row is mounted here on purpose: the duplicate is a+// render-side artifact of the interim/delta/complete ordering, not of the+// prompt row, and this keeps the fixture to the frames that matter. The+// boundary cases that must still paint twice have their own specs below.+const SID = 'interim-redelivery-duplicate'++const REPLY =+ 'The Chinese posts all point at one third-party directory: it claims 1081 Meta Muse use cases across 28 pages, and the invite-code replies are the bulk of the chatter.'++const PROSE = 'Let me check that directory before I answer.'++let stream: MessageStreamHarness++const mountStream = () => {+ vi.useFakeTimers()+ stream = renderMessageStream(SID)+}++const start = () => act(() => stream.handleEvent({ payload: {}, session_id: SID, type: 'message.start' }))++const delta = (text: string) => act(() => stream.handleEvent({ payload: { text }, session_id: SID, type: 'message.delta' }))++const interim = (text: string) =>+ act(() => stream.handleEvent({ payload: { text, already_streamed: true }, session_id: SID, type: 'message.interim' }))++const tool = (name: string) =>+ act(() => {+ stream.handleEvent({ payload: { args: { command: 'ls' }, name, tool_id: 'call-1' }, session_id: SID, type: 'tool.start' })+ stream.handleEvent({ payload: { name, result: 'ok', tool_id: 'call-1' }, session_id: SID, type: 'tool.complete' })+ })++const complete = (text: string) =>+ act(() => stream.handleEvent({ payload: { text }, session_id: SID, type: 'message.complete' }))++const flushDeltas = () =>+ act(async () => {+ await vi.advanceTimersByTimeAsync(STREAM_DELTA_FLUSH_MS + 10)+ })++const state = (): ClientSessionState => stream.state()++/** Every visible assistant bubble's text, in transcript order. */+const visibleAssistantTexts = (): string[] =>+ state()+ .messages.filter(message => message.role === 'assistant' && !message.hidden)+ .map(message => chatMessageText(message).trim())+ .filter(Boolean)++const toolCallCount = (): number =>+ state().messages.flatMap(message => message.parts).filter(part => part.type === 'tool-call').length++describe('a reply the turn re-streams after sealing it as an interim paints once', () => {+ afterEach(() => {+ cleanup()+ vi.useRealTimers()+ vi.restoreAllMocks()+ })++ it('keeps one bubble when the sealed interim already carries the final reply', async () => {+ mountStream()+ await start()+ await interim(REPLY)+ await delta(REPLY)+ await flushDeltas()+ await complete(REPLY)++ expect(visibleAssistantTexts()).toEqual([REPLY])+ })++ it('still keeps a distinct interim segment beside the reply', async () => {+ mountStream()+ await start()+ await interim(PROSE)+ await delta(REPLY)+ await flushDeltas()+ await complete(REPLY)++ expect(visibleAssistantTexts()).toEqual([PROSE, REPLY])+ })++ it('never drops an interim that carries tool rows', async () => {+ mountStream()+ await start()+ await tool('terminal')+ await delta(REPLY)+ await flushDeltas()+ await interim(REPLY)+ await delta(REPLY)+ await flushDeltas()+ await complete(REPLY)++ // The interim owns the tool row, so it survives even though its text+ // matches the reply: dropping it would lose the completed tool card.+ expect(toolCallCount()).toBe(1)+ expect(visibleAssistantTexts()).toEqual([REPLY, REPLY])+ })+})