Skip to content

The agent that grows with you

fix(desktop): retire the composer busy latch on gateway reconnect (#93059)

RayCharlizard616d6c5432a5
diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
index e99c262c881..4a381a19bfe 100644
--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
@@ -254,6 +254,45 @@ describe('useSessionTileDelegate resumeTile', () => {
})
})
+describe('useSessionTileDelegate retireBusyClaim', () => {
+ it('retires a stale busy claim through the session-state write path (#93059)', () => {
+ const busyState = { awaitingResponse: true, busy: true, messages: [{ id: 'm1' }], storedSessionId: 'stored-d' }
+ const sessionStateByRuntimeIdRef = { current: new Map([['runtime-dead', busyState]]) }
+ const updateSessionState = vi.fn()
+
+ renderTile(
+ vi.fn(async () => ({}) as never),
+ { sessionStateByRuntimeIdRef, updateSessionState }
+ )
+
+ expect(sessionTileDelegate()!.retireBusyClaim!('runtime-dead')).toBe(true)
+ expect(updateSessionState).toHaveBeenCalledWith('runtime-dead', expect.any(Function))
+
+ // The updater is the downgrade: busy/awaiting off, everything else intact.
+ const updater = updateSessionState.mock.calls[0][1] as (state: typeof busyState) => typeof busyState
+
+ expect(updater(busyState)).toEqual({ ...busyState, awaitingResponse: false, busy: false })
+ })
+
+ it('reports a miss instead of minting a cache entry for a runtime it never held', () => {
+ // No phantoms: updateSessionState mints a state for any id it is handed,
+ // and prune never collects a transcript-less entry — so a miss must not
+ // reach the write path; the store retires its own mirror instead.
+ const idle = { awaitingResponse: false, busy: false, messages: [{ id: 'm1' }], storedSessionId: 'stored-e' }
+ const sessionStateByRuntimeIdRef = { current: new Map([['runtime-idle', idle]]) }
+ const updateSessionState = vi.fn()
+
+ renderTile(
+ vi.fn(async () => ({}) as never),
+ { sessionStateByRuntimeIdRef, updateSessionState }
+ )
+
+ expect(sessionTileDelegate()!.retireBusyClaim!('runtime-unknown')).toBe(false)
+ expect(sessionTileDelegate()!.retireBusyClaim!('runtime-idle')).toBe(false)
+ expect(updateSessionState).not.toHaveBeenCalled()
+ })
+})
+
describe('useSessionTileDelegate interruptSession', () => {
beforeEach(() => {
setSessions([])
diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
index 593017df64a..841ea84d8e0 100644
--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
@@ -119,6 +119,21 @@ export function useSessionTileDelegate({
}
}
},
+ // Reconnect reconcile (#93059): retire an orphaned runtime's busy claim
+ // through updateSessionState so the cache, focused view, busyRef and
+ // tile mirrors settle together. A runtime this cache never held reports
+ // false instead of minting an entry; the store downgrades its mirror.
+ retireBusyClaim: runtimeId => {
+ const cached = sessionStateByRuntimeIdRef.current.get(runtimeId)
+
+ if (!cached || (!cached.busy && !cached.awaitingResponse)) {
+ return false
+ }
+
+ updateSessionState(runtimeId, state => ({ ...state, awaitingResponse: false, busy: false }))
+
+ return true
+ },
interruptSession: async runtimeId => {
// Same cooldown as the primary chat's Stop (#83855): the gateway may
// still be winding down after this interrupt, so a quick edit/resend
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx
index 46f7129e7bc..80a792394c5 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx
@@ -21,6 +21,8 @@ import { notifyError } from '@/store/notifications'
import { $activeGatewayProfile, $profiles, ensureGatewayProfile } from '@/store/profile'
import {
$activeSessionId,
+ $awaitingResponse,
+ $busy,
$connection,
$currentCwd,
$gatewayState,
@@ -282,6 +284,8 @@ beforeEach(() => {
;(globalThis as { WebSocket: unknown }).WebSocket = FakeWebSocket
;(window as { hermesDesktop?: unknown }).hermesDesktop = fakeDesktop()
$gatewayState.set('idle')
+ $busy.set(false)
+ $awaitingResponse.set(false)
$desktopBoot.set({
error: null,
fakeMode: false,
@@ -324,6 +328,8 @@ afterEach(() => {
delete (window as { hermesDesktop?: unknown }).hermesDesktop
window.localStorage.removeItem('hermes.desktop.workspace-cwd')
$currentCwd.set('')
+ $busy.set(false)
+ $awaitingResponse.set(false)
})
// Let pending microtasks (awaits) AND the queued 0ms socket open/error fire.
@@ -1156,6 +1162,31 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>
expect(secondaryBot).toMatchObject({ runtimeId: 'runtime-secondary-live' })
})
+ it('FIX: a successful reconnect retires the focused composer busy latch (#93059)', async () => {
+ // Backend respawned mid-turn (auto-update, sleep/wake): the focused
+ // composer's draft latches never get their terminal busy:false, and Send
+ // silently no-ops behind the busy guard until restart (#93059).
+ render(<Harness />)
+ await flushAsync()
+ expect($gatewayState.get()).toBe('open')
+
+ // A turn was mid-flight when the backend went away.
+ act(() => {
+ $busy.set(true)
+ $awaitingResponse.set(true)
+ })
+
+ act(() => FakeWebSocket.instances[0].drop())
+ await flushAsync()
+
+ // The respawned backend answers the next dial.
+ await advanceBackoff()
+
+ expect($gatewayState.get()).toBe('open')
+ expect($busy.get()).toBe(false)
+ expect($awaitingResponse.get()).toBe(false)
+ })
+
it('manual reconnect revalidates, re-resolves, re-mints, and re-dials the dropped socket', async () => {
const desktop = fakeDesktop()
diff --git a/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx b/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx
index bb6f4e74a81..0a3d85977ea 100644
--- a/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx
@@ -21,7 +21,13 @@ import {
setCurrentServiceTier,
setTurnStartedAt
} from '@/store/session'
-import { $sessionStates } from '@/store/session-states'
+import {
+ $sessionStates,
+ clearAllSessionStates,
+ reconcileBusyStatesOnReconnect,
+ type SessionTileDelegate,
+ setSessionTileDelegate
+} from '@/store/session-states'
import { useSessionStateCache } from './use-session-state-cache'
@@ -520,3 +526,53 @@ describe('useSessionStateCache — cross-thread error isolation', () => {
expect(cache.getRuntimeIdForStoredSession('stored-A')).toBeNull()
})
})
+
+// #93059: reconnect used to downgrade the $sessionStates mirror only, leaving
+// this cache (which warm resume ORs over `running: false`) still busy.
+describe('useSessionStateCache — reconnect busy reconcile (#93059)', () => {
+ // Only retireBusyClaim is reachable from the store.
+ const asDelegate = (partial: Partial<SessionTileDelegate>) => partial as SessionTileDelegate
+
+ // Stands in for "no wiring mounted": every claim is a miss, nothing written.
+ const inertDelegate = asDelegate({ retireBusyClaim: () => false })
+
+ afterEach(() => {
+ cleanup()
+ setSessionTileDelegate(inertDelegate)
+ clearAllSessionStates()
+ setActiveSessionId(null)
+ })
+
+ it('retires the wiring cache entry, not just the store mirror', () => {
+ let cache!: Cache
+
+ setActiveSessionId('runtime-1')
+ render(
+ <Harness activeSessionId="runtime-1" onReady={value => (cache = value)} selectedStoredSessionId="stored-1" />
+ )
+
+ // The wiring layer's own retireBusyClaim, over the REAL updateSessionState.
+ setSessionTileDelegate(
+ asDelegate({
+ retireBusyClaim: runtimeId => {
+ cache.updateSessionState(runtimeId, state => ({ ...state, awaitingResponse: false, busy: false }))
+
+ return true
+ }
+ })
+ )
+
+ act(() => {
+ cache.updateSessionState('runtime-1', state => ({ ...state, awaitingResponse: true, busy: true }), 'stored-1')
+ })
+
+ expect(cache.sessionStateByRuntimeIdRef.current.get('runtime-1')?.busy).toBe(true)
+
+ // Backend respawned: no terminal busy:false can arrive for this runtime.
+ act(() => reconcileBusyStatesOnReconnect())
+
+ expect(cache.sessionStateByRuntimeIdRef.current.get('runtime-1')?.busy).toBe(false)
+ expect(cache.sessionStateByRuntimeIdRef.current.get('runtime-1')?.awaitingResponse).toBe(false)
+ expect($sessionStates.get()['runtime-1']?.busy).toBe(false)
+ })
+})
diff --git a/apps/desktop/src/store/session-states-reconnect.test.ts b/apps/desktop/src/store/session-states-reconnect.test.ts
index 8dd8d956caf..11929bb7235 100644
--- a/apps/desktop/src/store/session-states-reconnect.test.ts
+++ b/apps/desktop/src/store/session-states-reconnect.test.ts
@@ -4,7 +4,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { ClientSessionState } from '@/app/types'
import { createClientSessionState } from '@/lib/chat-runtime'
-import { $activeSessionId, $selectedStoredSessionId, $unreadFinishedSessionIds } from './session'
+import {
+ $activeSessionId,
+ $awaitingResponse,
+ $busy,
+ $selectedStoredSessionId,
+ $unreadFinishedSessionIds
+} from './session'
import {
$attentionSessionIds,
$stalledSessionIds,
@@ -13,13 +19,39 @@ import {
publishSessionState,
reconcileBusyStatesOnReconnect,
recordSessionEventScope,
- SESSION_WATCHDOG_TIMEOUT_MS
+ SESSION_WATCHDOG_TIMEOUT_MS,
+ type SessionTileDelegate,
+ setSessionTileDelegate
} from './session-states'
function state(over: Partial<ClientSessionState> = {}): ClientSessionState {
return { ...createClientSessionState(null), storedSessionId: 's1', ...over }
}
+// Stand-in for the wiring layer's `retireBusyClaim`: cache keyed by runtime
+// id, miss (or idle) → false and no write, hit → write + mirror publish. No
+// unset API exists, so `noDelegate` (empty cache) plays "no wiring mounted".
+function tileDelegate(cache: Map<string, ClientSessionState>): SessionTileDelegate {
+ return {
+ retireBusyClaim: runtimeId => {
+ const cached = cache.get(runtimeId)
+
+ if (!cached || (!cached.busy && !cached.awaitingResponse)) {
+ return false
+ }
+
+ const next = { ...cached, awaitingResponse: false, busy: false }
+
+ cache.set(runtimeId, next)
+ publishSessionState(runtimeId, next)
+
+ return true
+ }
+ } as SessionTileDelegate
+}
+
+const noDelegate = tileDelegate(new Map())
+
// The stale-flag half of #53902/#73082: a backend respawn re-mints runtime
// ids, so a pre-reconnect busy state never receives its terminal busy:false
// and the session's running arc stays armed forever. The reconnect paths call
@@ -32,6 +64,9 @@ describe('reconcileBusyStatesOnReconnect', () => {
$unreadFinishedSessionIds.set([])
$selectedStoredSessionId.set(null)
$activeSessionId.set(null)
+ $busy.set(false)
+ $awaitingResponse.set(false)
+ setSessionTileDelegate(noDelegate)
})
afterEach(() => {
@@ -41,6 +76,9 @@ describe('reconcileBusyStatesOnReconnect', () => {
$unreadFinishedSessionIds.set([])
$selectedStoredSessionId.set(null)
$activeSessionId.set(null)
+ $busy.set(false)
+ $awaitingResponse.set(false)
+ setSessionTileDelegate(noDelegate)
})
it('clears a stale busy session on primary reconnect', () => {
@@ -102,6 +140,61 @@ describe('reconcileBusyStatesOnReconnect', () => {
expect($workingSessionIds.get()).toContain('sLocal')
})
+ // #93059: the store is a mirror of the wiring cache; downgrading only the
+ // mirror leaves the cache busy, and warm resume ORs it over `running: false`.
+ it('routes the downgrade through the session-state write path (#93059)', () => {
+ const cache = new Map<string, ClientSessionState>()
+ const stale = state({ awaitingResponse: true, busy: true, storedSessionId: 's1' })
+
+ cache.set('rt1', stale)
+ publishSessionState('rt1', stale)
+ setSessionTileDelegate(tileDelegate(cache))
+ expect($workingSessionIds.get()).toContain('s1')
+
+ reconcileBusyStatesOnReconnect()
+
+ expect(cache.get('rt1')?.busy).toBe(false)
+ expect(cache.get('rt1')?.awaitingResponse).toBe(false)
+ expect($workingSessionIds.get()).not.toContain('s1')
+ })
+
+ // Cache miss (background-profile rows, cold window): the mirror is still
+ // retired and nothing is minted in the cache.
+ it('falls back to the mirror when the write path has no state for the runtime', () => {
+ const cache = new Map<string, ClientSessionState>()
+
+ publishSessionState('rt1', state({ busy: true, storedSessionId: 's1' }))
+ setSessionTileDelegate(tileDelegate(cache))
+
+ reconcileBusyStatesOnReconnect()
+
+ expect(cache.has('rt1')).toBe(false)
+ expect($workingSessionIds.get()).not.toContain('s1')
+ })
+
+ // With no live slice, PRIMARY_SESSION_VIEW and busyRef fall back to the
+ // draft latches — a stuck one silently no-ops Send until restart (#93059).
+ it('retires the focused composer latches on primary reconnect (#93059)', () => {
+ $busy.set(true)
+ $awaitingResponse.set(true)
+
+ reconcileBusyStatesOnReconnect()
+
+ expect($busy.get()).toBe(false)
+ expect($awaitingResponse.get()).toBe(false)
+ })
+
+ it('a scoped reconcile leaves the focused composer alone', () => {
+ // A background socket returning says nothing about the primary composer.
+ $busy.set(true)
+ $awaitingResponse.set(true)
+
+ reconcileBusyStatesOnReconnect(registryBackendScopeKey('connA', 'default'))
+
+ expect($busy.get()).toBe(true)
+ expect($awaitingResponse.get()).toBe(true)
+ })
+
it('a live turn re-asserting busy after reconcile re-arms the arc', () => {
const s = state({ busy: true, storedSessionId: 's1' })
publishSessionState('rt1', s)
diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.ts
index 59449da07c8..e112ecc5998 100644
--- a/apps/desktop/src/store/session-states.ts
+++ b/apps/desktop/src/store/session-states.ts
@@ -48,6 +48,8 @@ import {
markSessionRead,
sessionMatchesStoredId,
setActiveSessionStoredIdRotation,
+ setAwaitingResponse,
+ setBusy,
setSessions
} from './session'
import { requestForSessionProfile, type SessionOwnerScope, type SessionProfileRoute } from './session-request-router'
@@ -441,7 +443,17 @@ export function clearAllSessionStates() {
* answer, and post-reconnect refresh re-asserts or retires it via its own
* path. Transition side-effects run through publishSessionState, so
* watchdogs disarm, stall hints drop, and settle/unread bookkeeping stays
- * consistent. */
+ * consistent.
+ *
+ * The downgrade goes through the delegate's `retireBusyClaim` (the wiring
+ * cache's updateSessionState), not straight into this mirror: the claim has
+ * four holders — wiring cache, mirror, the focused view's draft latches,
+ * busyRef — and retiring only the mirror left Send silently no-oping behind
+ * a stale busy until restart (#93059). The mirror publish stays as the
+ * fallback for runtimes the cache never held (background-sync rows, no
+ * wiring mounted). A PRIMARY reconcile also clears the focused draft
+ * latches, which outlive the state they mirrored; a scoped one leaves them
+ * alone — a background socket says nothing about the primary composer. */
export function reconcileBusyStatesOnReconnect(scope?: string) {
const states = $sessionStates.get()
@@ -456,7 +468,19 @@ export function reconcileBusyStatesOnReconnect(scope?: string) {
continue
}
- publishSessionState(runtimeId, { ...state, awaitingResponse: false, busy: false })
+ sessionTileDelegate()?.retireBusyClaim?.(runtimeId)
+
+ // Re-read — the write path may have republished (and released) this entry.
+ const published = $sessionStates.get()[runtimeId]
+
+ if (published?.busy || published?.awaitingResponse) {
+ publishSessionState(runtimeId, { ...published, awaitingResponse: false, busy: false })
+ }
+ }
+
+ if (scope === undefined) {
+ setBusy(false)
+ setAwaitingResponse(false)
}
}
@@ -1052,6 +1076,12 @@ export interface SessionTileDelegate {
/** Bind a live runtime id for a stored session (resume without touching
* the main view). Returns the runtime id, or throws. */
resumeTile(storedSessionId: string): Promise<string>
+ /** Retire one runtime's busy/awaiting claim through the wiring cache
+ * (updateSessionState), so cache, focused view, busyRef, and tile mirrors
+ * settle together. Returns false when the cache holds no busy state for
+ * it — the caller downgrades the mirror itself. Reconnect-time twin of
+ * invalidateRuntimeBindings (#93059). */
+ retireBusyClaim?(runtimeId: string): boolean
/** Submit a prompt to a tile's live session. */
submitToSession(runtimeId: string, text: string): Promise<void>
/** THE session-state write path — routes through the wiring cache so the