The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): wake probe counts the foreground turn as in-flight work; sibling pins and prune follow-through
kshitijk4poore796a2986629
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.tsindex 51fd4ec77c6..62eeff9c574 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@ -14,7 +14,11 @@ import type { DesktopBootProgress, HermesConnection, HermesWindowState } from '@import { HermesGateway } from '@/hermes'import { translateNow } from '@/i18n'import { desktopDefaultCwd } from '@/lib/desktop-fs'-import { decideLivenessForceClose, LIVENESS_REPROBE_DELAY_MS } from '@/lib/gateway-liveness-policy'+import {+ decideLivenessForceClose,+ LIVENESS_PROBE_TIMEOUT_MS,+ LIVENESS_REPROBE_DELAY_MS+} from '@/lib/gateway-liveness-policy'import { BACKEND_BOOT_WAIT_TIMEOUT_MS, RECONNECT_ATTEMPT_TIMEOUT_MS, withTimeout } from '@/lib/with-timeout'import {$desktopBoot,@@ -119,7 +123,6 @@ const RECONNECT_ESCALATE_AFTER_MS = 300_000// TIMEOUT alone no longer tears the socket down mid-turn (#95327): while a// turn is in flight the first timeout defers behind one bounded re-probe, so// only a STREAK of unanswered pings rebuilds the transport.-const GATEWAY_LIVENESS_PROBE_TIMEOUT_MS = 5_000// Renderer twin of the main process's POWER_RESUME_REVALIDATION_HOLDOFF_MS:// forced wake reconnects (online / power resume) are coalesced into one per@@ -571,7 +574,7 @@ export function useGatewayBoot({// one inconclusive probe DEFERS the teardown behind a bounded re-probe;// only an exhausted streak (or no in-flight work) closes.try {- await gateway.request('ping', {}, GATEWAY_LIVENESS_PROBE_TIMEOUT_MS)+ await gateway.request('ping', {}, LIVENESS_PROBE_TIMEOUT_MS)livenessProbeFailures = 0} catch (probeErr) {// A version-skewed backend that predates the ping method answers@@ -905,6 +908,7 @@ export function useGatewayBoot({// primary thread or a just-created session's owner hold is bound to// (#93892).foregroundScopes: foregroundSessionScopes,+ liveScopes: liveSessionScopes,onLocalProfileRetired: forgetProfileOnlyRuntimeOwners,onActiveConnectionChanged: publish,// Keep $activeGatewayProfile in lockstep with the registry's OWN record@@ -1028,14 +1032,18 @@ export function useGatewayBoot({return}+ // Only the destructive half is coalesced: a second wake inside the+ // holdoff (macOS fires resume then 'online' seconds apart) still runs+ // the cheap, idempotent nudge — primary ping probe, redial of already+ // closed secondaries — without touching open sockets.const now = Date.now()+ const forced = now - lastForcedWakeReconnectAt >= WAKE_RECONNECT_HOLDOFF_MS- if (now - lastForcedWakeReconnectAt < WAKE_RECONNECT_HOLDOFF_MS) {- return+ if (forced) {+ lastForcedWakeReconnectAt = now}- lastForcedWakeReconnectAt = now- void reconnectNow({ forceOpenSocket: true })+ void reconnectNow({ forceOpenSocket: forced })}const offPowerResume = desktop.onPowerResume?.(() => void forceReconnectNow())@@ -1136,6 +1144,10 @@ export function useGatewayBoot({const keepaliveTimer = setInterval(() => {touchActiveGatewayBackend()touchSecondaryGateways()+ // The pruner is otherwise event-driven: a socket spared by the+ // min-lifetime grace with no store change afterwards would hold its+ // pool slot forever.+ recomputeKeptGateways()}, 60_000)// Bound concurrency cost to consumers: keep a background socket while itsdiff --git a/apps/desktop/src/lib/gateway-liveness-policy.ts b/apps/desktop/src/lib/gateway-liveness-policy.tsindex 7e525f765b7..b5653d521f9 100644--- a/apps/desktop/src/lib/gateway-liveness-policy.ts+++ b/apps/desktop/src/lib/gateway-liveness-policy.ts@@ -35,6 +35,9 @@*//** Consecutive unanswered probes tolerated while work is in flight. */+/** Ping budget for a liveness probe (primary and secondary sockets share it). */+export const LIVENESS_PROBE_TIMEOUT_MS = 5_000+export const LIVENESS_PROBE_FAILURE_STREAK = 2/** How long after a deferred probe we try again (bounded, coalesced). */diff --git a/apps/desktop/src/store/gateway-activation-prune-lease.test.ts b/apps/desktop/src/store/gateway-activation-prune-lease.test.tsindex ca04ae69fec..c38f2fa41e9 100644--- a/apps/desktop/src/store/gateway-activation-prune-lease.test.ts+++ b/apps/desktop/src/store/gateway-activation-prune-lease.test.ts@@ -53,7 +53,8 @@ const {ensureGatewayForAgent,ensureGatewayForProfile,pruneSecondaryGateways,- setPrimaryGateway+ setPrimaryGateway,+ SECONDARY_MIN_LIFETIME_MS} = await import('./gateway')function installDesktop(): void {@@ -154,7 +155,7 @@ describe('activation lease vs. the live-work pruner (#89622)', () => {// Age the socket past the min-lifetime grace so this prune asserts the// lease release, not the freshly-opened spare (#94769).- vi.useFakeTimers({ now: Date.now() + 31_000 })+ vi.useFakeTimers({ now: Date.now() + SECONDARY_MIN_LIFETIME_MS + 1_000 })pruneSecondaryGateways(new Set())vi.useRealTimers()@@ -180,7 +181,7 @@ describe('activation lease vs. the live-work pruner (#89622)', () => {// Past the lease window: reclaimed. (Lease is wall-clock bounded so a// leaked lease cannot pin a dead entry forever.)- vi.setSystemTime(Date.now() + 31_000)+ vi.setSystemTime(Date.now() + SECONDARY_MIN_LIFETIME_MS + 1_000)pruneSecondaryGateways(new Set())expect(secondaryGateways[0].close).toHaveBeenCalled()@@ -207,7 +208,7 @@ describe('activation lease vs. the live-work pruner (#89622)', () => {expect(secondaryGateways[0].close).not.toHaveBeenCalled()// Past the grace window: reclaimed as idle, as before.- vi.setSystemTime(Date.now() + 31_000)+ vi.setSystemTime(Date.now() + SECONDARY_MIN_LIFETIME_MS + 1_000)pruneSecondaryGateways(new Set())expect(secondaryGateways[0].close).toHaveBeenCalled()})diff --git a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts b/apps/desktop/src/store/gateway-connection-lifecycle.test.tsindex dac711f97fb..155341c930b 100644--- a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts+++ b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts@@ -83,7 +83,8 @@ const {retainGatewayForAgent,retainGatewayForSessionTurn,retireLocalProfileGateways,- setPrimaryGateway+ setPrimaryGateway,+ SECONDARY_MIN_LIFETIME_MS} = await import('./gateway')function installDesktop(stub: Record<string, unknown>): void {@@ -330,7 +331,7 @@ describe('secondary reconnect runtime scope', () => {// Age the socket past the min-lifetime grace so this prune exercises the// stale-binding invalidation path, not the freshly-opened spare (#94769).- vi.useFakeTimers({ now: Date.now() + 31_000 })+ vi.useFakeTimers({ now: Date.now() + SECONDARY_MIN_LIFETIME_MS + 1_000 })pruneSecondaryGateways(new Set())vi.useRealTimers()expect(firstSocket.close).toHaveBeenCalledOnce()@@ -485,9 +486,14 @@ describe('reconnectSecondaryGateways', () => {// prompt.submit). The wake path probes instead: a dead transport is// closed; a healthy one — including a version-skewed backend answering// -32601 — keeps its socket (#94769 review).+ // The foreground turn is in flight on this scope. prompt.submit has long+ // since returned (turn completion arrives as stream events), so the entry+ // shows no counted request — the registry's live-scope hook is what tells+ // the probe there is work to protect.configureGatewayRegistry({onEvent: vi.fn(),- foregroundScopes: () => new Set(['conn:homelab::default'])+ foregroundScopes: () => new Set(['conn:homelab::default']),+ liveScopes: () => new Set(['conn:homelab::default'])} as never)const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) =>@@ -514,17 +520,11 @@ describe('reconnectSecondaryGateways', () => {expect(socket.close).not.toHaveBeenCalled()expect(socket.connectionState).toBe('open')- // Mid-turn: an in-flight request holds the entry's lease, and the backend- // — alive, but starved past the probe budget by a long tool call — cannot- // answer the ping. ONE unanswered probe must NOT close it: force-closing- // feeds the backend's ws_orphan_reap and interrupts the valid turn- // (#94769 review). The first failure defers behind a bounded re-probe.- socket.request = vi.fn(() => new Promise(() => {}))- void requestGatewayForAgent('homelab', 'default', 'prompt.submit', {})- await vi.waitFor(() => {- expect(socket.request).toHaveBeenCalled()- })-+ // Mid-turn, the backend — alive, but starved past the probe budget by a+ // long tool call — cannot answer the ping. ONE unanswered probe must NOT+ // close it: force-closing feeds the backend's ws_orphan_reap and+ // interrupts the valid turn (#94769 review). The first failure defers+ // behind a bounded re-probe.vi.useFakeTimers()socket.request = vi.fn(async () => {throw new Error('probe timeout')@@ -974,12 +974,12 @@ describe('cooperative pool retirement (supersedes #104871)', () => {})})-describe('rejected secondary authentication', () => {it('parks only the rejected source across automatic nudges and recovers on explicit selection', async () => {vi.useFakeTimers()const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({- ...descriptorFor(connectionId, profile), authMode: 'oauth'+ ...descriptorFor(connectionId, profile),+ authMode: 'oauth'}))const getGatewayWsUrlFor = vi.fn(async () => ({ ok: true, wsUrl: 'wss://cloud.invalid/api/ws?ticket=fresh' }))installDesktop({ getConnectionFor, getGatewayWsUrlFor })@@ -1008,7 +1008,8 @@ describe('rejected secondary authentication', () => {vi.useFakeTimers()const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({- ...descriptorFor(connectionId, profile), authMode: 'oauth'+ ...descriptorFor(connectionId, profile),+ authMode: 'oauth'}))const getGatewayWsUrlFor = vi.fn(async () => ({ ok: true, wsUrl: 'wss://cloud.invalid/api/ws?ticket=fresh' }))@@ -1030,11 +1031,11 @@ describe('rejected secondary authentication', () => {})})-it('keeps background auth rejection after socket disposal until recovery or connection removal', async () => {const { requestGatewayForAgent } = await import('./gateway')const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({- ...descriptorFor(connectionId, profile), authMode: 'oauth'+ ...descriptorFor(connectionId, profile),+ authMode: 'oauth'}))const getGatewayWsUrlFor = vi.fn(async () => ({ ok: false, needsOauthLogin: true, error: 'Sign in again' }))installDesktop({ getConnectionFor, getGatewayWsUrlFor })@@ -1054,14 +1055,16 @@ it('keeps background auth rejection after socket disposal until recovery or connexpect(getGatewayWsUrlFor).toHaveBeenCalledTimes(3)})-it('does not let a removed connection repopulate the auth rejection', async () => {const { requestGatewayForAgent } = await import('./gateway')const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({- ...descriptorFor(connectionId, profile), authMode: 'oauth'+ ...descriptorFor(connectionId, profile),+ authMode: 'oauth'}))let rejectTicket!: (error: Error) => void- const ticket = new Promise<never>((_resolve, reject) => { rejectTicket = reject })+ const ticket = new Promise<never>((_resolve, reject) => {+ rejectTicket = reject+ })const getGatewayWsUrlFor = vi.fn(() => ticket)installDesktop({ getConnectionFor, getGatewayWsUrlFor })const pending = requestGatewayForAgent('cloud', 'default', 'session.list')diff --git a/apps/desktop/src/store/gateway-connection-scope.test.ts b/apps/desktop/src/store/gateway-connection-scope.test.tsindex 047c6013d96..c043675e1b5 100644--- a/apps/desktop/src/store/gateway-connection-scope.test.ts+++ b/apps/desktop/src/store/gateway-connection-scope.test.ts@@ -49,7 +49,8 @@ const {openGatewayForAgent,pruneSecondaryGateways,setPrimaryGateway,- setPrimaryGatewayConnectionId+ setPrimaryGatewayConnectionId,+ SECONDARY_MIN_LIFETIME_MS} = await import('./gateway')const { setApiRequestConnection } = await import('@/hermes')@@ -133,7 +134,7 @@ describe('pruneSecondaryGateways with registry-scoped entries', () => {// one prune tick, so reclamation assertions age the socket past the grace// window first; spare assertions are unaffected by aging.const pruneAged = (keep?: Set<string>) => {- vi.useFakeTimers({ now: Date.now() + 31_000 })+ vi.useFakeTimers({ now: Date.now() + SECONDARY_MIN_LIFETIME_MS + 1_000 })pruneSecondaryGateways(keep ?? new Set())vi.useRealTimers()}diff --git a/apps/desktop/src/store/gateway-foreground-retention.test.ts b/apps/desktop/src/store/gateway-foreground-retention.test.tsindex 8e16e2dcd83..b51eb01ef84 100644--- a/apps/desktop/src/store/gateway-foreground-retention.test.ts+++ b/apps/desktop/src/store/gateway-foreground-retention.test.ts@@ -41,7 +41,8 @@ const {openGatewayForAgent,pruneSecondaryGateways,requestGatewayForAgent,- setPrimaryGateway+ setPrimaryGateway,+ SECONDARY_MIN_LIFETIME_MS} = await import('./gateway')const { $sessionTiles, foregroundSessionScopes, liveSessionScopes } = await import('./session-states')@@ -101,7 +102,7 @@ describe('foreground tile retention vs. the live-work pruner (#93892)', () => {// one prune tick, so reclamation assertions age the socket past the grace// window first; spare assertions are unaffected by aging.const pruneAged = () => {- vi.useFakeTimers({ now: Date.now() + 31_000 })+ vi.useFakeTimers({ now: Date.now() + SECONDARY_MIN_LIFETIME_MS + 1_000 })pruneSecondaryGateways(idleKeepSet())vi.useRealTimers()}diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex c625ca640f6..77c01ca2456 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -2,7 +2,6 @@ import {type ConnectionState,type GatewayEvent,isGatewayReauthRequired,- JsonRpcGatewayError,reconnectBackoffDelayMs,registryBackendScopeKey,resolveGatewayWsUrl,@@ -13,7 +12,12 @@ import { atom } from 'nanostores'import type { HermesConnection } from '@/global'import { HermesGateway, setApiRequestConnection } from '@/hermes'import { translateNow } from '@/i18n'-import { decideLivenessForceClose, LIVENESS_REPROBE_DELAY_MS } from '@/lib/gateway-liveness-policy'+import {+ decideLivenessForceClose,+ LIVENESS_PROBE_TIMEOUT_MS,+ LIVENESS_REPROBE_DELAY_MS+} from '@/lib/gateway-liveness-policy'+import { isMissingRpcMethod } from '@/lib/gateway-rpc'import { isTimeoutError, RECONNECT_ATTEMPT_TIMEOUT_MS, withTimeout } from '@/lib/with-timeout'import { notifyError, RECOVERY_ACTIONS } from '@/store/notifications'import { markNativeNotifyBaseline } from '@/store/notify-baseline'@@ -94,6 +98,12 @@ interface RegistryConfig {* follows the tile set, so closing the tile releases the socket.*/foregroundScopes?: () => ReadonlySet<string>+ /**+ * Scopes with a running or needs-input session runtime. The wake-path+ * liveness probe counts these as in-flight work: prompt.submit returns+ * before the turn ends, so `activeRequests` is 0 during most of a turn.+ */+ liveScopes?: () => ReadonlySet<string>}// ── Secondary (pool) backends ──────────────────────────────────────────────@@ -105,8 +115,6 @@ interface Secondary {connectionId: null | stringconnection: HermesConnection | nullgateway: HermesGateway- /** True after this entry completed at least one socket connection. */- openedOnce: boolean/*** Date.now() of the most recent socket 'open'. The live-work pruner's* min-lifetime grace reads this: an idle prune can race an on-demand dial@@ -672,7 +680,7 @@ async function openSecondary(entry: Secondary, spawnPriority: SpawnPriority = 'b// open. Awaiting it is intentional: correctness at the generation boundary// outranks the single local-module microtask this adds to a reconnect.const openedScopes = openedSecondaryScopes()- const reopening = entry.openedOnce || entry.connection !== null || openedScopes.has(entry.scope)+ const reopening = entry.lastOpenedAt > 0 || entry.connection !== null || openedScopes.has(entry.scope)let reconcileBusyAfterOpen: null | (() => void) = nullif (reopening) {@@ -744,7 +752,6 @@ async function openSecondary(entry: Secondary, spawnPriority: SpawnPriority = 'bthrow error}- entry.openedOnce = trueentry.lastOpenedAt = Date.now()// A fresh socket owes nothing to a previous socket's missed pings.entry.livenessProbeFailures = 0@@ -930,7 +937,6 @@ function createSecondary(profile: string, connectionId: null | string = null): SconnectionId,connection: null,gateway,- openedOnce: false,lastOpenedAt: 0,activeRequests: 0,connectPromise: null,@@ -1919,21 +1925,9 @@ const ACTIVE_GATEWAY_OPEN_WAIT_MS = 8_000// Grace period before the live-work pruner may dispose a freshly opened// secondary socket; see the min-lifetime guard in pruneSecondaryGateways-// (#94769 prune ↔ redial race).-const SECONDARY_MIN_LIFETIME_MS = 30_000+// (#94769 prune ↔ redial race). Exported for the tests that age a socket past it.+export const SECONDARY_MIN_LIFETIME_MS = 30_000-// Wake-path liveness probe budget for a live-in-use secondary: mirrors-// GATEWAY_LIVENESS_PROBE_TIMEOUT_MS in use-gateway-boot (the primary's probe).-const SECONDARY_WAKE_PROBE_TIMEOUT_MS = 5_000--// Probe a live-in-use secondary instead of blind-closing it on a forced wake,-// and close it only when the probe proves it not alive. A half-open TCP-// connection (sleep/wake, silent network drop) reports connectionState-// 'open' forever and fires no close event, so without this close an in-flight-// request rides a dead transport until its per-call timeout — prompt.submit's-// is 30 minutes. Closing arms the entry's ordinary reconnect backoff via its-// onState('closed') handler; a healthy-but-busy backend answers the ping and-// keeps its socket (#94769 review).// A deferred liveness re-probe for one entry: cleared when the probe is// answered, the socket is redialed (fresh streak), or the entry is disposed.function clearSecondaryLivenessReprobe(entry: Secondary): void {@@ -1943,12 +1937,16 @@ function clearSecondaryLivenessReprobe(entry: Secondary): void {}}+// Probe a live-in-use secondary instead of blind-closing it on a forced wake,+// and close it only when the probe proves it not alive. A half-open TCP+// connection (sleep/wake, silent network drop) reports connectionState+// 'open' forever and fires no close event, so without this close an in-flight+// request rides a dead transport until its per-call timeout — prompt.submit's+// is 30 minutes. Closing arms the entry's ordinary reconnect backoff via its+// onState('closed') handler; a healthy-but-busy backend answers the ping and+// keeps its socket (#94769 review).function probeSecondaryLiveness(entry: Secondary): void {- if (typeof entry.gateway.request !== 'function') {- return- }-- void entry.gateway.request('ping', {}, SECONDARY_WAKE_PROBE_TIMEOUT_MS).then(+ void entry.gateway.request('ping', {}, LIVENESS_PROBE_TIMEOUT_MS).then(() => {entry.livenessProbeFailures = 0clearSecondaryLivenessReprobe(entry)@@ -1957,7 +1955,7 @@ function probeSecondaryLiveness(entry: Secondary): void {// -32601 (method not found) = a version-skewed but HEALTHY backend that// predates the ping method — the same compatibility carve-out the// primary's probe makes in use-gateway-boot.- if (error instanceof JsonRpcGatewayError && error.code === -32601) {+ if (isMissingRpcMethod(error)) {entry.livenessProbeFailures = 0clearSecondaryLivenessReprobe(entry)@@ -1979,8 +1977,13 @@ function probeSecondaryLiveness(entry: Secondary): void {// exhausted — or immediately when nothing is in flight to protect.entry.livenessProbeFailures += 1+ // Counted RPCs alone under-report in-flight work: prompt.submit returns+ // before the turn ends, so a foreground turn mid tool call shows+ // activeRequests 0. The registry's live-scope hook supplies the turn.+ const turnInFlight = g.config?.liveScopes?.().has(entry.scope) ? 1 : 0+const decision = decideLivenessForceClose({- workingSessionCount: entry.activeRequests,+ workingSessionCount: entry.activeRequests + turnInFlight,consecutiveFailures: entry.livenessProbeFailures})@@ -2039,7 +2042,7 @@ export function reconnectSecondaryGateways({ forceOpenSockets = false }: { force// request would hang until its per-call timeout. Probe liveness instead —// a healthy-but-busy backend answers and keeps its socket; a dead// transport is closed and healed by the ordinary reconnect backoff.- if (entry.activeRequests > 0 || foregroundPinned(entry)) {+ if (entry.activeRequests > 0 || relayRetained(entry) || foregroundPinned(entry)) {probeSecondaryLiveness(entry)continue@@ -2216,10 +2219,9 @@ export function pruneSecondaryGateways(keep: Set<string>): void {// its consumer registered in the keep-set — closing it detaches the// runtime, the backend orphan-reaps it, and the reclaimed surface// re-resumes on a fresh socket the next recompute closes again: the- // #94769 flicker loop. A young socket rides one prune tick; the idle- // reap still catches it on a later recompute. Number guard: legacy/HMR- // entries may predate the field.- if (entry.lastOpenedAt > 0 && now - entry.lastOpenedAt < SECONDARY_MIN_LIFETIME_MS) {+ // #94769 flicker loop. A young socket rides one prune tick; the keepalive+ // tick recomputes the keep-set so an idle one is still reaped within a minute.+ if (now - entry.lastOpenedAt < SECONDARY_MIN_LIFETIME_MS) {continue}diff --git a/apps/desktop/src/store/session-request-router.test.ts b/apps/desktop/src/store/session-request-router.test.tsindex 376b6787af0..579b1744a40 100644--- a/apps/desktop/src/store/session-request-router.test.ts+++ b/apps/desktop/src/store/session-request-router.test.ts@@ -76,7 +76,8 @@ const {ensureGatewayForProfile,pruneSecondaryGateways,retireLocalProfileGateways,- setPrimaryGateway+ setPrimaryGateway,+ SECONDARY_MIN_LIFETIME_MS} = await import('./gateway')const { requestForSessionProfile, sessionRpcNeedsProfileRoute } = await import('./session-request-router')@@ -509,7 +510,7 @@ describe('requestForSessionProfile', () => {// Age the socket past the min-lifetime grace (#94769) so this prune// asserts the turn-lease release, not the freshly-opened spare.- vi.useFakeTimers({ now: Date.now() + 31_000 })+ vi.useFakeTimers({ now: Date.now() + SECONDARY_MIN_LIFETIME_MS + 1_000 })pruneSecondaryGateways(new Set())vi.useRealTimers()expect(secondaryGateways[0].close).toHaveBeenCalledOnce()