Skip to content

The agent that grows with you

fix(desktop): stop background polls from out-dialing the reconnect ladder

rodricksz4h5fd0b98f62564
diff --git a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts
index 3f3bf79c259..c1e3e084ee2 100644
--- a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts
+++ b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts
@@ -840,6 +840,73 @@ describe('secondary stalled-dial budget', () => {
expect(getConnectionFor.mock.calls.length).toBeLessThanOrEqual(6)
})
+ it('background polls against a dying scope do not out-dial the reconnect ladder (#121865)', async () => {
+ vi.useFakeTimers()
+
+ const stalled = () =>
+ new Error('Local backend start for "bot-a" timed out while waiting for a free slot. (background)')
+
+ const getConnectionFor = vi
+ .fn()
+ .mockResolvedValueOnce(descriptorFor('homelab', 'bot-a'))
+ .mockRejectedValue(stalled())
+
+ installDesktop({ getConnectionFor })
+
+ await ensureGatewayForAgent('homelab', 'bot-a')
+ const socket = gatewayMocks.instances[0] as unknown as { connectionState: string }
+ socket.connectionState = 'closed'
+
+ const dialsAfterOpen = getConnectionFor.mock.calls.length
+
+ // The automatic loop runs while a poller (session.control.read against a
+ // cross-profile session) keeps issuing routed RPCs, which default to
+ // spawnPriority 'background'. Each one used to dial straight past the
+ // ladder whenever the socket was down: one dial per poll tick.
+ reconnectSecondaryGateways()
+ await vi.advanceTimersByTimeAsync(0)
+
+ // 20 polls inside ONE second of virtual time. The ladder's floor is 300ms,
+ // so a healthy scope dials at most a couple of times in that window; a
+ // storm dials once per poll.
+ for (let index = 0; index < 20; index += 1) {
+ await requestGatewayForAgent('homelab', 'bot-a', 'session.control.read', {}).catch(() => undefined)
+ await vi.advanceTimersByTimeAsync(50)
+ }
+
+ expect(getConnectionFor.mock.calls.length - dialsAfterOpen).toBeLessThanOrEqual(5)
+ })
+
+ it('a foreground request still dials at once while background polls are cooling down (#121865)', async () => {
+ vi.useFakeTimers()
+
+ const getConnectionFor = vi
+ .fn()
+ .mockResolvedValueOnce(descriptorFor('homelab', 'bot-a'))
+ .mockRejectedValueOnce(new Error('Failed to connect to Hermes gateway'))
+
+ installDesktop({ getConnectionFor })
+
+ await ensureGatewayForAgent('homelab', 'bot-a')
+ const socket = gatewayMocks.instances[0] as unknown as { connectionState: string }
+ socket.connectionState = 'closed'
+
+ // A background poll dials, fails, and opens the cooldown window.
+ await requestGatewayForAgent('homelab', 'bot-a', 'session.control.read', {}).catch(() => undefined)
+ const dialsAfterFailure = getConnectionFor.mock.calls.length
+
+ // A second poll inside the window must not dial.
+ await requestGatewayForAgent('homelab', 'bot-a', 'session.control.read', {}).catch(() => undefined)
+ expect(getConnectionFor.mock.calls.length).toBe(dialsAfterFailure)
+
+ // A user action inside the same window dials immediately.
+ getConnectionFor.mockResolvedValue(descriptorFor('homelab', 'bot-a'))
+ await requestGatewayForAgent('homelab', 'bot-a', 'session.activate', {}, undefined, undefined, {
+ spawnPriority: 'foreground'
+ }).catch(() => undefined)
+ expect(getConnectionFor.mock.calls.length).toBe(dialsAfterFailure + 1)
+ })
+
it('re-arms a parked scope on the wake/online/focus nudge', async () => {
vi.useFakeTimers()
diff --git a/apps/desktop/src/store/gateway-profile-request.test.ts b/apps/desktop/src/store/gateway-profile-request.test.ts
index 5665bf8b320..5b0d32f1bd1 100644
--- a/apps/desktop/src/store/gateway-profile-request.test.ts
+++ b/apps/desktop/src/store/gateway-profile-request.test.ts
@@ -111,6 +111,98 @@ describe('requestGatewayForProfile', () => {
expect($gateway.get()).toBe(primary)
})
+ it('background polls on a down local profile leave redialing to the ladder; a user action still dials (#121865)', async () => {
+ vi.useFakeTimers()
+
+ try {
+ setPrimaryGateway(makePrimary() as never, 'default')
+
+ // The target profile's backend never comes up.
+ const getConnection = vi.fn(async (profile: null | string) => {
+ if (profile === 'jody') {
+ throw new Error('Failed to connect to Hermes gateway')
+ }
+
+ return { port: 4242, token: 'primary-token' }
+ })
+
+ installDesktop(getConnection)
+ await ensureGatewayForProfile('default')
+
+ const jodyDials = () => getConnection.mock.calls.filter(([profile]) => profile === 'jody').length
+
+ // session.control.read against a cross-profile session, polled 20 times in one second.
+ for (let index = 0; index < 20; index += 1) {
+ await requestGatewayForProfile('jody', 'session.control.read', {}).catch(() => undefined)
+ await vi.advanceTimersByTimeAsync(50)
+ }
+
+ // Every attempt is two dials into main: the shared-primary probe, then the secondary.
+ // Before, all 20 polls attempted (40 dials). Now attempts wait out a window that doubles
+ // from 300ms, so one second holds three of them: t=0, t=300, t=900.
+ const backgroundDials = jodyDials()
+ expect(backgroundDials).toBe(6)
+
+ // Inside the same cooldown, a user action is not held back.
+ await requestGatewayForProfile('jody', 'session.activate', {}, undefined, undefined, {
+ spawnPriority: 'foreground'
+ }).catch(() => undefined)
+ expect(jodyDials()).toBeGreaterThan(backgroundDials)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('a served request clears dial history, so the next outage starts back at the shortest window (#121865)', async () => {
+ vi.useFakeTimers()
+
+ try {
+ setPrimaryGateway(makePrimary() as never, 'default')
+
+ let jodyUp = false
+
+ const getConnection = vi.fn(async (profile: null | string) => {
+ if (profile === 'jody') {
+ if (!jodyUp) {
+ throw new Error('Failed to connect to Hermes gateway')
+ }
+
+ return { port: 5151, profile, token: 'secondary-token' }
+ }
+
+ return { port: 4242, token: 'primary-token' }
+ })
+
+ installDesktop(getConnection)
+ await ensureGatewayForProfile('default')
+
+ const poll = () => requestGatewayForProfile('jody', 'session.control.read', {}).catch(() => undefined)
+ const jodyDials = () => getConnection.mock.calls.filter(([profile]) => profile === 'jody').length
+
+ // Three failed attempts in the first second widen the window to 1200ms.
+ for (let index = 0; index < 20; index += 1) {
+ await poll()
+ await vi.advanceTimersByTimeAsync(50)
+ }
+
+ // The backend recovers and serves a request once the widened window has passed.
+ jodyUp = true
+ await vi.advanceTimersByTimeAsync(2_000)
+ await expect(requestGatewayForProfile('jody', 'session.control.read', {})).resolves.toBeDefined()
+
+ // A fresh outage: one failure opens a 300ms window again, so a poll 300ms later dials.
+ // Had the old streak survived, the window would be 2400ms and that poll would be held.
+ jodyUp = false
+ const before = jodyDials()
+ await poll()
+ await vi.advanceTimersByTimeAsync(300)
+ await poll()
+ expect(jodyDials() - before).toBe(4)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
it('dials the profile with foreground priority when a Settings-scoped caller asks for it (#111651)', async () => {
setPrimaryGateway(makePrimary() as never, 'default')
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index 831b2be9173..302e8e78324 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -227,6 +227,9 @@ interface GatewayRegistryState {
secondaries: Map<string, Secondary>
// Auth rejection outlives the disposable socket, including background request leases.
reauthFailures: Map<string, { connectionId: string | null; error: Error }>
+ // Dial failures outlive the disposable socket too: a background request lease disposes its
+ // entry on failure, so history kept on the entry reset on every poll (#121865).
+ dialFailures: Map<string, { at: number; streak: number; connectionId: string | null }>
/** Scopes that opened in this renderer generation, even if later pruned. */
openedSecondaryScopes?: Set<string>
/** Scopes whose re-activation after a connection redial has not landed yet. */
@@ -252,6 +255,7 @@ function createRegistryState(): GatewayRegistryState {
activationEpoch: 0,
secondaries: new Map<string, Secondary>(),
reauthFailures: new Map(),
+ dialFailures: new Map(),
openedSecondaryScopes: new Set<string>(),
reactivatingScopes: new Set<string>(),
turnLeases: new Map<string, () => void>(),
@@ -284,6 +288,7 @@ function gatewayState(): GatewayRegistryState {
// Existing dev-HMR containers predate whole-turn leases.
store[STATE_KEY].reauthFailures ??= new Map()
+ store[STATE_KEY].dialFailures ??= new Map()
store[STATE_KEY].turnLeases ??= new Map()
store[STATE_KEY].turnLeaseReleaseTimers ??= new Map()
@@ -894,6 +899,12 @@ function rearmSecondary(entry: Secondary, priority: SpawnPriority = 'foreground'
g.reauthFailures.delete(entry.scope)
+ // Only an explicit (foreground) re-arm resets dial history: every background request rearms
+ // its scope before dialing, so clearing it here would lift the throttle on each poll.
+ if (priority === 'foreground') {
+ g.dialFailures.delete(entry.scope)
+ }
+
if (entry.retiredByPool && priority !== 'foreground') {
throw new Error(`Backend for "${entry.profile}" was retired; open it explicitly to reconnect.`)
}
@@ -903,6 +914,56 @@ function rearmSecondary(entry: Secondary, priority: SpawnPriority = 'foreground'
entry.retiredByPool = false
}
+function recordDialFailure(entry: Secondary, error?: unknown): void {
+ // Auth rejection has its own ledger (reauthFailures) that already fails background callers fast.
+ if (error !== undefined && isGatewayReauthRequired(error)) {
+ return
+ }
+
+ const previous = g.dialFailures.get(entry.scope)
+
+ g.dialFailures.set(entry.scope, {
+ at: Date.now(),
+ streak: (previous?.streak ?? 0) + 1,
+ connectionId: entry.connectionId ?? null
+ })
+}
+
+/** True while a background caller must leave redialing to the ladder: the scope's last dial
+ * failed (or its socket died before RECONNECT_STABLE_OPEN_MS) inside a window that widens with
+ * the failure streak, on the same ceilings as the reconnect ladder. History clears on proof of
+ * health (a served RPC, or a socket that lived) and on a fresh start (foreground re-arm, connection
+ * removal, full teardown) — never on a bare open, so an accept-then-close backend keeps escalating. */
+function backgroundDialCoolingDown(scope: string, now = Date.now()): boolean {
+ const failure = g.dialFailures.get(scope)
+
+ return failure !== undefined && now - failure.at < reconnectBackoffDelayMs(failure.streak - 1, { jitter: false })
+}
+
+/** Dial a request's secondary if it is down. Both request paths (a plain profile via
+ * gatewayForProfile, a registry route via requestGatewayForAgent) used to dial straight past
+ * the reconnect ladder, and openSecondary only coalesces CONCURRENT dials, so a poller against
+ * a scope whose socket accepts and then dies redialed once per tick (session.control.read on a
+ * cross-profile session, #121865). After a failure, background callers fail fast and leave
+ * redialing to scheduleReconnect; a user action (foreground) still dials at once. */
+async function openSecondaryForRequest(entry: Secondary, spawnPriority: SpawnPriority): Promise<void> {
+ if (isOpen(entry.gateway)) {
+ return
+ }
+
+ if (spawnPriority !== 'foreground' && backgroundDialCoolingDown(entry.scope)) {
+ scheduleReconnect(entry)
+ throw new Error(`Backend for "${entry.profile}" is reconnecting; retry after it settles.`)
+ }
+
+ try {
+ await openSecondary(entry, spawnPriority)
+ } catch (error) {
+ recordDialFailure(entry, error)
+ throw error
+ }
+}
+
function scheduleReconnect(entry: Secondary): void {
if (entry.reconnecting || entry.reconnectTimer !== null || !entry.wantOpen) {
return
@@ -928,6 +989,10 @@ async function reconnectSecondary(entry: Secondary): Promise<void> {
try {
await openSecondary(entry)
} catch (error) {
+ // Restart the background-request cooldown from the ladder's own failure too, or a poll
+ // could slip a dial in between two ladder attempts on an older, expired window.
+ recordDialFailure(entry, error)
+
if (isGatewayReauthRequired(error)) {
notifyError(error, translateNow('boot.errors.gatewaySignInRequired'), { action: RECOVERY_ACTIONS.openGateways() })
@@ -1050,6 +1115,9 @@ function createSecondary(profile: string, connectionId: null | string = null): S
// is a failed attempt, so the ladder resets only after a socket that lived.
if (isStableOpen(entry.openedAt)) {
entry.reconnectAttempt = 0
+ g.dialFailures.delete(scope)
+ } else if (entry.openedAt !== null) {
+ recordDialFailure(entry)
}
entry.openedAt = null
@@ -1126,6 +1194,14 @@ async function gatewayForProfile(
return { gateway: g.primaryGateway, key, release: noRelease, scopeProfile: false }
}
+ // sharedPrimaryRoute is itself a dial into main (it can start the profile's spawn), so a
+ // cooling-down scope has to be held back before it, not just before openSecondary.
+ const existing = g.secondaries.get(key)
+
+ if (spawnPriority !== 'foreground' && !(existing && isOpen(existing.gateway)) && backgroundDialCoolingDown(key)) {
+ throw new Error(`Backend for "${key}" is reconnecting; retry after it settles.`)
+ }
+
if (await sharedPrimaryRoute(key, spawnPriority)) {
return { gateway: g.primaryGateway, key, release: noRelease, scopeProfile: true }
}
@@ -1175,9 +1251,7 @@ async function gatewayForProfile(
}
try {
- if (!isOpen(entry.gateway)) {
- await openSecondary(entry, spawnPriority)
- }
+ await openSecondaryForRequest(entry, spawnPriority)
} catch (error) {
release()
throw error
@@ -1214,9 +1288,15 @@ export async function requestGatewayForProfile<T>(
// Same arity contract as the ambient path in session-request-router: only
// pass the deadline args through when the caller set them, so a plain
// profile-routed RPC keeps its two-argument call shape.
- return await (timeoutMs === undefined && signal === undefined
+ const result = await (timeoutMs === undefined && signal === undefined
? route.gateway.request<T>(method, routedParams)
: route.gateway.request<T>(method, routedParams, timeoutMs, signal))
+
+ // A served RPC proves the backend answers, not just accepts, so it clears the dial history.
+ // Lease requests dispose their entry right after, before a close could prove the socket stable.
+ g.dialFailures.delete(route.key)
+
+ return result
} finally {
route.release()
}
@@ -1285,13 +1365,15 @@ export async function requestGatewayForAgent<T>(
entry.activeRequests += 1
try {
- if (!isOpen(entry.gateway)) {
- await openSecondary(entry, spawnPriority)
- }
+ await openSecondaryForRequest(entry, spawnPriority)
- return await (timeoutMs === undefined && signal === undefined
+ const result = await (timeoutMs === undefined && signal === undefined
? entry.gateway.request<T>(method, params)
: entry.gateway.request<T>(method, params, timeoutMs, signal))
+
+ g.dialFailures.delete(entry.scope)
+
+ return result
} finally {
entry.activeRequests = Math.max(0, entry.activeRequests - 1)
@@ -2366,6 +2448,12 @@ export function closeLegacySecondaryGateways(): void {
}
}
+ for (const [scope, failure] of g.dialFailures) {
+ if (failure.connectionId === null) {
+ g.dialFailures.delete(scope)
+ }
+ }
+
closeSecondariesWhere(isLegacySecondary)
}
@@ -2384,6 +2472,7 @@ export function closeSecondaryGateways(): void {
}
g.turnLeases.clear()
+ g.dialFailures.clear()
closeSecondariesWhere(() => true)
openedSecondaryScopes().clear()
@@ -2454,6 +2543,13 @@ export function disposeSecondariesForConnection(connectionId: string, opts: { re
}
}
+ // Replacing a connection is a fresh start: its old failures must not hold back the new dial.
+ for (const [scope, failure] of g.dialFailures) {
+ if (failure.connectionId === id) {
+ g.dialFailures.delete(scope)
+ }
+ }
+
for (const [key, entry] of [...g.secondaries]) {
if (entry.connectionId !== id) {
continue