Skip to content

The agent that grows with you

fix(desktop): latch approval and goal polls off a dead runtime

Brooklyn Nicholson36bea5013912
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.test.ts
index 398a67d2080..eda6b693b0e 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.test.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.test.ts
@@ -1,5 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { ClientSessionState } from '@/app/types'
+import { createClientSessionState } from '@/lib/chat-runtime'
import {
$currentCwd,
$selectedStoredSessionId,
@@ -105,4 +107,43 @@ describe('handleSessionInfoEvent workspace ownership', () => {
expect($currentCwd.get()).toBe('/repo/mine')
expect($workspaceCwdOwner.get()).toBe('selected-session')
})
+
+ it('keeps runtime state identity when a heartbeat only restates cached fields', () => {
+ const original = {
+ ...createClientSessionState('stored-1'),
+ cwd: '/repo/mine',
+ fast: true,
+ model: 'model-1',
+ provider: 'provider-1'
+ }
+
+ const ctx = sessionInfoEvent({
+ activeSessionId: 'runtime-1',
+ cwd: '/repo/mine',
+ explicitSid: 'runtime-1',
+ storedSessionId: 'stored-1'
+ })
+
+ let next: ClientSessionState | undefined
+
+ ctx.payload = {
+ ...ctx.payload,
+ fast: true,
+ model: 'model-1',
+ provider: 'provider-1'
+ }
+ ctx.deps.sessionStateByRuntimeIdRef.current.set('runtime-1', original)
+ ctx.deps.updateSessionState = vi.fn(
+ (_sessionId: string, updater: (state: ClientSessionState) => ClientSessionState) => {
+ const updated = updater(original)
+ next = updated
+
+ return updated
+ }
+ )
+
+ handleSessionInfoEvent(ctx)
+
+ expect(next).toBe(original)
+ })
})
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts
index 40143a232d6..29a7b629ddc 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts
@@ -28,7 +28,12 @@ import {
import { reportInstallMethodWarning } from '@/store/updates'
import { finalizeInterruptedMessages } from '../../use-prompt-actions/rewind'
-import { hasSessionInfoStatePatch, PRE_TURN_LIVE_SETTLE_GRACE_MS, sessionInfoStatePatch } from '../utils'
+import {
+ applySessionInfoStatePatch,
+ hasSessionInfoStatePatch,
+ PRE_TURN_LIVE_SETTLE_GRACE_MS,
+ sessionInfoStatePatch
+} from '../utils'
import type { GatewayEventContext } from './types'
@@ -253,12 +258,7 @@ export function handleSessionInfoEvent(ctx: GatewayEventContext): boolean {
if (sessionId && hasStatePatch) {
updateSessionState(
sessionId,
- state => ({
- ...state,
- ...statePatch,
- branch: statePatch.branch ?? state.branch,
- cwd: statePatch.cwd ?? state.cwd
- }),
+ state => applySessionInfoStatePatch(state, statePatch),
payload?.stored_session_id || undefined
)
}
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/utils.ts b/apps/desktop/src/app/session/hooks/use-message-stream/utils.ts
index 99219daf979..391e3293050 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/utils.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/utils.ts
@@ -56,6 +56,30 @@ export function hasSessionInfoStatePatch(patch: SessionRuntimeStatePatch): boole
return Object.keys(patch).length > 0
}
+/** Keep the runtime-state object when a heartbeat only restates cached fields.
+ * `$sessionStates` feeds every mounted session surface, so an equivalent spread
+ * re-renders them all at the heartbeat cadence. */
+export function applySessionInfoStatePatch(
+ state: ClientSessionState,
+ patch: SessionRuntimeStatePatch
+): ClientSessionState {
+ if (
+ (patch.branch === undefined || patch.branch === state.branch) &&
+ (patch.cwd === undefined || patch.cwd === state.cwd) &&
+ (patch.fast === undefined || patch.fast === state.fast) &&
+ (patch.model === undefined || patch.model === state.model) &&
+ (patch.personality === undefined || patch.personality === state.personality) &&
+ (patch.provider === undefined || patch.provider === state.provider) &&
+ (patch.reasoningEffort === undefined || patch.reasoningEffort === state.reasoningEffort) &&
+ (patch.serviceTier === undefined || patch.serviceTier === state.serviceTier) &&
+ (patch.yolo === undefined || patch.yolo === state.yolo)
+ ) {
+ return state
+ }
+
+ return { ...state, ...patch }
+}
+
// Minimum gap between two assistant-text flushes during a stream. Was 16ms
// (rAF only), which at typical LLM token rates of ~30-80 tok/sec meant every
// token got its own React commit + Streamdown markdown re-parse, scaling
diff --git a/apps/desktop/src/store/composer-status.ts b/apps/desktop/src/store/composer-status.ts
index e02402d7218..ce891688e53 100644
--- a/apps/desktop/src/store/composer-status.ts
+++ b/apps/desktop/src/store/composer-status.ts
@@ -1,4 +1,3 @@
-import { JsonRpcGatewayError } from '@hermes/shared'
import { atom, computed } from 'nanostores'
import { translateNow } from '@/i18n'
@@ -9,12 +8,19 @@ import { $gateway } from './gateway'
import { $goalsBySession, type GoalStatus } from './goals'
import { dispatchNativeNotification } from './native-notifications'
import { notifyError } from './notifications'
-import { markRuntimeGone, noteRuntimeAlive } from './runtime-gone'
+import { isSessionGone, isSessionGoneForBackgroundPolling, markSessionGone, noteRuntimeAlive } from './runtime-gone'
import { $sessions, lineageAliases } from './session'
import { $sessionStates } from './session-states'
import { $subagentsBySession, type SubagentProgress } from './subagents'
import { $todosBySession } from './todos'
+export {
+ isSessionGone,
+ isSessionGoneForBackgroundPolling,
+ markSessionGone,
+ resetBackgroundPollingGuard
+} from './runtime-gone'
+
/** Composer status stack feed — merged todos, subagents, background per session. */
export type StatusItemState = 'done' | 'failed' | 'running'
export type StatusItemType = 'background' | 'goal' | 'subagent' | 'todo'
@@ -386,55 +392,11 @@ export function reconcileBackgroundProcesses(sid: string, procs: GatewayProcessE
writeBackground(sid, next)
}
-/** Session ids the gateway has told us are gone. A session-scoped RPC against a
- * runtime the gateway no longer holds fails 4001 "session not found" — a
- * TERMINAL condition, not the transient socket loss the catch below assumes.
- *
- * The status stack re-polls `process.list` every 5s while a running row is on
- * screen, so treating 4001 as transient meant re-sending the same dead id
- * forever: one runtime id accumulated 18,614 gateway rejections in a single day
- * (#94219 fallout). Latch the id here and skip it until something rebinds it. */
-const goneSessions = new Set<string>()
-
-/** Gateway JSON-RPC code for "session not found" (tui_gateway _sess_nowait). */
-const GATEWAY_SESSION_NOT_FOUND_CODE = 4001
-
-/** A gone session is unrecoverable for THIS runtime id; a timeout or transport
- * blip is not. Only the former may stop the poll — misclassifying a transient
- * failure would silently freeze the status stack on a healthy session.
- *
- * Match the gateway's 4001 code when the error carries one (JsonRpcGatewayError
- * from a structured RPC rejection) — a message substring alone could latch on
- * an unrelated error class that merely mentions "session not found" (e.g. a
- * wrapped tool/report string). The message fallback survives only for errors
- * with no numeric code at all, where the frame's structure was lost. */
-export function isSessionGoneForBackgroundPolling(error: unknown): boolean {
- if (error instanceof JsonRpcGatewayError && typeof error.code === 'number') {
- return error.code === GATEWAY_SESSION_NOT_FOUND_CODE
- }
-
- const message = error instanceof Error ? error.message : String(error ?? '')
-
- return /session not found/i.test(message)
-}
-
-/** Clear the gone-latch. Called with a session id when a fresh runtime binds to
- * it (so polling resumes), or with no argument to reset everything (tests). */
-export function resetBackgroundPollingGuard(sid?: string): void {
- if (sid) {
- goneSessions.delete(sid)
-
- return
- }
-
- goneSessions.clear()
-}
-
/** Pull the session's live process snapshot from the gateway. */
export async function refreshBackgroundProcesses(sid: string): Promise<void> {
const gateway = $gateway.get()
- if (!sid || !gateway || goneSessions.has(sid)) {
+ if (!sid || !gateway || isSessionGone(sid)) {
return
}
@@ -449,12 +411,7 @@ export async function refreshBackgroundProcesses(sid: string): Promise<void> {
// A gone session never comes back under this runtime id: stop polling it,
// or the 5s timer hammers the gateway with 4001s for the window's lifetime.
if (isSessionGoneForBackgroundPolling(error)) {
- goneSessions.add(sid)
- // Latching stops the storm; it does not make the window usable again.
- // This poll is the only caller that runs while the user is idle, so it is
- // the only one that can carry the gateway's "resume the stored session"
- // verdict to the view before the user types into a dead binding.
- markRuntimeGone(sid)
+ markSessionGone(sid)
return
}
diff --git a/apps/desktop/src/store/goals.test.ts b/apps/desktop/src/store/goals.test.ts
index 04653193f58..e355776f364 100644
--- a/apps/desktop/src/store/goals.test.ts
+++ b/apps/desktop/src/store/goals.test.ts
@@ -1,6 +1,8 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { $goalsBySession, applyGoalStatusText, clearSessionGoal } from './goals'
+import { $gateway } from './gateway'
+import { $goalsBySession, applyGoalStatusText, clearSessionGoal, refreshSessionGoal } from './goals'
+import { resetBackgroundPollingGuard } from './runtime-gone'
describe('goal store', () => {
afterEach(() => {
@@ -108,3 +110,37 @@ describe('goal store', () => {
expect($goalsBySession.get().s2).toMatchObject({ status: 'paused', title: 'other work' })
})
})
+
+describe('refreshSessionGoal dead-session guard', () => {
+ afterEach(() => {
+ $gateway.set(null as never)
+ resetBackgroundPollingGuard()
+ })
+
+ it('stops re-asking a runtime the gateway no longer holds', async () => {
+ const request = vi.fn(async () => {
+ throw new Error('session not found')
+ })
+
+ $gateway.set({ request } as never)
+
+ await refreshSessionGoal('dead-1')
+ await refreshSessionGoal('dead-1')
+ await refreshSessionGoal('dead-1')
+
+ expect(request).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not latch on a transient failure', async () => {
+ const request = vi.fn(async () => {
+ throw new Error('request timed out after 30s: slash.exec')
+ })
+
+ $gateway.set({ request } as never)
+
+ await refreshSessionGoal('s1')
+ await refreshSessionGoal('s1')
+
+ expect(request).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/apps/desktop/src/store/goals.ts b/apps/desktop/src/store/goals.ts
index 84cf234026a..aa51be46ce9 100644
--- a/apps/desktop/src/store/goals.ts
+++ b/apps/desktop/src/store/goals.ts
@@ -3,6 +3,7 @@ import { atom } from 'nanostores'
import { keyedTimeouts } from '@/lib/keyed-timeouts'
import { $gateway } from './gateway'
+import { isSessionGone, isSessionGoneForBackgroundPolling, markSessionGone } from './runtime-gone'
export type GoalStatus = 'active' | 'done' | 'paused' | 'waiting'
@@ -163,7 +164,7 @@ export function applyGoalStatusText(sid: string, text: string, opts?: { hydrate?
export async function refreshSessionGoal(sid: string): Promise<void> {
const gateway = $gateway.get()
- if (!sid || !gateway) {
+ if (!sid || !gateway || isSessionGone(sid)) {
return
}
@@ -171,7 +172,13 @@ export async function refreshSessionGoal(sid: string): Promise<void> {
const result = await gateway.request<{ output?: string }>('slash.exec', { command: 'goal status', session_id: sid })
applyGoalStatusText(sid, result?.output ?? '', { hydrate: true })
- } catch {
- // Best-effort: older gateways or detached sessions simply won't hydrate it.
+ } catch (error) {
+ if (isSessionGoneForBackgroundPolling(error)) {
+ markSessionGone(sid)
+
+ return
+ }
+
+ // Best-effort: older gateways or a transport blip simply won't hydrate it.
}
}
diff --git a/apps/desktop/src/store/prompts.test.ts b/apps/desktop/src/store/prompts.test.ts
index bbe2d2f2ca3..9f0e761f718 100644
--- a/apps/desktop/src/store/prompts.test.ts
+++ b/apps/desktop/src/store/prompts.test.ts
@@ -16,6 +16,7 @@ import {
setSecretRequest,
setSudoRequest
} from './prompts'
+import { resetBackgroundPollingGuard } from './runtime-gone'
import { $activeSessionId } from './session'
// Prompts are parked per-session; the exported $*Request views are scoped to the
@@ -218,3 +219,92 @@ describe('$activeSessionAwaitingInput', () => {
expect($activeSessionAwaitingInput.get()).toBe(true)
})
})
+
+describe('pending approval replay backoff', () => {
+ afterEach(() => {
+ resetBackgroundPollingGuard()
+ })
+
+ it('stops polling a runtime the gateway no longer holds', async () => {
+ const calls: string[] = []
+
+ const gateway = {
+ request: async (method: string) => {
+ calls.push(method)
+ throw new Error('4001: session not found')
+ }
+ }
+
+ for (let i = 0; i < 5; i++) {
+ await replayPendingApproval(gateway, 'dead-1')
+ }
+
+ expect(calls).toEqual(['approval.pending'])
+ })
+
+ it('keeps polling every other runtime', async () => {
+ const calls: string[] = []
+
+ const gateway = {
+ request: async (_method: string, params: Record<string, unknown>) => {
+ calls.push(String(params.session_id))
+
+ if (params.session_id === 'dead-1') {
+ throw new Error('4001: session not found')
+ }
+
+ return { approvals: [] }
+ }
+ }
+
+ await replayPendingApproval(gateway, 'dead-1')
+ await replayPendingApproval(gateway, 'dead-1')
+ await replayPendingApproval(gateway, 'alive-1')
+ await replayPendingApproval(gateway, 'alive-1')
+
+ expect(calls).toEqual(['dead-1', 'alive-1', 'alive-1'])
+ })
+
+ it('does not latch on a transient failure', async () => {
+ const calls: string[] = []
+
+ const gateway = {
+ request: async (method: string) => {
+ calls.push(method)
+ throw new Error('websocket disconnected')
+ }
+ }
+
+ await replayPendingApproval(gateway, 's1').catch(() => undefined)
+ await replayPendingApproval(gateway, 's1').catch(() => undefined)
+
+ expect(calls).toHaveLength(2)
+ })
+
+ it('polls again once the gone-latch is cleared', async () => {
+ const calls: string[] = []
+ let dead = true
+
+ const gateway = {
+ request: async (method: string) => {
+ calls.push(method)
+
+ if (dead) {
+ throw new Error('4001: session not found')
+ }
+
+ return { approvals: [] }
+ }
+ }
+
+ await replayPendingApproval(gateway, 's1')
+ await replayPendingApproval(gateway, 's1')
+ expect(calls).toHaveLength(1)
+
+ dead = false
+ resetBackgroundPollingGuard()
+ await replayPendingApproval(gateway, 's1')
+
+ expect(calls).toHaveLength(2)
+ })
+})
diff --git a/apps/desktop/src/store/prompts.ts b/apps/desktop/src/store/prompts.ts
index da9c7dedb54..4aca295eded 100644
--- a/apps/desktop/src/store/prompts.ts
+++ b/apps/desktop/src/store/prompts.ts
@@ -1,6 +1,7 @@
import { atom, computed, type ReadableAtom } from 'nanostores'
import { $clarifyRequest, $clarifyRequests } from './clarify'
+import { isSessionGone, isSessionGoneForBackgroundPolling, markSessionGone } from './runtime-gone'
import { $activeSessionId } from './session'
// Blocking interactive prompts the gateway raises mid-turn. Each maps to a
@@ -127,13 +128,25 @@ export async function receiveApprovalRequest(gateway: ApprovalGateway | null, re
}
export async function replayPendingApproval(gateway: ApprovalGateway | null, sessionId: string | null): Promise<void> {
- if (!gateway || !sessionId) {
+ if (!gateway || !sessionId || isSessionGone(sessionId)) {
return
}
- const rawResult = await gateway.request('approval.pending', {
- session_id: sessionId
- })
+ let rawResult: unknown
+
+ try {
+ rawResult = await gateway.request('approval.pending', {
+ session_id: sessionId
+ })
+ } catch (error) {
+ if (isSessionGoneForBackgroundPolling(error)) {
+ markSessionGone(sessionId)
+
+ return
+ }
+
+ throw error
+ }
const result =
rawResult && typeof rawResult === 'object' ? (rawResult as { approvals?: PendingApprovalPayload[] }) : {}
diff --git a/apps/desktop/src/store/runtime-gone.ts b/apps/desktop/src/store/runtime-gone.ts
index c9b6ae81d56..8d65c7d693d 100644
--- a/apps/desktop/src/store/runtime-gone.ts
+++ b/apps/desktop/src/store/runtime-gone.ts
@@ -1,15 +1,74 @@
import { $activeSessionId, requestSessionResume } from './session'
import { $sessionStates, $sessionTiles, unbindTileRuntime } from './session-states'
+/** Session ids the gateway has told us are gone. A session-scoped RPC against a
+ * runtime the gateway no longer holds fails 4001 "session not found" — terminal
+ * for THIS runtime id, not a transient socket loss.
+ *
+ * Shared by every background poller (process.list, approval.pending, goal
+ * status). One set, one clear path: a fresh-runtime rebind calls
+ * {@link resetBackgroundPollingGuard} and every poller resumes. */
+const goneSessions = new Set<string>()
+
+/** Gateway JSON-RPC code for "session not found" (tui_gateway `_sess_nowait`). */
+const GATEWAY_SESSION_NOT_FOUND_CODE = 4001
+
+/** A gone session is unrecoverable for THIS runtime id; a timeout or transport
+ * blip is not. Only the former may stop a poll — misclassifying a transient
+ * failure would silently freeze a healthy session.
+ *
+ * Match the gateway's 4001 code when the error carries one. The message
+ * fallback survives only for errors with no numeric code at all. */
+export function isSessionGoneForBackgroundPolling(error: unknown): boolean {
+ const code =
+ error && typeof error === 'object' && typeof (error as { code?: unknown }).code === 'number'
+ ? (error as { code: number }).code
+ : undefined
+
+ if (code !== undefined) {
+ return code === GATEWAY_SESSION_NOT_FOUND_CODE
+ }
+
+ const message = error instanceof Error ? error.message : String(error ?? '')
+
+ return /session not found/i.test(message)
+}
+
+export function isSessionGone(sid: string): boolean {
+ return goneSessions.has(sid)
+}
+
+/** Latch `sid` off and heal the bound view. Safe to call on every 4001. */
+export function markSessionGone(sid: string): void {
+ if (!sid) {
+ return
+ }
+
+ goneSessions.add(sid)
+ markRuntimeGone(sid)
+}
+
+/** Clear the gone-latch. Called with a session id when a fresh runtime binds to
+ * it (so polling resumes), or with no argument to reset everything (tests /
+ * gateway reconnect). */
+export function resetBackgroundPollingGuard(sid?: string): void {
+ if (sid) {
+ goneSessions.delete(sid)
+
+ return
+ }
+
+ goneSessions.clear()
+}
+
/** Heal a session view whose bound runtime id the gateway no longer holds.
*
- * The desktop learns a runtime is gone through two channels, and only one of
- * them ever repaired anything:
+ * The desktop learns a runtime is gone through two channels:
*
- * - PUSH — `session.reclaimed`. `gateway-event/lifecycle.ts` drops the cached
- * state and calls `unbindTileRuntime`, which re-arms SessionTilePane's
- * resume effect (gated on `!runtimeId`) so the tile rebinds a fresh runtime
- * from the intact stored row.
+ * - PUSH — `session.reclaimed`. `gateway-event/lifecycle.ts` calls
+ * {@link markRuntimeGone} (same levers as the pull path) before dropping
+ * the cached state, so the primary chat resumes instead of sitting on the
+ * dead runtime until the user types.
* - PULL — a session-scoped RPC rejected `4001 "session not found"`. The
* gateway logs "client should resume the stored session" precisely because
* this is the terminal verdict; `_sess_nowait` has no other way to say it.
@@ -21,14 +80,9 @@ import { $sessionStates, $sessionTiles, unbindTileRuntime } from './session-stat
* id forever or (with the gone-latch) went silent against it, and in both cases
* the view stayed bound to a phantom runtime for the rest of its life.
*
- * That gap is only reachable through the pull channel. The push channel cannot
- * cover a runtime that died with a previous app process (boot-restore), was
- * reaped while this client was disconnected, or was reaped by a remote gateway
- * this renderer had not yet dialled — the broadcast has no live listener. In
- * those cases the 4001 is the *only* notice that ever arrives.
- *
- * So route it to the same recovery the broadcast drives. Both surfaces that can
- * hold a binding get their existing re-arm lever pulled:
+ * The pull channel is the only notice when the client missed the broadcast
+ * (boot-restore, disconnect, remote gateway). Both surfaces that can hold a
+ * binding get their existing re-arm lever pulled:
*
* - Tiles: `unbindTileRuntime` (SessionTilePane's resume effect refires).
* - The primary chat: `requestSessionResume`, the explicit-request lever. Its