Skip to content

The agent that grows with you

fix(desktop): stop bot-relay drain loop from redialing a WebSocket per connection per tick

Teknium06fc941d2315
diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.js
index 756098d728e..ebbdde4b24f 100644
--- a/apps/desktop/src/plugins/hermes-bots/plugin.js
+++ b/apps/desktop/src/plugins/hermes-bots/plugin.js
@@ -1500,7 +1500,12 @@ function handleSessionsGatewayTransition() {
// Older backends without the RPCs fail per-call and are skipped — the
// relay degrades to whatever subset of connections supports it.
const RELAY_ROSTER_INTERVAL_MS = 60_000
-const RELAY_DRAIN_INTERVAL_MS = 4_000
+// Backstop cadence only (#93594): the push path below carries envelope latency,
+// so the interval poll exists for older backends and missed events — 30s
+// matches LIVE_SESSION_STATUS_BACKSTOP_INTERVAL_MS. It was 4s back when the
+// poll WAS the delivery path, which (before route retention) also meant a
+// fresh WebSocket dial + teardown per registered connection every 4s.
+const RELAY_DRAIN_INTERVAL_MS = 30_000
// Push path (#93091): the gateway broadcasts `bot_relay.outbox.pending` when
// an envelope lands on disk; a burst of signals inside this window collapses
// to ONE drain. The interval poll above stays as the backstop for older
@@ -1517,6 +1522,58 @@ let relayPushDebounceTimer = null
// the gateway signature is monotone (one event per new envelope, never
// re-broadcast) — so remember it and re-schedule after the drain finishes.
let relayDrainRerun = false
+// Relay-route socket retention (#93594): connection id → release fn. While
+// the relay is active each registered connection's pooled socket is pinned
+// open (host.retainProfileSocket) so drain RPCs reuse ONE persistent
+// WebSocket instead of dialing and tearing down a fresh one per tick.
+// Feature-detected — older shells lack the door and fall back to per-call
+// leases. Local routes get a no-op release inside the host (idle-reaper
+// exemption). stopBotRelay releases everything.
+const relayRouteRetentions = new Map()
+
+/** Reconcile retention with the CURRENT connection set: pin new connections,
+ * release removed ones. Runs on every drain/roster connection fetch. */
+function syncRelayRetention(connections) {
+ if (typeof host.retainProfileSocket !== 'function') {
+ return
+ }
+
+ const live = new Set(connections.map(connection => connection.id))
+
+ for (const [id, release] of [...relayRouteRetentions]) {
+ if (!live.has(id)) {
+ relayRouteRetentions.delete(id)
+ try {
+ release()
+ } catch {
+ // Never let a release failure break the relay loop.
+ }
+ }
+ }
+
+ if (relayDisposed) {
+ return
+ }
+
+ for (const connection of connections) {
+ if (!relayRouteRetentions.has(connection.id)) {
+ relayRouteRetentions.set(connection.id, host.retainProfileSocket(connection.route))
+ }
+ }
+}
+
+/** Drop every relay pin — stop/dispose path. */
+function releaseRelayRetention() {
+ for (const release of relayRouteRetentions.values()) {
+ try {
+ release()
+ } catch {
+ // Disposer from an older shell shape — never break teardown.
+ }
+ }
+
+ relayRouteRetentions.clear()
+}
/** One representative route per reachable connection id. */
async function relayConnections() {
@@ -1661,6 +1718,10 @@ async function drainRelayOutboxes() {
try {
const connections = await relayConnections()
+ // Retention follows the relay-eligible set: with fewer than two
+ // connections there is nothing to relay, so nothing stays pinned.
+ syncRelayRetention(connections.length >= 2 ? connections : [])
+
if (connections.length < 2) {
return
}
@@ -1788,6 +1849,9 @@ function stopBotRelay() {
// A rerun remembered mid-drain must not leak into the next start —
// it would fire one stale drain after restart.
relayDrainRerun = false
+ // Unpin every relay-retained socket (#93594): with the relay stopped the
+ // pooled entries return to dispose-at-refcount-0 semantics.
+ releaseRelayRetention()
if (relayRosterTimer !== null) {
clearInterval(relayRosterTimer)
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/bot-relay.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/bot-relay.test.mjs
index e4592fd85dc..d7b8cfae621 100644
--- a/apps/desktop/src/plugins/hermes-bots/tests/bot-relay.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/bot-relay.test.mjs
@@ -20,8 +20,10 @@ test('relay loops start in register() and stop on dispose', () => {
assert.match(pluginSource, /ctx\.onDispose\(stopBotRelay\)/)
// teardown really clears both timers
const stop = pluginSource.slice(pluginSource.indexOf('function stopBotRelay'))
- assert.match(stop.slice(0, 500), /clearInterval\(relayRosterTimer\)/)
- assert.match(stop.slice(0, 500), /clearInterval\(relayDrainTimer\)/)
+ // 800-char window: stopBotRelay grew a retention release (#93594) ahead of
+ // the timer teardown it also must keep doing.
+ assert.match(stop.slice(0, 800), /clearInterval\(relayRosterTimer\)/)
+ assert.match(stop.slice(0, 800), /clearInterval\(relayDrainTimer\)/)
})
test('roster loop syncs OTHER connections agents to each gateway', () => {
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/relay-push-drain.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/relay-push-drain.test.mjs
index 0314b02fb2b..fb429b51eb9 100644
--- a/apps/desktop/src/plugins/hermes-bots/tests/relay-push-drain.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/relay-push-drain.test.mjs
@@ -78,9 +78,12 @@ test('subscription is feature-detected, disposed, and the poll backstop stays',
const block = pluginSource.slice(start - 400, start + 400)
assert.match(block, /typeof host\.onEvent === 'function'/)
assert.match(pluginSource, /relayPushUnsub\(\)/)
- // The 4s interval poll is untouched — push is an accelerator, not a
- // replacement (older backends never emit the event).
- assert.match(pluginSource, /RELAY_DRAIN_INTERVAL_MS = 4_000/)
+ // The interval poll survives as a BACKSTOP — push is the delivery path,
+ // the poll covers older backends that never emit the event and connections
+ // whose events don't reach the tap. #93594 moved it from 4s (its cadence
+ // when the poll WAS the delivery path) to 30s backstop cadence, matching
+ // the live-session status backstop.
+ assert.match(pluginSource, /RELAY_DRAIN_INTERVAL_MS = 30_000/)
assert.match(pluginSource, /setInterval\(\(\) => void drainRelayOutboxes\(\), RELAY_DRAIN_INTERVAL_MS\)/)
})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/relay-socket-retention.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/relay-socket-retention.test.mjs
new file mode 100644
index 00000000000..3f05db32919
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/relay-socket-retention.test.mjs
@@ -0,0 +1,130 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+// Relay-route socket retention (#93594): while the bot relay is active, each
+// registered connection's pooled socket is pinned open via
+// host.retainProfileSocket so the drain loop reuses ONE persistent WebSocket
+// instead of dialing and tearing down a fresh one per tick. Contracts:
+// - retention is feature-detected (host.retainProfileSocket) — older shells
+// simply keep the per-call lease behavior;
+// - a connection is pinned once, not once per drain tick;
+// - a connection leaving the registry releases exactly its own pin;
+// - releaseRelayRetention drops every pin, and stopBotRelay calls it.
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function loadRetention({ retainProfileSocket } = {}) {
+ const start = pluginSource.indexOf('const relayRouteRetentions = new Map()')
+ const end = pluginSource.indexOf('/** One representative route per reachable connection id. */', start)
+ assert.ok(start > 0, 'plugin defines relayRouteRetentions')
+ assert.ok(end > start, 'retention block has a stable source boundary')
+
+ const releases = []
+ const context = {
+ relayDisposed: false,
+ retainCalls: [],
+ releases,
+ host: {
+ retainProfileSocket:
+ retainProfileSocket === null
+ ? undefined
+ : route => {
+ context.retainCalls.push(route)
+ let released = false
+ const release = () => {
+ if (!released) {
+ released = true
+ releases.push(route)
+ }
+ }
+ return release
+ }
+ }
+ }
+ vm.createContext(context)
+ vm.runInContext(
+ `${pluginSource.slice(start, end)}
+globalThis.syncRelayRetention = syncRelayRetention
+globalThis.releaseRelayRetention = releaseRelayRetention
+globalThis.relayRouteRetentions = relayRouteRetentions`,
+ context
+ )
+ return context
+}
+
+const conn = id => ({ id, route: { connectionId: id, profile: 'default', targetProfile: 'default' } })
+
+test('each connection is pinned ONCE across multiple drain ticks', () => {
+ const ctx = loadRetention()
+ const connections = [conn('a'), conn('b')]
+
+ for (let tick = 0; tick < 4; tick += 1) {
+ ctx.syncRelayRetention(connections)
+ }
+
+ assert.equal(ctx.retainCalls.length, 2, 'one pin per connection, not per tick')
+ assert.equal(ctx.relayRouteRetentions.size, 2)
+ assert.equal(ctx.releases.length, 0, 'nothing released while connections stay registered')
+})
+
+test('a connection leaving the registry releases exactly its own pin', () => {
+ const ctx = loadRetention()
+
+ ctx.syncRelayRetention([conn('a'), conn('b')])
+ ctx.syncRelayRetention([conn('a')])
+
+ assert.equal(ctx.releases.length, 1)
+ assert.equal(ctx.releases[0].connectionId, 'b')
+ assert.equal(ctx.relayRouteRetentions.size, 1)
+})
+
+test('releaseRelayRetention drops every pin (stop/dispose path)', () => {
+ const ctx = loadRetention()
+
+ ctx.syncRelayRetention([conn('a'), conn('b'), conn('c')])
+ ctx.releaseRelayRetention()
+
+ assert.equal(ctx.releases.length, 3)
+ assert.equal(ctx.relayRouteRetentions.size, 0)
+
+ // Idempotent — a second stop releases nothing new.
+ ctx.releaseRelayRetention()
+ assert.equal(ctx.releases.length, 3)
+})
+
+test('a disposed relay never pins new connections but still releases stale ones', () => {
+ const ctx = loadRetention()
+
+ ctx.syncRelayRetention([conn('a')])
+ ctx.relayDisposed = true
+ ctx.syncRelayRetention([conn('b')])
+
+ assert.equal(ctx.retainCalls.length, 1, 'no new pin after dispose')
+ assert.equal(ctx.releases.length, 1, "the departed connection's pin was released")
+})
+
+test('retention is feature-detected: an older shell without the door is a no-op', () => {
+ const ctx = loadRetention({ retainProfileSocket: null })
+
+ ctx.syncRelayRetention([conn('a'), conn('b')])
+
+ assert.equal(ctx.relayRouteRetentions.size, 0)
+})
+
+test('stopBotRelay releases retention (source contract)', () => {
+ const stop = pluginSource.slice(
+ pluginSource.indexOf('function stopBotRelay('),
+ pluginSource.indexOf('/** Per-bot appearance')
+ )
+ assert.match(stop, /releaseRelayRetention\(\)/)
+
+ // And the drain loop reconciles retention with the CURRENT connection set
+ // before deciding whether there is anything to relay.
+ const drain = pluginSource.slice(
+ pluginSource.indexOf('async function drainRelayOutboxes'),
+ pluginSource.indexOf('function scheduleRelayPushDrain')
+ )
+ assert.match(drain, /syncRelayRetention\(/)
+})
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts
index befb2bf46a8..67beeadc755 100644
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@ -49,6 +49,7 @@ import {
openGatewayForProfile,
requestGatewayForAgent,
requestGatewayForProfile,
+ retainGatewayForRelay,
retireLocalProfileGateways
} from '@/store/gateway'
import { notify, notifyError } from '@/store/notifications'
@@ -1132,6 +1133,21 @@ export const host = {
params: Record<string, unknown> = {}
): Promise<T> => requestPluginProfile<T>(route, method, params),
+ /** Pin a route's pooled gateway socket open across repeated `requestProfile`
+ * calls (#93594: the bot-relay drain loop was dialing and tearing down a
+ * fresh WebSocket per registered connection per tick). Returns a once-only
+ * release. Local routes are exempt (no-op release) so the idle reaper can
+ * still reclaim spawned local backends. Feature-detect on older desktops
+ * (`typeof host.retainProfileSocket === 'function'`). */
+ retainProfileSocket: (route: PluginProfileRoute | string): (() => void) => {
+ if (typeof route === 'string' || !route) {
+ // Bare-profile compatibility overload: local/legacy routing — exempt.
+ return () => undefined
+ }
+
+ return retainGatewayForRelay(route.connectionId, route.profile)
+ },
+
/** Gateway JSON-RPC — sessions, config, skills, cron, kanban, everything
* the app itself uses. Lazy: resolves the LIVE socket per call. */
request: async <T>(method: string, params: Record<string, unknown> = {}): Promise<T> => {
diff --git a/apps/desktop/src/store/gateway-relay-retention.test.ts b/apps/desktop/src/store/gateway-relay-retention.test.ts
new file mode 100644
index 00000000000..132d34003e0
--- /dev/null
+++ b/apps/desktop/src/store/gateway-relay-retention.test.ts
@@ -0,0 +1,169 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+// Bot-relay socket retention (#93594): the desktop bot relay RPCs every
+// registered connection on its drain loop through requestGatewayForAgent's
+// per-request lease. With nothing else holding the entry, the refcount hit 0
+// after every tick and the pooled socket was disposed — a fresh WebSocket
+// dial + teardown per registered connection every 4 seconds, flooding the
+// gateway logs with connect/disconnect pairs. retainGatewayForRelay pins the
+// route's pooled entry for the relay's active lifetime; releasing (stopBotRelay
+// / plugin dispose) restores dispose-at-refcount-0. Local routes are exempt so
+// the idle reaper can still reclaim spawned local backends.
+
+const gatewayMocks = vi.hoisted(() => ({
+ constructions: 0,
+ connect: vi.fn(async (_wsUrl: string): Promise<void> => undefined),
+ setConnection: vi.fn(),
+ setGatewayState: vi.fn()
+}))
+
+vi.mock('@/hermes', () => ({
+ setApiRequestConnection: vi.fn(),
+ HermesGateway: class {
+ connectionState = 'closed'
+ constructor() {
+ gatewayMocks.constructions += 1
+ }
+ connect = async (wsUrl: string): Promise<void> => {
+ await gatewayMocks.connect(wsUrl)
+ this.connectionState = 'open'
+ }
+ close = (): void => {
+ this.connectionState = 'closed'
+ }
+ request = async (): Promise<unknown> => ({})
+ onEvent = vi.fn(() => () => {})
+ onState = vi.fn(() => () => {})
+ }
+}))
+vi.mock('@/store/session', () => ({
+ setConnection: gatewayMocks.setConnection,
+ setGatewayState: gatewayMocks.setGatewayState
+}))
+vi.mock('@/store/notify-baseline', () => ({ markNativeNotifyBaseline: vi.fn() }))
+
+const {
+ closeSecondaryGateways,
+ configureGatewayRegistry,
+ pruneSecondaryGateways,
+ requestGatewayForAgent,
+ retainGatewayForRelay,
+ setPrimaryGateway
+} = await import('./gateway')
+
+const agentConn = {
+ authMode: 'token',
+ baseUrl: 'https://homelab.invalid',
+ mode: 'remote',
+ profile: 'research',
+ token: 'fake-test-token',
+ wsUrl: 'wss://homelab.invalid/api/ws?token=fake-test-token'
+}
+
+function installDesktop(): void {
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {
+ getConnection: vi.fn(async () => agentConn),
+ getConnectionFor: vi.fn(async () => agentConn)
+ }
+}
+
+beforeEach(() => {
+ configureGatewayRegistry({ onEvent: vi.fn() })
+ setPrimaryGateway({ connectionState: 'open' } as never, 'default')
+ installDesktop()
+ gatewayMocks.constructions = 0
+})
+
+afterEach(() => {
+ closeSecondaryGateways()
+ vi.clearAllMocks()
+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
+})
+
+describe('bot-relay gateway retention (#93594)', () => {
+ it('without retention every drain tick dials a fresh socket (the churn this fix removes)', async () => {
+ // Baseline: three request-leased RPCs against an otherwise-unheld route.
+ for (let tick = 0; tick < 3; tick += 1) {
+ await requestGatewayForAgent('homelab', 'research', 'bot_relay.outbox.drain', {})
+ }
+
+ // Refcount hits 0 after each call → dispose → next tick constructs anew.
+ expect(gatewayMocks.constructions).toBe(3)
+ expect(gatewayMocks.connect).toHaveBeenCalledTimes(3)
+ })
+
+ it('a retained relay route holds ONE persistent socket across multiple drain ticks', async () => {
+ const release = retainGatewayForRelay('homelab', 'research')
+
+ for (let tick = 0; tick < 5; tick += 1) {
+ await requestGatewayForAgent('homelab', 'research', 'bot_relay.outbox.drain', {})
+ }
+
+ expect(gatewayMocks.constructions).toBe(1)
+ expect(gatewayMocks.connect).toHaveBeenCalledTimes(1)
+
+ release()
+ })
+
+ it('release (stopBotRelay) drops retention: the socket is disposed and the next tick redials', async () => {
+ const release = retainGatewayForRelay('homelab', 'research')
+
+ await requestGatewayForAgent('homelab', 'research', 'bot_relay.outbox.drain', {})
+ expect(gatewayMocks.constructions).toBe(1)
+
+ release()
+
+ // With retention gone (and no in-flight lease), the entry was disposed —
+ // a later drain tick constructs a fresh gateway again.
+ await requestGatewayForAgent('homelab', 'research', 'bot_relay.outbox.drain', {})
+ expect(gatewayMocks.constructions).toBe(2)
+ })
+
+ it('release is once-only and counted: double-release cannot strip a second retainer', async () => {
+ const first = retainGatewayForRelay('homelab', 'research')
+ const second = retainGatewayForRelay('homelab', 'research')
+
+ first()
+ first() // once-only: must not decrement again
+
+ await requestGatewayForAgent('homelab', 'research', 'bot_relay.outbox.drain', {})
+ await requestGatewayForAgent('homelab', 'research', 'bot_relay.outbox.drain', {})
+ expect(gatewayMocks.constructions).toBe(1)
+
+ second()
+ })
+
+ it('the live-work pruner does not evict a relay-retained route between ticks', async () => {
+ const release = retainGatewayForRelay('homelab', 'research')
+
+ await requestGatewayForAgent('homelab', 'research', 'bot_relay.outbox.drain', {})
+
+ // Empty keep-set: everything idle is evictable — except the relay pin.
+ pruneSecondaryGateways(new Set())
+
+ await requestGatewayForAgent('homelab', 'research', 'bot_relay.outbox.drain', {})
+ expect(gatewayMocks.constructions).toBe(1)
+
+ release()
+
+ // After release the same prune reclaims it.
+ pruneSecondaryGateways(new Set())
+ await requestGatewayForAgent('homelab', 'research', 'bot_relay.outbox.drain', {})
+ expect(gatewayMocks.constructions).toBe(2)
+ })
+
+ it('local routes are exempt: retention is a no-op so the idle reaper can reclaim spawned backends', () => {
+ // Pinning a local route would keep the secondaries touch-loop pinging its
+ // Electron-spawned backend forever, defeating the idle reaper
+ // (gateway.ts local-backend lifecycle). Both the null/legacy and explicit
+ // `local` source ids must decline the pin.
+ const releaseNull = retainGatewayForRelay(null, 'research')
+ const releaseLocal = retainGatewayForRelay('local', 'research')
+
+ // No entry was created or pinned — nothing dials, nothing retains.
+ expect(gatewayMocks.constructions).toBe(0)
+
+ releaseNull()
+ releaseLocal()
+ })
+})
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index 25b11b7a6ec..f6a3ccff593 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -56,6 +56,16 @@ interface Secondary {
reconnecting: boolean
/** True when a foreground/prewarmed consumer owns this entry beyond one RPC. */
retained: boolean
+ /**
+ * Bot-relay retainers pinning this socket open across drain ticks (#93594).
+ * The relay's drain loop RPCs every registered connection on an interval;
+ * without retention each tick dialed and tore down a fresh WebSocket per
+ * connection (refcount hit 0 → dispose). Counted, not boolean, so relay
+ * retention can never clobber (or be clobbered by) the foreground
+ * `retained` flag. Only non-local registry routes are ever counted here —
+ * see retainGatewayForRelay.
+ */
+ relayRetainCount: number
// While true the entry auto-reconnects on drop; pruning flips it off so a
// deliberate close doesn't trigger the backoff loop.
wantOpen: boolean
@@ -486,6 +496,7 @@ function createSecondary(profile: string, connectionId: null | string = null): S
reconnectAttempt: 0,
reconnecting: false,
retained: false,
+ relayRetainCount: 0,
wantOpen: true,
activationLeaseUntil: 0
}
@@ -582,7 +593,7 @@ async function gatewayForProfile(
released = true
entry.activeRequests = Math.max(0, entry.activeRequests - 1)
- if (entry.activeRequests === 0 && !entry.retained && g.activeKey !== entry.scope) {
+ if (entry.activeRequests === 0 && !entry.retained && !relayRetained(entry) && g.activeKey !== entry.scope) {
disposeSecondary(entry)
if (g.secondaries.get(entry.scope) === entry) {
@@ -686,7 +697,7 @@ export async function requestGatewayForAgent<T>(
} finally {
entry.activeRequests = Math.max(0, entry.activeRequests - 1)
- if (entry.activeRequests === 0 && !entry.retained && g.activeKey !== entry.scope) {
+ if (entry.activeRequests === 0 && !entry.retained && !relayRetained(entry) && g.activeKey !== entry.scope) {
disposeSecondary(entry)
if (g.secondaries.get(entry.scope) === entry) {
@@ -696,6 +707,73 @@ export async function requestGatewayForAgent<T>(
}
}
+// ── Bot-relay socket retention (#93594) ─────────────────────────────────────
+// The desktop bot relay RPCs EVERY registered connection on its drain loop.
+// Each of those calls runs through requestGatewayForAgent's per-request lease,
+// so a connection with no other consumer dialed a fresh WebSocket and tore it
+// down again on every tick — a connect/disconnect pair per connection per tick
+// flooding the gateway logs. While the relay is active, its routes hold a
+// counted retention that keeps the pooled socket (and its existing
+// scheduleReconnect/backoff machinery) alive across ticks; stopBotRelay (and
+// plugin dispose) releases it, restoring the dispose-at-refcount-0 behavior.
+
+/** True when the bot relay currently pins this entry open. Number guard:
+ * dev-HMR entries predate the field. */
+function relayRetained(entry: Secondary): boolean {
+ return Number.isFinite(entry.relayRetainCount) && entry.relayRetainCount > 0
+}
+
+/**
+ * Pin the pooled socket for one relay route open across drain ticks. Returns
+ * a once-only release. Local routes (null/empty or explicit `local` source)
+ * are deliberately EXEMPT and get a no-op release: their Electron-spawned
+ * backend answers to the idle reaper, and a relay pin would keep the
+ * touch-loop pinging it forever, resurrecting backends the reaper is meant to
+ * reclaim (see the retireLocalProfileGateways note). Local relay traffic is
+ * either the primary socket (no churn) or a short-lived local dial — never
+ * the remote reconnect flood this retention exists to stop.
+ */
+export function retainGatewayForRelay(connectionId: null | string, profile: string): () => void {
+ const key = normKey(profile)
+ const connection = String(connectionId ?? '').trim()
+
+ if (!connection || connection === 'local') {
+ return () => undefined
+ }
+
+ const scope = registryBackendScopeKey(connection, key)
+ const entry = g.secondaries.get(scope) ?? createSecondary(key, connection)
+
+ if (!Number.isFinite(entry.relayRetainCount)) {
+ entry.relayRetainCount = 0
+ }
+
+ entry.relayRetainCount += 1
+ entry.wantOpen = true
+
+ let released = false
+
+ return () => {
+ if (released) {
+ return
+ }
+
+ released = true
+ entry.relayRetainCount = Math.max(0, (entry.relayRetainCount || 0) - 1)
+
+ if (
+ entry.relayRetainCount === 0 &&
+ entry.activeRequests === 0 &&
+ !entry.retained &&
+ g.activeKey !== entry.scope &&
+ g.secondaries.get(entry.scope) === entry
+ ) {
+ disposeSecondary(entry)
+ g.secondaries.delete(entry.scope)
+ }
+ }
+}
+
// Open `profile`'s socket WITHOUT making it active — the hover-intent pre-warm
// (store/profile). Runs the same spawn + connect chain as a real switch, so by
// click time ensureGatewayForProfile finds an open socket and just activates
@@ -959,6 +1037,10 @@ export function pruneSecondaryGateways(keep: Set<string>): void {
keep.has(key) ||
(!entry.connectionId && keep.has(entry.profile)) ||
entry.activeRequests > 0 ||
+ // Bot-relay retention (#93594): the relay pins its remote routes for
+ // its whole active lifetime; the live-work pruner must not undo that
+ // pin between drain ticks or the socket churn returns.
+ relayRetained(entry) ||
// Mid-dial activation target: the profile being switched TO is not yet
// active and has no live work, so without this lease any recompute
// during its cold spawn disposed the entry and the click died silently