Skip to content

The agent that grows with you

fix(desktop): keep open stream across reordered running=false heartbeat (Closes #119569)

finn763384e4a54f936
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 910b0b87851..f834128cdb9 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
@@ -132,6 +132,13 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {
// Backend accepted the turn — the no-payload settle gate below may
// now treat a running=false heartbeat as a real turn end.
turnLive: true,
+ // A new turn owns a new stream. Normally the previous complete
+ // already nulled this; the reset matters when the previous turn
+ // died without its terminal frame (gateway crash) and the
+ // running=false recovery deliberately kept the id so a reordered
+ // late complete can still settle onto its bubble (#119569) — without
+ // the reset the next turn's deltas would append into that stale row.
+ streamId: null,
// Keep the submit-time seed (submit.ts seedOptimistic) — resetting
// here would hide the submit→accept round trip from the timer.
// Backend-originated turns (queue drain elsewhere, goal follow-up)
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts
index 84fa3b54f95..ef543d4a6eb 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts
@@ -281,6 +281,10 @@ export function handleSessionInfoEvent(ctx: GatewayEventContext): boolean {
// message never arrived. The updater is invoked exactly once,
// synchronously, by updateSessionState.
let recoveredIncompleteTurn = false
+ // Set when THIS event ends a confirmed live turn, whether or not its
+ // terminal message arrived. Drives the sidebar refresh; the hydrate
+ // below stays gated on recoveredIncompleteTurn.
+ let endedLiveTurn = false
const nextState = updateSessionState(
sessionId,
@@ -359,7 +363,23 @@ export function handleSessionInfoEvent(ctx: GatewayEventContext): boolean {
// per-session busy flag is authoritative for isTargetSessionBusy,
// so submitPrompt and the slash dispatcher silently returned false
// and the session accepted no further input.
- recoveredIncompleteTurn = state.turnLive
+ //
+ // A turn whose stream is still OPEN here is NOT incomplete: its
+ // terminal message.complete may simply be reordered behind this
+ // heartbeat (#119569). Treating it as broken finalizes the bubble
+ // early (streamId=null), so the late complete misses its row and
+ // appends a duplicate — or a stored-history hydrate here races
+ // the gateway commit and drops the just-delivered reply from view
+ // until reload. Release the turn flags (running=false is
+ // authoritative) but leave the open stream for the complete frame
+ // to settle; a complete that never arrives leaves visible
+ // streamed text, and the next message.start re-seeds the stream.
+ // A sealed stream (streamId null — interim seal or an already
+ // settled bubble) has no in-flight owner, so the classic
+ // incomplete-turn recovery below still applies in full.
+ endedLiveTurn = state.turnLive
+ const streamOpen = state.streamId !== null
+ recoveredIncompleteTurn = state.turnLive && !streamOpen
return {
...state,
@@ -376,7 +396,7 @@ export function handleSessionInfoEvent(ctx: GatewayEventContext): boolean {
// already settled everything and this is a no-op.
messages: finalizeInterruptedMessages(state.messages, state.streamId, occurredAt),
pendingBranchGroup: null,
- streamId: null,
+ streamId: streamOpen ? state.streamId : null,
turnStartedAt: null,
turnLive: false
}
@@ -384,21 +404,26 @@ export function handleSessionInfoEvent(ctx: GatewayEventContext): boolean {
payload?.stored_session_id || undefined
)
- if (recoveredIncompleteTurn) {
+ if (endedLiveTurn) {
// Stays unscoped, like the settle above: a background session's
// sidebar row has to drop its working dot without the user opening
// it. This fires on the recovery edge only — once turnLive is false
// the `state.busy === busy` guard above short-circuits every later
- // heartbeat — so it costs one coalesced refresh per broken turn,
+ // heartbeat — so it costs one coalesced refresh per ended turn,
// not one per tick.
scheduleSessionsRefresh()
- // The transcript catch-up IS scoped. The stream died, but the turn
- // itself may have completed and been persisted, so refetch stored
- // history for the session actually on screen; a background session
- // reads its history when the user opens it, and hydrating every one
- // of them here would fan a REST call out per idle session.
- if (isActiveEvent) {
+ // The transcript catch-up IS scoped, and only for turns with no open
+ // stream. A turn with live output owns its settle: the complete
+ // frame is likely just reordered behind this heartbeat (#119569),
+ // and a hydrate now can race the gateway commit and drop the
+ // just-delivered reply from view until reload. The stream died,
+ // but the turn itself may have completed and been persisted, so
+ // refetch stored history for the session actually on screen; a
+ // background session reads its history when the user opens it, and
+ // hydrating every one of them here would fan a REST call out per
+ // idle session.
+ if (recoveredIncompleteTurn && isActiveEvent) {
void hydrateFromStoredSession(3, nextState.storedSessionId, sessionId)
}
}
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/heartbeat-complete-reorder.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/heartbeat-complete-reorder.test.tsx
new file mode 100644
index 00000000000..8e1e9b834cf
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/heartbeat-complete-reorder.test.tsx
@@ -0,0 +1,202 @@
+import type { GatewayEventName } from '@hermes/shared'
+import { QueryClient } from '@tanstack/react-query'
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { useRef } from 'react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+import { type ChatMessage, chatMessageText } from '@/lib/chat-messages'
+import { clearInFlightTurnJournal } from '@/lib/inflight-turn-journal'
+import { $messages, setActiveSessionId, setMessages } from '@/store/session'
+import { $sessionStates } from '@/store/session-states'
+
+import { usePromptActions } from '../use-prompt-actions'
+import { useSessionStateCache } from '../use-session-state-cache'
+
+import { useMessageStream } from './index'
+
+const SID = 'race119569-runtime'
+const STORED = 'race119569-stored'
+const noop = async () => undefined
+
+const requestGateway = async <T,>(method: string): Promise<T> =>
+ (method === 'prompt.submit' ? { status: 'started' } : { status: 'redirected' }) as T
+
+function mount() {
+ const queryClient = new QueryClient()
+ const hydrate = vi.fn(noop)
+
+ const hook = renderHook(() => {
+ const busyRef = useRef(false)
+
+ const cache = useSessionStateCache({
+ activeSessionId: SID,
+ selectedStoredSessionId: STORED,
+ busyRef,
+ setAwaitingResponse: () => undefined,
+ setBusy: value => {
+ busyRef.current = value
+ },
+ setMessages
+ })
+
+ const stream = useMessageStream({
+ activeSessionIdRef: cache.activeSessionIdRef,
+ sessionStateByRuntimeIdRef: cache.sessionStateByRuntimeIdRef,
+ updateSessionState: cache.updateSessionState,
+ queryClient,
+ hydrateFromStoredSession: hydrate,
+ refreshHermesConfig: noop,
+ refreshSessions: noop
+ })
+
+ const actions = usePromptActions({
+ activeSessionId: SID,
+ activeSessionIdRef: cache.activeSessionIdRef,
+ branchCurrentSession: async () => true,
+ busyRef,
+ createBackendSessionForSend: async () => SID,
+ getRoutedStoredSessionId: () => STORED,
+ getRuntimeIdForStoredSession: () => SID,
+ getRouteToken: () => 'race-route',
+ handleSkinCommand: () => '',
+ openMemoryGraph: () => undefined,
+ refreshSessions: noop,
+ requestGateway,
+ resumeStoredSession: noop,
+ runtimeIdByStoredSessionIdRef: cache.runtimeIdByStoredSessionIdRef,
+ selectedStoredSessionIdRef: cache.selectedStoredSessionIdRef,
+ startFreshSessionDraft: () => undefined,
+ sttEnabled: false,
+ updateSessionState: cache.updateSessionState
+ })
+
+ return { cache, stream, actions }
+ })
+
+ act(() => hook.result.current.cache.ensureSessionState(SID, STORED))
+
+ return {
+ hydrate,
+ state: () => hook.result.current.cache.sessionStateByRuntimeIdRef.current.get(SID)!,
+ send: (type: GatewayEventName, payload: Record<string, unknown> = {}) =>
+ act(() => hook.result.current.stream.handleGatewayEvent({ type, payload, session_id: SID })),
+ submit: () =>
+ act(async () => {
+ expect(await hook.result.current.actions.submitText('Search flights.', { attachments: [] })).toBe(true)
+ }),
+ dispose: () => {
+ hook.unmount()
+ queryClient.clear()
+ }
+ }
+}
+
+const timeline = (messages: ChatMessage[]) => messages.map(message => [message.role, chatMessageText(message)])
+
+const flush = () =>
+ act(async () => {
+ await vi.advanceTimersByTimeAsync(50)
+ })
+
+const settle = () =>
+ act(async () => {
+ await vi.advanceTimersByTimeAsync(5000)
+ })
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ localStorage.clear()
+ $sessionStates.set({})
+ setMessages([])
+ setActiveSessionId(SID)
+})
+
+afterEach(() => {
+ cleanup()
+ clearInFlightTurnJournal(STORED)
+ vi.clearAllTimers()
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+})
+
+const FULL = 'Voos de Porto Alegre para Sao Paulo: opcao 1 ... opcao 2 ... (long reply)'
+
+async function toolHeavyTurn(h: ReturnType<typeof mount>) {
+ await h.submit()
+ await h.send('message.start')
+ await h.send('message.delta', { text: 'Searching flights ' })
+ await h.send('tool.start', { name: 'mcp__kiwi__search_flight', tool_id: 't1' })
+ await h.send('tool.complete', { name: 'mcp__kiwi__search_flight', tool_id: 't1', result: 'ok-1' })
+ await h.send('tool.start', { name: 'mcp__kiwi__search_flight', tool_id: 't2' })
+ await h.send('tool.complete', { name: 'mcp__kiwi__search_flight', tool_id: 't2', result: 'ok-2' })
+ await h.send('tool.start', { name: 'mcp__kiwi__search_flight', tool_id: 't3' })
+ await h.send('tool.complete', { name: 'mcp__kiwi__search_flight', tool_id: 't3', result: 'ok-3' })
+ await h.send('message.delta', { text: FULL })
+ await flush()
+}
+
+it('#119569 V1: tool-heavy turn keeps the just-delivered reply across complete', async () => {
+ const h = mount()
+ await toolHeavyTurn(h)
+ await h.send('message.complete', { text: `Searching flights ${FULL}` })
+ await settle()
+
+ const texts = timeline(h.state().messages)
+ const viewTexts = timeline($messages.get())
+ expect(texts.filter(([, t]) => (t as string).includes('Voos de Porto Alegre'))).toHaveLength(1)
+ expect(viewTexts).toEqual(texts)
+ h.dispose()
+})
+
+it('#119569 V2: interim-sealed tool turn keeps both segments across complete', async () => {
+ const h = mount()
+ await h.submit()
+ await h.send('message.start')
+ await h.send('message.delta', { text: 'Let me look that up.' })
+ await h.send('tool.start', { name: 'mcp__kiwi__search_flight', tool_id: 't1' })
+ await h.send('tool.complete', { name: 'mcp__kiwi__search_flight', tool_id: 't1', result: 'ok' })
+ await h.send('message.interim', { text: 'Let me look that up.', already_streamed: true })
+ await h.send('message.delta', { text: FULL })
+ await flush()
+ await h.send('message.complete', { text: FULL })
+ await settle()
+
+ const texts = timeline(h.state().messages)
+ expect(texts.filter(([, t]) => (t as string).includes('Voos de Porto Alegre'))).toHaveLength(1)
+ expect(timeline($messages.get())).toEqual(texts)
+ h.dispose()
+})
+
+it('#119569 V3: running=false heartbeat before complete must not drop the reply', async () => {
+ const h = mount()
+ await toolHeavyTurn(h)
+ // Agent-loop finally-block heartbeat wins the race against the terminal frame.
+ await h.send('session.info', { running: false, stored_session_id: STORED })
+ await h.send('message.complete', { text: `Searching flights ${FULL}` })
+ await settle()
+
+ const texts = timeline(h.state().messages)
+ // The reordered heartbeat must not orphan the late complete into a second
+ // bubble, and must not fire a stored-history hydrate that can race the
+ // gateway commit and drop the just-delivered reply from view (#119569).
+ expect(h.hydrate).not.toHaveBeenCalled()
+ expect(texts.filter(([, t]) => (t as string).includes('Voos de Porto Alegre'))).toHaveLength(1)
+ expect(timeline($messages.get())).toEqual(texts)
+ h.dispose()
+})
+
+it('#119569 V6: same-ms redelivered complete frames must not key-collide bubbles away', async () => {
+ const h = mount()
+ await toolHeavyTurn(h)
+ await h.send('message.complete', { text: `Searching flights ${FULL}` })
+ // Redelivery / retry of the terminal frame inside the same millisecond.
+ await h.send('message.complete', { text: `Searching flights ${FULL} (updated)` })
+ await settle()
+
+ const ids = h.state().messages.map(m => m.id)
+ expect(new Set(ids).size).toBe(ids.length)
+ const texts = timeline(h.state().messages)
+ expect(texts.filter(([, t]) => (t as string).includes('Voos de Porto Alegre')).length).toBeGreaterThanOrEqual(1)
+ expect(timeline($messages.get())).toEqual(texts)
+ h.dispose()
+})