Skip to content

The agent that grows with you

fix(desktop): settle a reused final instead of painting it twice in one bubble

kshitijk4poor2c00700d784e
diff --git a/apps/desktop/e2e/core/reply-painted-once.spec.ts b/apps/desktop/e2e/core/reply-painted-once.spec.ts
new file mode 100644
index 00000000000..329ee4a0007
--- /dev/null
+++ b/apps/desktop/e2e/core/reply-painted-once.spec.ts
@@ -0,0 +1,263 @@
+/**
+ * C2 core: a reply is painted ONCE inside its bubble, whatever tool round
+ * the turn ends on.
+ *
+ * Report: "Hermes Desktop sometimes duplicates the same agent output twice
+ * consecutively within a single message bubble, with no line break or UI
+ * elements between them."
+ *
+ * The backend has one path that ends a turn on text the user has already seen.
+ * The model answers beside a housekeeping tool call (memory / todo_list /
+ * skill_manage / session_search), then sends an empty follow-up. The agent
+ * then reuses that answer as the final reply (turn_empty_response.py,
+ * `fallback_prior_turn_content`). The answer was streamed BEFORE the tool, so
+ * the final names text that sits ahead of the bubble's last tool row. A
+ * renderer that bounds "the current response" at the last tool row appends
+ * it again. A silent tool (todo_list) draws no row between the copies, which
+ * is the reported "twice, back to back".
+ *
+ * Every step runs the real Electron app against a real `hermes serve`; only
+ * the LLM is scripted (provider.ts). The transcript oracle checks each
+ * marker is rendered exactly once, live and after a reload. An in-page
+ * sampler fails on any transient double paint. A bubble-scoped check also
+ * names the exact symptom (one bubble holding the reply twice).
+ *
+ * The scenarios:
+ * - answer + housekeeping tool + empty follow-up, with message.interim
+ * sealing on (the default) and off (display.interim_assistant_messages:
+ * false: no seal, so the deltas and the final land in ONE bubble). The
+ * silent `todo_list` and the visible `memory` row are both covered;
+ * - a substantive tool round first, then the same ending (several rounds in
+ * one bubble, the shape a last-tool-only bound misses);
+ * - control: a different final after a tool keeps both responses.
+ */
+
+import { type ElectronApplication, expect, type Page, test } from '@playwright/test'
+
+import {
+ coreAppEnv,
+ type CoreSandbox,
+ createCoreSandbox,
+ currentSessionId,
+ launchCoreApp,
+ recordWebSockets,
+ send,
+ waitForInteractive,
+ writeProviderHome,
+ type WsRecorder
+} from './harness'
+import { assertTranscriptOracle, installDuplicateSampler, type OracleTarget } from './oracle'
+import { type ScriptedProvider, startScriptedProvider, type Step } from './provider'
+
+const nonce = Math.random()
+ .toString(36)
+ .slice(2, 8)
+ .replace(/[^a-z0-9]/g, 'x')
+ .padEnd(4, 'q')
+
+const U = (n: number) => `U${n}-${nonce}`
+const A = (n: number) => `A${n}-${nonce}`
+const AI = (n: number) => `A${n}i-${nonce}`
+
+const words = (marker: string, ...rest: string[]) => [
+ `${marker} `,
+ ...rest.map((w, i) => (i === rest.length - 1 ? w : `${w} `))
+]
+
+const todo = (tag: string) => ({
+ name: 'todo_list',
+ args: { todos: [{ id: `core-${tag}`, content: `core ${tag}`, status: 'completed' }] }
+})
+
+const memory = (tag: string) => ({
+ name: 'memory',
+ args: { action: 'add', target: 'memory', content: `core e2e ${tag} ${nonce}` }
+})
+
+const echo = (tag: string) => ({ name: 'terminal', args: { command: `echo core-${tag}` } })
+
+// interim_assistant_messages toggles the live seal; review off keeps the
+// background memory fork from adding rows that are not part of the turn;
+// tool search off keeps todo_list directly callable (it is deferred otherwise).
+const config = (interim: boolean) => `display:
+ interim_assistant_messages: ${interim}
+memory:
+ nudge_interval: 0
+tools:
+ tool_search:
+ enabled: off
+`
+
+function viewport(page: Page) {
+ return page.locator('[data-slot="aui_thread-viewport"]').filter({ visible: true }).first()
+}
+
+/** The turn as the wire and the provider saw it, for failure messages. */
+function wireTail(ws: WsRecorder, provider?: ScriptedProvider): string {
+ const frames = ws.events
+ .filter(e => /^(message|tool)\./.test(e.type))
+ .slice(-14)
+ .map(e => `${e.type} ${JSON.stringify(e.payload?.text ?? e.payload?.name ?? '').slice(0, 80)}`)
+
+ const calls = (provider?.completions ?? [])
+ .slice(-6)
+ .map(
+ c =>
+ `${c.marker}#${c.step} finished=${c.finished} tools=${c.toolCalls.join(',')} text=${JSON.stringify(c.sentText).slice(0, 60)}`
+ )
+
+ return `wire:\n ${frames.join('\n ')}\nprovider:\n ${calls.join('\n ')}`
+}
+
+async function settled(page: Page, ws: WsRecorder, marker: string, provider?: ScriptedProvider) {
+ try {
+ await expect
+ .poll(
+ () => ws.events.some(e => e.type === 'message.complete' && String(e.payload?.text ?? '').includes(marker)),
+ {
+ timeout: 120_000,
+ message: `message.complete for ${marker}`
+ }
+ )
+ .toBe(true)
+ } catch (error) {
+ throw new Error(`${(error as Error).message}\n${wireTail(ws, provider)}`)
+ }
+
+ await expect(page.locator('[data-slot="composer-root"] button[aria-label="Stop"]')).toHaveCount(0, {
+ timeout: 30_000
+ })
+}
+
+/** Assistant bubbles that contain `marker`, with how often each holds it. */
+async function bubblesHolding(page: Page, marker: string): Promise<{ count: number; text: string }[]> {
+ return page.evaluate(m => {
+ const re = new RegExp(`\\b${m}\\b`, 'g')
+
+ return (
+ [
+ ...document.querySelectorAll('[data-slot="aui_thread-viewport"] [data-slot="aui_assistant-message-root"]')
+ ] as HTMLElement[]
+ )
+ .filter(el => el.getClientRects().length > 0 && el.innerText.includes(m))
+ .map(el => ({
+ count: (el.innerText.match(re) ?? []).length,
+ text: el.innerText.replace(/\s+/g, ' ').slice(0, 300)
+ }))
+ }, marker)
+}
+
+async function expectPaintedOnce(page: Page, marker: string, label: string) {
+ await expect
+ .poll(() => bubblesHolding(page, marker), { timeout: 30_000, message: `${label}: ${marker} in one bubble, once` })
+ .toEqual([expect.objectContaining({ count: 1 })])
+}
+
+async function withApp(
+ label: string,
+ interim: boolean,
+ body: (ctx: {
+ app: ElectronApplication
+ page: Page
+ provider: ScriptedProvider
+ sandbox: CoreSandbox
+ ws: WsRecorder
+ }) => Promise<void>
+) {
+ const provider = await startScriptedProvider()
+ const sandbox = createCoreSandbox(label)
+ writeProviderHome(sandbox.hermesHome, provider.url, config(interim))
+ const { app, page } = await launchCoreApp(coreAppEnv(sandbox))
+ const ws = recordWebSockets(page)
+
+ try {
+ await waitForInteractive(app, page)
+ await installDuplicateSampler(page)
+ await body({ app, page, provider, sandbox, ws })
+ } finally {
+ await app.close().catch(() => undefined)
+ await provider.close()
+ sandbox.cleanup()
+ }
+}
+
+interface Turn {
+ n: number
+ label: string
+ steps: Step[]
+ /** Markers whose text must be on screen exactly once, in one bubble. */
+ once: string[]
+}
+
+const TURNS: Turn[] = [
+ {
+ n: 1,
+ label: 'answer beside a silent todo_list, empty follow-up',
+ steps: [{ text: words(A(1), 'answered', 'beside', 'a', 'todo'), toolCalls: [todo('t1')] }, { text: [] }],
+ once: [A(1)]
+ },
+ {
+ n: 2,
+ label: 'answer beside memory, empty follow-up',
+ steps: [{ text: words(A(2), 'answered', 'beside', 'memory'), toolCalls: [memory('t2')] }, { text: [] }],
+ once: [A(2)]
+ },
+ {
+ n: 3,
+ label: 'a substantive tool round, then the answer beside todo_list',
+ steps: [
+ { text: words(AI(3), 'looking', 'first'), toolCalls: [echo('t3')] },
+ { text: words(A(3), 'answered', 'after', 'looking'), toolCalls: [todo('t3')] },
+ { text: [] }
+ ],
+ once: [AI(3), A(3)]
+ },
+ {
+ n: 4,
+ label: 'control: a different final after a tool',
+ steps: [
+ { text: words(AI(4), 'checking'), toolCalls: [echo('t4')] },
+ { text: words(A(4), 'the', 'real', 'answer') }
+ ],
+ once: [AI(4), A(4)]
+ }
+]
+
+for (const interim of [true, false]) {
+ test(`a reply already streamed before the last tool renders once (interim seal ${interim ? 'on' : 'off'})`, async () => {
+ await withApp(`reply-once-${interim ? 'seal' : 'noseal'}`, interim, async ({ app, page, provider, ws }) => {
+ const session: OracleTarget = { sessionId: '', expectUserMarkers: [] }
+
+ for (const turn of TURNS) {
+ await test.step(turn.label, async () => {
+ provider.script(U(turn.n), turn.steps)
+ await send(page, `${U(turn.n)} ${turn.label}`, 'Enter', ws)
+ await settled(page, ws, turn.once.at(-1)!, provider)
+ session.sessionId ||= await currentSessionId(page)
+ session.expectUserMarkers.push(U(turn.n))
+
+ for (const marker of turn.once) {
+ await expectPaintedOnce(page, marker, `live: ${turn.label}`)
+ }
+
+ await assertTranscriptOracle(page, ws, provider, session, `live: ${turn.label}`)
+ })
+ }
+
+ await test.step('reload: history renders every reply once', async () => {
+ await page.reload()
+ await waitForInteractive(app, page)
+ await expect(viewport(page)).toContainText(A(4), { timeout: 60_000 })
+ await installDuplicateSampler(page)
+
+ for (const turn of TURNS) {
+ for (const marker of turn.once) {
+ await expectPaintedOnce(page, marker, `reload: ${turn.label}`)
+ }
+ }
+
+ await assertTranscriptOracle(page, ws, provider, session, 'after reload')
+ })
+ })
+ })
+}
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
index 73f24b3af68..7ce9b6af0e1 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
@@ -373,7 +373,8 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {
occurredAt,
payload?.persisted_turn,
Boolean(payload?.response_transformed),
- typeof payload?.status === 'string' ? payload.status : undefined
+ typeof payload?.status === 'string' ? payload.status : undefined,
+ payload?.response_reused === true
)
// Onboarding's first build: between turns is the only moment Setup may
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/types.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/types.ts
index 0bde5ab7883..0cb8b6e24a3 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/types.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/types.ts
@@ -23,7 +23,8 @@ export interface GatewayEventDeps {
occurredAt?: number,
persistedTurn?: PersistedTurn | null,
responseTransformed?: boolean,
- status?: string
+ status?: string,
+ responseReused?: boolean
) => void
failAssistantMessage: (
sessionId: string,
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.ts
index 5c9911053fd..eabba2cfdbb 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
@@ -13,6 +13,8 @@ import {
completeOpenTimelineParts,
type GatewayEventPayload,
mergeFinalAssistantText,
+ normalizeWs,
+ partsText,
reasoningPart,
renderMediaTags,
sealOpenToolParts,
@@ -725,7 +727,8 @@ export function useMessageStream({
occurredAt = Date.now() / 1000,
persistedTurn?: PersistedTurn | null,
responseTransformed?: boolean,
- status?: string
+ status?: string,
+ responseReused?: boolean
) => {
let shouldHydrate = false
@@ -760,6 +763,8 @@ export function useMessageStream({
// bubble failed, instead of stripping the text.
const keepFailedPartialText = Boolean(failure?.partial && finalText)
const interimBoundaryPending = state.interimBoundaryPending
+ // A failed turn's text is the retained buffer, never a reused response.
+ const reusedResponse = Boolean(responseReused && finalText && !completionError)
// Wall-clock seconds this turn actually ran (message.start stamped
// turnStartedAt). Read BEFORE the state return below nulls it.
@@ -768,6 +773,16 @@ export function useMessageStream({
: undefined
const replaceTextPart = (parts: ChatMessagePart[], interim: boolean) => {
+ // The backend names this final a response the turn already delivered
+ // (it streamed before the bubble's last tool, or was sealed as an
+ // interim): every word is on screen. Settle as is; a text merge
+ // bounded at the last tool row would paint it a second time. Only
+ // when this bubble does hold it — a bubble that lost those deltas
+ // (reconnect) still takes the text through the normal merge.
+ if (reusedResponse && normalizeWs(partsText(parts)).includes(normalizeWs(finalText))) {
+ return parts
+ }
+
const visibleFinalText = stripGeneratedImageEchoes(finalText, generatedImageEchoSources(parts)).trim()
// Partial terminal errors carry the whole retained assistant buffer,
@@ -898,10 +913,9 @@ export function useMessageStream({
const index = fallbackIndex
const existing = prev[index]
- const existingText = chatMessageText({
- ...existing,
- parts: existing.interim || keepFailedPartialText ? existing.parts : currentResponseParts(existing.parts)
- }).trim()
+ const existingText = partsText(
+ existing.interim || keepFailedPartialText ? existing.parts : currentResponseParts(existing.parts)
+ ).trim()
// The last assistant row is a sealed interim (a tool-call turn or a
// verify-on-stop candidate — `message.interim` fires for BOTH, see
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/reused-final-after-tool.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/reused-final-after-tool.test.tsx
new file mode 100644
index 00000000000..e2d7a9dd5e0
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/reused-final-after-tool.test.tsx
@@ -0,0 +1,71 @@
+import { cleanup } from '@testing-library/react'
+import { afterEach, expect, it } from 'vitest'
+
+import { chatMessageText } from '@/lib/chat-messages'
+
+import { type GatewayFrame, playFrames } from './test-harness'
+
+// The housekeeping-tool fallback ends a turn on the answer the model streamed
+// BEFORE its tool call; the backend names that final `response_reused`. The
+// merge bounds "the current response" at the bubble's last tool row, so the
+// final was appended after the tool: the reply twice in one bubble, with
+// nothing between the copies when the tool is silent (todo_list).
+
+const SID = 'reused-final'
+const ANSWER = 'Here is the answer.'
+
+afterEach(cleanup)
+
+const toolRound = (id: string, name: string): GatewayFrame[] => [
+ ['tool.start', { name, tool_id: id, args: {} }],
+ ['tool.complete', { name, tool_id: id, result: 'ok' }]
+]
+
+const reused = { text: ANSWER, response_previewed: true, response_reused: true }
+
+const texts = async (frames: GatewayFrame[]) =>
+ (await playFrames(SID, [['message.start', {}], ...frames])).map(message => chatMessageText(message).trim())
+
+it.each([
+ ['a silent todo_list, no interim seal', [['message.delta', { text: ANSWER }], ...toolRound('m', 'todo_list')]],
+ [
+ 'a visible memory row, sealed interim',
+ [
+ ['message.delta', { text: ANSWER }],
+ ['message.interim', { text: ANSWER, already_streamed: true }],
+ ...toolRound('m', 'memory')
+ ]
+ ],
+ [
+ 'an earlier tool round in the same bubble',
+ [
+ ['message.delta', { text: 'Let me look.' }],
+ ...toolRound('t', 'terminal'),
+ ['message.delta', { text: `\n\n${ANSWER}` }],
+ ...toolRound('m', 'todo_list')
+ ]
+ ]
+] as [string, GatewayFrame[]][])('a reused final after %s settles the reply once', async (_label, frames) => {
+ const all = (await texts([...frames, ['message.complete', reused]])).join('\n')
+
+ expect(all.split(ANSWER).length - 1).toBe(1)
+})
+
+it('a reused final whose deltas never reached this window still paints the reply', async () => {
+ // Reconnect shape: the window missed the streamed answer. Settling "as is"
+ // would leave the bubble without the reply.
+ expect(await texts([...toolRound('m', 'todo_list'), ['message.complete', reused]])).toEqual([ANSWER])
+})
+
+it('the same words in a second response are not a reused final: both stay', async () => {
+ const all = (
+ await texts([
+ ['message.delta', { text: 'Done.' }],
+ ...toolRound('t', 'terminal'),
+ ['message.delta', { text: '\n\nDone.' }],
+ ['message.complete', { text: 'Done.' }]
+ ])
+ ).join('\n')
+
+ expect(all.split('Done.').length - 1).toBe(2)
+})
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/test-harness.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/test-harness.tsx
index 33b1937d7a1..aae720f349d 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/test-harness.tsx
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/test-harness.tsx
@@ -1,6 +1,6 @@
-import type { GatewayEvent } from '@hermes/shared'
+import type { GatewayEvent, GatewayEventName } from '@hermes/shared'
import { QueryClient } from '@tanstack/react-query'
-import { render } from '@testing-library/react'
+import { act, render } from '@testing-library/react'
import { useEffect, useRef } from 'react'
import { vi } from 'vitest'
@@ -15,6 +15,8 @@ export interface MessageStreamHarnessOptions extends Partial<Parameters<typeof u
states?: Map<string, ClientSessionState>
}
+export type GatewayFrame = [GatewayEventName, Record<string, unknown>]
+
export interface MessageStreamHarness {
/** Feed a gateway event into the mounted hook. */
handleEvent: (event: GatewayEvent) => void
@@ -132,3 +134,15 @@ export function renderMessageStream(
}
}
}
+
+/** Mount the hook, play `frames` for one session in order, and return that
+ * session's visible assistant messages. Callers still own `cleanup()`. */
+export async function playFrames(sessionId: string, frames: GatewayFrame[]) {
+ const stream = renderMessageStream(sessionId)
+
+ for (const [type, payload] of frames) {
+ await act(() => stream.handleEvent({ type, payload, session_id: sessionId }))
+ }
+
+ return stream.state().messages.filter(message => message.role === 'assistant' && !message.hidden)
+}
diff --git a/apps/desktop/src/lib/chat-messages/index.ts b/apps/desktop/src/lib/chat-messages/index.ts
index dd4309bce11..73f646c1b07 100644
--- a/apps/desktop/src/lib/chat-messages/index.ts
+++ b/apps/desktop/src/lib/chat-messages/index.ts
@@ -11,6 +11,7 @@ export {
finalizeInterruptedMessages,
mergeFinalAssistantText,
normalizeWs,
+ partsText,
reasoningPart,
reasoningTextFromDetails,
renderMediaTags,
diff --git a/apps/desktop/src/lib/chat-messages/parts.ts b/apps/desktop/src/lib/chat-messages/parts.ts
index 4290759a8c1..dd468f9b1fa 100644
--- a/apps/desktop/src/lib/chat-messages/parts.ts
+++ b/apps/desktop/src/lib/chat-messages/parts.ts
@@ -306,13 +306,17 @@ export function assistantTextPart(text: string, timestamp?: number): ChatMessage
return textPart(renderMediaTags(text), timestamp)
}
-export function chatMessageText(message: ChatMessage): string {
- return message.parts
+export function partsText(parts: ChatMessagePart[]): string {
+ return parts
.filter((part): part is Extract<ChatMessagePart, { type: 'text' }> => part.type === 'text')
.map(part => part.text)
.join('')
}
+export function chatMessageText(message: ChatMessage): string {
+ return partsText(message.parts)
+}
+
export interface UnspokenTurnSpeech {
/** First unspoken assistant bubble — stable for the turn, the live speech session binds to it. */
id: string
@@ -465,12 +469,7 @@ export function mergeFinalAssistantText(
const dedupeReference = normalizeWs(finalText)
- const streamedText = normalizeWs(
- parts
- .filter((part): part is Extract<ChatMessagePart, { type: 'text' }> => part.type === 'text')
- .map(part => part.text)
- .join('')
- )
+ const streamedText = normalizeWs(partsText(parts))
// An authoritative final that is exactly the concatenation of streamed text
// confirms the content without erasing text↔reasoning activity boundaries.
@@ -486,10 +485,7 @@ export function mergeFinalAssistantText(
if (lastToolIndex >= 0) {
const earlier = parts.slice(0, lastToolIndex + 1)
- const earlierText = earlier
- .filter((part): part is Extract<ChatMessagePart, { type: 'text' }> => part.type === 'text')
- .map(part => part.text)
- .join('')
+ const earlierText = partsText(earlier)
// Some terminal frames carry cumulative text. Strip only an exact prefix;
// fuzzy similarity is not proof that two assistant messages are the same.
diff --git a/apps/desktop/src/lib/chat-messages/types.ts b/apps/desktop/src/lib/chat-messages/types.ts
index 141213298dd..a50858d2bf9 100644
--- a/apps/desktop/src/lib/chat-messages/types.ts
+++ b/apps/desktop/src/lib/chat-messages/types.ts
@@ -221,6 +221,8 @@ export type GatewayEventPayload = {
// message.complete — a transform_llm_output hook rewrote the final text after streaming;
// it authoritatively replaces the current turn's streamed text even without a prefix match.
response_transformed?: MessageCompletePayload['response_transformed']
+ // message.complete — `text` is a response this turn already delivered: it adds no text.
+ response_reused?: MessageCompletePayload['response_reused']
persisted_turn?: PersistedTurn | null
// message.complete — history-commit note the gateway surfaced instead of dropping.
warning?: string