The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): clear stale turn state after lost stream events
KIAgent01c0e07837c2af
diff --git a/apps/desktop/src/app/contrib/hooks/live-status-reap.test.ts b/apps/desktop/src/app/contrib/hooks/live-status-reap.test.tsindex 8b4688331c0..b5d92aa13ae 100644--- a/apps/desktop/src/app/contrib/hooks/live-status-reap.test.ts+++ b/apps/desktop/src/app/contrib/hooks/live-status-reap.test.ts@@ -1,7 +1,14 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { $selectedStoredSessionId, $unreadFinishedSessionIds } from '@/store/session'-import { $attentionSessionIds, $workingSessionIds, clearAllSessionStates } from '@/store/session-states'+import { createClientSessionState } from '@/lib/chat-runtime'+import { $activeSessionId, $selectedStoredSessionId, $unreadFinishedSessionIds } from '@/store/session'+import {+ $attentionSessionIds,+ $sessionStates,+ $workingSessionIds,+ clearAllSessionStates,+ publishSessionState+} from '@/store/session-states'import { rehydrateLiveSessionStatuses } from './use-background-sync'@@ -25,6 +32,7 @@ describe('rehydrateLiveSessionStatuses — reaping vanished runtimes', () => {vi.useRealTimers()clearAllSessionStates()$unreadFinishedSessionIds.set([])+ $activeSessionId.set(null)})it('clears a working session that disappears from the live snapshot', () => {@@ -76,4 +84,55 @@ describe('rehydrateLiveSessionStatuses — reaping vanished runtimes', () => {expect($workingSessionIds.get()).toEqual(['stored-other'])})++ it('seals open tool parts and clears awaitingResponse when a session vanishes', () => {+ const openTool = {+ type: 'tool-call',+ toolCallId: 'call-1',+ toolName: 'patch',+ args: {},+ argsText: '{}'+ } as never++ publishSessionState('runtime-tools', {+ ...createClientSessionState('stored-tools'),+ busy: true,+ awaitingResponse: true,+ messages: [+ { id: 'a1', role: 'assistant', parts: [openTool], pending: false } as never+ ]+ })++ // Keep the runtime referenced so the settled state stays in the store+ // instead of being evicted as no-longer-needed.+ $activeSessionId.set('runtime-tools')++ rehydrateLiveSessionStatuses({+ sessions: [{ id: 'runtime-tools', session_key: 'stored-tools', status: 'working' }]+ })+ rehydrateLiveSessionStatuses({ sessions: [] })++ const state = $sessionStates.get()['runtime-tools']++ expect(state.busy).toBe(false)+ expect(state.awaitingResponse).toBe(false)+ expect((state.messages[0].parts[0] as { result?: unknown }).result).toBeDefined()+ })++ it('clears a session stuck awaiting a response without the busy flag', () => {+ publishSessionState('runtime-await', {+ ...createClientSessionState('stored-await'),+ awaitingResponse: true,+ busy: false+ })++ $activeSessionId.set('runtime-await')++ rehydrateLiveSessionStatuses({+ sessions: [{ id: 'runtime-await', session_key: 'stored-await', status: 'working' }]+ })+ rehydrateLiveSessionStatuses({ sessions: [] })++ expect($sessionStates.get()['runtime-await'].awaitingResponse).toBe(false)+ })})diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.tsindex e42084999c1..1776d647101 100644--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts@@ -2,7 +2,7 @@ import { useStore } from '@nanostores/react'import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'import { getLatestSessionMessages } from '@/hermes'-import { preserveLocalAssistantErrors, toChatMessages } from '@/lib/chat-messages'+import { preserveLocalAssistantErrors, sealOpenToolParts, toChatMessages } from '@/lib/chat-messages'import { createClientSessionState } from '@/lib/chat-runtime'import { sessionMessagesSignature } from '@/lib/session-signatures'import { $changeEventsAvailable, $cronChangeTick, $sessionsChangeTick } from '@/store/live-sync'@@ -247,14 +247,19 @@ export function rehydrateLiveSessionStatuses(const existing = $sessionStates.get()[runtimeSessionId]- if (existing?.busy || existing?.needsInput) {+ if (existing?.busy || existing?.needsInput || existing?.awaitingResponse) {publishSessionState(runtimeSessionId, {...existing,awaitingResponse: false,busy: false,needsInput: false,streamId: null,- turnStartedAt: null+ turnStartedAt: null,+ // The turn ended without its completion events reaching us — a lost+ // `tool.complete` would otherwise leave a spinning tool row in an+ // idle session. Seal open tool parts the same way the settle path+ // does, so the transcript matches the state.+ messages: sealOpenToolParts(existing.messages)})}}diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.tsindex 4592653758b..238f3c9547b 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts@@ -12,7 +12,7 @@ import { translateNow } from '@/i18n'import { type GatewayEventPayload, textPart } from '@/lib/chat-messages'import { coerceGatewayText, coerceThinkingText, normalizePersonalityValue } from '@/lib/chat-runtime'import { playCompletionSound } from '@/lib/completion-sound'-import { approvalReplaySessionId, resolveGatewayEventSessionId } from '@/lib/gateway-events'+import { approvalReplaySessionId, resolveGatewayEventSessionId, UNSCOPED_STREAM_EVENT_TYPES } from '@/lib/gateway-events'import { triggerHaptic } from '@/lib/haptics'import { modelOptionsQueryKey } from '@/lib/model-options'import { isProviderSetupErrorMessage } from '@/lib/provider-setup-errors'@@ -321,6 +321,32 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {}const sessionId = route.sessionId++ // Late stragglers: an unscoped stream event attributed via the+ // active-session fallback (no pin) to a session that has no live turn+ // belongs to a turn that already ended elsewhere. Dropping it keeps the+ // previous session's tail events (a delayed `thinking.delta` or+ // `status.update`) from landing in a freshly opened chat (#43142 family:+ // busy/streaming UI inherited when switching sessions).+ if (+ sessionId &&+ !explicitSid &&+ !route.pinned &&+ event.type &&+ event.type !== 'message.start' &&+ UNSCOPED_STREAM_EVENT_TYPES.has(event.type)+ ) {+ const state = sessionStateByRuntimeIdRef.current.get(sessionId)++ const hasLiveTurn = Boolean(+ state && (state.awaitingResponse || state.busy || state.streamId || state.sawAssistantPayload)+ )++ if (!hasLiveTurn) {+ return+ }+ }+const isActiveEvent = !!sessionId && sessionId === activeSessionIdRef.currentconst replaySessionId = approvalReplaySessionId(event.type, activeSessionIdRef.current, 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.tsindex 01cf8df499a..745c95db59d 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,7 @@ import {mergeFinalAssistantText,reasoningPart,renderMediaTags,+ sealOpenToolParts,upsertToolPart} from '@/lib/chat-messages'import {@@ -666,6 +667,12 @@ export function useMessageStream({}}+ // Turn-settle reconciliation: a `tool.complete` event lost to a+ // degraded websocket leaves its tool row spinning forever. The turn is+ // provably done here — nothing can still be running — so seal any+ // tool-call parts that never saw their completion event.+ nextMessages = sealOpenToolParts(nextMessages)+const hasInlineError = nextMessages.some(m => m.role === 'assistant' && m.error && !m.hidden)const lastVisible = [...nextMessages].reverse().find(m => !m.hidden)const unresolvedUserTail = lastVisible?.role === 'user'diff --git a/apps/desktop/src/lib/chat-messages.test.ts b/apps/desktop/src/lib/chat-messages.test.tsindex fa1a6744cd9..af178036a46 100644--- a/apps/desktop/src/lib/chat-messages.test.ts+++ b/apps/desktop/src/lib/chat-messages.test.ts@@ -12,6 +12,7 @@ import {preserveLocalAssistantErrors,reasoningPart,renderMediaTags,+ sealOpenToolParts,toChatMessages,upsertToolPart} from './chat-messages'@@ -1166,3 +1167,65 @@ describe('collectUnspokenTurnSpeech', () => {expect(collectUnspokenTurnSpeech([user('u1', 'hello'), assistant('a1', '')], null)).toBeNull()})})++describe('sealOpenToolParts', () => {+ const toolPart = (over: Partial<ChatMessagePart> = {}): ChatMessagePart =>+ ({+ type: 'tool-call',+ toolCallId: 'call-1',+ toolName: 'terminal',+ args: {},+ argsText: '{}',+ ...over+ }) as ChatMessagePart++ const assistantWithParts = (parts: ChatMessagePart[], over: Partial<ChatMessage> = {}): ChatMessage =>+ ({+ id: 'a1',+ role: 'assistant',+ parts,+ ...over+ }) as ChatMessage++ it('seals open tool-call parts in settled assistant messages', () => {+ const messages = [assistantWithParts([toolPart()])]++ const next = sealOpenToolParts(messages)++ expect(next[0].parts[0]).toHaveProperty('result')+ })++ it('leaves already-completed tool parts untouched', () => {+ const done = toolPart({ result: { code: 0 } })+ const messages = [assistantWithParts([done])]++ const next = sealOpenToolParts(messages)++ expect(next[0].parts[0]).toBe(done)+ })++ it('leaves pending messages alone', () => {+ const messages = [assistantWithParts([toolPart()], { pending: true })]++ const next = sealOpenToolParts(messages)++ expect(next[0].parts[0]).not.toHaveProperty('result')+ })++ it('leaves non-tool parts untouched', () => {+ const text = { type: 'text', text: 'hello' } as ChatMessagePart+ const messages = [assistantWithParts([text, toolPart()])]++ const next = sealOpenToolParts(messages)++ expect(next[0].parts[0]).toBe(text)+ expect(next[0].parts[1]).toHaveProperty('result')+ })++ it('returns the same array reference when nothing needs sealing', () => {+ const done = toolPart({ result: { code: 0 } })+ const messages = [assistantWithParts([done])]++ expect(sealOpenToolParts(messages)).toBe(messages)+ })+})diff --git a/apps/desktop/src/lib/chat-messages.ts b/apps/desktop/src/lib/chat-messages.tsindex fa98550a006..3328672e7dd 100644--- a/apps/desktop/src/lib/chat-messages.ts+++ b/apps/desktop/src/lib/chat-messages.ts@@ -711,6 +711,47 @@ export function upsertToolPart(return next}+/**+ * Turn-settle reconciliation: close every tool-call part that never received+ * its completion event. A `tool.complete` lost to a degraded websocket+ * (reconnect, profile swap, hidden window) leaves the part without a `result`,+ * which renders as a permanently spinning tool row even though the turn itself+ * completed. A settled session cannot have tools still running, so an open+ * part at settle time is a lost event, not live work. Pending messages are+ * left alone, and no-op calls return the input array unchanged.+ */+export function sealOpenToolParts(messages: ChatMessage[]): ChatMessage[] {+ let changed = false++ const next = messages.map(message => {+ if (message.role !== 'assistant' || message.pending) {+ return message+ }++ let partChanged = false++ const parts = message.parts.map(part => {+ if (part.type !== 'tool-call' || Object.hasOwn(part, 'result')) {+ return part+ }++ partChanged = true++ return { ...part, result: {} }+ })++ if (!partChanged) {+ return message+ }++ changed = true++ return { ...message, parts }+ })++ return changed ? next : messages+}+function recordFromUnknown(value: unknown): Record<string, unknown> | null {return value && typeof value === 'object' ? (value as Record<string, unknown>) : null}diff --git a/apps/desktop/src/lib/gateway-events.test.ts b/apps/desktop/src/lib/gateway-events.test.tsindex 907acbdd80a..5ec527d0bcf 100644--- a/apps/desktop/src/lib/gateway-events.test.ts+++ b/apps/desktop/src/lib/gateway-events.test.ts@@ -43,6 +43,7 @@ describe('gateway event routing', () => {expect(started).toEqual({drop: false,nextUnscopedStreamSessionId: 'session-a',+ pinned: false,sessionId: 'session-a'})@@ -56,6 +57,7 @@ describe('gateway event routing', () => {expect(delta).toEqual({drop: false,nextUnscopedStreamSessionId: 'session-a',+ pinned: true,sessionId: 'session-a'})@@ -69,6 +71,7 @@ describe('gateway event routing', () => {expect(completed).toEqual({drop: false,nextUnscopedStreamSessionId: null,+ pinned: true,sessionId: 'session-a'})})@@ -84,6 +87,27 @@ describe('gateway event routing', () => {expect(routed).toEqual({drop: false,nextUnscopedStreamSessionId: 'session-b',+ pinned: false,+ sessionId: 'session-b'+ })+ })++ it('attributes an unpinned stream event to the active session without the pin flag', () => {+ // A late straggler (no pin left after the previous turn completed) falls+ // back to the active session. The handler drops this case when the target+ // session has no live turn — the straggler belongs to a turn that already+ // ended elsewhere (#43142 family).+ const routed = resolveGatewayEventSessionId({+ activeSessionId: 'session-b',+ eventType: 'thinking.delta',+ explicitSessionId: '',+ unscopedStreamSessionId: null+ })++ expect(routed).toEqual({+ drop: false,+ nextUnscopedStreamSessionId: null,+ pinned: false,sessionId: 'session-b'})})@@ -99,6 +123,7 @@ describe('gateway event routing', () => {expect(routed).toEqual({drop: false,nextUnscopedStreamSessionId: null,+ pinned: true,sessionId: 'session-a'})})diff --git a/apps/desktop/src/lib/gateway-events.ts b/apps/desktop/src/lib/gateway-events.tsindex c937acf50c2..6375955510d 100644--- a/apps/desktop/src/lib/gateway-events.ts+++ b/apps/desktop/src/lib/gateway-events.ts@@ -17,7 +17,12 @@ function asRecord(payload: unknown): Record<string, unknown> {* Without this, ``explicitSid || activeSessionId`` reattributes live deltas to* the newly focused chat.*/-const UNSCOPED_STREAM_EVENT_TYPES = new Set([+/** Unscoped stream events that must stay pinned to the session that received+ * ``message.start`` after the user switches chats mid-turn (#47709 / #48281).+ * Without this, ``explicitSid || activeSessionId`` reattributes live deltas to+ * the newly focused chat. Exported so the event handler can tell which events+ * are pin-eligible when deciding whether an unpinned straggler is legitimate. */+export const UNSCOPED_STREAM_EVENT_TYPES = new Set(['approval.request','browser.progress','clarify.request',@@ -67,6 +72,11 @@ export interface GatewayEventSessionRouteInput {export interface GatewayEventSessionRoute {drop: booleannextUnscopedStreamSessionId: null | string+ /** True when the event was attributed via the pinned stream session rather+ * than the active-session fallback. The caller uses this to drop late+ * stragglers: an unpinned stream event landing on a session that has no+ * live turn belongs to a turn that already ended elsewhere. */+ pinned: booleansessionId: null | string}@@ -108,6 +118,7 @@ export function resolveGatewayEventSessionId({return {drop: false,nextUnscopedStreamSessionId,+ pinned: true,sessionId: explicitSessionId}}@@ -116,6 +127,7 @@ export function resolveGatewayEventSessionId({return {drop: true,nextUnscopedStreamSessionId: unscopedStreamSessionId,+ pinned: false,sessionId: null}}@@ -140,6 +152,7 @@ export function resolveGatewayEventSessionId({return {drop: false,nextUnscopedStreamSessionId,+ pinned: streamEvent && eventType !== 'message.start' && Boolean(unscopedStreamSessionId),sessionId}}