The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): stop stale session RPC retries
Shinji Kaneko16021395f900
diff --git a/apps/desktop/src/store/composer-status.test.ts b/apps/desktop/src/store/composer-status.test.tsindex d47103b0cbe..5173f8aa237 100644--- a/apps/desktop/src/store/composer-status.test.ts+++ b/apps/desktop/src/store/composer-status.test.ts@@ -7,9 +7,11 @@ import {isSessionGoneForBackgroundPolling,reconcileBackgroundProcesses,refreshBackgroundProcesses,- resetBackgroundPollingGuard+ resetBackgroundPollingGuard,+ stopBackgroundProcess} from './composer-status'import { $gateway } from './gateway'+import { markSessionGone } from './runtime-gone'const SID = 'sess-1'@@ -263,6 +265,41 @@ describe('refreshBackgroundProcesses dead-session guard', () => {expect(request).toHaveBeenCalledTimes(2)})++ it('dismisses a stale process row when Stop is clicked after the runtime is gone', async () => {+ reconcileBackgroundProcesses(SID, [running('stale')])+ markSessionGone(SID)+ $gateway.set({ request: vi.fn() } as never)++ await stopBackgroundProcess(SID, 'stale')++ expect(items()).toEqual([])+ })++ it('dismisses a stale process row while the gateway is disconnected', async () => {+ reconcileBackgroundProcesses(SID, [running('disconnected')])+ markSessionGone(SID)+ $gateway.set(null as never)++ await stopBackgroundProcess(SID, 'disconnected')++ expect(items()).toEqual([])+ })++ it('dismisses and latches when Stop discovers the runtime is gone', async () => {+ const request = vi.fn(async () => {+ throw new Error('session not found')+ })++ reconcileBackgroundProcesses(SID, [running('rejected')])+ $gateway.set({ request } as never)++ await stopBackgroundProcess(SID, 'rejected')+ await stopBackgroundProcess(SID, 'rejected')++ expect(items()).toEqual([])+ expect(request).toHaveBeenCalledTimes(1)+ })})// ── Review-thread hardenings on the guard (#94950) ───────────────────────────diff --git a/apps/desktop/src/store/composer-status.ts b/apps/desktop/src/store/composer-status.tsindex ce891688e53..ea2d7ae04c3 100644--- a/apps/desktop/src/store/composer-status.ts+++ b/apps/desktop/src/store/composer-status.ts@@ -8,9 +8,15 @@ import { $gateway } from './gateway'import { $goalsBySession, type GoalStatus } from './goals'import { dispatchNativeNotification } from './native-notifications'import { notifyError } from './notifications'-import { isSessionGone, isSessionGoneForBackgroundPolling, markSessionGone, noteRuntimeAlive } from './runtime-gone'+import {+ isSessionGone,+ isSessionGoneForBackgroundPolling,+ markSessionGone,+ noteRuntimeAlive,+ resetBackgroundPollingGuard+} from './runtime-gone'import { $sessions, lineageAliases } from './session'-import { $sessionStates } from './session-states'+import { $sessionStates, requestForOwnedSession } from './session-states'import { $subagentsBySession, type SubagentProgress } from './subagents'import { $todosBySession } from './todos'@@ -401,7 +407,14 @@ export async function refreshBackgroundProcesses(sid: string): Promise<void> {}try {- const result = await gateway.request<{ processes?: GatewayProcessEntry[] }>('process.list', { session_id: sid })+ const ambientRequest = <T>(method: string, params?: Record<string, unknown>) =>+ gateway.request<T>(method, params ?? {})+ const result = await requestForOwnedSession<{ processes?: GatewayProcessEntry[] }>(+ sid,+ ambientRequest,+ 'process.list',+ { session_id: sid }+ )reconcileBackgroundProcesses(sid, result?.processes ?? [])// The binding answered, so it is healthy: refund the stored session's@@ -441,10 +454,34 @@ export function dismissBackgroundProcess(sid: string, id: string) {* row while the process lived on, stranding rogue tasks. On failure the row* stays so the user can retry / see it didn't die. */export async function stopBackgroundProcess(sid: string, id: string): Promise<void> {+ const gateway = $gateway.get()++ if (isSessionGone(sid)) {+ // The backend has already declared this runtime gone, so there is no+ // authoritative process left to kill through this session. Remove the+ // stale local row instead of leaving the Stop button permanently inert.+ dismissBackgroundProcess(sid, id)++ return+ }++ if (!gateway) {+ return+ }+try {- await $gateway.get()?.request('process.kill', { process_id: id, session_id: sid })+ const ambientRequest = <T>(method: string, params?: Record<string, unknown>) =>+ gateway.request<T>(method, params ?? {})+ await requestForOwnedSession(sid, ambientRequest, 'process.kill', { process_id: id, session_id: sid })dismissBackgroundProcess(sid, id)} catch (err) {+ if (isSessionGoneForBackgroundPolling(err)) {+ dismissBackgroundProcess(sid, id)+ markSessionGone(sid)++ return+ }+notifyError(err, 'Could not stop the process')}}@@ -471,7 +508,18 @@ export function resetSessionBackground(sid: string) {dismissed.add(item.id)if (item.state === 'running') {- void gateway?.request('process.kill', { process_id: item.id, session_id: sid }).catch(() => undefined)+ if (gateway && !isSessionGone(sid)) {+ const ambientRequest = <T>(method: string, params?: Record<string, unknown>) =>+ gateway.request<T>(method, params ?? {})+ void requestForOwnedSession(sid, ambientRequest, 'process.kill', {+ process_id: item.id,+ session_id: sid+ }).catch(error => {+ if (isSessionGoneForBackgroundPolling(error)) {+ markSessionGone(sid)+ }+ })+ }}}diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex 7601ea258ed..cbd643f0663 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -531,18 +531,6 @@ async function openSecondary(entry: Secondary): Promise<void> {// real store; a failed import must not make the transport unrecoverable.}- // Runtime re-mint also invalidates the status-stack gone-latch: ids- // the dead runtime 4001'd may be live again once tiles re-resume.- // Fire-and-forget: composer-status imports from this module, so the- // import must stay dynamic (cycle), and it must NOT sit on the timed- // redial path — awaiting the module load here pushed cold-start- // redials past test/waitFor budgets. The reset needs no ordering- // guarantee relative to the dial.- void import('@/store/composer-status')- .then(({ resetBackgroundPollingGuard }) => resetBackgroundPollingGuard())- .catch(() => {- // Best effort for partial test/HMR graphs, same as above.- })}// Registry-scoped entries dial through getConnectionFor when the bridge hasdiff --git a/apps/desktop/src/store/goals.test.ts b/apps/desktop/src/store/goals.test.tsindex e355776f364..c69ab23b2de 100644--- a/apps/desktop/src/store/goals.test.ts+++ b/apps/desktop/src/store/goals.test.ts@@ -1,3 +1,4 @@+import { JsonRpcGatewayError } from '@hermes/shared'import { afterEach, describe, expect, it, vi } from 'vitest'import { $gateway } from './gateway'@@ -8,6 +9,8 @@ describe('goal store', () => {afterEach(() => {vi.useRealTimers()$goalsBySession.set({})+ $gateway.set(null as never)+ resetBackgroundPollingGuard()})it('stores active goals from /goal output', () => {@@ -109,6 +112,19 @@ describe('goal store', () => {expect($goalsBySession.get().s2).toMatchObject({ status: 'paused', title: 'other work' })})++ it('does not retry goal hydration for a runtime rejected as session-not-found', async () => {+ const request = vi.fn(async () => {+ throw new JsonRpcGatewayError('session not found', { code: 4001 })+ })++ $gateway.set({ request } as never)++ await refreshSessionGoal('dead-runtime')+ await refreshSessionGoal('dead-runtime')++ expect(request).toHaveBeenCalledTimes(1)+ })})describe('refreshSessionGoal dead-session guard', () => {diff --git a/apps/desktop/src/store/goals.ts b/apps/desktop/src/store/goals.tsindex aa51be46ce9..1bd648b5257 100644--- a/apps/desktop/src/store/goals.ts+++ b/apps/desktop/src/store/goals.ts@@ -4,6 +4,7 @@ import { keyedTimeouts } from '@/lib/keyed-timeouts'import { $gateway } from './gateway'import { isSessionGone, isSessionGoneForBackgroundPolling, markSessionGone } from './runtime-gone'+import { requestForOwnedSession } from './session-states'export type GoalStatus = 'active' | 'done' | 'paused' | 'waiting'@@ -169,7 +170,14 @@ export async function refreshSessionGoal(sid: string): Promise<void> {}try {- const result = await gateway.request<{ output?: string }>('slash.exec', { command: 'goal status', session_id: sid })+ const ambientRequest = <T>(method: string, params?: Record<string, unknown>) =>+ gateway.request<T>(method, params ?? {})+ const result = await requestForOwnedSession<{ output?: string }>(+ sid,+ ambientRequest,+ 'slash.exec',+ { command: 'goal status', session_id: sid }+ )applyGoalStatusText(sid, result?.output ?? '', { hydrate: true })} catch (error) {diff --git a/apps/desktop/src/store/native-notifications.ts b/apps/desktop/src/store/native-notifications.tsindex 09edafc2bbd..341d31a1eaf 100644--- a/apps/desktop/src/store/native-notifications.ts+++ b/apps/desktop/src/store/native-notifications.ts@@ -7,6 +7,7 @@ import { $gateway } from './gateway'import { withinNativeNotifyBaseline } from './notify-baseline'import { clearApprovalRequest } from './prompts'import { $activeSessionId } from './session'+import { isSessionGoneForBackgroundPolling, markSessionGone } from './runtime-gone'import { requestForOwnedSession } from './session-states'export type { HermesOpenTarget }@@ -373,7 +374,11 @@ export async function respondToApprovalAction(sessionId: null | string, actionId{ choice, session_id: sessionId ?? undefined })clearApprovalRequest(sessionId)- } catch {+ } catch (error) {+ if (isSessionGoneForBackgroundPolling(error)) {+ markSessionGone(sessionId)+ }+// Leave the prompt parked so the user can still resolve it in-app.}}diff --git a/apps/desktop/src/store/prompts.test.ts b/apps/desktop/src/store/prompts.test.tsindex 9f0e761f718..d1e8360f912 100644--- a/apps/desktop/src/store/prompts.test.ts+++ b/apps/desktop/src/store/prompts.test.ts@@ -1,4 +1,5 @@-import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { JsonRpcGatewayError } from '@hermes/shared'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { clearClarifyRequest, setClarifyRequest } from './clarify'import {@@ -16,8 +17,8 @@ import {setSecretRequest,setSudoRequest} from './prompts'-import { resetBackgroundPollingGuard } from './runtime-gone'import { $activeSessionId } from './session'+import { isSessionGone, resetBackgroundPollingGuard } from './runtime-gone'// Prompts are parked per-session; the exported $*Request views are scoped to the// active session, so each test focuses the session it's asserting on.@@ -29,6 +30,7 @@ afterEach(() => {clearAllPrompts()clearClarifyRequest()$activeSessionId.set(null)+ resetBackgroundPollingGuard()})describe('approval prompt store', () => {@@ -130,6 +132,34 @@ describe('approval prompt store', () => {['approval.received', { request_id: 'r1', session_id: 's1' }]])})++ it('does not replay a pending approval after the runtime is rejected as gone', async () => {+ const request = vi.fn(async () => {+ throw new JsonRpcGatewayError('session not found', { code: 4001 })+ })++ await replayPendingApproval({ request }, 'dead-runtime')+ await replayPendingApproval({ request }, 'dead-runtime')++ expect(request).toHaveBeenCalledTimes(1)+ expect(isSessionGone('dead-runtime')).toBe(true)+ expect($approvalRequest.get()).toBeNull()+ })++ it('keeps approval receipt failures contained and marks the runtime gone', async () => {+ const request = vi.fn(async () => {+ throw new JsonRpcGatewayError('session not found', { code: 4001 })+ })++ $activeSessionId.set('dead-runtime')++ await expect(+ receiveApprovalRequest({ request }, { command: 'x', description: 'd', requestId: 'r1', sessionId: 'dead-runtime' })+ ).resolves.toBeUndefined()++ expect(isSessionGone('dead-runtime')).toBe(true)+ expect($approvalRequest.get()?.requestId).toBe('r1')+ })})describe('sudo prompt store', () => {diff --git a/apps/desktop/src/store/prompts.ts b/apps/desktop/src/store/prompts.tsindex 4aca295eded..ae34ee2db0f 100644--- a/apps/desktop/src/store/prompts.ts+++ b/apps/desktop/src/store/prompts.ts@@ -3,6 +3,7 @@ import { atom, computed, type ReadableAtom } from 'nanostores'import { $clarifyRequest, $clarifyRequests } from './clarify'import { isSessionGone, isSessionGoneForBackgroundPolling, markSessionGone } from './runtime-gone'import { $activeSessionId } from './session'+import { requestForOwnedSession } from './session-states'// Blocking interactive prompts the gateway raises mid-turn. Each maps to a// `*.request` event the Python side emits while it blocks the agent thread@@ -120,10 +121,21 @@ export async function receiveApprovalRequest(gateway: ApprovalGateway | null, resetApprovalRequest(request)if (gateway && request.requestId && request.sessionId) {- await gateway.request('approval.received', {- request_id: request.requestId,- session_id: request.sessionId- })+ try {+ const ambientRequest = <T>(method: string, params?: Record<string, unknown>) =>+ gateway.request(method, params ?? {}) as Promise<T>++ await requestForOwnedSession(+ request.sessionId,+ ambientRequest,+ 'approval.received',+ { request_id: request.requestId, session_id: request.sessionId }+ )+ } catch (error) {+ if (isSessionGoneForBackgroundPolling(error)) {+ markSessionGone(request.sessionId)+ }+ }}}@@ -135,17 +147,21 @@ export async function replayPendingApproval(gateway: ApprovalGateway | null, seslet rawResult: unknowntry {- rawResult = await gateway.request('approval.pending', {- session_id: sessionId- })+ const ambientRequest = <T>(method: string, params?: Record<string, unknown>) =>+ gateway.request(method, params ?? {}) as Promise<T>++ rawResult = await requestForOwnedSession(+ sessionId,+ ambientRequest,+ 'approval.pending',+ { session_id: sessionId }+ )} catch (error) {if (isSessionGoneForBackgroundPolling(error)) {markSessionGone(sessionId)-- return}- throw error+ return}const result =diff --git a/apps/desktop/src/store/runtime-gone.test.ts b/apps/desktop/src/store/runtime-gone.test.tsindex c7e52806164..31585a27902 100644--- a/apps/desktop/src/store/runtime-gone.test.ts+++ b/apps/desktop/src/store/runtime-gone.test.ts@@ -1,8 +1,17 @@+import { JsonRpcGatewayError } from '@hermes/shared'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { refreshBackgroundProcesses, resetBackgroundPollingGuard } from './composer-status'import { $gateway } from './gateway'-import { markRuntimeGone, noteRuntimeAlive, resetRuntimeGoneHealing } from './runtime-gone'+import {+ isSessionGone,+ isSessionGoneForBackgroundPolling,+ markRuntimeGone,+ markSessionGone,+ noteRuntimeAlive,+ resetBackgroundPollingGuardAfterRebind,+ resetRuntimeGoneHealing+} from './runtime-gone'import { $activeSessionId, $sessionResumeRequest } from './session'import { $sessionStates, $sessionTiles } from './session-states'@@ -147,3 +156,30 @@ describe('refreshBackgroundProcesses recovery', () => {expect($sessionResumeRequest.get()).toBeNull()})})++describe('gone-latch classifier and rebind seam', () => {+ it('recognizes structured 4001 and bare legacy text without misclassifying coded errors', () => {+ expect(isSessionGoneForBackgroundPolling(new JsonRpcGatewayError('gone', { code: 4001 }))).toBe(true)+ expect(isSessionGoneForBackgroundPolling(new JsonRpcGatewayError('session not found', { code: 5007 }))).toBe(false)+ expect(isSessionGoneForBackgroundPolling(new JsonRpcGatewayError('session not found'))).toBe(true)+ expect(isSessionGoneForBackgroundPolling(new Error("Error invoking remote method 'x': Error: session not found"))).toBe(+ true+ )+ expect(isSessionGoneForBackgroundPolling(new Error('tool failed: upstream said session not found'))).toBe(false)+ })++ it('clears the latch only for ids a successful resume/activate rebound', () => {+ markSessionGone('rt-dead')+ markSessionGone('rt-other')++ resetBackgroundPollingGuardAfterRebind('process.list', { session_id: 'rt-dead' }, { session_id: 'rt-dead' })+ expect(isSessionGone('rt-dead')).toBe(true)++ resetBackgroundPollingGuardAfterRebind('session.resume', { session_id: 'stored-1' }, { session_id: 'rt-dead' })+ expect(isSessionGone('rt-dead')).toBe(false)+ expect(isSessionGone('rt-other')).toBe(true)++ resetBackgroundPollingGuardAfterRebind('session.activate', { session_id: 'rt-other' }, undefined)+ expect(isSessionGone('rt-other')).toBe(false)+ })+})diff --git a/apps/desktop/src/store/runtime-gone.ts b/apps/desktop/src/store/runtime-gone.tsindex 8d65c7d693d..42ba916051c 100644--- a/apps/desktop/src/store/runtime-gone.ts+++ b/apps/desktop/src/store/runtime-gone.ts@@ -29,9 +29,15 @@ export function isSessionGoneForBackgroundPolling(error: unknown): boolean {return code === GATEWAY_SESSION_NOT_FOUND_CODE}- const message = error instanceof Error ? error.message : String(error ?? '')-- return /session not found/i.test(message)+ // Codeless errors: the frame's structure was lost somewhere (IPC bridge,+ // wrapped rethrow). Accept only a bare "session not found" body — a tool or+ // report string that merely mentions the phrase must not latch a live runtime.+ const message = (error instanceof Error ? error.message : String(error ?? ''))+ .trim()+ .replace(/^Error invoking remote method '[^']+':\s*Error:\s*/i, '')+ .replace(/^Error:\s*/i, '')++ return /^(?:4001\s*[:,-]?\s*)?session not found[.!]?$/i.test(message)}export function isSessionGone(sid: string): boolean {@@ -61,6 +67,32 @@ export function resetBackgroundPollingGuard(sid?: string): void {goneSessions.clear()}+/** Clear the gone-latch for the ids a successful `session.resume` /+ * `session.activate` just rebound — the stored id it was asked for and the+ * runtime id it answered with.+ *+ * A socket reconnect is NOT a rebind: the backend may have reaped the old+ * runtime, and merely reopening a WebSocket does not make that id valid+ * again. Only a successful resume/activate response is proof the runtime can+ * be targeted, so this is the one seam that un-latches per id. */+export function resetBackgroundPollingGuardAfterRebind(+ method: string,+ params: Record<string, unknown>,+ result: unknown+): void {+ if (method !== 'session.activate' && method !== 'session.resume') {+ return+ }++ const candidates = [params.session_id, (result as { session_id?: unknown } | null)?.session_id]++ for (const value of candidates) {+ if (typeof value === 'string' && value.trim()) {+ goneSessions.delete(value.trim())+ }+ }+}+/** Heal a session view whose bound runtime id the gateway no longer holds.** The desktop learns a runtime is gone through two channels:diff --git a/apps/desktop/src/store/session-request-router.test.ts b/apps/desktop/src/store/session-request-router.test.tsindex 3ec852e2849..10268403e87 100644--- a/apps/desktop/src/store/session-request-router.test.ts+++ b/apps/desktop/src/store/session-request-router.test.ts@@ -1,5 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { isSessionGone, markSessionGone, resetBackgroundPollingGuard } from './runtime-gone'+// Regression coverage for the #89206 wake-failure class: session-scoped RPCs// routed to a backend that does not own the session's profile. Three layers:// 1. The registry publishes the ACTIVE route's profile ($activeGatewayRoute)@@ -105,6 +107,7 @@ beforeEach(() => {secondaryGateways.length = 0promptAckStatus = null$connectionsRegistry.set(null)+ resetBackgroundPollingGuard()configureGatewayRegistry({ onEvent: vi.fn() })closeSecondaryGateways()})@@ -112,6 +115,7 @@ beforeEach(() => {afterEach(() => {closeSecondaryGateways()vi.clearAllMocks()+ resetBackgroundPollingGuard()delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop})@@ -179,6 +183,29 @@ describe('sessionRpcNeedsProfileRoute', () => {})describe('requestForSessionProfile', () => {+ it('clears a dead-runtime latch only after a successful resume or activate', async () => {+ const ambient = vi.fn(async () => ({ session_id: 'rt-rebound' }))++ markSessionGone('rt-rebound')+ expect(isSessionGone('rt-rebound')).toBe(true)++ await requestForSessionProfile(null, ambient as never, 'session.activate', { session_id: 'rt-rebound' })+ expect(isSessionGone('rt-rebound')).toBe(false)++ markSessionGone('rt-rebound')+ await expect(+ requestForSessionProfile(+ null,+ vi.fn(async () => {+ throw new Error('resume failed')+ }) as never,+ 'session.resume',+ { session_id: 'rt-rebound' }+ )+ ).rejects.toThrow('resume failed')+ expect(isSessionGone('rt-rebound')).toBe(true)+ })+it('keeps routing a bare profile owner through its legacy profile pool when a connection registry exists', async () => {// A profile pick on the primary or the explicit `local` source takes the// legacy profile-only door (store/profile activateOnCurrentSource), so adiff --git a/apps/desktop/src/store/session-request-router.ts b/apps/desktop/src/store/session-request-router.tsindex 3cb1993c33c..e328bd6f891 100644--- a/apps/desktop/src/store/session-request-router.ts+++ b/apps/desktop/src/store/session-request-router.ts@@ -1,5 +1,7 @@import { requestGatewayForAgent, requestGatewayForProfile, retainGatewayForSessionTurn } from '@/store/gateway'+import { resetBackgroundPollingGuardAfterRebind } from './runtime-gone'+/*** The ONE authoritative exact owner of a session: the registry connection whose* socket minted (or resumed) the runtime, plus the Desktop profile that selects@@ -114,6 +116,7 @@ async function withRoutedTurnLease<T>(try {const result = await request()+ resetBackgroundPollingGuardAfterRebind(method, params, result)if (!turnKeepsRunning(result)) {release()@@ -126,6 +129,17 @@ async function withRoutedTurnLease<T>(}}+async function requestWithRebindGuard<T>(+ method: string,+ params: Record<string, unknown>,+ request: () => Promise<T>+): Promise<T> {+ const result = await request()+ resetBackgroundPollingGuardAfterRebind(method, params, result)++ return result+}+/*** True when a session-scoped RPC must be pinned to `ownerProfile`'s own socket.*@@ -193,14 +207,14 @@ export function requestForSessionProfile<T>(// for a deadline (the plugin host bridge in contrib/wiring is the only one// that does).if (signal !== undefined) {- return ambientRequest<T>(method, params, timeoutMs, signal)+ return requestWithRebindGuard(method, params, () => ambientRequest<T>(method, params, timeoutMs, signal))}if (timeoutMs !== undefined) {- return ambientRequest<T>(method, params, timeoutMs)+ return requestWithRebindGuard(method, params, () => ambientRequest<T>(method, params, timeoutMs))}- return ambientRequest<T>(method, params)+ return requestWithRebindGuard(method, params, () => ambientRequest<T>(method, params))}const profile = normKey(ownerProfile)