Skip to content

The agent that grows with you

fix(desktop): settle a heartbeat-reordered complete onto its own bubble

brooklyn!d9a6f25a55b0
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/background-review-interrupt.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/background-review-interrupt.test.tsx
index 77ff0407584..904d33fd036 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/background-review-interrupt.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/background-review-interrupt.test.tsx
@@ -1,12 +1,12 @@
import type { GatewayEvent } from '@hermes/shared'
// Repro for #119543: user sends a new message while the previous turn's
-// `background_review` fork is still in flight. The backend supersedes the
-// review (hard interrupt, socket shutdown) and its turn-end signal can race
-// the new turn's `message.start`. A straggler delta from the superseded
-// attempt may still sit in the per-session delta queue when the new turn
-// starts. Flushing it then seeds a bubble the new turn inherits (or that
-// settles beside it), painting a stale duplicate of the previous reply into
-// the transcript. Restart clears it because it was never persisted.
+// `background_review` fork is still in flight. The fork itself emits nothing
+// to the desktop, but the supersede window is where the previous turn's own
+// frames can arrive reordered: a delta that lands after that turn settled
+// still sits in the per-session queue when the new turn starts. Flushing it
+// then seeds a bubble the new turn inherits (or that settles beside it),
+// painting a stale duplicate of the previous reply into the transcript.
+// Restart clears it because it was never persisted.
//
// Spec: bytes queued BEFORE `message.start` while no turn is live are
// orphans of a dead attempt and must be dropped at the boundary — never
@@ -16,7 +16,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { chatMessageText } from '@/lib/chat-messages'
-import { renderMessageStream, type MessageStreamHarness } from './test-harness'
+import { type MessageStreamHarness, renderMessageStream } from './test-harness'
import { STREAM_DELTA_FLUSH_MS } from './utils'
const SID = 'background-review-interrupt-session'
@@ -64,9 +64,8 @@ describe('background-review interrupt must not paint stale bytes into the next t
expect(assistantTexts()).toEqual([STALE])
expect(stream.state()?.streamId).toBeNull()
- // A straggler from the superseded background-review attempt lands in the
- // delta queue after turn A settled (abort unblocking the reader) and has
- // not flushed yet when the user sends the next message.
+ // A reordered delta from turn A lands in the queue after turn A settled
+ // and has not flushed yet when the user sends the next message.
emit({ payload: { text: STALE }, session_id: SID, type: 'message.delta' })
// New turn starts: the orphan must be dropped at the boundary, not
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 8ffb1dd1f4a..e11d496a87b 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
@@ -89,16 +89,17 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {
}
// Turn-boundary orphan drop (#119543): when no turn is live, anything
- // still queued belongs to the superseded attempt (straggler bytes the
- // background-review abort released racing the new turn) — flushing it
- // would seed a bubble the new turn inherits, painting a stale duplicate
- // of the previous reply. A still-live previous turn (steer) keeps the
- // flush: those bytes are real output of the bubble on screen.
+ // still queued belongs to a turn that already ended (a delta reordered
+ // behind its own complete or heartbeat). Flushing it would seed a bubble
+ // the new turn inherits, painting a stale duplicate of the previous
+ // reply. A still-live previous turn (steer) keeps the flush: those bytes
+ // are real output of the bubble on screen.
if (sessionStateByRuntimeIdRef.current.get(sessionId)?.turnLive) {
flushQueuedDeltas(sessionId)
} else {
dropQueuedDeltas(sessionId)
}
+
pruneFinishedSessionSubagents(sessionId)
setSessionCompacting(sessionId, false)
compactedTurnRef.current.delete(sessionId)
@@ -143,13 +144,9 @@ 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,
+ // A new turn is a new occurrence: the previous turn's late terminal
+ // frame (#119569) can no longer claim its heartbeat-settled bubble.
+ heartbeatSettledStreamId: 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 ef543d4a6eb..e19dd4dbd4e 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
@@ -364,22 +364,20 @@ export function handleSessionInfoEvent(ctx: GatewayEventContext): boolean {
// so submitPrompt and the slash dispatcher silently returned false
// and the session accepted no further input.
//
- // 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.
+ // The terminal message.complete can also just be reordered behind
+ // this heartbeat (#119569). The bubble still settles here, but a
+ // stream bubble that kept streamed output is remembered so the late
+ // frame settles onto it instead of appending a duplicate. That
+ // turn's output is on screen, so it skips the stored-history
+ // hydrate too: fired now, it can race the gateway commit and drop
+ // the just-delivered reply from view until reload.
+ const messages = finalizeInterruptedMessages(state.messages, state.streamId, occurredAt)
+
+ const heartbeatSettledStreamId =
+ state.streamId && messages.some(message => message.id === state.streamId) ? state.streamId : null
+
endedLiveTurn = state.turnLive
- const streamOpen = state.streamId !== null
- recoveredIncompleteTurn = state.turnLive && !streamOpen
+ recoveredIncompleteTurn = state.turnLive && !heartbeatSettledStreamId
return {
...state,
@@ -394,9 +392,10 @@ export function handleSessionInfoEvent(ctx: GatewayEventContext): boolean {
// finalizeInterruptedMessages un-pends kept text and drops
// empty placeholders; on the normal path message.complete
// already settled everything and this is a no-op.
- messages: finalizeInterruptedMessages(state.messages, state.streamId, occurredAt),
+ heartbeatSettledStreamId,
+ messages,
pendingBranchGroup: null,
- streamId: streamOpen ? state.streamId : null,
+ streamId: null,
turnStartedAt: null,
turnLive: false
}
@@ -413,16 +412,13 @@ export function handleSessionInfoEvent(ctx: GatewayEventContext): boolean {
// not one per tick.
scheduleSessionsRefresh()
- // 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.
+ // The transcript catch-up IS scoped, and skipped when a streamed
+ // bubble survived the settle (its late complete owns it, see above).
+ // 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/index.ts b/apps/desktop/src/app/session/hooks/use-message-stream/index.ts
index 82317a31468..1e65fc3baf4 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
@@ -645,7 +645,7 @@ export function useMessageStream({
}
}
- const streamId = state.streamId
+ const streamId = state.streamId ?? state.heartbeatSettledStreamId ?? null
const finalText = renderMediaTags(text).trim()
// Structured failure from the terminal frame wins over the legacy text
// heuristic ("Error: <provider detail>" texts don't match the regexes).
@@ -898,6 +898,7 @@ export function useMessageStream({
...state,
messages: nextMessages,
adoptedRunningTurn: false,
+ heartbeatSettledStreamId: null,
streamId: null,
pendingBranchGroup: null,
awaitingResponse: false,
diff --git a/apps/desktop/src/app/types.ts b/apps/desktop/src/app/types.ts
index 59c889d1ba1..02294c81ea5 100644
--- a/apps/desktop/src/app/types.ts
+++ b/apps/desktop/src/app/types.ts
@@ -177,6 +177,11 @@ export interface ClientSessionState {
interrupted: boolean
/** True after message.interim finalized a bubble in the still-running turn. */
interimBoundaryPending: boolean
+ /** Stream bubble a running=false heartbeat settled before its turn's
+ * message.complete arrived. The frame can be reordered behind the
+ * heartbeat (#119569); when it lands it settles onto this bubble instead of
+ * appending a duplicate. Cleared by the next message.start or complete. */
+ heartbeatSettledStreamId?: null | string
/** A blocking clarify prompt is waiting on the user for this session. Drives
* the sidebar "needs input" indicator; cleared when the turn resumes/ends. */
needsInput: boolean