Skip to content

The agent that grows with you

fix(desktop): reconnect only the active gateway route

Teknium5f02693fe0f5
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.tsx
index 58a4389fb85..a8685af6876 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
@@ -15,8 +15,10 @@ import {
closeSecondaryGateways,
disposeSecondariesForConnection,
ensureGatewayForAgent,
+ ensureGatewayForProfile,
isActivePrimary,
- requestGatewayForAgent
+ requestGatewayForAgent,
+ retainGatewayForAgent
} from '@/store/gateway'
import { reconnectGateway } from '@/store/gateway-reconnect'
import {
@@ -1323,8 +1325,12 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>
expect($awaitingResponse.get()).toBe(false)
})
- it('manual reconnect revalidates, re-resolves, re-mints, and re-dials the dropped socket', async () => {
- const desktop = fakeDesktop()
+ it('manual reconnect replaces an open primary without closing background profiles', async () => {
+ const desktop = {
+ ...fakeDesktop(),
+ getConnectionFor: vi.fn(async () => coderConn),
+ getGatewayWsUrlFor: vi.fn(async () => coderConn.wsUrl)
+ }
;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop
@@ -1332,12 +1338,34 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>
await flushAsync()
expect($gatewayState.get()).toBe('open')
- act(() => FakeWebSocket.instances[0].drop())
- FakeWebSocket.mode = 'open'
+ vi.useRealTimers()
+ await ensureGatewayForAgent('coder-remote', 'coder')
+ const release = await retainGatewayForAgent('coder-remote', 'coder')
+ await ensureGatewayForProfile('default')
+ vi.useFakeTimers()
+ const backgroundSocket = FakeWebSocket.instances[1]
+ const oldPrimary = FakeWebSocket.instances[0]
+
+ const tiles = ['default', 'writer'].map(profile => ({
+ ownerRoute: { connectionId: 'primary-vps', mode: 'remote' as const, profile, targetProfile: profile },
+ runtimeId: `runtime-${profile}`,
+ storedSessionId: `chat-${profile}`,
+ workspaceMode: 'bots' as const,
+ workspaceOwnerKey: `primary-vps::${profile}`
+ }))
+
+ const revalidated = deferred<{ ok: boolean; rebuilt: boolean }>()
+ desktop.revalidateConnection.mockReturnValue(revalidated.promise)
await act(async () => {
const reconnect = reconnectGateway()
await vi.advanceTimersByTimeAsync(0)
+ await ensureGatewayForAgent('coder-remote', 'coder')
+ $sessionTiles.set(tiles)
+ $busy.set(true)
+ $awaitingResponse.set(true)
+ revalidated.resolve({ ok: true, rebuilt: false })
+ await vi.advanceTimersByTimeAsync(0)
await reconnect
})
@@ -1348,8 +1376,38 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>
const lastCall = desktop.getConnection.mock.calls.at(-1) ?? []
expect(lastCall.length === 0 || lastCall[0] == null || lastCall[0] === '').toBe(true)
expect(desktop.getGatewayWsUrl).toHaveBeenCalledTimes(2)
- expect(FakeWebSocket.instances).toHaveLength(2)
+ expect(oldPrimary.readyState).toBe(FakeWebSocket.CLOSED)
+ expect(backgroundSocket.readyState).toBe(FakeWebSocket.OPEN)
+ expect(FakeWebSocket.instances).toHaveLength(3)
+ expect($sessionTiles.get()[0]).not.toHaveProperty('runtimeId')
+ expect($sessionTiles.get()[1].runtimeId).toBe('runtime-writer')
+ expect($busy.get()).toBe(true)
+ expect($awaitingResponse.get()).toBe(true)
expect($gatewayState.get()).toBe('open')
+ release()
+ })
+
+ it('manual reconnect replaces only the active secondary route', async () => {
+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = {
+ ...fakeDesktop(),
+ getConnectionFor: vi.fn(async () => coderConn),
+ getGatewayWsUrlFor: vi.fn(async () => coderConn.wsUrl)
+ }
+ render(<Harness />)
+ await flushAsync()
+ vi.useRealTimers()
+ await ensureGatewayForAgent('coder-remote', 'coder')
+ const primarySocket = FakeWebSocket.instances[0]
+ const oldSecondary = FakeWebSocket.instances[1]
+ await reconnectGateway()
+
+ expect(primarySocket.readyState).toBe(FakeWebSocket.OPEN)
+ expect(oldSecondary.readyState).toBe(FakeWebSocket.CLOSED)
+ expect(FakeWebSocket.instances).toHaveLength(3)
+ expect(FakeWebSocket.instances[2].url).toBe(coderConn.wsUrl)
+ expect(activeGateway()?.connectionState).toBe('open')
+ expect(isActivePrimary()).toBe(false)
+ expect($connection.get()?.profile).toBe('coder')
})
it('power resume force-redials a half-open primary socket that still reports OPEN', async () => {
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
index bbb560257b2..edc957284c3 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -20,11 +20,13 @@ import {
import { resetBackgroundPollingGuard } from '@/store/composer-status'
import {
$gateway,
+ activeGateway,
activeGatewayConnectionId,
closeLegacySecondaryGateways,
closeSecondaryGateways,
configureGatewayRegistry,
disposeSecondariesForConnection,
+ ensureActiveGatewayOpen,
ensureGatewayForProfile,
gatewayActivationEpoch,
isActivePrimary,
@@ -300,7 +302,7 @@ export function useGatewayBoot({
}, LIVENESS_REPROBE_DELAY_MS)
}
- const attemptReconnect = async () => {
+ const attemptReconnect = async (manual?: { profile: string; activationEpoch: number }) => {
if (cancelled || reconnecting || gatewayOpen() || $gatewaySwitching.get()) {
return
}
@@ -371,23 +373,29 @@ export function useGatewayBoot({
// A legacy remote primary has no registry identity to scope by; fall
// back to preserving only Bot runtimes owned by provably-live
// secondaries so the restarted backend's own tiles still rebind.
+ const primaryConnectionId = primaryRuntimeConnectionId(conn)
resetTileRuntimeBindings(
- primaryRuntimeConnectionId(conn) ?? { liveConnectionIds: liveSecondaryConnectionIds() }
+ manual && primaryConnectionId
+ ? { connectionId: primaryConnectionId, profile: manual.profile }
+ : (primaryConnectionId ?? { liveConnectionIds: liveSecondaryConnectionIds() })
)
// The status-stack poll guard latches session ids the OLD runtime
// reported gone (4001). A respawned backend re-mints runtimes, so
// those ids may be live again after re-resume — clear the latch with
// the same lifetime as the runtime bindings it shadows.
resetBackgroundPollingGuard()
+
// Same staleness, other half: pre-reconnect busy flags are keyed by
// those dead runtime ids and would never receive their terminal
// busy:false — clear them or the sidebar running arc lies forever
// (#53902/#73082). A genuinely live turn re-asserts busy on its next
// post-reconnect event.
- reconcileBusyStatesOnReconnect()
- // Resync state that may have moved on the backend while we were asleep.
- await callbacksRef.current.refreshHermesConfig().catch(() => undefined)
- await callbacksRef.current.refreshSessions().catch(() => undefined)
+ // A manual retry may finish after the user has moved to another route.
+ if (!manual || (isActivePrimary() && gatewayActivationEpoch() === manual.activationEpoch)) {
+ reconcileBusyStatesOnReconnect()
+ await callbacksRef.current.refreshHermesConfig().catch(() => undefined)
+ await callbacksRef.current.refreshSessions().catch(() => undefined)
+ }
} catch (err) {
// OAuth session expired mid-reconnect: surface the actionable "sign in
// again" recovery overlay once instead of silently looping the backoff
@@ -857,7 +865,34 @@ export function useGatewayBoot({
const forceReconnectNow = () => reconnectNow({ forceOpenSocket: true })
const offPowerResume = desktop.onPowerResume?.(() => void forceReconnectNow())
const offConnectionApplied = desktop.onConnectionApplied?.(() => void softSwitch())
- const offGatewayReconnect = registerGatewayReconnect(forceReconnectNow)
+
+ const offGatewayReconnect = registerGatewayReconnect(async () => {
+ if (cancelled || !bootCompleted || $gatewaySwitching.get()) {
+ return
+ }
+
+ // Explicit recovery targets the route the user is viewing, not every
+ // warm profile. A responsive ping does not prove delivery is unstuck.
+ if (!isActivePrimary()) {
+ activeGateway()?.close()
+
+ if (!(await ensureActiveGatewayOpen())) {
+ throw new Error('Hermes gateway is not connected')
+ }
+
+ return
+ }
+
+ gateway.close()
+ clearReconnectTimer()
+ reconnectAttempt = 0
+ reconnectFailingSince = null
+ escalated = false
+ await attemptReconnect({
+ profile: normalizeProfileKey($activeGatewayProfile.get()),
+ activationEpoch: gatewayActivationEpoch()
+ })
+ })
// Registry lifecycle: a removed connection's secondaries must close NOW
// (remote/cloud have no local process whose death would drop the socket —
diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md
index 5f18c6279bc..0580240824e 100644
--- a/website/docs/user-guide/desktop.md
+++ b/website/docs/user-guide/desktop.md
@@ -449,6 +449,10 @@ another profile's agent plugins without switching the whole app (the backend
## Troubleshooting
+### Reconnect without restarting the app
+
+If a Desktop chat or bot stops responding while the connection still shows **Connected**, select that bot/profile or gateway, open the status bar's gateway menu, and click **Reconnect gateway**. Reconnect stays available for open, connecting, and disconnected transports. It redials the active route without restarting Desktop or deliberately closing other routes' sockets. In-flight requests on the selected socket can be interrupted; this is an explicit recovery action, not a backend or model restart.
+
### Failed turns name the failing layer
When a turn fails, the chat renders an error card that names **which layer