Skip to content

The agent that grows with you

fix(desktop): reconnect the client socket after a requested gateway restart

Yuan Li8b24396c0123
diff --git a/apps/desktop/src/store/system-actions.test.ts b/apps/desktop/src/store/system-actions.test.ts
new file mode 100644
index 00000000000..bbdff15b53e
--- /dev/null
+++ b/apps/desktop/src/store/system-actions.test.ts
@@ -0,0 +1,134 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type * as HermesApi from '@/hermes'
+import { registerGatewayReconnect } from '@/store/gateway-reconnect'
+
+// The REST layer is the only seam these flows own; the confirm dialog and
+// notifications stay real. getStatus answers a standalone gateway so
+// confirmSharedGatewayRestart() takes the silent no-dialog path.
+const getActionStatus = vi.fn()
+const restartGateway = vi.fn()
+
+vi.mock('@/hermes', async importOriginal => ({
+ ...(await importOriginal<typeof HermesApi>()),
+ getActionStatus: (name: string, timeout?: number) => getActionStatus(name, timeout),
+ getStatus: async () => ({}),
+ restartGateway: () => restartGateway()
+}))
+
+import { runGatewayRestart, watchGatewayRestartOutcome } from './system-actions'
+
+// Mirrors POLL_INTERVAL_MS × POLL_ATTEMPTS in system-actions.ts: the poll
+// window the flows own. Driven as one advance so timers AND promise
+// microtasks interleave the way the real loop runs.
+const POLL_WINDOW_MS = 18 * 1_200
+
+const settlePollWindow = () => vi.advanceTimersByTimeAsync(POLL_WINDOW_MS + 1_000)
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ restartGateway.mockResolvedValue({ ok: true, pid: 4242, name: 'gateway-restart' })
+})
+
+afterEach(() => {
+ vi.useRealTimers()
+ vi.clearAllMocks()
+})
+
+// The backend accepted the restart POST and then went down for the restart
+// itself: every poll refused — the exact window #123111 reports.
+const refusedBackend = () => getActionStatus.mockRejectedValue(new Error('fetch failed'))
+
+// A replacement process whose in-memory action registry never saw this action
+// id (the registry died with the process the restart replaced).
+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()
+
+ const outcome = runGatewayRestart()
+
+ await settlePollWindow()
+ await expect(outcome).resolves.toBe(true)
+ expect(getActionStatus).toHaveBeenCalled()
+ })
+
+ it('resolves success when a fresh process reports the action unknown', async () => {
+ freshProcess()
+
+ const outcome = runGatewayRestart()
+
+ await settlePollWindow()
+ await expect(outcome).resolves.toBe(true)
+ })
+
+ 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: [] })
+
+ const outcome = runGatewayRestart()
+
+ await settlePollWindow()
+ await expect(outcome).resolves.toBe(false)
+ })
+
+ it('hands reconnection to the gateway reconnect owner after the restart', async () => {
+ refusedBackend()
+ const handler = vi.fn()
+ const off = registerGatewayReconnect(handler)
+
+ try {
+ const outcome = runGatewayRestart()
+
+ await settlePollWindow()
+ await expect(outcome).resolves.toBe(true)
+ expect(handler).toHaveBeenCalledOnce()
+ } finally {
+ off()
+ }
+ })
+
+ it('hands reconnection to the owner even when the recorded exit failed', async () => {
+ getActionStatus.mockResolvedValue({ name: 'gateway-restart', running: false, exit_code: 1, pid: null, lines: [] })
+ const handler = vi.fn()
+ const off = registerGatewayReconnect(handler)
+
+ try {
+ const outcome = runGatewayRestart()
+
+ await settlePollWindow()
+ await expect(outcome).resolves.toBe(false)
+ expect(handler).toHaveBeenCalledOnce()
+ } finally {
+ off()
+ }
+ })
+})
+
+describe('watchGatewayRestartOutcome (backend-spawned restart)', () => {
+ it('resolves true across a refused poll window and reconnects', async () => {
+ refusedBackend()
+ const handler = vi.fn()
+ const off = registerGatewayReconnect(handler)
+
+ try {
+ const outcome = watchGatewayRestartOutcome()
+
+ await settlePollWindow()
+ await expect(outcome).resolves.toBe(true)
+ expect(handler).toHaveBeenCalledOnce()
+ } finally {
+ off()
+ }
+ })
+
+ it('resolves false on a recorded non-zero exit', async () => {
+ getActionStatus.mockResolvedValue({ name: 'gateway-restart', running: false, exit_code: 1, pid: null, lines: [] })
+
+ const outcome = watchGatewayRestartOutcome()
+
+ await settlePollWindow()
+ await expect(outcome).resolves.toBe(false)
+ })
+})
diff --git a/apps/desktop/src/store/system-actions.ts b/apps/desktop/src/store/system-actions.ts
index 1b2c67ea5d4..38b2982e534 100644
--- a/apps/desktop/src/store/system-actions.ts
+++ b/apps/desktop/src/store/system-actions.ts
@@ -4,6 +4,7 @@ import { getActionStatus, getStatus, restartGateway } from '@/hermes'
import { translateNow } from '@/i18n'
import { sharedGatewayProfiles } from '@/lib/shared-gateway-restart'
import { confirm } from '@/store/confirm'
+import { reconnectGateway } from '@/store/gateway-reconnect'
import { notify, notifyError } from '@/store/notifications'
import type { ActionResponse } from '@/types/hermes'
@@ -21,10 +22,32 @@ export const $gatewayRestarting = atom(false)
// non-zero exit so the caller can surface the failure. In no-service installs
// the child becomes the foreground gateway and never exits, so "still running
// when the window closes" counts as success.
+//
+// `gateway-restart` is polled against the very backend the restart takes down:
+// 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).
async function awaitAction(name: string): Promise<void> {
for (let attempt = 0; attempt < POLL_ATTEMPTS; attempt += 1) {
await new Promise(resolve => window.setTimeout(resolve, POLL_INTERVAL_MS))
- const status = await getActionStatus(name, POLL_TIMEOUT_S)
+
+ let status: Awaited<ReturnType<typeof getActionStatus>>
+
+ try {
+ status = await getActionStatus(name, POLL_TIMEOUT_S)
+ } catch {
+ // The backend accepted the restart POST a moment ago and is now
+ // refusing — the expected shape of the restart window itself.
+ continue
+ }
+
+ 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.
+ continue
+ }
if (!status.running) {
if (status.exit_code != null && status.exit_code !== 0) {
@@ -97,12 +120,20 @@ export async function runGatewayRestart(): Promise<boolean> {
return false
} finally {
$gatewayRestarting.set(false)
+ // The restart took down the process serving this client's own WebSocket
+ // (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)
}
}
// Watch a restart the BACKEND spawned (e.g. after Telegram QR onboarding writes
// credentials) instead of one this app requested. Same indicator, same bounded
-// poll; resolves `false` on a non-zero exit so the caller can re-arm its banner.
+// poll, same restart-window tolerance and reconnect follow-through.
export async function watchGatewayRestartOutcome(): Promise<boolean> {
$gatewayRestarting.set(true)
@@ -114,5 +145,6 @@ export async function watchGatewayRestartOutcome(): Promise<boolean> {
return false
} finally {
$gatewayRestarting.set(false)
+ void reconnectGateway().catch(() => undefined)
}
}