The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): defer gateway liveness force-close while a turn is in flight (#95327)
Finn763b1f133d4ea12
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.tsxindex 781d310ed5a..58a4389fb85 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@@ -2,6 +2,7 @@ import { act, cleanup, render } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { DesktopConnectionsRegistry } from '@/global'+import { createClientSessionState } from '@/lib/chat-runtime'import { $desktopBoot } from '@/store/boot'import {$connectionsRegistry,@@ -39,7 +40,7 @@ import {setActiveSessionId,setSelectedStoredSessionId} from '@/store/session'-import { $sessionTiles } from '@/store/session-states'+import { $sessionTiles, $workingSessionIds, clearAllSessionStates, publishSessionState } from '@/store/session-states'import { deferred } from '../../../test/deferred'@@ -1688,4 +1689,98 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>expect(FakeWebSocket.instances.length).toBe(socketCountBefore)expect($gatewayState.get()).toBe('open')})++ // #95327: every focus/visibility/power-resume nudge probes an OPEN socket+ // and force-closes it when the liveness ping times out. A backend that is+ // merely BUSY (a long silent tool call holding the loop) fails that probe+ // without being dead — closing the socket mid-turn is exactly what feeds the+ // gateway's ws_orphan_reap interrupt ("Operation interrupted." placeholder).+ // While any session still reports working, one inconclusive timeout must+ // defer the teardown (bounded re-probe) instead of killing the transport.+ it('wake probe: a timeout while a turn is IN FLIGHT defers the force-close', async () => {+ render(<Harness />)+ await flushAsync()+ expect($gatewayState.get()).toBe('open')+ const socketCountBefore = FakeWebSocket.instances.length++ // A turn is running on this very socket; backend silence is expected until+ // the tool call returns.+ act(() => {+ publishSessionState('rt-live-turn', {+ ...createClientSessionState(null),+ storedSessionId: 's-live-turn',+ busy: true+ })+ })+ expect($workingSessionIds.get()).toContain('s-live-turn')++ // Busy-but-alive: the ping is swallowed (loop starved), not refused.+ FakeWebSocket.pingMode = 'silent'++ act(() => window.dispatchEvent(new Event('online')))+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5_100)+ })++ // First inconclusive probe with work in flight: the socket must survive —+ // not merely "some socket is open again after a teardown + redial", but+ // THIS incarnation, whose transcript stream the running turn rides on.+ expect($gatewayState.get()).toBe('open')+ const survivingSocket = FakeWebSocket.instances[socketCountBefore - 1]++ expect(survivingSocket.readyState).toBe(FakeWebSocket.OPEN)++ clearAllSessionStates()++ // Recovery must not wedge once the working flag is gone: persistent+ // silence still exhausts the streak and rebuilds the transport.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(45_000)+ })++ FakeWebSocket.pingMode = 'pong'+ await act(async () => {+ await vi.advanceTimersByTimeAsync(20_000)+ })++ expect($gatewayState.get()).toBe('open')+ expect(FakeWebSocket.instances.length).toBeGreaterThanOrEqual(socketCountBefore)+ })++ it('wake probe: repeated timeouts while busy still rebuild the socket (no deadlock)', async () => {+ render(<Harness />)+ await flushAsync()+ expect($gatewayState.get()).toBe('open')+ const socketCountBefore = FakeWebSocket.instances.length++ act(() => {+ publishSessionState('rt-live-turn-2', {+ ...createClientSessionState(null),+ storedSessionId: 's-live-turn-2',+ busy: true+ })+ })++ // Genuinely dead under the working flag: EVERY probe keeps timing out.+ FakeWebSocket.pingMode = 'silent'++ for (let nudge = 0; nudge < 3; nudge += 1) {+ act(() => window.dispatchEvent(new Event('online')))+ await act(async () => {+ await vi.advanceTimersByTimeAsync(10_000)+ })+ }++ clearAllSessionStates()++ // The streak guard only DELAYS the teardown; a persistently unresponsive+ // socket is still rebuilt rather than trusted forever.+ expect(FakeWebSocket.instances.length).toBeGreaterThan(socketCountBefore)++ FakeWebSocket.pingMode = 'pong'+ await act(async () => {+ await vi.advanceTimersByTimeAsync(20_000)+ })+ expect($gatewayState.get()).toBe('open')+ })})diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.tsindex cc1d4afffa0..8d0b3ff9bfe 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@ -6,6 +6,7 @@ import type { HermesConnection } from '@/global'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 { reconnectBackoffDelayMs } from '@/lib/reconnect-backoff'import { BACKEND_BOOT_WAIT_TIMEOUT_MS, RECONNECT_ATTEMPT_TIMEOUT_MS, withTimeout } from '@/lib/with-timeout'import {@@ -96,7 +97,10 @@ const RECONNECT_ESCALATE_AFTER_MS = 300_000// ride out a busy-but-healthy backend's scheduling jitter, short enough that a// half-open socket fails fast instead of hanging the wake path. Independent of// PROMPT_SUBMIT_REQUEST_TIMEOUT_MS (30 min) — that long timeout is correct for-// an in-flight turn, but must never be what a dead connection burns.+// an in-flight turn, but must never be what a dead connection burns. A probe+// 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// Bounded self-heal for a failed REMOTE boot (#82679): when the primary boot@@ -214,6 +218,14 @@ export function useGatewayBoot({let reconnecting = falselet reconnectTimer: ReturnType<typeof setTimeout> | null = nulllet reconnectAttempt = 0+ // Consecutive unanswered liveness probes (#95327): a busy-but-healthy+ // backend can fail one probe; only a STREAK proves a genuinely dead+ // socket while turns are in flight. Reset on any successful probe or a+ // clean socket open.+ let livenessProbeFailures = 0+ // Bounded re-probe scheduled instead of an immediate teardown when a+ // probe times out mid-turn (see gateway-liveness-policy.ts).+ let livenessReprobeTimer: ReturnType<typeof setTimeout> | null = null// Wall-clock start of the current disconnect episode (first failed// reconnect attempt); null while healthy. Drives the time-based// escalation below. Reset on a clean open or a manual/wake reconnect.@@ -263,6 +275,28 @@ export function useGatewayBoot({}}+ const clearLivenessReprobeTimer = () => {+ if (livenessReprobeTimer !== null) {+ clearTimeout(livenessReprobeTimer)+ livenessReprobeTimer = null+ }+ }++ // One bounded retry before a mid-turn teardown: the first probe timeout+ // while work is in flight is inconclusive (a busy backend starves the+ // loop without being dead), so re-probe once after a short delay instead+ // of force-closing a socket a running turn still rides on (#95327).+ const scheduleLivenessReprobe = () => {+ if (cancelled || livenessReprobeTimer !== null || $gatewaySwitching.get()) {+ return+ }++ livenessReprobeTimer = setTimeout(() => {+ livenessReprobeTimer = null+ void reconnectNow()+ }, LIVENESS_REPROBE_DELAY_MS)+ }+const attemptReconnect = async () => {if (cancelled || reconnecting || gatewayOpen() || $gatewaySwitching.get()) {return@@ -436,18 +470,43 @@ export function useGatewayBoot({// ping; on failure force the socket down so the onState handler above// schedules a reconnect (and resetTileRuntimeBindings re-resumes tiles),// instead of letting the user's next submit hang against a dead socket.+ //+ // A TIMEOUT is not always proof of death, though (#95327): a backend+ // mid-tool-call can starve its loop past this budget while perfectly+ // alive, and tearing the socket down then feeds the gateway's+ // ws_orphan_reap interrupt — the turn dies as a bare "Operation+ // interrupted." placeholder. While any session still reports working,+ // 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)+ livenessProbeFailures = 0} catch (probeErr) {// A version-skewed backend that predates the ping method answers// -32601 (method not found) — a HEALTHY response, not a dead socket.// Force-closing on it would spin the reconnect loop forever. Every// other failure (timeout on a swallowed ping, transport error) means- // the socket is not actually alive and must be rebuilt.+ // the socket is not PROVABLY alive and must eventually be rebuilt.if (probeErr instanceof JsonRpcGatewayError && probeErr.code === -32601) {+ livenessProbeFailures = 0++ return+ }++ livenessProbeFailures += 1++ const decision = decideLivenessForceClose({+ workingSessionCount: $workingSessionIds.get().length,+ consecutiveFailures: livenessProbeFailures+ })++ if (!decision.close) {+ scheduleLivenessReprobe()+return}+ livenessProbeFailures = 0gateway.close()}}@@ -523,6 +582,8 @@ export function useGatewayBoot({const ownsSwitch = () => !cancelled && switchToken !== null && isCurrentGatewaySwitch(switchToken)clearReconnectTimer()clearBootRetryTimer()+ clearLivenessReprobeTimer()+ livenessProbeFailures = 0bootRetryAttempt = 0reconnectAttempt = 0reconnectFailingSince = null@@ -747,7 +808,9 @@ export function useGatewayBoot({reconnectFailingSince = nullreauthNotified = falseescalated = false+ livenessProbeFailures = 0clearReconnectTimer()+ clearLivenessReprobeTimer()// A revalidate-driven reconnect can rebuild the backend in place when the// cached remote was found dead, which re-drives the boot-progress overlay.@@ -1076,6 +1139,7 @@ export function useGatewayBoot({endGatewaySwitch()clearReconnectTimer()clearBootRetryTimer()+ clearLivenessReprobeTimer()clearInterval(keepaliveTimer)offWorking()offAttention()diff --git a/apps/desktop/src/lib/gateway-liveness-policy.test.ts b/apps/desktop/src/lib/gateway-liveness-policy.test.tsnew file mode 100644index 00000000000..841124be1b0--- /dev/null+++ b/apps/desktop/src/lib/gateway-liveness-policy.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from 'vitest'++import {+ decideLivenessForceClose,+ LIVENESS_PROBE_FAILURE_STREAK,+ LIVENESS_REPROBE_DELAY_MS+} from './gateway-liveness-policy'++describe('decideLivenessForceClose', () => {+ it('keeps the socket on the first timeout while a turn is in flight (#95327)', () => {+ const decision = decideLivenessForceClose({ workingSessionCount: 1, consecutiveFailures: 1 })++ expect(decision.close).toBe(false)+ expect(decision.reason).toBe('in-flight-work-deferred')+ })++ it('defers for every busy session count, not just one', () => {+ for (const workingSessionCount of [1, 2, 7]) {+ const decision = decideLivenessForceClose({ workingSessionCount, consecutiveFailures: 1 })++ expect(decision).toEqual({ close: false, reason: 'in-flight-work-deferred' })+ }+ })++ it('closes once the unanswered streak reaches the limit even while busy', () => {+ const decision = decideLivenessForceClose({+ workingSessionCount: 3,+ consecutiveFailures: LIVENESS_PROBE_FAILURE_STREAK+ })++ expect(decision.close).toBe(true)+ expect(decision.reason).toBe('failure-streak-exhausted')+ })++ it('closes immediately with no work in flight (legacy shape unchanged)', () => {+ const decision = decideLivenessForceClose({ workingSessionCount: 0, consecutiveFailures: 1 })++ expect(decision.close).toBe(true)+ expect(decision.reason).toBe('no-in-flight-work')+ })++ it('never lets a deferred defer outlive the streak boundary', () => {+ // Walk the whole streak: every failure below the limit defers; the limit+ // itself and anything beyond close.+ for (let failures = 1; failures <= LIVENESS_PROBE_FAILURE_STREAK + 2; failures += 1) {+ const decision = decideLivenessForceClose({ workingSessionCount: 1, consecutiveFailures: failures })++ expect(decision.close).toBe(failures >= LIVENESS_PROBE_FAILURE_STREAK)+ }+ })++ it('coerces malformed counters defensively instead of throwing', () => {+ expect(decideLivenessForceClose({ workingSessionCount: Number.NaN, consecutiveFailures: 0 })).toEqual({+ close: true,+ reason: 'no-in-flight-work'+ })+ expect(decideLivenessForceClose({ workingSessionCount: -3, consecutiveFailures: -10 })).toEqual({+ close: true,+ reason: 'no-in-flight-work'+ })+ })++ it('keeps the re-probe delay far below the probe budget stack so detection stays bounded', () => {+ // The re-probe is a second 5s liveness ping after this delay; together+ // they must stay well under the reconnect-escalation horizon (5 min).+ expect(LIVENESS_REPROBE_DELAY_MS).toBeGreaterThan(0)+ expect(LIVENESS_REPROBE_DELAY_MS).toBeLessThan(60_000)+ })+})diff --git a/apps/desktop/src/lib/gateway-liveness-policy.ts b/apps/desktop/src/lib/gateway-liveness-policy.tsnew file mode 100644index 00000000000..7e525f765b7--- /dev/null+++ b/apps/desktop/src/lib/gateway-liveness-policy.ts@@ -0,0 +1,85 @@+/**+ * Liveness-probe force-close policy for the primary gateway socket (#95327).+ *+ * Why this exists+ * ───────────────+ * Every window-lifecycle recovery signal (power resume, network online,+ * focus, visibility) nudges `reconnectNow()`. When the socket still reports+ * open, that path probes liveness with a short-bounded ping and FORCE-CLOSES+ * the socket when the ping times out — "a half-open TCP connection must not+ * swallow the user's next submit".+ *+ * A ping timeout proves a dead TRANSPORT, but it also fires for a live,+ * BUSY backend: a long silent tool call (a quiet build, an OCR worker, a+ * large download) starves the gateway's event loop past the 5s probe budget+ * (#74874's GIL-stall family, amplified on Windows by AV/filter-driver+ * latency). Tearing down the renderer↔backend WebSocket at that moment is a+ * false kill: the gateway sees its client vanish mid-turn, the+ * `ws_orphan_reap` grace expires, and the running turn is interrupted into a+ * bare "Operation interrupted." placeholder — the exact #95327 report.+ *+ * Policy+ * ──────+ * While ANY session still reports working (`$workingSessionIds`), backend+ * silence is EXPECTED, so a probe timeout is inconclusive rather than proof+ * of death. The first such timeout is deferred: keep the socket and schedule+ * one bounded re-probe instead. Only when the failure STREAK reaches+ * `LIVENESS_PROBE_FAILURE_STREAK` (the re-probe also went unanswered — or no+ * turn is in flight at all) do we treat the socket as genuinely dead and let+ * the normal close→backoff→redial machinery take over. Worst case this adds+ * one re-probe interval to genuine-dead detection; it removes the mid-turn+ * teardown entirely for busy-but-healthy backends.+ *+ * Pure and Electron-free so the streak boundaries are assertable directly+ * (mirroring gateway-liveness usage in use-gateway-boot).+ */++/** Consecutive unanswered probes tolerated while work is in flight. */+export const LIVENESS_PROBE_FAILURE_STREAK = 2++/** How long after a deferred probe we try again (bounded, coalesced). */+export const LIVENESS_REPROBE_DELAY_MS = 3_000++export interface LivenessForceCloseInput {+ /**+ * How many sessions currently report working (mid-turn). Zero means no+ * turn is riding this socket, so silence has no innocent explanation.+ */+ workingSessionCount: number+ /**+ * Length of the CURRENT unanswered-probe streak, INCLUDING the failure+ * being decided (first failure = 1).+ */+ consecutiveFailures: number+}++export type LivenessForceCloseReason = 'in-flight-work-deferred' | 'failure-streak-exhausted' | 'no-in-flight-work'++export interface LivenessForceCloseDecision {+ close: boolean+ reason: LivenessForceCloseReason+}++/**+ * Decide whether one liveness-probe failure should force the socket down.+ *+ * - No work in flight → close immediately (unchanged legacy shape:+ * a dead idle socket buys nothing by waiting).+ * - Work in flight, streak < max → keep the socket; the caller schedules a+ * bounded re-probe ('in-flight-work-deferred').+ * - Work in flight, streak ≥ max → close anyway ('failure-streak-exhausted'):+ * a persistently unresponsive socket must+ * still be rebuilt, never trusted forever.+ */+export function decideLivenessForceClose(input: LivenessForceCloseInput): LivenessForceCloseDecision {+ const workingSessionCount = Math.max(0, Math.floor(input.workingSessionCount))+ const consecutiveFailures = Math.max(1, Math.floor(input.consecutiveFailures))++ if (workingSessionCount > 0 && consecutiveFailures < LIVENESS_PROBE_FAILURE_STREAK) {+ return { close: false, reason: 'in-flight-work-deferred' }+ }++ return workingSessionCount > 0+ ? { close: true, reason: 'failure-streak-exhausted' }+ : { close: true, reason: 'no-in-flight-work' }+}