Skip to content

The agent that grows with you

fix(desktop): stop forced wake reconnects from churning live secondary sockets

psam69c51bb008ff
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 e678b755dc0..9e77961cb03 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -121,6 +121,11 @@ const RECONNECT_ESCALATE_AFTER_MS = 300_000
// 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
+// window instead of tearing down every secondary socket on each signal (#94769).
+const WAKE_RECONNECT_HOLDOFF_MS = 15_000
+
// Bounded self-heal for a failed REMOTE boot (#82679): main classifies every
// fault it can see (via getBootProgress().retryable); the renderer adds the one
// it cannot — a valid remote WebSocket dial that fails before becoming usable.
@@ -1001,7 +1006,30 @@ export function useGatewayBoot({
// Wake signals: power resume (macOS/Windows), network coming back, and the
// window regaining focus/visibility. Each nudges an immediate reconnect.
- const forceReconnectNow = () => reconnectNow({ forceOpenSocket: true })
+ //
+ // Forced reconnects (power resume / 'online') close and redial every open
+ // secondary socket. Windows fires 'online' on any interface change — VPN
+ // connects, Wi-Fi blips, virtual adapter enumeration — so an unthrottled
+ // handler reaped healthy sockets in bursts and the UI remounted on every
+ // redial: the #94769 flicker loop. Coalesce forced wakes like the main
+ // process already does for power-resume revalidation
+ // (POWER_RESUME_REVALIDATION_HOLDOFF_MS): one forced reconnect per
+ // holdoff window; a socket dropped in between is still picked up by the
+ // ordinary close/reconnect backoff and by the non-forced focus/visibility
+ // nudges below.
+ let lastForcedWakeReconnectAt = 0
+
+ const forceReconnectNow = () => {
+ const now = Date.now()
+
+ if (now - lastForcedWakeReconnectAt < WAKE_RECONNECT_HOLDOFF_MS) {
+ return
+ }
+
+ lastForcedWakeReconnectAt = now
+ void reconnectNow({ forceOpenSocket: true })
+ }
+
const offPowerResume = desktop.onPowerResume?.(() => void forceReconnectNow())
const offConnectionApplied = desktop.onConnectionApplied?.(() => void softSwitch())
diff --git a/apps/desktop/src/store/gateway-activation-prune-lease.test.ts b/apps/desktop/src/store/gateway-activation-prune-lease.test.ts
index 184f75f5ed9..ca04ae69fec 100644
--- a/apps/desktop/src/store/gateway-activation-prune-lease.test.ts
+++ b/apps/desktop/src/store/gateway-activation-prune-lease.test.ts
@@ -152,7 +152,11 @@ describe('activation lease vs. the live-work pruner (#89622)', () => {
// lease released, the idle entry must be disposed exactly as before.
await ensureGatewayForProfile('default')
+ // 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 })
pruneSecondaryGateways(new Set())
+ vi.useRealTimers()
expect(secondaryGateways[0].close).toHaveBeenCalled()
})
@@ -182,4 +186,29 @@ describe('activation lease vs. the live-work pruner (#89622)', () => {
releaseConnect()
})
+
+ it('a freshly opened idle secondary rides one prune tick before reaping (#94769)', async () => {
+ vi.useFakeTimers()
+
+ // A socket that just opened is a prune ↔ on-demand-dial race in the making:
+ // its consumer may not have registered in the keep-set yet, and closing it
+ // detaches the runtime → backend orphan-reap → `session.reclaimed` →
+ // re-resume on a fresh socket the next recompute closes again. The
+ // min-lifetime grace bounds that race without pinning the entry forever.
+ await ensureGatewayForProfile('bot')
+ expect(secondaryGateways[0].connectionState).toBe('open')
+
+ // Move away so 'bot' is neither active nor in the keep-set.
+ await ensureGatewayForProfile('default')
+ expect(secondaryGateways).toHaveLength(1)
+
+ // Immediately after open: spared by the grace window.
+ pruneSecondaryGateways(new Set())
+ expect(secondaryGateways[0].close).not.toHaveBeenCalled()
+
+ // Past the grace window: reclaimed as idle, as before.
+ vi.setSystemTime(Date.now() + 31_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.ts
index 6b2c7fa3821..26d569d2530 100644
--- a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts
+++ b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts
@@ -318,7 +318,12 @@ describe('secondary reconnect runtime scope', () => {
await openGatewayForAgent('homelab', 'writer')
const firstSocket = gatewayMocks.instances[0]
+
+ // 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 })
pruneSecondaryGateways(new Set())
+ vi.useRealTimers()
expect(firstSocket.close).toHaveBeenCalledOnce()
let finishReconnect!: () => void
@@ -436,6 +441,34 @@ describe('reconnectSecondaryGateways', () => {
expect(getConnectionFor).toHaveBeenCalledTimes(2)
expect(gatewayMocks.instances[0].connectionState).toBe('open')
})
+
+ it('spares a foreground-pinned secondary from the forced wake redial (#94769)', async () => {
+ // A forced wake (power resume / network online) closing a socket a mounted
+ // surface is bound to detaches its runtime → backend orphan-reap →
+ // `session.reclaimed` → re-resume on a fresh socket the same signal may
+ // close again: the reconnect/remount flicker loop. The registry's
+ // foregroundScopes hook is the same pin the live-work pruner honors.
+ configureGatewayRegistry({
+ onEvent: vi.fn(),
+ foregroundScopes: () => new Set(['conn:homelab::default'])
+ } as never)
+
+ const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) =>
+ descriptorFor(connectionId, profile)
+ )
+
+ installDesktop({ getConnectionFor })
+
+ await ensureGatewayForAgent('homelab', 'default')
+ expect(gatewayMocks.instances[0].connectionState).toBe('open')
+
+ reconnectSecondaryGateways({ forceOpenSockets: true })
+ await Promise.resolve()
+
+ expect(gatewayMocks.instances[0].close).not.toHaveBeenCalled()
+ expect(gatewayMocks.instances[0].connectionState).toBe('open')
+ expect(getConnectionFor).toHaveBeenCalledTimes(1)
+ })
})
describe('reconnect fail-stop on a removed connection', () => {
diff --git a/apps/desktop/src/store/gateway-connection-scope.test.ts b/apps/desktop/src/store/gateway-connection-scope.test.ts
index 5fb959a00b8..047c6013d96 100644
--- a/apps/desktop/src/store/gateway-connection-scope.test.ts
+++ b/apps/desktop/src/store/gateway-connection-scope.test.ts
@@ -129,6 +129,15 @@ describe('primary gateway registry scope', () => {
})
describe('pruneSecondaryGateways with registry-scoped entries', () => {
+ // The min-lifetime grace (#94769) spares a freshly opened idle socket for
+ // 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 })
+ pruneSecondaryGateways(keep ?? new Set())
+ vi.useRealTimers()
+ }
+
it('keeps the previous source socket open when Sessions switches backends', async () => {
await ensureGatewayForAgent('work', 'default')
await ensureGatewayForAgent('homelab', 'default')
@@ -144,7 +153,7 @@ describe('pruneSecondaryGateways with registry-scoped entries', () => {
// LOCAL source has live work; that must not pin homelab's socket.
await openGatewayForAgent('homelab', 'default')
- pruneSecondaryGateways(new Set(['default']))
+ pruneAged(new Set(['default']))
expect(gatewayMocks.closed).toEqual(['wss://homelab.invalid/api/ws?profile=default'])
})
@@ -172,11 +181,11 @@ describe('pruneSecondaryGateways with registry-scoped entries', () => {
it('still keeps a local (profile-keyed) secondary via its bare profile name', async () => {
await openGatewayForAgent(null, 'research')
- pruneSecondaryGateways(new Set(['research']))
+ pruneAged(new Set(['research']))
expect(gatewayMocks.closed).toEqual([])
- pruneSecondaryGateways(new Set())
+ pruneAged()
expect(gatewayMocks.closed).toHaveLength(1)
})
@@ -189,7 +198,7 @@ describe('pruneSecondaryGateways with registry-scoped entries', () => {
await openGatewayForAgent(null, 'default')
await openGatewayForAgent('homelab', 'default')
- pruneSecondaryGateways(new Set(['conn:homelab::default']))
+ pruneAged(new Set(['conn:homelab::default']))
expect(gatewayMocks.closed).toEqual(['wss://local.invalid/api/ws?token=t'])
})
diff --git a/apps/desktop/src/store/gateway-foreground-retention.test.ts b/apps/desktop/src/store/gateway-foreground-retention.test.ts
index baf801bdf2c..8e16e2dcd83 100644
--- a/apps/desktop/src/store/gateway-foreground-retention.test.ts
+++ b/apps/desktop/src/store/gateway-foreground-retention.test.ts
@@ -97,6 +97,15 @@ afterEach(() => {
})
describe('foreground tile retention vs. the live-work pruner (#93892)', () => {
+ // The min-lifetime grace (#94769) spares a freshly opened idle socket for
+ // 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 })
+ pruneSecondaryGateways(idleKeepSet())
+ vi.useRealTimers()
+ }
+
it('keeps an idle Bot Chat tile’s owner socket across prune recomputes', async () => {
// The BOTS workspace dials the bot's own backend without activating it
// (keepAllProfilesScope) and opens the canonical chat as a tile on that
@@ -107,8 +116,8 @@ describe('foreground tile retention vs. the live-work pruner (#93892)', () => {
// Idle: no working / needs-input session anywhere. Before the fix this
// recompute closed the socket → backend reaped the runtime → reclaim →
// unbind → resume → … forever.
- pruneSecondaryGateways(idleKeepSet())
- pruneSecondaryGateways(idleKeepSet())
+ pruneAged()
+ pruneAged()
expect(gatewayMocks.closed).toEqual([])
})
@@ -117,7 +126,7 @@ describe('foreground tile retention vs. the live-work pruner (#93892)', () => {
await openGatewayForAgent('local', 'bot')
$sessionTiles.set([{ ...BOT_TILE, runtimeId: undefined }])
- pruneSecondaryGateways(idleKeepSet())
+ pruneAged()
expect(gatewayMocks.closed).toEqual([])
})
@@ -125,11 +134,11 @@ describe('foreground tile retention vs. the live-work pruner (#93892)', () => {
it('releases the socket once the tile is closed — the pin never latches', async () => {
await openGatewayForAgent('local', 'bot')
$sessionTiles.set([BOT_TILE])
- pruneSecondaryGateways(idleKeepSet())
+ pruneAged()
expect(gatewayMocks.closed).toEqual([])
$sessionTiles.set([])
- pruneSecondaryGateways(idleKeepSet())
+ pruneAged()
expect(gatewayMocks.closed).toEqual(['wss://local.invalid/api/ws?profile=bot'])
})
@@ -161,7 +170,7 @@ describe('foreground tile retention vs. the live-work pruner (#93892)', () => {
// the same `retained` flag; with no tile bound to it, it is idle garbage.
await openGatewayForAgent('local', 'bot')
- pruneSecondaryGateways(idleKeepSet())
+ pruneAged()
expect(gatewayMocks.closed).toEqual(['wss://local.invalid/api/ws?profile=bot'])
})
@@ -170,7 +179,7 @@ describe('foreground tile retention vs. the live-work pruner (#93892)', () => {
await openGatewayForAgent('homelab', 'bot')
$sessionTiles.set([BOT_TILE])
- pruneSecondaryGateways(idleKeepSet())
+ pruneAged()
expect(gatewayMocks.closed).toEqual(['wss://homelab.invalid/api/ws?profile=bot'])
})
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index 81c49a688c1..4e3f43adb62 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -105,6 +105,14 @@ interface Secondary {
gateway: 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
+ * (prune → redial → prune) and close freshly opened sockets before their
+ * consumer registers in the keep-set, re-triggering the orphan-reap /
+ * remount loop (#94769). 0 = never opened.
+ */
+ lastOpenedAt: number
activeRequests: number
connectPromise: Promise<void> | null
offEvent: () => void
@@ -726,6 +734,7 @@ async function openSecondary(entry: Secondary, spawnPriority: SpawnPriority = 'b
}
entry.openedOnce = true
+ entry.lastOpenedAt = Date.now()
openedScopes.add(entry.scope)
try {
@@ -908,6 +917,7 @@ function createSecondary(profile: string, connectionId: null | string = null): S
connection: null,
gateway,
openedOnce: false,
+ lastOpenedAt: 0,
activeRequests: 0,
connectPromise: null,
offEvent: () => {},
@@ -1891,6 +1901,11 @@ export async function ensureActiveGatewayOpen({ explicit = false }: { explicit?:
// activation before reporting the gateway as unavailable.
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
+
// Recovery signal: nudge every live secondary back open. Power-resume/network
// signals can force sockets that still report open to retire before redialing.
export function reconnectSecondaryGateways({ forceOpenSockets = false }: { forceOpenSockets?: boolean } = {}): void {
@@ -1912,6 +1927,17 @@ export function reconnectSecondaryGateways({ forceOpenSockets = false }: { force
continue
}
+ // A forced wake (power resume / network online) used to close EVERY open
+ // secondary socket before redialing. Closing one that is mid-use detaches
+ // its runtime → the backend orphan-reaps it → `session.reclaimed` → the
+ // surface re-resumes on a fresh socket the same signal may close again:
+ // the #94769 flicker loop. Only force-redial quiescent sockets; live
+ // ones ride through and ordinary close/reconnect still heals them if
+ // the wake genuinely dropped them.
+ if (entry.activeRequests > 0 || foregroundPinned(entry)) {
+ continue
+ }
+
entry.gateway.close()
}
@@ -2077,6 +2103,18 @@ export function pruneSecondaryGateways(keep: Set<string>): void {
continue
}
+ // Min-lifetime grace: an idle prune can race an on-demand dial (prune →
+ // redial → prune) and dispose a socket that opened moments ago, before
+ // 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) {
+ continue
+ }
+
// The route is no longer live work. Release turn leases first so their
// counted request holds cannot outlive a disposed route or leave a stale
// release closure attached to a later same-key socket.
diff --git a/apps/desktop/src/store/session-request-router.test.ts b/apps/desktop/src/store/session-request-router.test.ts
index 8c3261b402e..376b6787af0 100644
--- a/apps/desktop/src/store/session-request-router.test.ts
+++ b/apps/desktop/src/store/session-request-router.test.ts
@@ -507,7 +507,11 @@ describe('requestForSessionProfile', () => {
})
expect(secondaryGateways[0].close).not.toHaveBeenCalled()
+ // 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 })
pruneSecondaryGateways(new Set())
+ vi.useRealTimers()
expect(secondaryGateways[0].close).toHaveBeenCalledOnce()
await requestForSessionProfile(route, ambient as never, 'session.resume', { session_id: 'rt-pruned' })