The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): drop superseded-turn delta orphans at message.start Closes #119543
finn7637c0b206cc9ef
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.tsxnew file mode 100644index 00000000000..77ff0407584--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-message-stream/background-review-interrupt.test.tsx@@ -0,0 +1,99 @@+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.+//+// 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+// materialized into the transcript.+import { act, cleanup } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'++import { chatMessageText } from '@/lib/chat-messages'++import { renderMessageStream, type MessageStreamHarness } from './test-harness'+import { STREAM_DELTA_FLUSH_MS } from './utils'++const SID = 'background-review-interrupt-session'+const STALE = 'previous answer fragment'+const LIVE = 'new reply'++let stream: MessageStreamHarness++async function mountHarness() {+ vi.useFakeTimers()+ stream = renderMessageStream(SID)+ await act(async () => {+ await Promise.resolve()+ })+}++const flushDeltas = async () => {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(STREAM_DELTA_FLUSH_MS)+ })+}++const emit = (event: GatewayEvent) => act(() => stream.handleEvent(event))++const assistantTexts = () =>+ (stream.state()?.messages ?? [])+ .filter(message => message.role === 'assistant' && !message.hidden)+ .map(message => chatMessageText(message))++describe('background-review interrupt must not paint stale bytes into the next turn (#119543)', () => {+ afterEach(() => {+ cleanup()+ vi.useRealTimers()+ vi.restoreAllMocks()+ })++ it('drops a superseded-turn straggler queued before the new message.start', async () => {+ await mountHarness()++ // Turn A runs to completion and settles.+ emit({ payload: {}, session_id: SID, type: 'message.start' })+ emit({ payload: { text: STALE }, session_id: SID, type: 'message.delta' })+ await flushDeltas()+ emit({ payload: { text: STALE }, session_id: SID, type: 'message.complete' })+ 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.+ emit({ payload: { text: STALE }, session_id: SID, type: 'message.delta' })++ // New turn starts: the orphan must be dropped at the boundary, not+ // painted. Then the aborted review's turn-end signal races in.+ emit({ payload: {}, session_id: SID, type: 'message.start' })+ emit({ payload: { running: false }, session_id: SID, type: 'session.info' })++ // Turn B streams and completes normally.+ emit({ payload: { text: LIVE }, session_id: SID, type: 'message.delta' })+ await flushDeltas()+ emit({ payload: { text: LIVE }, session_id: SID, type: 'message.complete' })++ // Exactly turn A and turn B — no stale bubble seeded between them and no+ // stale fragment merged into the new reply.+ expect(assistantTexts()).toEqual([STALE, LIVE])+ })++ it('still flushes a live previous turn at message.start (steer keeps its text)', async () => {+ await mountHarness()++ // Turn A is still streaming when the next message.start arrives (steer /+ // chained start mid-turn): its queued bytes are live output of the bubble+ // on screen and must be kept.+ emit({ payload: {}, session_id: SID, type: 'message.start' })+ emit({ payload: { text: 'first half ' }, session_id: SID, type: 'message.delta' })+ emit({ payload: {}, session_id: SID, type: 'message.start' })++ expect(chatMessageText(stream.state()?.messages.at(-1)!)).toBe('first half ')+ })+})diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.tsindex 6432dfdfe1d..7773e7b1e5c 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts@@ -251,6 +251,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {deps.failAssistantMessage,deps.finalizeInterimAssistantMessage,deps.flushQueuedDeltas,+ deps.dropQueuedDeltas,deps.hydrateFromStoredSession,deps.lastCwdInfoSessionRef,deps.nativeSubagentSessionsRef,diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.test.tsindex a5612b1cc89..a792be8fd04 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.test.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.test.ts@@ -23,6 +23,7 @@ function context(type: GatewayEventName): GatewayEventContext {failAssistantMessage: vi.fn(),finalizeInterimAssistantMessage: vi.fn(),flushQueuedDeltas: vi.fn(),+ dropQueuedDeltas: vi.fn(),hydrateFromStoredSession: vi.fn(async () => undefined),lastCwdInfoSessionRef: { current: null },nativeSubagentSessionsRef: { current: new Set() },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.tsindex f834128cdb9..8ffb1dd1f4a 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@@ -77,6 +77,7 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {completeAssistantMessage,finalizeInterimAssistantMessage,flushQueuedDeltas,+ dropQueuedDeltas,nativeSubagentSessionsRef,sessionStateByRuntimeIdRef,updateSessionState@@ -87,7 +88,17 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {return true}- flushQueuedDeltas(sessionId)+ // 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.+ if (sessionStateByRuntimeIdRef.current.get(sessionId)?.turnLive) {+ flushQueuedDeltas(sessionId)+ } else {+ dropQueuedDeltas(sessionId)+ }pruneFinishedSessionSubagents(sessionId)setSessionCompacting(sessionId, false)compactedTurnRef.current.delete(sessionId)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.tsindex d5e6217b676..d7b40035c74 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@@ -30,6 +30,7 @@ export interface GatewayEventDeps {surface?: ErrorSurface | null) => voidflushQueuedDeltas: (sessionId?: string) => void+ dropQueuedDeltas: (sessionId?: string) => voidfinalizeInterimAssistantMessage: (sessionId: string, text: string, occurredAt?: number) => voidhydrateFromStoredSession: (attempts?: number,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 b6bffb47a87..82317a31468 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@@ -257,6 +257,21 @@ export function useMessageStream({[mutateStream])+ // Turn-boundary orphan drop (#119543): discard queued bytes without+ // painting them. Used when a new turn starts while no turn is live — the+ // queue can only hold stragglers of the superseded attempt then.+ const dropQueuedDeltas = useCallback((sessionId?: string) => {+ const queue = queuedDeltasRef.current++ if (sessionId) {+ queue.delete(sessionId)++ return+ }++ queue.clear()+ }, [])+const scheduleDeltaFlush = useCallback(() => {if (flushHandleRef.current !== null) {return@@ -1000,6 +1015,7 @@ export function useMessageStream({completeAssistantMessage,failAssistantMessage,flushQueuedDeltas,+ dropQueuedDeltas,finalizeInterimAssistantMessage,hydrateFromStoredSession,queryClient,diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/steering-recovery.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/steering-recovery.test.tsxindex 8f7e444bb38..3b994b36755 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/steering-recovery.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/steering-recovery.test.tsx@@ -355,6 +355,7 @@ it.each(rebuiltRuntimeCases)(completeAssistantMessage: vi.fn(),failAssistantMessage: vi.fn(),flushQueuedDeltas: vi.fn(),+ dropQueuedDeltas: vi.fn(),finalizeInterimAssistantMessage: vi.fn(),hydrateFromStoredSession: vi.fn(async () => undefined),queryClient: new QueryClient(),