The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): settle a silent live turn and offer retry
brooklyn!c4ff1d89f4f9
diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.tsindex 7f4b2d0e74b..a8727c1d9c1 100644--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts@@ -29,6 +29,7 @@ import {$sessionStates,$sessionTiles,confirmReconnectSettlesExcept,+ noteSessionEvent,publishSessionState,SESSION_WATCHDOG_TIMEOUT_MS,setSessionStalled@@ -652,6 +653,13 @@ export function rehydrateLiveSessionStatuses(})}+ if (working) {+ // A poll that still lists the turn is an event. Reset the silence clock+ // so a quiet tool call is not settled; a dead backend stops answering+ // this poll and the clock runs out.+ noteSessionEvent(runtimeSessionId)+ }+if (!working) {setSessionStalled(storedSessionId, false)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 7773e7b1e5c..6693f6b0908 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@@ -13,6 +13,7 @@ import { $activeGatewayProfile, normalizeProfileKey } from '@/store/profile'import { replayPendingApproval } from '@/store/prompts'import { setSessionProviderWait } from '@/store/provider-wait'import { isSessionGone } from '@/store/session-gone-latch'+import { noteSessionEvent } from '@/store/session-states'import { setSessionDraftingTool } from '@/store/tool-drafting'import { handleDesktopBridgeEvent } from './desktop-bridge'@@ -231,9 +232,18 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {scheduleConfigRefresh}- for (const handler of HANDLERS) {- if (handler(ctx)) {- return+ try {+ for (const handler of HANDLERS) {+ if (handler(ctx)) {+ return+ }+ }+ } finally {+ // Any attributed event — including a heartbeat that does not change+ // state — proves this session is still producing. Silence after the+ // last one force-settles a dead turn, partial payload included.+ if (sessionId) {+ noteSessionEvent(sessionId)}}},diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.tsindex 1da294e4eb5..5531cb0e9ba 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -32,6 +32,8 @@ import {} from '@/components/pane-shell/tree/store'import { resolveRememberedActivePane, workspaceScopeKey } from '@/components/pane-shell/workspace-scope'import type { WorkspaceMode } from '@/contrib/types'+import type { ChatMessage } from '@/lib/chat-messages'+import type { ErrorSurface } from '@/lib/error-surface'import { stableArray } from '@/lib/stable-array'import { readJson, writeJson } from '@/lib/storage'import type { SessionInfo } from '@/types/hermes'@@ -357,6 +359,110 @@ export function setSessionStalled(storedSessionId: string | null | undefined, st// suspect. Eight minutes was the other failure — longer than a user is willing// to sit and wonder, so the hint arrived after they had already given up on it.export const SESSION_WATCHDOG_TIMEOUT_MS = 5 * 60 * 1000+// A live turn that stops producing events — including after a partial payload —+// must not wait out the presentation hint above. The clock resets on every+// session event and on a live-status poll that still reports the turn working,+// so a quiet tool call is left alone. The window outlasts the 30s live-status+// backstop: a dead backend stops both events and polls, and this settles it+// instead of leaving the spinner up. Not keyed on a model name or an error string.+export const LIVE_TURN_EVENT_SILENCE_MS = 45_000+const sessionEventSilenceTimers = new Map<string, ReturnType<typeof setTimeout>>()++function clearEventSilence(runtimeId: string) {+ const timer = sessionEventSilenceTimers.get(runtimeId)++ if (timer) {+ clearTimeout(timer)+ sessionEventSilenceTimers.delete(runtimeId)+ }+}++function isLiveTurnAwaitingEvents(state: ClientSessionState | undefined): boolean {+ return Boolean(state && (state.busy || state.awaitingResponse || state.turnLive) && !state.needsInput)+}++const SILENT_TURN_RETRY: ErrorSurface = { code: 'stream_drop', layer: 'streaming', retryable: true }++function withSilentTurnRetry(messages: ChatMessage[], streamId: string | null): ChatMessage[] {+ const occurredAt = Date.now() / 1000+ const error = 'The connection dropped before the reply finished.'+ const targetId =+ (streamId && messages.some(message => message.id === streamId) ? streamId : null) ??+ [...messages].reverse().find(message => message.role === 'assistant' && message.pending)?.id ??+ null++ const unpended = messages+ .filter(message => !(message.pending && message.parts.length === 0 && message.id !== targetId))+ .map(message =>+ message.pending || message.id === targetId ? { ...message, completedAt: occurredAt, pending: false } : message+ )++ if (targetId && unpended.some(message => message.id === targetId)) {+ return unpended.map(message =>+ message.id === targetId ? { ...message, error, errorSurface: SILENT_TURN_RETRY, pending: false } : message+ )+ }++ return [+ ...unpended,+ {+ completedAt: occurredAt,+ error,+ errorSurface: SILENT_TURN_RETRY,+ id: `assistant-interrupted-${Date.now()}`,+ parts: [],+ pending: false,+ role: 'assistant',+ timestamp: occurredAt+ }+ ]+}++function settleSilentLiveTurn(runtimeId: string) {+ const current = $sessionStates.get()[runtimeId]++ if (!current || !isLiveTurnAwaitingEvents(current)) {+ return+ }++ publishSessionState(runtimeId, {+ ...current,+ awaitingResponse: false,+ busy: false,+ interrupted: true,+ messages: withSilentTurnRetry(current.messages, current.streamId),+ pendingBranchGroup: null,+ streamId: null,+ turnLive: false,+ turnStartedAt: null+ })+}++/** Record that this session just produced an event. A live turn that then goes+ * silent is force-settled; a turn still receiving events, or waiting on the+ * user, is not. */+export function noteSessionEvent(runtimeId: string) {+ if (!runtimeId) {+ return+ }++ const current = $sessionStates.get()[runtimeId]++ clearEventSilence(runtimeId)++ if (!isLiveTurnAwaitingEvents(current)) {+ return+ }++ sessionEventSilenceTimers.set(+ runtimeId,+ setTimeout(() => {+ sessionEventSilenceTimers.delete(runtimeId)+ settleSilentLiveTurn(runtimeId)+ }, LIVE_TURN_EVENT_SILENCE_MS)+ )+}+const sessionWatchdogTimers = new Map<string, ReturnType<typeof setTimeout>>()function armWatchdog(runtimeId: string) {@@ -490,6 +596,11 @@ function handleTransition(previous: ClientSessionState | null, next: ClientSessiarmWatchdog(runtimeId)} else {clearWatchdog(runtimeId)++ if (!isLiveTurnAwaitingEvents(next)) {+ clearEventSilence(runtimeId)+ }+setSessionStalled(next.storedSessionId, false)setSessionStalled(previous?.storedSessionId, false)}@@ -681,6 +792,7 @@ export function dropSessionState(runtimeId: string) {// a just-finished session's row survives merge eviction even if its tile or// cached runtime is dropped in the meantime.clearWatchdog(runtimeId)+ clearEventSilence(runtimeId)clearSessionProviderWait(runtimeId)sessionScopeByRuntimeId.delete(runtimeId)sessionOwnerByRuntimeId.delete(runtimeId)@@ -707,6 +819,11 @@ export function clearAllSessionStates() {}sessionWatchdogTimers.clear()+ for (const timer of sessionEventSilenceTimers.values()) {+ clearTimeout(timer)+ }++ sessionEventSilenceTimers.clear()settledExpiry.clear()unconfirmedReconnectSettles.clear()clearAllProviderWaits()diff --git a/apps/desktop/src/store/session-watchdog.test.ts b/apps/desktop/src/store/session-watchdog.test.tsindex c080985e884..22919c60127 100644--- a/apps/desktop/src/store/session-watchdog.test.ts+++ b/apps/desktop/src/store/session-watchdog.test.ts@@ -2,12 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { ClientSessionState } from '@/app/types'import { createClientSessionState } from '@/lib/chat-runtime'+import { errorRecoveryPlan } from '@/lib/error-surface'import { $activeSessionId, $selectedStoredSessionId, $unreadFinishedSessionIds } from './session'import {+ $sessionStates,$stalledSessionIds,$workingSessionIds,clearAllSessionStates,+ LIVE_TURN_EVENT_SILENCE_MS,+ noteSessionEvent,publishSessionState,SESSION_WATCHDOG_TIMEOUT_MS} from './session-states'@@ -123,3 +127,146 @@ describe('computed $workingSessionIds', () => {expect($workingSessionIds.get()).toEqual([])})})++const SILENCE_MS = LIVE_TURN_EVENT_SILENCE_MS++function partial(text: string, over: Partial<ClientSessionState> = {}): ClientSessionState {+ return state({+ awaitingResponse: true,+ busy: true,+ messages: [+ {+ id: 'a1',+ parts: [{ type: 'text', text }],+ pending: true,+ role: 'assistant'+ }+ ],+ model: 'any-model',+ sawAssistantPayload: true,+ streamId: 'a1',+ turnLive: true,+ turnStartedAt: Date.now(),+ ...over+ })+}++describe('live turn event silence', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ clearAllSessionStates()+ $unreadFinishedSessionIds.set([])+ $selectedStoredSessionId.set(null)+ $activeSessionId.set(null)+ })++ afterEach(() => {+ vi.runOnlyPendingTimers()+ vi.useRealTimers()+ clearAllSessionStates()+ $unreadFinishedSessionIds.set([])+ $selectedStoredSessionId.set(null)+ $activeSessionId.set(null)+ })++ it('force-settles a silent live turn even after a partial payload and offers retry', () => {+ $activeSessionId.set('rt1')+ publishSessionState('rt1', partial('partial answer', { model: 'glm-5.3-flash', storedSessionId: 's1' }))+ noteSessionEvent('rt1')++ vi.advanceTimersByTime(SILENCE_MS)++ const settled = $sessionStates.get().rt1+ expect($workingSessionIds.get()).not.toContain('s1')+ expect(settled?.busy).toBe(false)+ expect(settled?.awaitingResponse).toBe(false)+ expect(settled?.turnLive).toBe(false)+ expect(settled?.messages.every(message => !message.pending)).toBe(true)+ expect(+ settled?.messages.some(message =>+ message.parts.some(part => part.type === 'text' && part.text === 'partial answer')+ )+ ).toBe(true)++ const failed = settled?.messages.find(message => message.errorSurface)+ expect(failed?.errorSurface?.retryable).toBe(true)+ expect(errorRecoveryPlan(failed?.errorSurface).retry).toBe(true)+ expect(failed?.error).not.toMatch(/glm|deepseek|interrupted mid-run/i)+ })++ it('force-settles a silent live turn that never produced a payload', () => {+ $activeSessionId.set('rt-empty')+ publishSessionState(+ 'rt-empty',+ state({ awaitingResponse: true, busy: true, model: 'deepseek-chat', storedSessionId: 's-empty', turnLive: true })+ )+ noteSessionEvent('rt-empty')++ vi.advanceTimersByTime(SILENCE_MS)++ const settled = $sessionStates.get()['rt-empty']+ expect($workingSessionIds.get()).not.toContain('s-empty')+ expect(settled?.busy).toBe(false)+ expect(settled?.turnLive).toBe(false)+ const failed = settled?.messages.find(message => message.role === 'assistant' && message.errorSurface)+ expect(failed?.errorSurface?.retryable).toBe(true)+ expect(errorRecoveryPlan(failed?.errorSurface).retry).toBe(true)+ })++ it('does not settle a live turn that keeps producing events', () => {+ publishSessionState('rt-live', partial('still working', { storedSessionId: 's-live' }))+ noteSessionEvent('rt-live')++ vi.advanceTimersByTime(SILENCE_MS - 1)+ noteSessionEvent('rt-live')+ vi.advanceTimersByTime(SILENCE_MS - 1)++ expect($workingSessionIds.get()).toContain('s-live')+ expect($sessionStates.get()['rt-live']?.messages.some(message => message.errorSurface)).toBe(false)+ })++ it('does not settle a turn the user is still answering', () => {+ publishSessionState('rt-ask', partial('need a choice', { needsInput: true, storedSessionId: 's-ask' }))+ noteSessionEvent('rt-ask')++ vi.advanceTimersByTime(SILENCE_MS)++ expect($workingSessionIds.get()).toContain('s-ask')+ expect($sessionStates.get()['rt-ask']?.messages.some(message => message.errorSurface)).toBe(false)+ })++ it('settles only the session that stopped producing events', () => {+ $activeSessionId.set('rt-a')+ publishSessionState('rt-a', partial('a', { storedSessionId: 's-a' }))+ publishSessionState('rt-b', partial('b', { storedSessionId: 's-b' }))+ noteSessionEvent('rt-a')+ noteSessionEvent('rt-b')++ vi.advanceTimersByTime(SILENCE_MS - 1)+ noteSessionEvent('rt-b')+ vi.advanceTimersByTime(1)++ expect($workingSessionIds.get()).not.toContain('s-a')+ expect($workingSessionIds.get()).toContain('s-b')+ expect($sessionStates.get()['rt-a']?.messages.some(message => message.errorSurface?.retryable)).toBe(true)+ expect($sessionStates.get()['rt-b']?.busy).toBe(true)+ })++ it('does not stamp a retry when the turn settles before the silence window', () => {+ const working = partial('done soon', { storedSessionId: 's-done' })+ publishSessionState('rt-done', working)+ noteSessionEvent('rt-done')+ publishSessionState('rt-done', {+ ...working,+ awaitingResponse: false,+ busy: false,+ messages: working.messages.map(message => ({ ...message, pending: false })),+ turnLive: false+ })++ vi.advanceTimersByTime(SILENCE_MS)++ expect($sessionStates.get()['rt-done']?.messages.some(message => message.errorSurface)).toBe(false)+ expect($workingSessionIds.get()).not.toContain('s-done')+ })+})