The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): drained restart polls fail and the restart reconnect probes before closing
Yuan Lia1725000fc15
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 e26404ebeb7..30a30467deb 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@@ -2658,6 +2658,97 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>})expect($gatewayState.get()).toBe('open')})++ // A restart recovery handed over from system-actions must not blind-close a+ // socket the restart never touched: `serve` dies with the app but the+ // messaging gateway survives it, so the common case is a HEALTHY socket.+ // Force-closing it rejects every in-flight RPC and forces a full re-bind —+ // the recovery would self-inflict the reconnect it exists to perform.+ it('explicit reconnect: a healthy socket answers the probe and is left untouched', async () => {+ render(<Harness />)+ await flushAsync()+ expect($gatewayState.get()).toBe('open')+ const socketCountBefore = FakeWebSocket.instances.length++ // Default FakeWebSocket.pingMode='pong': the probe answers, so the+ // handler must return without close() and without a redial.+ await act(async () => {+ await expect(reconnectGateway({ source: 'restart-followthrough' })).resolves.toBeUndefined()+ })++ expect(FakeWebSocket.instances.length).toBe(socketCountBefore)+ expect($gatewayState.get()).toBe('open')+ })++ it('explicit reconnect: a mid-turn inconclusive probe defers the teardown like the wake path', async () => {+ render(<Harness />)+ await flushAsync()+ expect($gatewayState.get()).toBe('open')+ const socketCountBefore = FakeWebSocket.instances.length++ act(() => {+ publishSessionState('rt-restart-turn', {+ ...createClientSessionState(null),+ storedSessionId: 's-restart-turn',+ busy: true+ })+ })+ expect($workingSessionIds.get()).toContain('s-restart-turn')++ // Busy-but-alive: the ping is swallowed, the first failure is inconclusive.+ FakeWebSocket.pingMode = 'silent'++ await act(async () => {+ const recovery = reconnectGateway({ source: 'restart-followthrough' })++ // The 5s probe budget must elapse before the deferral is decided.+ await vi.advanceTimersByTimeAsync(5_100)+ await expect(recovery).resolves.toBeUndefined()+ })++ // Deferred: the socket that the in-flight turn rides on is untouched.+ expect($gatewayState.get()).toBe('open')+ const survivingSocket = FakeWebSocket.instances[socketCountBefore - 1]+ expect(survivingSocket.readyState).toBe(FakeWebSocket.OPEN)++ clearAllSessionStates()++ // The deferral is bounded: the scheduled re-probe also goes unanswered and+ // no work is in flight anymore, so the socket is rebuilt after all.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(45_000)+ })++ expect(FakeWebSocket.instances.length).toBeGreaterThan(socketCountBefore)++ FakeWebSocket.pingMode = 'pong'+ await act(async () => {+ await vi.advanceTimersByTimeAsync(20_000)+ })+ expect($gatewayState.get()).toBe('open')+ })++ it('explicit reconnect: a dead idle socket is still force-closed and rebuilt', async () => {+ render(<Harness />)+ await flushAsync()+ expect($gatewayState.get()).toBe('open')+ const socketCountBefore = FakeWebSocket.instances.length++ // No turn in flight: silence has no innocent explanation.+ FakeWebSocket.pingMode = 'silent'++ await act(async () => {+ const recovery = reconnectGateway({ source: 'restart-followthrough' })++ // The probe budget elapses, the close fires, the backoff loop takes over.+ await vi.advanceTimersByTimeAsync(5_100)+ await expect(recovery).resolves.toBeUndefined()+ })+ await advanceBackoff()++ expect(FakeWebSocket.instances.length).toBeGreaterThan(socketCountBefore)+ expect($gatewayState.get()).toBe('open')+ })})describe('window-state IPC before the first connection publishes (#108641)', () => {diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.tsindex dd0c9270214..cdc9d4f0edc 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@ -56,7 +56,11 @@ import {setPrimaryGatewayConnection,touchSecondaryGateways} from '@/store/gateway'-import { reconnectGateway, registerGatewayReconnect } from '@/store/gateway-reconnect'+import {+ type GatewayReconnectOptions,+ reconnectGateway,+ registerGatewayReconnect+} from '@/store/gateway-reconnect'import {$gatewaySwitching,beginGatewaySwitch,@@ -1164,7 +1168,7 @@ export function useGatewayBoot({const offPowerResume = desktop.onPowerResume?.(() => void forceReconnectNow())const offConnectionApplied = desktop.onConnectionApplied?.(() => void softSwitch())- const offGatewayReconnect = registerGatewayReconnect(async () => {+ const offGatewayReconnect = registerGatewayReconnect(async (options?: GatewayReconnectOptions) => {if (cancelled || !bootCompleted || $gatewaySwitching.get()) {return}@@ -1181,9 +1185,64 @@ export function useGatewayBoot({return}- // Only explicit recovery may retry a credential that requires sign-in.- primaryReauthError = null- reauthNotified = false+ // Only MANUAL recovery may retry a credential that requires sign-in;+ // it keeps the unconditional re-dial as the escape hatch for a socket+ // the probe path cannot certify.+ if (options?.source !== 'restart-followthrough') {+ primaryReauthError = null+ reauthNotified = false+ ownCloseReason = 'manual'+ gateway.close()+ clearReconnectTimer()+ resetReconnectBackoff()++ await attemptReconnect({+ profile: normalizeProfileKey($activeGatewayProfile.get()),+ activationEpoch: gatewayActivationEpoch()+ })++ return+ }++ // A restart follow-through does not automatically need a teardown.+ // `serve` dies with the app but the messaging gateway survives it+ // (apps/desktop/AGENTS.md), so in the common case this socket is still+ // healthy — force-closing it would reject every in-flight RPC and+ // self-inflict the reconnect the follow-through is meant to perform.+ // Probe first: a provably-alive transport is left alone, and while a+ // turn is in flight an inconclusive probe defers behind the same+ // bounded re-probe the wake path uses (#95327) instead of+ // deterministically killing it. A probe that stays unanswered with no+ // work in flight still closes and re-dials, so a restart that DID take+ // this socket down is recovered here and now.+ try {+ await gateway.request('ping', {}, LIVENESS_PROBE_TIMEOUT_MS)+ livenessProbeFailures = 0++ return+ } catch (probeErr) {+ // A version-skewed backend that predates the ping method answers+ // -32601 (method not found) — a HEALTHY response, not a dead socket.+ if (probeErr instanceof JsonRpcGatewayError && probeErr.code === -32601) {+ livenessProbeFailures = 0++ return+ }++ const decision = decideLivenessForceClose({+ workingSessionCount: $workingSessionIds.get().length,+ consecutiveFailures: livenessProbeFailures + 1+ })++ if (!decision.close) {+ livenessProbeFailures += 1+ scheduleLivenessReprobe()++ return+ }++ livenessProbeFailures = 0+ }ownCloseReason = 'manual'gateway.close()clearReconnectTimer()diff --git a/apps/desktop/src/store/gateway-reconnect.ts b/apps/desktop/src/store/gateway-reconnect.tsindex 8c5a59a696b..dff8fc1f8d9 100644--- a/apps/desktop/src/store/gateway-reconnect.ts+++ b/apps/desktop/src/store/gateway-reconnect.ts@@ -1,6 +1,20 @@import { translateNow } from '@/i18n'-type GatewayReconnectHandler = () => Promise<void> | void+export type GatewayReconnectSource = 'manual' | 'restart-followthrough'++export interface GatewayReconnectOptions {+ /**+ * Why the reconnect is running. `'manual'` (default) is an explicit user+ * recovery — the handler may unconditionally re-dial, including retrying a+ * credential that requires sign-in. `'restart-followthrough'` is the+ * automatic hand-off after a gateway restart: the socket often SURVIVED+ * (the restart targets the messaging gateway, not this client's backend),+ * so the handler probes first instead of force-closing a healthy socket.+ */+ source?: GatewayReconnectSource+}++type GatewayReconnectHandler = (options?: GatewayReconnectOptions) => Promise<void> | voidlet activeHandler: GatewayReconnectHandler | null = nulllet inFlight: Promise<void> | null = null@@ -15,7 +29,7 @@ export function registerGatewayReconnect(handler: GatewayReconnectHandler): () =}}-export function reconnectGateway(): Promise<void> {+export function reconnectGateway(options?: GatewayReconnectOptions): Promise<void> {if (inFlight) {return inFlight}@@ -27,7 +41,7 @@ export function reconnectGateway(): Promise<void> {}inFlight = Promise.resolve()- .then(handler)+ .then(() => handler(options)).finally(() => {inFlight = null})diff --git a/apps/desktop/src/store/system-actions.test.ts b/apps/desktop/src/store/system-actions.test.tsindex bbdff15b53e..2150b46aad5 100644--- a/apps/desktop/src/store/system-actions.test.ts+++ b/apps/desktop/src/store/system-actions.test.ts@@ -35,8 +35,25 @@ afterEach(() => {vi.clearAllMocks()})-// The backend accepted the restart POST and then went down for the restart-// itself: every poll refused — the exact window #123111 reports.+// A backend that is down for the restart itself: polls refuse until `healthy`+// attempts in, then answer — the exact window #123111 reports. The status+// endpoint 404s for an action the (new) registry never saw and errors while+// the backend is down, so a REFUSAL is "no answer", not a terminal verdict.+const backendDownUntil = (healthyAt: number) => {+ let polls = 0++ getActionStatus.mockImplementation(async () => {+ polls += 1++ if (polls < healthyAt) {+ throw new Error('fetch failed')+ }++ return { name: 'gateway-restart', running: true, exit_code: null, pid: 4242, lines: [] }+ })+}++// A permanently dead backend: every poll for the whole window is refused.const refusedBackend = () => getActionStatus.mockRejectedValue(new Error('fetch failed'))// A replacement process whose in-memory action registry never saw this action@@ -45,8 +62,8 @@ const freshProcess = () =>getActionStatus.mockResolvedValue({ name: 'gateway-restart', running: false, exit_code: null, pid: null, lines: [] })describe('runGatewayRestart during the restart window (#123111)', () => {- it('resolves success when the status poll is refused mid-restart', async () => {- refusedBackend()+ it('resolves success when the status poll is refused mid-window, then answers', async () => {+ backendDownUntil(4)const outcome = runGatewayRestart()@@ -64,6 +81,18 @@ describe('runGatewayRestart during the restart window (#123111)', () => {await expect(outcome).resolves.toBe(true)})+ it('fails when the poll window is refused end to end — the restart never confirmed', async () => {+ refusedBackend()++ const outcome = runGatewayRestart()++ await settlePollWindow()+ // Draining the whole budget with zero answered polls must NOT resolve+ // success: the callers' failure banners stay up and the user sees the+ // failure toast instead of a cleared banner over a down gateway.+ await expect(outcome).resolves.toBe(false)+ })+it('still surfaces a real failure: a recorded non-zero exit', async () => {getActionStatus.mockResolvedValue({ name: 'gateway-restart', running: false, exit_code: 1, pid: null, lines: [] })@@ -73,8 +102,8 @@ describe('runGatewayRestart during the restart window (#123111)', () => {await expect(outcome).resolves.toBe(false)})- it('hands reconnection to the gateway reconnect owner after the restart', async () => {- refusedBackend()+ it('hands reconnection to the gateway reconnect owner after a confirmed restart', async () => {+ backendDownUntil(4)const handler = vi.fn()const off = registerGatewayReconnect(handler)@@ -107,8 +136,8 @@ describe('runGatewayRestart during the restart window (#123111)', () => {})describe('watchGatewayRestartOutcome (backend-spawned restart)', () => {- it('resolves true across a refused poll window and reconnects', async () => {- refusedBackend()+ it('resolves true across a refused-then-answered poll window and reconnects', async () => {+ backendDownUntil(4)const handler = vi.fn()const off = registerGatewayReconnect(handler)@@ -123,6 +152,15 @@ describe('watchGatewayRestartOutcome (backend-spawned restart)', () => {}})+ it('resolves false when the poll window is refused end to end', async () => {+ refusedBackend()++ const outcome = watchGatewayRestartOutcome()++ await settlePollWindow()+ await expect(outcome).resolves.toBe(false)+ })+it('resolves false on a recorded non-zero exit', async () => {getActionStatus.mockResolvedValue({ name: 'gateway-restart', running: false, exit_code: 1, pid: null, lines: [] })diff --git a/apps/desktop/src/store/system-actions.ts b/apps/desktop/src/store/system-actions.tsindex 38b2982e534..2a0e80f5634 100644--- a/apps/desktop/src/store/system-actions.ts+++ b/apps/desktop/src/store/system-actions.ts@@ -10,7 +10,6 @@ import type { ActionResponse } from '@/types/hermes'const POLL_ATTEMPTS = 18const POLL_INTERVAL_MS = 1200-const POLL_TIMEOUT_S = 180const GATEWAY_RESTART_ACTION = 'gateway-restart'// True while a gateway restart is in flight — drives the statusbar gateway@@ -27,25 +26,37 @@ export const $gatewayRestarting = atom(false)// while the old process exits and the new one binds, requests refuse/fail and// the in-memory action registry dies with the old process (a 404 or a fresh// process's `running:false, exit_code:null` is a healthy mid-restart state,-// not a failure). Those poll errors are tolerated so the restart the user-// asked for cannot surface as a false "restart failed" toast (#123111).+// not a failure). Mid-window refusals are therefore tolerated (#123111) — but+// only an ANSWERED poll proves the replacement backend actually came back, so+// a window refused end to end is a failure, not a silent success: resolving it+// would erase the caller's "restart needed" banner while the gateway stays+// down.async function awaitAction(name: string): Promise<void> {+ let sawAnsweredPoll = false+ let lastPollError: unknown = null+for (let attempt = 0; attempt < POLL_ATTEMPTS; attempt += 1) {await new Promise(resolve => window.setTimeout(resolve, POLL_INTERVAL_MS))let status: Awaited<ReturnType<typeof getActionStatus>>try {- status = await getActionStatus(name, POLL_TIMEOUT_S)- } catch {+ status = await getActionStatus(name)+ } catch (err) {// The backend accepted the restart POST a moment ago and is now// refusing — the expected shape of the restart window itself.+ lastPollError = err+continue}+ sawAnsweredPoll = true+ lastPollError = null+if (!status.running && status.exit_code == null) {// A fresh process that never saw this action id answers exactly this- // way; only a recorded non-zero exit (or a full budget) is a failure.+ // way; only a recorded non-zero exit is a failure (an entirely+ // unanswered window is handled after the loop).continue}@@ -57,6 +68,10 @@ async function awaitAction(name: string): Promise<void> {return}}++ if (!sawAnsweredPoll) {+ throw lastPollError ?? new Error(translateNow('commandCenter.gatewayRestartFailed'))+ }}// Under `gateway.multiplex_profiles` the profile in view has no gateway of its@@ -124,10 +139,14 @@ export async function runGatewayRestart(): Promise<boolean> {// (and any action-registry state with it), so leaving recovery to the// passive close→backoff machinery lets a Windows close-frame-less drop sit// as a zombie until the 45s heartbeat deadline — or until the user- // relaunches the app. Hand reconnection to the owner that knows how; a- // not-yet-registered handler or a still-down backend rejects and is- // swallowed (the boot loop keeps retrying regardless).- void reconnectGateway().catch(() => undefined)+ // relaunches the app. Hand reconnection to the owner that knows how, as a+ // RESTART follow-through: the owner probes the socket first, so a restart+ // that never touched this client's backend doesn't tear a healthy+ // connection down (and one that did gets rebuilt without the manual+ // path's unconditional close). A not-yet-registered handler or a+ // still-down backend rejects and is swallowed (the boot loop keeps+ // retrying regardless).+ void reconnectGateway({ source: 'restart-followthrough' }).catch(() => undefined)}}@@ -145,6 +164,8 @@ export async function watchGatewayRestartOutcome(): Promise<boolean> {return false} finally {$gatewayRestarting.set(false)- void reconnectGateway().catch(() => undefined)+ // Same restart follow-through as the requested flow above: probe-first+ // recovery, never the manual path's unconditional teardown.+ void reconnectGateway({ source: 'restart-followthrough' }).catch(() => undefined)}}