The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): settle a turn that ends with no assistant payload
briandevans3e46389e4060
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 08acaec29ef..c65c35cff10 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@@ -231,8 +231,14 @@ interface GatewayEventDeps {failAssistantMessage: (sessionId: string, errorMessage: string, occurredAt?: number) => voidflushQueuedDeltas: (sessionId?: string) => voidfinalizeInterimAssistantMessage: (sessionId: string, text: string, occurredAt?: number) => void+ hydrateFromStoredSession: (+ attempts?: number,+ storedSessionId?: string | null,+ runtimeSessionId?: string | null+ ) => Promise<void>queryClient: QueryClientrefreshHermesConfig: () => Promise<void>+ scheduleSessionsRefresh: () => voidsessionInterrupted: (sessionId: string) => booleansessionStateByRuntimeIdRef: MutableRefObject<Map<string, ClientSessionState>>updateSessionState: (@@ -263,8 +269,10 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {failAssistantMessage,flushQueuedDeltas,finalizeInterimAssistantMessage,+ hydrateFromStoredSession,queryClient,refreshHermesConfig,+ scheduleSessionsRefresh,sessionInterrupted,sessionStateByRuntimeIdRef,updateSessionState,@@ -566,7 +574,13 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {// mutates the per-runtime cache entry, and syncSessionStateToView// guards the view publish to the active session, so this is safe.if (runningChanged && sessionId) {- updateSessionState(+ // Set when THIS event released a turn that ended without ever+ // producing an assistant payload, so the catch-up side effects below+ // run on that edge only. The updater is invoked exactly once,+ // synchronously, by updateSessionState.+ let recoveredWithoutPayload = false++ const nextState = updateSessionState(sessionId,state => {const busy = Boolean(payload!.running)@@ -592,10 +606,30 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {}}- if (state.awaitingResponse && !state.sawAssistantPayload) {+ // The turn has not started backend-side yet. submit arms+ // busy/awaitingResponse optimistically, so a running=false+ // heartbeat that lands in the gap before the turn spins up is a+ // pre-start report, not a finished turn — settling on it would+ // drop the spinner and re-open the send guard mid-flight.+ // turnStartedAt is stamped only once the backend reports the turn+ // live (message.start, the running=true edge, or a resumed+ // in-flight turn) and is cleared by every settle, so a null value+ // here is exactly "no turn has been reported running yet".+ if (state.awaitingResponse && !state.sawAssistantPayload && !state.turnStartedAt) {return state}+ // Past that gate the turn DID start and the backend now reports it+ // finished. When no assistant payload ever arrived (gateway crash+ // mid-stream, provider error before the first delta, agent-build+ // failure) message.complete never fires, so this is the only event+ // that can release the session. Bailing here instead left+ // awaitingResponse/busy latched until app restart (#46517): the+ // per-session busy flag is authoritative for isTargetSessionBusy,+ // so submitPrompt and the slash dispatcher silently returned false+ // and the session accepted no further input.+ recoveredWithoutPayload = state.awaitingResponse && !state.sawAssistantPayload+return {...state,awaitingResponse: false,@@ -617,6 +651,25 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {},payload?.stored_session_id || undefined)++ if (recoveredWithoutPayload) {+ // 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 awaitingResponse+ // is false the `state.busy === busy` guard above short-circuits+ // every later heartbeat — so it costs one coalesced refresh per+ // broken 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) {+ void hydrateFromStoredSession(3, nextState.storedSessionId, sessionId)+ }+ }}if (payload?.usage && (!explicitSid || isActiveEvent)) {@@ -1461,10 +1514,12 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {failAssistantMessage,finalizeInterimAssistantMessage,flushQueuedDeltas,+ hydrateFromStoredSession,lastCwdInfoSessionRef,nativeSubagentSessionsRef,queryClient,scheduleConfigRefresh,+ scheduleSessionsRefresh,sessionInterrupted,sessionStateByRuntimeIdRef,updateSessionState,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 ccf60aa9169..c417ab7c3ed 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@@ -832,8 +832,10 @@ export function useMessageStream({failAssistantMessage,flushQueuedDeltas,finalizeInterimAssistantMessage,+ hydrateFromStoredSession,queryClient,refreshHermesConfig,+ scheduleSessionsRefresh,sessionInterrupted,sessionStateByRuntimeIdRef,updateSessionState,diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/session-info-side-effects.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/session-info-side-effects.test.tsxindex 305d31f8334..bfe4305412f 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/session-info-side-effects.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/session-info-side-effects.test.tsx@@ -3,6 +3,7 @@ import { act, cleanup, render, waitFor } from '@testing-library/react'import { useEffect, useRef } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { isTargetSessionBusy } from '@/app/session/hooks/use-prompt-actions/utils'import type { ClientSessionState } from '@/app/types'import { createClientSessionState } from '@/lib/chat-runtime'import { modelOptionsQueryKey } from '@/lib/model-options'@@ -21,16 +22,20 @@ const ACTIVE_PROFILE = 'compass'let handleEvent: ((event: RpcEvent) => void) | null = nulllet refreshHermesConfig: ReturnType<typeof vi.fn<() => Promise<void>>>let refreshSessions: ReturnType<typeof vi.fn<() => Promise<void>>>+let hydrateFromStoredSession: ReturnType<typeof vi.fn<() => Promise<void>>>let queryClient: QueryClient+let sessionStates: Map<string, ClientSessionState> | null = nullfunction Harness() {const activeSessionIdRef = useRef<string | null>(ACTIVE_SID)const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())+ sessionStates = sessionStateByRuntimeIdRef.current+const stream = useMessageStream({activeGatewayProfile: ACTIVE_PROFILE,activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),+ hydrateFromStoredSession,queryClient,refreshHermesConfig,refreshSessions,@@ -61,8 +66,10 @@ const sessionInfo = (sessionId: string, payload: Record<string, unknown>) =>beforeEach(() => {handleEvent = null+ sessionStates = nullrefreshHermesConfig = vi.fn<() => Promise<void>>(async () => undefined)refreshSessions = vi.fn<() => Promise<void>>(async () => undefined)+ hydrateFromStoredSession = vi.fn<() => Promise<void>>(async () => undefined)queryClient = new QueryClient()setCurrentModel('')setCurrentProvider('')@@ -139,6 +146,95 @@ describe('session.info model-options invalidation gating', () => {})})+describe('session.info settles a turn that produced no assistant payload', () => {+ // #46517: a turn that ends without ever emitting an assistant payload (gateway+ // crash mid-stream, provider error before the first delta, agent-build+ // failure) never reaches message.complete, so session.info running=false is+ // the only event that can release it. It used to return state unchanged,+ // latching awaitingResponse/busy until app restart — and because+ // isTargetSessionBusy reads the per-session busy flag as authoritative,+ // submitPrompt and the slash dispatcher then silently refused every send.+ const busyFor = (sessionId: string) =>+ isTargetSessionBusy(Object.fromEntries(sessionStates!), sessionId, false)++ const startTurn = (sessionId: string) =>+ act(() => handleEvent!({ payload: {}, session_id: sessionId, type: 'message.start' }))++ it('leaves the session sendable after a started turn ends with no payload', async () => {+ await mountStream()++ startTurn(ACTIVE_SID)+ expect(busyFor(ACTIVE_SID)).toBe(true)++ sessionInfo(ACTIVE_SID, { running: false })++ const state = sessionStates!.get(ACTIVE_SID)!+ expect(state.awaitingResponse).toBe(false)+ expect(state.busy).toBe(false)+ expect(state.streamId).toBeNull()+ expect(state.turnStartedAt).toBeNull()+ // The predicate submit.ts and slash.ts actually gate on.+ expect(busyFor(ACTIVE_SID)).toBe(false)+ })++ it('keeps waiting when running=false lands before the turn ever started', async () => {+ await mountStream()++ // submit arms busy/awaitingResponse optimistically; this heartbeat is the+ // pre-start report, not a finished turn, so the spinner must stay up and+ // the send guard must stay closed.+ act(() => {+ sessionStates!.set(ACTIVE_SID, {+ ...createClientSessionState(),+ awaitingResponse: true,+ busy: true,+ sawAssistantPayload: false,+ turnStartedAt: null+ })+ })++ sessionInfo(ACTIVE_SID, { running: false })++ const state = sessionStates!.get(ACTIVE_SID)!+ expect(state.awaitingResponse).toBe(true)+ expect(busyFor(ACTIVE_SID)).toBe(true)+ expect(hydrateFromStoredSession).not.toHaveBeenCalled()+ })++ it('un-latches a background session but does not hydrate its transcript', async () => {+ await mountStream()++ startTurn('session-background')+ sessionInfo('session-background', { running: false })++ // The settle is unscoped — a background session's sidebar dot must clear+ // without the user opening it.+ expect(busyFor('session-background')).toBe(false)+ // The transcript refetch is scoped to the session on screen, so an idle+ // background session does not cost a REST fan-out.+ expect(hydrateFromStoredSession).not.toHaveBeenCalled()+ })++ it('hydrates the foreground transcript once and coalesces the sidebar refresh', async () => {+ await mountStream()++ startTurn(ACTIVE_SID)+ vi.useFakeTimers()++ sessionInfo(ACTIVE_SID, { running: false })+ // Later heartbeats hit the unchanged-state guard, so recovery is edge-only.+ sessionInfo(ACTIVE_SID, { running: false })+ sessionInfo(ACTIVE_SID, { running: false })++ await act(async () => {+ await vi.advanceTimersByTimeAsync(400)+ })++ expect(hydrateFromStoredSession).toHaveBeenCalledTimes(1)+ expect(refreshSessions).toHaveBeenCalledTimes(1)+ })+})+describe('message.complete sidebar refresh coalescing', () => {it('collapses near-simultaneous completions into one refresh', async () => {await mountStream()