The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): fold the stale-RPC guard into runtime-gone and refund heal budget on rebind
kshitijk4poor3f87a8090c39
diff --git a/apps/desktop/src/store/runtime-gone.test.ts b/apps/desktop/src/store/runtime-gone.test.tsindex 31585a27902..0abc60ceade 100644--- a/apps/desktop/src/store/runtime-gone.test.ts+++ b/apps/desktop/src/store/runtime-gone.test.ts@@ -182,4 +182,24 @@ describe('gone-latch classifier and rebind seam', () => {resetBackgroundPollingGuardAfterRebind('session.activate', { session_id: 'rt-other' }, undefined)expect(isSessionGone('rt-other')).toBe(false)})++ it('refunds the stored session heal budget on a successful rebind', () => {+ // Three reaps exhaust MAX_CONSECUTIVE_HEALS for STORED...+ for (const rt of ['rt-1', 'rt-2', 'rt-3']) {+ $sessionStates.set({ [rt]: cachedState(STORED) })+ $sessionTiles.set([tile(STORED, rt)])+ expect(markRuntimeGone(rt)).toBe(true)+ }++ $sessionStates.set({ 'rt-4': cachedState(STORED) })+ $sessionTiles.set([tile(STORED, 'rt-4')])+ expect(markRuntimeGone('rt-4')).toBe(false)++ // ...but a rebind of STORED proves it alive, so the next reap heals again.+ resetBackgroundPollingGuardAfterRebind('session.resume', { session_id: STORED }, { session_id: 'rt-5' })++ $sessionStates.set({ 'rt-5': cachedState(STORED) })+ $sessionTiles.set([tile(STORED, 'rt-5')])+ expect(markRuntimeGone('rt-5')).toBe(true)+ })})diff --git a/apps/desktop/src/store/runtime-gone.ts b/apps/desktop/src/store/runtime-gone.tsindex 42ba916051c..41cbd383d41 100644--- a/apps/desktop/src/store/runtime-gone.ts+++ b/apps/desktop/src/store/runtime-gone.ts@@ -1,47 +1,20 @@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- }-- // 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 {- return goneSessions.has(sid)+import {+ healsByStoredId,+ isSessionGone,+ isSessionGoneForBackgroundPolling,+ latchSessionGone,+ resetBackgroundPollingGuard,+ resetBackgroundPollingGuardAfterRebind+} from './session-gone-latch'++export {+ isSessionGone,+ isSessionGoneForBackgroundPolling,+ resetBackgroundPollingGuard,+ resetBackgroundPollingGuardAfterRebind}/** Latch `sid` off and heal the bound view. Safe to call on every 4001. */@@ -50,49 +23,10 @@ export function markSessionGone(sid: string): void {return}- goneSessions.add(sid)+ latchSessionGone(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()-}--/** 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:@@ -128,11 +62,12 @@ export function resetBackgroundPollingGuardAfterRebind(* for the same id could only come from a duplicate report of the same death. */const healedRuntimes = new Set<string>()-/** Consecutive heals per stored session id, reset by {@link noteRuntimeAlive}.- * A backend that reaps as fast as we resume would otherwise turn this into the- * very storm it exists to stop — one resume per poll tick, forever. Cap it and- * let the user's next action (which carries its own recovery) take over. */-const healsByStoredId = new Map<string, number>()+/** Consecutive heals per stored session id live in `session-gone-latch`+ * (`healsByStoredId`), reset by {@link noteRuntimeAlive} and by a successful+ * rebind. A backend that reaps as fast as we resume would otherwise turn this+ * into the very storm it exists to stop — one resume per poll tick, forever.+ * Cap it and let the user's next action (which carries its own recovery)+ * take over. *//** Enough to ride out a reap that races a resume, low enough that a backend* reaping on sight cannot be turned into a resume loop. */diff --git a/apps/desktop/src/store/session-gone-latch.ts b/apps/desktop/src/store/session-gone-latch.tsnew file mode 100644index 00000000000..d6cc153c2cf--- /dev/null+++ b/apps/desktop/src/store/session-gone-latch.ts@@ -0,0 +1,115 @@+import { JsonRpcGatewayError } from '@hermes/shared'++/** 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) and by the owner-routed RPC seam that clears it. This module is a+ * dependency-free leaf on purpose: `session-request-router` (which every+ * store imports) must be able to clear the latch after a successful rebind+ * without pulling the session/tile stores into its import graph. The public+ * surface for callers is `runtime-gone.ts`, which re-exports everything here. */+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. Codeless errors+ * (the frame's structure was lost across the IPC bridge or a wrapped rethrow)+ * are accepted only with a bare "session not found" body — a tool or report+ * string that merely mentions the phrase must not latch a live runtime. */+export function isSessionGoneForBackgroundPolling(error: unknown): boolean {+ if (error instanceof JsonRpcGatewayError && typeof error.code === 'number') {+ return error.code === GATEWAY_SESSION_NOT_FOUND_CODE+ }++ 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 ?? ''))+ .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: null | string | undefined): boolean {+ return Boolean(sid && goneSessions.has(sid))+}++/** Latch `sid` off. Idempotent. */+export function latchSessionGone(sid: string): void {+ if (sid) {+ goneSessions.add(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 /+ * a respawned backend that re-mints every runtime id). */+export function resetBackgroundPollingGuard(sid?: string): void {+ if (sid) {+ goneSessions.delete(sid)++ return+ }++ goneSessions.clear()+}++/** Ids a successful `session.resume` / `session.activate` just rebound — the+ * stored id it was asked for and the runtime id it answered with. Empty for+ * any other method: a socket reconnect is NOT a rebind (the backend may have+ * reaped the old runtime, and reopening a WebSocket does not make that id+ * valid again). Only a successful resume/activate response is proof. */+function reboundSessionIds(method: string, params: Record<string, unknown>, result: unknown): string[] {+ if (method !== 'session.activate' && method !== 'session.resume') {+ return []+ }++ const ids: string[] = []++ for (const value of [params.session_id, (result as { session_id?: unknown } | null)?.session_id]) {+ if (typeof value === 'string' && value.trim()) {+ ids.push(value.trim())+ }+ }++ return ids+}++/** Consecutive heals per stored session id (see `runtime-gone.ts`+ * `markRuntimeGone`). Lives here so the rebind seam below can refund it+ * without importing the heal module. */+export const healsByStoredId = new Map<string, number>()++/** Un-latch the ids a successful `session.resume` / `session.activate` just+ * rebound and refund the stored session's heal budget: a rebind is proof of+ * life, so the NEXT reap can still be healed. Without the refund a backend+ * that reaps a detached runtime a few times (per-request lease sockets+ * closing between polls) exhausts the heal cap and the view is stuck on a+ * phantom id forever (#100639: 1,230 approval.pending 4001s on one runtime+ * id in 42 minutes, zero recovery). Called by the session request router on+ * every routed RPC result; a no-op for every method but resume/activate. */+export function resetBackgroundPollingGuardAfterRebind(+ method: string,+ params: Record<string, unknown>,+ result: unknown+): void {+ for (const id of reboundSessionIds(method, params, result)) {+ goneSessions.delete(id)+ healsByStoredId.delete(id)+ }+}diff --git a/apps/desktop/src/store/session-request-router.test.ts b/apps/desktop/src/store/session-request-router.test.tsindex 9bd5a6d0ad2..8c3261b402e 100644--- a/apps/desktop/src/store/session-request-router.test.ts+++ b/apps/desktop/src/store/session-request-router.test.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { isSessionGone, markSessionGone, resetBackgroundPollingGuard } from './runtime-gone'+import { isSessionGone, latchSessionGone, resetBackgroundPollingGuard } from './session-gone-latch'// 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:@@ -186,13 +186,13 @@ 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')+ latchSessionGone('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')+ latchSessionGone('rt-rebound')await expect(requestForSessionProfile(null,@@ -212,7 +212,7 @@ describe('requestForSessionProfile', () => {installDesktop()const ambient = vi.fn(async () => ({ ambient: true }))- markSessionGone('profile-rebound')+ latchSessionGone('profile-rebound')await requestForSessionProfile('loki', ambient as never, 'session.resume', {session_id: 'profile-rebound'@@ -227,7 +227,7 @@ describe('requestForSessionProfile', () => {installDesktop()const ambient = vi.fn(async () => ({ ambient: true }))- markSessionGone('connection-rebound')+ latchSessionGone('connection-rebound')await requestForSessionProfile({ connectionId: 'source-a', profile: 'default' },diff --git a/apps/desktop/src/store/session-request-router.ts b/apps/desktop/src/store/session-request-router.tsindex 91cb5d2fdbb..943ed192e74 100644--- a/apps/desktop/src/store/session-request-router.ts+++ b/apps/desktop/src/store/session-request-router.ts@@ -1,6 +1,6 @@import { requestGatewayForAgent, requestGatewayForProfile, retainGatewayForSessionTurn } from '@/store/gateway'-import { resetBackgroundPollingGuardAfterRebind } from './runtime-gone'+import { resetBackgroundPollingGuardAfterRebind } from './session-gone-latch'/*** The ONE authoritative exact owner of a session: the registry connection whose