Skip to content

The agent that grows with you

refactor(desktop): remove the dead local-backend pool subsystem

Tekniumc63d465dbc2b
diff --git a/apps/desktop/electron/backend-descriptor-cache.test.ts b/apps/desktop/electron/backend-descriptor-cache.test.ts
new file mode 100644
index 00000000000..a7b193583bc
--- /dev/null
+++ b/apps/desktop/electron/backend-descriptor-cache.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest'
+
+import { assertDescriptorStillOwned, forgetFailedDescriptor } from './backend-descriptor-cache'
+
+// The descriptor cache never owns a process: an entry is a promise for a
+// gateway descriptor. Two invariants keep concurrent dials and profile
+// mutations honest around the `gateway ensure` await.
+
+describe('backend descriptor cache ownership', () => {
+ it('a late dial failure forgets only its own entry, never a newer descriptor installed under the same key', () => {
+ const cache = new Map<string, { connectionPromise: Promise<unknown> | null }>()
+ const stale = { connectionPromise: Promise.reject(new Error('first dial died')) }
+ const fresh = { connectionPromise: Promise.resolve({ baseUrl: 'http://127.0.0.1:1' }) }
+
+ stale.connectionPromise.catch(() => undefined)
+ cache.set('research', stale)
+ // A retire + re-dial raced ahead of the stale rejection.
+ cache.set('research', fresh)
+
+ forgetFailedDescriptor(cache, 'research', stale)
+
+ expect(cache.get('research')).toBe(fresh)
+
+ forgetFailedDescriptor(cache, 'research', fresh)
+
+ expect(cache.has('research')).toBe(false)
+ })
+
+ it('a dial whose entry was forgotten mid-flight (profile delete, retirement) refuses to hand back a descriptor', () => {
+ const cache = new Map<string, { connectionPromise: Promise<unknown> | null }>()
+ const entry = { connectionPromise: null }
+
+ cache.set('research', entry)
+ expect(() => assertDescriptorStillOwned(cache, 'research', entry)).not.toThrow()
+
+ // Profile delete lands while `gateway ensure` is still running.
+ cache.delete('research')
+
+ expect(() => assertDescriptorStillOwned(cache, 'research', entry)).toThrow(/cancelled/)
+
+ // A replacement installed by a newer caller is not ours either.
+ cache.set('research', { connectionPromise: null })
+
+ expect(() => assertDescriptorStillOwned(cache, 'research', entry)).toThrow(/cancelled/)
+ })
+})
diff --git a/apps/desktop/electron/backend-descriptor-cache.ts b/apps/desktop/electron/backend-descriptor-cache.ts
new file mode 100644
index 00000000000..13f10456a4b
--- /dev/null
+++ b/apps/desktop/electron/backend-descriptor-cache.ts
@@ -0,0 +1,34 @@
+/**
+ * Ownership helpers for the main-process descriptor cache (`backendPool` in
+ * main.ts): keyed promises for gateway connection descriptors, never process
+ * handles. A dial yields at the `gateway ensure` / update-clearance awaits, so
+ * a profile delete, a retirement, or a faster sibling dial can replace or
+ * forget the entry underneath it. Both helpers compare by identity so the
+ * loser of that race can neither evict the winner nor resurrect itself.
+ */
+
+export interface BackendDescriptorEntry {
+ connectionPromise: Promise<unknown> | null
+}
+
+/** Drop a failed entry — only if it is still the installed one. */
+export function forgetFailedDescriptor<TEntry extends BackendDescriptorEntry>(
+ cache: Map<string, TEntry>,
+ key: string,
+ entry: TEntry
+): void {
+ if (cache.get(key) === entry) {
+ cache.delete(key)
+ }
+}
+
+/** Refuse to complete a dial whose entry is no longer the installed one. */
+export function assertDescriptorStillOwned<TEntry extends BackendDescriptorEntry>(
+ cache: Map<string, TEntry>,
+ key: string,
+ entry: TEntry
+): void {
+ if (cache.get(key) !== entry) {
+ throw new Error(`Profile backend start for "${key}" was cancelled before spawn.`)
+ }
+}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 8436ea940ed..d27b7c8bc2d 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -50,6 +50,7 @@ import {
} from './backend-claim'
import { dashboardFallbackArgs, sourceDeclaresServe } from './backend-command'
import { createBackendConnectionState } from './backend-connection-state'
+import { assertDescriptorStillOwned, forgetFailedDescriptor } from './backend-descriptor-cache'
import { BackendDialClaims } from './backend-dial-claim'
import { buildDesktopBackendEnv, hermesManagedNodePathEntries, normalizeHermesHomeRoot } from './backend-env'
import {
@@ -287,10 +288,6 @@ import {
localRouteFallbackProfiles,
undialedSshRouteSeeds
} from './plugin-profile-routes'
-import { selectPoolEvictions } from './pool-eviction'
-import { clampPoolLimits, parsePoolLimits, POOL_LIMITS_DEFAULTS } from './pool-limits'
-import { createPoolStopper } from './pool-stop'
-import { poolTouchKeys } from './pool-touch-scope'
import { createKeepAwake } from './power-save'
import { registerPreparedSubmissions } from './prepared-submissions'
import { capturePreviewContents } from './preview-capture'
@@ -1413,77 +1410,23 @@ const backendDialClaims = new BackendDialClaims()
// True while connection-config:apply soft-rehomes the primary — suppresses the
// backend-exit toast so an intentional kill doesn't look like a crash.
let softRehomeInProgress = false
-// Additional per-profile backends, keyed by profile name. The PRIMARY backend
-// (the desktop's launch profile) stays managed by backendConnectionState +
-// startHermes(); this pool only holds EXTRA profile
-// backends spawned lazily when a session belongs to a different profile. A user
-// with no named profiles never populates this map, so their experience is
-// byte-for-byte the single-backend behavior.
-const backendPool = new Map() // profile -> { process, port, token, connectionPromise, lastActiveAt }
+// Cached connection DESCRIPTORS for every non-primary (connectionId, profile)
+// scope the app has dialed: canonical local gateways reached through
+// `hermes gateway ensure`, registry remotes, per-profile remote overrides.
+// Never a process — the gateway owns its own lifetime; forgetting an entry only
+// forces the next ensure*() to re-dial. A user with no named profiles never
+// populates this map.
+const backendPool = new Map() // scope key -> { connectionPromise, remoteBaseUrl }
const profileDeletionGate = new ProfileDeletionGate()
-// Keep the pool light: cap concurrent profile backends (LRU eviction) and reap
-// idle ones. A user idles at exactly the primary backend; pool backends only
-// exist while a non-primary profile is actively being chatted through.
-// Pool sizing is a device preference (Settings → Advanced → pool rows), not a
-// launch constant: mutable at runtime, persisted in userData, applied live.
-// The legacy HERMES_DESKTOP_POOL_* env vars remain the initial-value fallback
-// for scripted/headless setups; after launch the stored preference wins.
-const POOL_LIMITS_PATH = path.join(app.getPath('userData'), 'pool-limits.json')
-
-function readPersistedPoolLimits() {
- try {
- const limits = parsePoolLimits(fs.readFileSync(POOL_LIMITS_PATH, 'utf8'))
- rememberLog(
- `[pool-limits] loaded from ${POOL_LIMITS_PATH}: maxBackends=${limits.maxBackends}, idleMs=${limits.idleMs}`
- )
-
- return limits
- } catch {
- // No persisted file yet — fall back to the legacy env vars so scripted
- // setups keep working. Log which source won: a silently-ignored env var
- // here costs a scripted-setup user a debugging session.
- const fromEnv = clampPoolLimits({
- maxBackends: Number(process.env.HERMES_DESKTOP_POOL_MAX) || undefined,
- idleMs: Number(process.env.HERMES_DESKTOP_POOL_IDLE_MS) || undefined
- })
-
- if (fromEnv.maxBackends !== POOL_LIMITS_DEFAULTS.maxBackends || fromEnv.idleMs !== POOL_LIMITS_DEFAULTS.idleMs) {
- rememberLog(
- `[pool-limits] no saved file; using env-var overrides: maxBackends=${fromEnv.maxBackends}, idleMs=${fromEnv.idleMs}`
- )
- } else {
- rememberLog('[pool-limits] no saved file and no env overrides; using defaults')
- }
-
- return fromEnv
- }
-}
-function persistPoolLimits(limits) {
- try {
- fs.mkdirSync(path.dirname(POOL_LIMITS_PATH), { recursive: true })
- // Atomic write: write to a temp file in the same directory, then rename.
- // A crash mid-write would otherwise leave truncated JSON and silently
- // lose the user's saved sizing.
- const tmpPath = `${POOL_LIMITS_PATH}.tmp`
- fs.writeFileSync(tmpPath, JSON.stringify(limits, null, 2), 'utf8')
- fs.renameSync(tmpPath, POOL_LIMITS_PATH)
- } catch (error) {
- rememberLog(`[pool-limits] write failed: ${error.message}`)
- }
-}
-
-// rememberLog() state. Declared here, before the top-level
-// readPersistedPoolLimits() call below, because that call logs during module
-// evaluation; declaring these later crashed launch with `undefined.push` in
-// the packaged build (esbuild lowers the TDZ to undefined instead of throwing).
+// rememberLog() state. Declared before any top-level caller that logs during
+// module evaluation; declaring these later crashed launch with `undefined.push`
+// in the packaged build (esbuild lowers the TDZ to undefined instead of throwing).
const hermesLog = []
let desktopLogBuffer = ''
let desktopLogFlushTimer = null
let desktopLogFlushPromise = Promise.resolve()
-let poolLimits = readPersistedPoolLimits()
-
// Land a spawn failure in desktop.log.
function logPoolSpawnFailure(label: string, error: unknown): void {
rememberLog(
@@ -1491,56 +1434,6 @@ function logPoolSpawnFailure(label: string, error: unknown): void {
)
}
-function poolMaxBackends() {
- return poolLimits.maxBackends
-}
-
-function poolIdleMs() {
- return poolLimits.idleMs
-}
-
-/**
- * Apply new limits live: persist, then converge the running pool — evict
- * LRU backends down to the new max, and let the (already running) idle
- * reaper handle a shortened idle window on its next tick. Returns the
- * limits actually in force (post-clamp).
- */
-function setPoolLimits(raw) {
- poolLimits = clampPoolLimits(raw)
- persistPoolLimits(poolLimits)
- evictLruPoolBackends(poolMaxBackends())
- startPoolIdleReaper()
-
- return { ...poolLimits }
-}
-
-// A backend touched within this window has a live renderer socket (the keepalive
-// pings every 60s for every open profile). LRU eviction must spare these — a
-// concurrent multi-profile session keeps several backends "fresh" at once, and
-// killing one to honor the soft cap would abort a running agent.
-//
-// The window is intentionally MUCH wider than the 60s ping cadence:
-// * 1 missed ping = +60s of apparent silence
-// * WSL2 IPC stall = the renderer's `hermes:backend:touch` roundtrips
-// through 9p; a single brief 9p hiccup can stretch a
-// ping to ~30s of observed silence (#95189: gateways
-// exited every ~2 min on WSL2 because the previous
-// 90s window left no headroom — one delayed ping
-// pushed a live backend past the threshold and the
-// cap-driven eviction killed the active profile's
-// backend mid-session, re-minting runtime ids and
-// re-allocating pooled gateway secondaries ~700×/day).
-// * 3× ping + 60s headroom = ~4 min, comfortable margin for two missed
-// pings + WSL2 IPC stall. The hard ceiling for the cap-eligible set is
-// pool idle window above (default 10 min) — this constant only governs the
-// "is this backend plausibly still alive" question for LRU eviction,
-// not when the idle reaper definitively tears a backend down.
-const POOL_KEEPALIVE_FRESH_MS = Math.max(
- 120_000,
- Number(process.env.HERMES_DESKTOP_POOL_KEEPALIVE_FRESH_MS) || 4 * 60_000
-)
-
-let poolIdleReaper = null
let backendOrphanReapPromise = null
// Auto-reload budget for renderer crashes, shared by EVERY window (primary,
// secondary session, instance) so a crash loop anywhere is suppressed after
@@ -3703,20 +3596,6 @@ async function claimBackendChild(child, command, profile, nonce, outputTail: Bac
}
}
-function releaseBackendChild(child) {
- const identity = child?.hermesBackendIdentity
-
- if (!identity) {
- return
- }
-
- try {
- backendOwnership.release(identity)
- } catch (error) {
- rememberLog(`Could not release backend ownership for PID ${identity.pid}: ${error.message}`)
- }
-}
-
function reapOrphanedBackendsOnce() {
if (!backendOrphanReapPromise) {
backendOrphanReapPromise = backendOwnership
@@ -3772,24 +3651,18 @@ async function releaseBackendLock(updateRoot, tag) {
const hermesProcess = backendConnectionState.getProcess()
- // Seed the release gate with every PID we are about to signal: the
- // supervised primary backend and all pool backends. The gate waits for
- // these to actually LEAVE the process table, not just for the shim to
- // unlock — the shim probe only covers venv\Scripts\hermes.exe, but the
- // backend is `python.exe -m hermes_cli.main serve`, which need not hold
- // the shim at all (#74805 first-attempt race).
+ // Seed the release gate with every PID we are about to signal (the
+ // supervised primary backend, when one exists). The gate waits for these to
+ // actually LEAVE the process table, not just for the shim to unlock — the
+ // shim probe only covers venv\Scripts\hermes.exe, but the backend is
+ // `python.exe -m hermes_cli.main serve`, which need not hold the shim at all
+ // (#74805 first-attempt race).
const initialPids = []
if (hermesProcess && Number.isInteger(hermesProcess.pid)) {
initialPids.push(hermesProcess.pid)
}
- for (const entry of backendPool.values()) {
- if (entry.process && Number.isInteger(entry.process.pid)) {
- initialPids.push(entry.process.pid)
- }
- }
-
stopBackendTreesForUpdate(hermesProcess, {
forceKillProcessTree,
stopAllPoolBackends
@@ -3832,12 +3705,6 @@ async function releaseBackendLock(updateRoot, tag) {
stragglers.push(currentHermesProcess.pid)
}
- for (const entry of backendPool.values()) {
- if (entry.process && Number.isInteger(entry.process.pid)) {
- stragglers.push(entry.process.pid)
- }
- }
-
return stragglers
},
killProcessTree: forceKillProcessTree,
@@ -11291,7 +11158,7 @@ function sendConnectionApplied() {
// every window must tear down (and, for edits, re-dial) its secondary sockets
// scoped to that connection. Without this, a removed remote/cloud source keeps
// its renderer WebSocket open and streaming as a ghost, and an edited one
-// keeps talking to the OLD endpoint until idle-reap.
+// keeps talking to the OLD endpoint indefinitely.
function broadcastConnectionsChanged(payload: { connectionId: string; reason: 'removed' | 'saved' | 'updated' }) {
for (const win of BrowserWindow.getAllWindows()) {
const { webContents } = win
@@ -11403,10 +11270,7 @@ async function forgetLocalGatewayDescriptor(profile) {
return
}
- const entry = backendPool.get(key)
-
- if (entry && !entry.process) {
- backendPool.delete(key)
+ if (backendPool.delete(key)) {
rememberLog(`[gateway] forgot stale canonical endpoint for profile "${key}"; re-ensuring`)
}
}
@@ -11431,48 +11295,26 @@ async function ensureBackend(profile) {
: connection
}
- // A backend for this key may still be dying (idle reap, LRU eviction, a
- // just-finished delete). Wait for its bounded exit before reusing or
- // spawning, so two children never share one profile's HERMES_HOME.
- const stopping = poolStopper.inFlight(key)
-
- if (stopping) {
- await stopping
- }
-
const existing = backendPool.get(key)
if (existing) {
- existing.lastActiveAt = Date.now()
-
const connection = await existing.connectionPromise
setWslBridgeProfileState(key, connection.mode !== 'remote')
return connection
}
- evictLruPoolBackends(poolMaxBackends() - 1)
-
- const entry = {
- process: null,
- port: null,
- token: null,
- connectionPromise: null,
- lastActiveAt: Date.now(),
- remoteBaseUrl: null
- }
+ const entry = newPoolEntry()
- entry.connectionPromise = spawnPoolBackend(key, entry).catch(async error => {
- // Land the failure in desktop.log: without this a spawn that dies before
- // its child exists (guard rejection, runtime resolution) leaves no trace
+ entry.connectionPromise = dialPoolBackend(key, entry).catch(error => {
+ // Land the failure in desktop.log: without this a dial that fails before
+ // the gateway answers (guard rejection, runtime resolution) leaves no trace
// beyond renderer-side rejections users never see in a bundle.
logPoolSpawnFailure(`"${key}"`, error)
-
- await teardownFailedLocalBackend(key, entry)
+ forgetFailedPoolEntry(key, entry)
throw error
})
backendPool.set(key, entry)
- startPoolIdleReaper()
const connection = await entry.connectionPromise
setWslBridgeProfileState(key, connection.mode !== 'remote')
@@ -11484,9 +11326,9 @@ async function ensureBackend(profile) {
// Resolve a backend for (connectionId, profile) against the v2 registry.
// The LOCAL connection routes through ensureBackend() when the v1 route is
// itself local (so every single-source path stays byte-identical), and forces
-// a genuinely-local child when the v1 mode says remote; non-local connections
-// pool under the composite key from backendScopeKey() and reuse the same pool
-// entry lifecycle (LRU, idle reaper, touch) as per-profile local backends.
+// a genuinely-local dial when the v1 mode says remote; non-local connections
+// cache under the composite key from backendScopeKey() with the same entry
+// lifecycle as per-profile local descriptors.
async function ensureRegistryBackend(
connectionId,
profile,
@@ -11602,44 +11444,25 @@ async function ensureRegistryBackend(
return ensureBackend(profile)
}
- const stoppingLocal = poolStopper.inFlight(localRoute.poolKey)
-
- if (stoppingLocal) {
- await stoppingLocal
- }
-
const existingLocal = backendPool.get(localRoute.poolKey)
if (existingLocal) {
- existingLocal.lastActiveAt = Date.now()
-
return existingLocal.connectionPromise
}
- evictLruPoolBackends(poolMaxBackends() - 1)
-
- const localEntry = {
- process: null,
- port: null,
- token: null,
- connectionPromise: null,
- lastActiveAt: Date.now(),
- remoteBaseUrl: null
- }
+ const localEntry = newPoolEntry()
- localEntry.connectionPromise = spawnPoolBackend(profileKey, localEntry, {
+ localEntry.connectionPromise = dialPoolBackend(profileKey, localEntry, {
forceLocal: true,
poolKey: localRoute.poolKey
- }).catch(async error => {
- // Same trace rule as the v1 pool path: a forced-local child whose spawn
- // rejects before the child exists must still land in desktop.log.
+ }).catch(error => {
+ // Same trace rule as the v1 path: a forced-local dial that rejects must
+ // still land in desktop.log.
logPoolSpawnFailure(`"${profileKey}" (forced-local)`, error)
-
- await teardownFailedLocalBackend(localRoute.poolKey, localEntry)
+ forgetFailedPoolEntry(localRoute.poolKey, localEntry)
throw error
})
backendPool.set(localRoute.poolKey, localEntry)
- startPoolIdleReaper()
return localEntry.connectionPromise
}
@@ -11648,7 +11471,6 @@ async function ensureRegistryBackend(
const existing = backendPool.get(key)
if (existing) {
- existing.lastActiveAt = Date.now()
const connectionPromise = existing.connectionPromise
// A remote process can die while its local SSH forward stays LISTENing.
@@ -11682,16 +11504,7 @@ async function ensureRegistryBackend(
)
}
- evictLruPoolBackends(poolMaxBackends() - 1)
-
- const entry = {
- process: null,
- port: null,
- token: null,
- connectionPromise: null,
- lastActiveAt: Date.now(),
- remoteBaseUrl: null
- }
+ const entry = newPoolEntry()
entry.connectionPromise = connectRegistryBackend(
source,
@@ -11702,21 +11515,15 @@ async function ensureRegistryBackend(
source.kind === 'ssh' ? resolveRegistryEffectiveFingerprint() : null,
managedUpdateCorrelation
).catch(error => {
- if (backendPool.get(key) === entry) {
- backendPool.delete(key)
- }
-
+ forgetFailedPoolEntry(key, entry)
throw error
})
backendPool.set(key, entry)
- startPoolIdleReaper()
return entry.connectionPromise
}
-// Dial a non-local registry connection for one profile. Never spawns a local
-// child (entry.process stays null — stopPoolBackend/evict already tolerate
-// that shape from remote per-profile overrides).
+// Dial a non-local registry connection for one profile.
async function connectRegistryBackend(
source,
profile,
@@ -11813,19 +11620,10 @@ async function ensureManagedSshBackendAtKey(source, profile, key, correlationId,
const existing = backendPool.get(key)
if (existing) {
- existing.lastActiveAt = Date.now()
-
return existing.connectionPromise
}
- const entry = {
- process: null,
- port: null,
- token: null,
- connectionPromise: null,
- lastActiveAt: Date.now(),
- remoteBaseUrl: null
- }
+ const entry = newPoolEntry()
entry.connectionPromise = connectRegistryBackend(
source,
@@ -11837,14 +11635,10 @@ async function ensureManagedSshBackendAtKey(source, profile, key, correlationId,
correlationId,
tokenPersistenceSource
).catch(error => {
- if (backendPool.get(key) === entry) {
- backendPool.delete(key)
- }
-
+ forgetFailedPoolEntry(key, entry)
throw error
})
backendPool.set(key, entry)
- startPoolIdleReaper()
return entry.connectionPromise
}
@@ -12308,113 +12102,28 @@ async function stopRegistryConnectionBackends(connectionId) {
)
}
-// Mark a pool profile as recently used so the idle reaper spares it. The
-// renderer calls this when it opens a profile's chat WS and periodically while
-// streaming, since the main process can't see the direct renderer↔backend WS.
-function touchPoolBackend(profile) {
- for (const key of poolTouchKeys(profile)) {
- const entry = backendPool.get(key)
-
- if (entry) {
- entry.lastActiveAt = Date.now()
-
- return
- }
- }
+function newPoolEntry() {
+ return { connectionPromise: null, remoteBaseUrl: null }
}
-// Evict least-recently-used SPAWNED pool backends until at most `keep` remain —
-// but only ever evict backends without a live renderer socket (stale beyond the
-// keepalive window). When every backend is actively kept alive we let the pool
-// exceed the soft cap rather than kill a running session. Process-less
-// descriptor entries (remote/cloud registry sources, per-profile remote
-// overrides — `entry.process === null`) are excluded from the cap entirely:
-// they hold no local process, so counting them used to let a roster refresh
-// across N registered remote connections LRU-evict a REAL local backend that
-// was merely idle past the keepalive window. Descriptors are still reclaimed
-// by the idle reaper.
-function evictLruPoolBackends(keep) {
- const evictions = selectPoolEvictions(backendPool.entries(), Math.max(0, keep), Date.now(), POOL_KEEPALIVE_FRESH_MS)
-
- for (const profile of evictions) {
- rememberLog(`Evicting idle profile backend "${profile}" (LRU cap ${poolMaxBackends()})`)
- stopPoolBackend(profile)
- }
-}
-
-function startPoolIdleReaper() {
- if (poolIdleReaper) {
- return
- }
-
- poolIdleReaper = setInterval(() => {
- const now = Date.now()
-
- for (const [profile, entry] of [...backendPool.entries()]) {
- if (now - (entry.lastActiveAt || 0) > poolIdleMs()) {
- rememberLog(`Reaping idle profile backend "${profile}" (idle > ${Math.round(poolIdleMs() / 1000)}s)`)
- stopPoolBackend(profile)
- }
- }
-
- if (backendPool.size === 0 && poolIdleReaper) {
- clearInterval(poolIdleReaper)
- poolIdleReaper = null
- }
- }, 60_000)
-
- if (typeof poolIdleReaper.unref === 'function') {
- poolIdleReaper.unref()
- }
+function forgetFailedPoolEntry(poolKey: string, entry: any) {
+ forgetFailedDescriptor(backendPool, poolKey, entry)
}
function assertPoolEntryStillOwned(poolKey: string, entry: any) {
- if (backendPool.get(poolKey) !== entry) {
- throw new Error(`Profile backend start for "${poolKey}" was cancelled before spawn.`)
- }
-}
-
-const failedLocalBackendTeardowns = new WeakMap<object, Promise<void>>()
-
-function teardownFailedLocalBackend(poolKey: string, entry: any): Promise<void> {
- const existing = failedLocalBackendTeardowns.get(entry)
-
- if (existing) {
- return existing
- }
-
- if (backendPool.get(poolKey) === entry) {
- backendPool.delete(poolKey)
- }
-
- const child = entry.process
-
- const teardown = (async () => {
- stopBackendChild(child)
- await waitForBackendExit(child)
-
- if (child && child.exitCode === null && child.signalCode === null) {
- throw new Error(`Profile backend for "${poolKey}" did not exit.`)
- }
-
- releaseBackendChild(child)
- })()
-
- // Keep the settled promise in the WeakMap for the lifetime of this entry.
- // Error + exit + outer catch may all request cleanup; none may run it twice.
- failedLocalBackendTeardowns.set(entry, teardown)
-
- return teardown
-}
-
-// Spawn an additional dashboard backend pinned to a named profile. Mirrors the
-// local-spawn portion of startHermes() but without the boot-progress UI,
-// bootstrap, or remote handling (those belong to the primary backend only).
-// `opts.forceLocal` skips remote resolution entirely (the registry 'local'
-// entry means THIS machine regardless of the v1 routing table); `opts.poolKey`
-// is the backendPool key when it differs from the profile name (composite
-// registry scopes) so the exit/error cleanup evicts the right entry.
-async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; poolKey?: string } = {}) {
+ assertDescriptorStillOwned(backendPool, poolKey, entry)
+}
+
+// Resolve the connection descriptor for a named profile that is not the
+// primary: attach to (or start) its canonical local gateway via
+// `hermes gateway ensure`, or verify and describe its remote. Mirrors the local
+// portion of startHermes() without the boot-progress UI, bootstrap, or
+// first-run handling (those belong to the primary only). `opts.forceLocal`
+// skips remote resolution entirely (the registry 'local' entry means THIS
+// machine regardless of the v1 routing table); `opts.poolKey` is the
+// backendPool key when it differs from the profile name (composite registry
+// scopes) so failure cleanup forgets the right entry.
+async function dialPoolBackend(profile, entry, opts: { forceLocal?: boolean; poolKey?: string } = {}) {
const poolKey = opts.poolKey || profile
await reapOrphanedBackendsOnce()
@@ -12422,10 +12131,8 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; po
// A profile may point at its OWN remote backend (connection.json
// `profiles[name]`), or inherit the app-wide remote (env / global settings).
- // In either case there is no local child to spawn — we just verify the
- // remote is reachable and hand back its connection descriptor. The pool
- // entry keeps `entry.process === null`, which stopPoolBackend/evict already
- // tolerate.
+ // In either case we just verify the remote is reachable and hand back its
+ // connection descriptor.
const remote = opts.forceLocal ? null : await resolveRemoteBackend(profile, { poolKey })
profileDeletionGate.assertCanStart(profile)
@@ -12466,20 +12173,13 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; po
return { ...connection, profile, logs: hermesLog.slice(-80), ...getWindowState() }
}
-// Bounded, deduplicated pool teardown (see pool-stop.ts): every stop path —
-// idle reaper, LRU eviction, profile delete/rename, quit — shares one
-// in-flight stop per key and retains the process handle until the bounded
-// SIGTERM -> SIGKILL escalation in waitForBackendExit() resolves. Previously
-// SIGTERM + immediate entry delete dropped the handle and a slow child
-// survived detached under PID 1.
-const poolStopper = createPoolStopper({
- pool: backendPool,
- stopChild: child => stopBackendChild(child),
- waitForExit: child => waitForBackendExit(child)
-})
-
+// Forget a cached descriptor. Nothing is killed: the gateway behind it owns its
+// own lifetime (`hermes gateway ensure` attach semantics), so the next
+// ensure*() for this key simply re-dials. Every retire path — dispatch probe
+// failure, resume revalidation, registry removal, profile delete/rename, quit —
+// funnels through here so the verb stays in one place.
async function stopPoolBackend(profile: string) {
- await poolStopper.stop(profile)
+ backendPool.delete(profile)
}
async function teardownPoolBackendAndWait(profile) {
@@ -12487,21 +12187,14 @@ async function teardownPoolBackendAndWait(profile) {
}
async function stopAllPoolBackends() {
- await poolStopper.stopAll()
+ backendPool.clear()
}
const backendShutdown = createBackendShutdownCoordinator(async () => {
const primary = backendConnectionState.invalidate()
stopBackendChild(primary)
- const pooledStops = stopAllPoolBackends()
-
- if (poolIdleReaper) {
- clearInterval(poolIdleReaper)
- poolIdleReaper = null
- }
-
- await Promise.all([waitForBackendExit(primary), pooledStops])
+ await Promise.all([waitForBackendExit(primary), stopAllPoolBackends()])
})
async function exitAfterBackendShutdown(code) {
@@ -14424,8 +14117,8 @@ ipcMain.handle('hermes:connection:revalidate', async () => {
})
// Pooled remote descriptors get the same treatment as the primary: they have no
-// child process to signal their host's death, and the renderer's keepalive touch
-// spares them from the idle reaper, so nothing else can retire a dead one.
+// child process to signal their host's death, so nothing else can retire a dead
+// one.
function revalidatePool() {
return revalidatePooledRemoteBackends({
entries: backendPool.entries(),
@@ -14480,23 +14173,6 @@ function revalidateSuspectPoolAfterResume() {
)
}
-ipcMain.handle('hermes:backend:touch', async (_event, profile) => {
- touchPoolBackend(profile)
-
- return { ok: true }
-})
-// Pool sizing (Settings → Advanced): device-local, live-applied. Main is
-// authoritative (it owns the pool and the persisted copy); the returned
-// limits are what actually took effect post-clamp.
-ipcMain.handle('hermes:pool-limits:get', async () => ({ ...poolLimits }))
-ipcMain.handle('hermes:pool-limits:set', async (_event, raw) => {
- const next = setPoolLimits({
- maxBackends: typeof raw?.maxBackends === 'number' ? raw.maxBackends : poolLimits.maxBackends,
- idleMs: typeof raw?.idleMs === 'number' ? raw.idleMs : poolLimits.idleMs
- })
-
- return { ok: true, limits: next }
-})
ipcMain.handle('hermes:gateway:ws-url', async (_event, profile) => {
return gatewayWsUrlIpcResult(() => freshGatewayWsUrl(profile, _event.sender.id))
})
@@ -16083,7 +15759,7 @@ function registryConnectionKind(connectionId) {
async function teardownConnectionScopedProfileBackend(connectionId, profile) {
const key = backendScopeKey(connectionId, profile)
await Promise.all([
- poolStopper.stop(key),
+ stopPoolBackend(key),
sshBootstrapCoordinator.cancelAndWait(key).then(() => teardownSshConnection(key))
])
}
diff --git a/apps/desktop/electron/pool-eviction.test.ts b/apps/desktop/electron/pool-eviction.test.ts
deleted file mode 100644
index 4ad3c3fc0de..00000000000
--- a/apps/desktop/electron/pool-eviction.test.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-/**
- * Tests for electron/pool-eviction.ts — LRU cap accounting for the desktop
- * backend pool. The cap exists to bound SPAWNED local backends (real child
- * processes); process-less descriptor entries (remote/cloud registry sources,
- * per-profile remote overrides) must not count against it, or a roster
- * refresh across N registered remote connections evicts a real local backend
- * that was merely idle past the keepalive window.
- */
-
-import assert from 'node:assert/strict'
-
-import { test } from 'vitest'
-
-import { selectPoolEvictions } from './pool-eviction'
-
-const NOW = 1_000_000
-// Mirrors main.ts POOL_KEEPALIVE_FRESH_MS (4 minutes — see #95189).
-const FRESH_MS = 4 * 60_000
-
-/** A spawned local backend entry (has a child process). */
-const spawned = (idleMs: number) => ({ process: { pid: 123 }, lastActiveAt: NOW - idleMs })
-
-/** A process-less remote/cloud descriptor entry. */
-const descriptor = (idleMs: number) => ({ process: null, lastActiveAt: NOW - idleMs })
-
-test('process-less descriptors do not count toward the cap', () => {
- // 1 real spawned backend idle beyond the keepalive window + 3 remote
- // descriptors: total size (4) exceeds keep (2), but only ONE entry holds a
- // process, so nothing may be evicted. This is the roster-refresh regression:
- // the old size-based accounting evicted the real local backend here.
- const entries: [string, ReturnType<typeof spawned>][] = [
- ['default', spawned(120_000)],
- ['conn:homelab::default', descriptor(0)],
- ['conn:office::default', descriptor(0)],
- ['conn:cloud-a::default', descriptor(0)]
- ]
-
- assert.deepEqual(selectPoolEvictions(entries, 2, NOW, FRESH_MS), [])
-})
-
-test('spawned backends over the cap are still LRU-evicted', () => {
- const entries: [string, ReturnType<typeof spawned>][] = [
- ['a', spawned(500_000)],
- ['b', spawned(300_000)],
- ['c', spawned(100_000)],
- // Descriptors interleaved: must neither inflate the count nor be evicted.
- ['conn:x::a', descriptor(999_000)]
- ]
-
- // keep=2 → one spawned backend over; evict the least-recently-used ('a').
- assert.deepEqual(selectPoolEvictions(entries, 2, NOW, FRESH_MS), ['a'])
-})
-
-test('fresh spawned backends are spared even over the cap', () => {
- const entries: [string, ReturnType<typeof spawned>][] = [
- ['a', spawned(1_000)],
- ['b', spawned(2_000)],
- ['c', spawned(3_000)]
- ]
-
- // All within the keepalive window → the pool may exceed the soft cap.
- assert.deepEqual(selectPoolEvictions(entries, 1, NOW, FRESH_MS), [])
-})
-
-test('evicts only enough stale spawned backends to reach the cap', () => {
- const entries: [string, ReturnType<typeof spawned>][] = [
- ['a', spawned(500_000)],
- ['b', spawned(400_000)],
- ['c', spawned(300_000)],
- ['d', spawned(1_000)]
- ]
-
- // 4 spawned, keep 2 → remove 2, oldest first.
- assert.deepEqual(selectPoolEvictions(entries, 2, NOW, FRESH_MS), ['a', 'b'])
-})
-
-test('descriptor-only pools never evict', () => {
- const entries: [string, ReturnType<typeof descriptor>][] = [
- ['conn:a::p', descriptor(999_000)],
- ['conn:b::p', descriptor(999_000)],
- ['conn:c::p', descriptor(999_000)],
- ['conn:d::p', descriptor(999_000)]
- ]
-
- assert.deepEqual(selectPoolEvictions(entries, 2, NOW, FRESH_MS), [])
-})
-
-// ── #95189 — Keepalive-fresh window must tolerate transient missed pings ──
-// Symptom: gateway restarts every ~2 minutes on WSL2. Root cause: the renderer
-// pings every 60s; the LRU cap declared a backend "stale" if `lastActiveAt`
-// was > 90s ago — only 1.5× the ping interval. WSL2 IPC roundtrips (renderer
-// → 9p → Electron main → ipcMain.handle) commonly stall several seconds; one
-// delayed or missed ping pushed a live backend past the threshold and the
-// cap-driven eviction killed the active profile's backend mid-session,
-// forcing a restart loop that re-minted runtime ids and re-allocated pooled
-// gateway secondaries ~700×/day (#95189, related #87906/#84716/#88054).
-//
-// These tests pin the new tolerance: the keepalive-fresh window is wide
-// enough to absorb ≥1 missed ping (and the IPC stall headroom around it)
-// without evicting an active backend. Truly stale backends (multiple lapses,
-// minutes idle) are still evicted as before.
-
-test('#95189: one missed keepalive ping must NOT make the most-recently-touched backend evictable', () => {
- // Renderer's keepalive cadence is 60s. With the old freshMs=90s window,
- // a backend last touched 95s ago — i.e. exactly ONE missed/delayed ping —
- // was eligible for LRU eviction even though it had been actively
- // touched the moment before and would be touched again imminently.
- //
- // Build a pool where the only entry over the cap is the active one (95s
- // idle). With the old 90s window, it was evicted; with the widened window
- // the cap must instead be honored by leaving the pool over-cap for one
- // extra cycle — killing an active backend is far worse than briefly
- // exceeding the soft cap.
- const entries: [string, ReturnType<typeof spawned>][] = [
- ['active', spawned(95_000)], // 1 missed ping on a 60s cadence
- ['fresher', spawned(2_000)] // touched recently — must NOT be evicted
- ]
-
- // keep=1 → pool over cap by one. Active backend must be spared; the cap
- // may be exceeded rather than kill a live backend (the long-standing
- // "spare fresh backends" rule from #94381 / earlier pool-eviction tests).
- assert.deepEqual(selectPoolEvictions(entries, 1, NOW, FRESH_MS), [])
-})
-
-test('#95189: two missed keepalive pings (2-min IPC stall) must NOT evict an active backend', () => {
- // The reported symptom: gateways exited ~80–90s after start with a clean
- // disconnect (no stderr), recurring every ~2 min. Reproduce the boundary:
- // 125s of silence = just over two missed pings at 60s. A backend in this
- // state is still actively serving — the renderer is mid-reconnect, not
- // gone — so eviction here was the trigger for the restart loop.
- //
- // The other entries are all FRESH (well within the keepalive window), so
- // no eviction is correct even before any cap considerations.
- const entries: [string, ReturnType<typeof spawned>][] = [
- ['active', spawned(125_000)],
- ['fresher', spawned(2_000)],
- ['fresher-2', spawned(5_000)]
- ]
-
- assert.deepEqual(selectPoolEvictions(entries, 1, NOW, FRESH_MS), [])
-})
-
-test('#95189: a backend genuinely idle for minutes IS evicted (#95189 long-window scenario)', () => {
- // Sanity: the widening does NOT make the pool unbounded. 10 minutes of
- // silence (the documented POOL_IDLE_MS) is still fair game.
- const entries: [string, ReturnType<typeof spawned>][] = [
- ['idle', spawned(10 * 60_000)],
- ['fresh', spawned(5_000)]
- ]
-
- // keep=1, idle is over the cap AND past the fresh window → evicted.
- assert.deepEqual(selectPoolEvictions(entries, 1, NOW, FRESH_MS), ['idle'])
-})
diff --git a/apps/desktop/electron/pool-eviction.ts b/apps/desktop/electron/pool-eviction.ts
deleted file mode 100644
index 628a3311993..00000000000
--- a/apps/desktop/electron/pool-eviction.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-// LRU cap accounting for the desktop backend pool.
-//
-// The pool holds two very different kinds of entries under one Map:
-// 1. SPAWNED local profile backends — a real child process each (the thing
-// the POOL_MAX_BACKENDS cap exists to bound).
-// 2. Process-less connection DESCRIPTORS — remote/cloud registry sources and
-// per-profile remote overrides (`entry.process === null`). These hold no
-// local process; their only cost is a cached descriptor.
-//
-// Counting both kinds against the cap meant a roster refresh across N
-// registered remote connections could push the Map size over the cap and
-// LRU-evict a REAL spawned backend that had merely been idle past the
-// keepalive window. Cap accounting (and cap-driven eviction) therefore only
-// considers entries with a live child process; descriptor entries remain
-// subject to the idle reaper, just not to the process cap.
-
-export interface PoolEvictionEntry {
- lastActiveAt?: null | number
- process?: unknown
-}
-
-/**
- * Pick which pool keys the LRU cap should evict so that at most `keep`
- * SPAWNED backends remain. Only entries with a live child process count
- * toward the cap or are eligible for cap eviction, and — as before — only
- * entries idle beyond `freshMs` may be evicted (an actively kept-alive pool
- * may exceed the soft cap rather than kill a running session).
- */
-export function selectPoolEvictions<K>(
- entries: Iterable<[K, PoolEvictionEntry]>,
- keep: number,
- now: number,
- freshMs: number
-): K[] {
- const spawned = [...entries].filter(([, entry]) => Boolean(entry.process))
-
- if (spawned.length <= keep) {
- return []
- }
-
- const evictable = spawned
- .filter(([, entry]) => now - (entry.lastActiveAt || 0) > freshMs)
- .sort((a, b) => (a[1].lastActiveAt || 0) - (b[1].lastActiveAt || 0))
-
- let removable = spawned.length - Math.max(0, keep)
- const evictions: K[] = []
-
- for (const [key] of evictable) {
- if (removable <= 0) {
- break
- }
-
- evictions.push(key)
- removable -= 1
- }
-
- return evictions
-}
diff --git a/apps/desktop/electron/pool-limits.test.ts b/apps/desktop/electron/pool-limits.test.ts
deleted file mode 100644
index 5aff45f0883..00000000000
--- a/apps/desktop/electron/pool-limits.test.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { describe, expect, it } from 'vitest'
-
-import {
- clampPoolLimits,
- parsePoolLimits,
- POOL_LIMITS_BOUNDS,
- POOL_LIMITS_DEFAULTS,
- POOL_LIMITS_MIN
-} from './pool-limits'
-
-describe('parsePoolLimits', () => {
- it('falls back to defaults for null/empty/corrupt input', () => {
- expect(parsePoolLimits(null)).toEqual(POOL_LIMITS_DEFAULTS)
- expect(parsePoolLimits(undefined)).toEqual(POOL_LIMITS_DEFAULTS)
- expect(parsePoolLimits('')).toEqual(POOL_LIMITS_DEFAULTS)
- expect(parsePoolLimits('not json {')).toEqual(POOL_LIMITS_DEFAULTS)
- })
-
- it('parses a valid persisted blob', () => {
- expect(parsePoolLimits(JSON.stringify({ maxBackends: 11, idleMs: 7_200_000 }))).toEqual({
- maxBackends: 11,
- idleMs: 7_200_000
- })
- })
-
- it('fills missing keys from defaults', () => {
- expect(parsePoolLimits(JSON.stringify({ maxBackends: 5 }))).toEqual({ ...POOL_LIMITS_DEFAULTS, maxBackends: 5 })
- expect(parsePoolLimits('{}')).toEqual(POOL_LIMITS_DEFAULTS)
- })
-
- it('ignores non-numeric junk instead of NaN-poisoning the pool', () => {
- expect(parsePoolLimits(JSON.stringify({ maxBackends: 'lots', idleMs: null }))).toEqual(POOL_LIMITS_DEFAULTS)
- })
-})
-
-describe('clampPoolLimits', () => {
- it('clamps below the floors', () => {
- expect(clampPoolLimits({ maxBackends: 0 }).maxBackends).toBe(POOL_LIMITS_MIN.maxBackends)
- expect(clampPoolLimits({ idleMs: 100 }).idleMs).toBe(POOL_LIMITS_MIN.idleMs)
- })
-
- it('clamps absurdly high backend counts', () => {
- expect(clampPoolLimits({ maxBackends: 10_000 }).maxBackends).toBeLessThanOrEqual(64)
- })
-
- it('clamps idleMs to the shared ceiling (7 days)', () => {
- expect(clampPoolLimits({ idleMs: 999_000_000 }).idleMs).toBe(POOL_LIMITS_BOUNDS.idleMsMax)
- })
-
- it('floors fractional values', () => {
- expect(clampPoolLimits({ maxBackends: 2.9 }).maxBackends).toBe(2)
- })
-})
diff --git a/apps/desktop/electron/pool-limits.ts b/apps/desktop/electron/pool-limits.ts
deleted file mode 100644
index ee7e5b8a8a8..00000000000
--- a/apps/desktop/electron/pool-limits.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-/**
- * Pool limits — how many bot backends may stay spawned, and how long an
- * unused one survives.
- *
- * A device-local preference (each machine trades RAM against switching
- * speed for itself), stored in userData like keep-awake. The main process
- * is authoritative: it owns the pool AND the persisted copy, and applies a
- * new max IMMEDIATELY by evicting least-recently-used idle backends — no
- * app restart. The renderer mirrors the values for its UI and prewarm
- * guard over IPC.
- *
- * Defaults preserve the historical hard-coded behavior (3 backends, 10min
- * idle) so machines that never open Settings behave exactly as before.
- */
-
-export interface PoolLimits {
- /** Max concurrently spawned non-primary profile backends. */
- maxBackends: number
- /** Idle lifetime of an unused pool backend, in milliseconds. */
- idleMs: number
-}
-
-export const POOL_LIMITS_DEFAULTS: PoolLimits = {
- maxBackends: 3,
- idleMs: 10 * 60_000
-}
-
-/** Hard floors — match the clamps the env-var path always applied. */
-export const POOL_LIMITS_MIN: PoolLimits = {
- maxBackends: 1,
- idleMs: 60_000
-}
-
-/** Shared bounds for both pool knobs — imported by the Settings UI so the
- * advertised input ranges can never drift from what main actually clamps
- * to. idleMs has no ceiling: a user who wants backends kept warm all week
- * may have exactly that. */
-export const POOL_LIMITS_BOUNDS = {
- maxBackendsMax: 64,
- /** 7 days, matching the UI's suggestion ceiling. */
- idleMsMax: 7 * 24 * 60 * 60_000
-} as const
-
-const MAX_BACKENDS_CEILING = POOL_LIMITS_BOUNDS.maxBackendsMax
-const IDLE_MS_CEILING = POOL_LIMITS_BOUNDS.idleMsMax
-
-/** Clamp a raw partial to the floors/ceilings; missing keys fall to defaults. */
-export function clampPoolLimits(raw: Partial<PoolLimits>): PoolLimits {
- const maxBackends = Number.isFinite(raw.maxBackends)
- ? Math.min(MAX_BACKENDS_CEILING, Math.max(POOL_LIMITS_MIN.maxBackends, Math.floor(Number(raw.maxBackends))))
- : POOL_LIMITS_DEFAULTS.maxBackends
-
- const idleMs = Number.isFinite(raw.idleMs)
- ? Math.min(IDLE_MS_CEILING, Math.max(POOL_LIMITS_MIN.idleMs, Math.floor(Number(raw.idleMs))))
- : POOL_LIMITS_DEFAULTS.idleMs
-
- return { maxBackends, idleMs }
-}
-
-function clampLimits(raw: Partial<PoolLimits>): PoolLimits {
- return clampPoolLimits(raw)
-}
-
-/** Parse + clamp a persisted JSON blob; anything unreadable falls back to
- * defaults so a corrupted file can never wedge the pool. */
-export function parsePoolLimits(json: string | null | undefined): PoolLimits {
- if (!json) {
- return { ...POOL_LIMITS_DEFAULTS }
- }
-
- try {
- const parsed = JSON.parse(json)
-
- return clampLimits({
- maxBackends: typeof parsed?.maxBackends === 'number' ? parsed.maxBackends : undefined,
- idleMs: typeof parsed?.idleMs === 'number' ? parsed.idleMs : undefined
- })
- } catch {
- return { ...POOL_LIMITS_DEFAULTS }
- }
-}
diff --git a/apps/desktop/electron/pool-spawn-coordinator.test.ts b/apps/desktop/electron/pool-spawn-coordinator.test.ts
deleted file mode 100644
index e55c1921d49..00000000000
--- a/apps/desktop/electron/pool-spawn-coordinator.test.ts
+++ /dev/null
@@ -1,499 +0,0 @@
-import assert from 'node:assert/strict'
-import { spawn } from 'node:child_process'
-
-import { test } from 'vitest'
-
-import {
- LocalBackendSlotWaitTimeoutError,
- LocalBackendSpawnCoordinator,
- releaseLocalBackendSlotAfterExit
-} from './pool-spawn-coordinator'
-
-const deferred = () => {
- let resolve!: () => void
-
- const promise = new Promise<void>(done => {
- resolve = done
- })
-
- return { promise, resolve }
-}
-
-const flush = () => new Promise<void>(resolve => setImmediate(resolve))
-
-test('100 concurrent local requests never hold more than the configured slots', async () => {
- const limit = 12
- const coordinator = new LocalBackendSpawnCoordinator(limit)
- const gates = Array.from({ length: 100 }, deferred)
- let active = 0
- let maxActive = 0
-
- const tasks = gates.map(async (gate, index) => {
- const release = await coordinator.acquire(`profile-${index}`)
- active += 1
- maxActive = Math.max(maxActive, active)
-
- await gate.promise
-
- active -= 1
- release()
- })
-
- await flush()
- assert.equal(active, limit)
- assert.equal(coordinator.activeCount, limit)
- assert.equal(coordinator.queuedCount, 100 - limit)
-
- for (let start = 0; start < gates.length; start += limit) {
- for (const gate of gates.slice(start, start + limit)) {
- gate.resolve()
- }
-
- await flush()
- }
-
- await Promise.all(tasks)
- assert.equal(maxActive, limit)
- assert.equal(coordinator.activeCount, 0)
- assert.equal(coordinator.queuedCount, 0)
-})
-
-test('a queued start can be cancelled without waiting for an active backend', async () => {
- const coordinator = new LocalBackendSpawnCoordinator(1)
- const releaseFirst = await coordinator.acquire('first')
- const queued = coordinator.request('cancelled')
-
- assert.equal(coordinator.queuedCount, 1)
- assert.equal(queued.cancel(), true)
- await assert.rejects(queued.acquired, /cancelled while queued/)
- assert.equal(coordinator.activeCount, 1)
- assert.equal(coordinator.queuedCount, 0)
-
- releaseFirst()
- assert.equal(coordinator.activeCount, 0)
-})
-
-test('cancelling an old same-key request never rejects a newer waiter', async () => {
- const coordinator = new LocalBackendSpawnCoordinator(1)
- const blocker = coordinator.request('blocker')
- const releaseBlocker = await blocker.acquired
- const old = coordinator.request('same-profile')
-
- releaseBlocker()
- const newer = coordinator.request('same-profile')
-
- assert.equal(old.cancel(), false, 'the old request was already granted')
- assert.equal(coordinator.queuedCount, 1, 'the newer same-key waiter must remain queued')
-
- const releaseOld = await old.acquired
- releaseOld()
- const releaseNewer = await newer.acquired
- releaseNewer()
-
- assert.equal(coordinator.activeCount, 0)
- assert.equal(coordinator.queuedCount, 0)
-})
-
-test('a queued start times out with a clear error and frees its queue position', async () => {
- const coordinator = new LocalBackendSpawnCoordinator(1)
- const releaseFirst = await coordinator.acquire('first')
- const queued = coordinator.request('timed-out', { timeoutMs: 10 })
-
- await assert.rejects(queued.acquired, /timed out while waiting for a free slot/)
- assert.equal(coordinator.activeCount, 1)
- assert.equal(coordinator.queuedCount, 0)
-
- releaseFirst()
- assert.equal(coordinator.activeCount, 0)
-})
-
-test('100 real child processes never exceed twelve simultaneous local slots', async () => {
- const limit = 12
- const coordinator = new LocalBackendSpawnCoordinator(limit)
- const livePids = new Set<number>()
- const seenPids = new Set<number>()
- let maxLive = 0
-
- await Promise.all(
- Array.from({ length: 100 }, async (_, index) => {
- const release = await coordinator.acquire(`real-profile-${index}`)
-
- try {
- const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 40)'], {
- stdio: 'ignore'
- })
-
- assert.ok(child.pid)
- livePids.add(child.pid)
- seenPids.add(child.pid)
- maxLive = Math.max(maxLive, livePids.size)
-
- await new Promise<void>((resolve, reject) => {
- child.once('error', reject)
- child.once('exit', code => {
- if (code === 0) {
- resolve()
- } else {
- reject(new Error(`child ${child.pid} exited with ${code}`))
- }
- })
- })
-
- livePids.delete(child.pid)
- } finally {
- release()
- }
- })
- )
-
- assert.equal(seenPids.size, 100)
- assert.equal(maxLive, limit)
- assert.equal(livePids.size, 0)
- assert.equal(coordinator.activeCount, 0)
- assert.equal(coordinator.queuedCount, 0)
-})
-
-test('failed start keeps its slot until the child has actually exited', async () => {
- const coordinator = new LocalBackendSpawnCoordinator(1)
- const childExit = deferred()
- const releaseFailed = await coordinator.acquire('failed')
- let successorEntered = false
-
- const successor = coordinator.acquire('successor').then(release => {
- successorEntered = true
-
- return release
- })
-
- const cleanup = releaseLocalBackendSlotAfterExit(releaseFailed, () => childExit.promise)
- await flush()
-
- assert.equal(successorEntered, false)
- assert.equal(coordinator.activeCount, 1)
- assert.equal(coordinator.queuedCount, 1)
-
- childExit.resolve()
- await cleanup
- const releaseSuccessor = await successor
-
- assert.equal(successorEntered, true)
- assert.equal(coordinator.activeCount, 1)
- assert.equal(coordinator.queuedCount, 0)
-
- releaseSuccessor()
- assert.equal(coordinator.activeCount, 0)
-})
-
-test('a rejected wait keeps the slot occupied', async () => {
- const coordinator = new LocalBackendSpawnCoordinator(1)
- const releaseFailed = await coordinator.acquire('failed')
- let successorEntered = false
-
- const successor = coordinator.acquire('successor').then(release => {
- successorEntered = true
-
- return release
- })
-
- const cleanup = releaseLocalBackendSlotAfterExit(releaseFailed, async () => {
- throw new Error('exit unproven')
- })
-
- await assert.rejects(cleanup, /exit unproven/)
- await flush()
-
- assert.equal(successorEntered, false)
- assert.equal(coordinator.activeCount, 1)
- assert.equal(coordinator.queuedCount, 1)
-
- releaseFailed()
- const releaseSuccessor = await successor
- assert.equal(successorEntered, true)
- releaseSuccessor()
- assert.equal(coordinator.activeCount, 0)
- assert.equal(coordinator.queuedCount, 0)
-})
-
-test('an invalid timeout never enqueues a waiter', async () => {
- const coordinator = new LocalBackendSpawnCoordinator(1)
- const releaseFirst = await coordinator.acquire('first')
-
- assert.throws(() => coordinator.request('invalid', { timeoutMs: 0 }), /timeout must be a positive number/)
- assert.throws(() => coordinator.request('invalid', { timeoutMs: Number.NaN }), /timeout must be a positive number/)
- assert.throws(() => coordinator.request('invalid', { timeoutMs: -5 }), /timeout must be a positive number/)
-
- assert.equal(coordinator.activeCount, 1)
- assert.equal(coordinator.queuedCount, 0)
-
- releaseFirst()
- assert.equal(coordinator.activeCount, 0)
-})
-
-test('a failed or repeated cleanup releases exactly one slot', async () => {
- const coordinator = new LocalBackendSpawnCoordinator(1)
- const releaseFirst = await coordinator.acquire('first')
- let secondEntered = false
-
- const second = coordinator.acquire('second').then(release => {
- secondEntered = true
-
- return release
- })
-
- await flush()
- assert.equal(secondEntered, false)
- assert.equal(coordinator.activeCount, 1)
- assert.equal(coordinator.queuedCount, 1)
-
- releaseFirst()
- releaseFirst()
- const releaseSecond = await second
-
- assert.equal(secondEntered, true)
- assert.equal(coordinator.activeCount, 1)
- assert.equal(coordinator.queuedCount, 0)
-
- releaseSecond()
- assert.equal(coordinator.activeCount, 0)
-})
-
-test('raising the limit at runtime drains queued waiters into the new slots', async () => {
- const coordinator = new LocalBackendSpawnCoordinator(1)
- const first = await coordinator.acquire('a')
- const queuedB = coordinator.request('b')
- const queuedC = coordinator.request('c')
- await flush()
- assert.equal(coordinator.activeCount, 1)
- assert.equal(coordinator.queuedCount, 2)
-
- coordinator.setLimit(2)
- const releaseB = await queuedB.acquired
- assert.equal(coordinator.activeCount, 2)
- assert.equal(coordinator.queuedCount, 1)
-
- first()
- const releaseC = await queuedC.acquired
- assert.equal(coordinator.activeCount, 2)
- releaseB()
- releaseC()
- assert.equal(coordinator.activeCount, 0)
-})
-
-test('lowering the limit never revokes granted slots; new requests queue until under cap', async () => {
- const coordinator = new LocalBackendSpawnCoordinator(3)
- const releases = await Promise.all(['a', 'b', 'c'].map(key => coordinator.acquire(key)))
- coordinator.setLimit(1)
- assert.equal(coordinator.activeCount, 3, 'granted slots stay granted')
-
- const queued = coordinator.request('d')
- await flush()
- assert.equal(coordinator.queuedCount, 1)
-
- releases[0]()
- releases[1]()
- await flush()
- assert.equal(coordinator.queuedCount, 1, 'still over the new cap of 1')
-
- releases[2]()
- const releaseD = await queued.acquired
- assert.equal(coordinator.activeCount, 1)
- releaseD()
-})
-
-test('setLimit rejects a non-positive or fractional cap', () => {
- const coordinator = new LocalBackendSpawnCoordinator(2)
- assert.throws(() => coordinator.setLimit(0), RangeError)
- assert.throws(() => coordinator.setLimit(1.5), RangeError)
- assert.equal(coordinator.limit, 2)
-})
-
-test('cap 3: two background leases leave a reserved slot for foreground', async () => {
- const coordinator = new LocalBackendSpawnCoordinator(3)
- const bg1 = await coordinator.request('bg-1', { priority: 'background' }).acquired
- const bg2 = await coordinator.request('bg-2', { priority: 'background' }).acquired
- assert.equal(coordinator.activeCount, 2)
- assert.equal(coordinator.queuedCount, 0)
-
- let fgGranted = false
-
- const fgPromise = coordinator.request('fg', { priority: 'foreground' }).acquired.then(release => {
- fgGranted = true
-
- return release
- })
-
- await flush()
- assert.equal(fgGranted, true)
- assert.equal(coordinator.activeCount, 3)
-
- const releaseFg = await fgPromise
- bg1()
- bg2()
- releaseFg()
- assert.equal(coordinator.activeCount, 0)
-})
-
-test('untagged acquire still fills the cap (foreground default)', async () => {
- const coordinator = new LocalBackendSpawnCoordinator(3)
- const releases = await Promise.all(['a', 'b', 'c'].map(key => coordinator.acquire(key)))
- assert.equal(coordinator.activeCount, 3)
- assert.equal(coordinator.queuedCount, 0)
-
- for (const release of releases) {
- release()
- }
-
- assert.equal(coordinator.activeCount, 0)
-})
-
-test('foreground is granted the reserved slot ahead of a background hydration queue', async () => {
- const coordinator = new LocalBackendSpawnCoordinator(3)
-
- const bgRunning = await Promise.all(
- ['bg-run-1', 'bg-run-2'].map(key => coordinator.request(key, { priority: 'background' }).acquired)
- )
-
- const queued = Array.from({ length: 20 }, (_, index) =>
- coordinator.request(`bg-wait-${index}`, { priority: 'background', timeoutMs: 5_000 })
- )
-
- await flush()
- assert.equal(coordinator.activeCount, 2)
- assert.equal(coordinator.queuedCount, 20)
-
- const started = Date.now()
- const releaseFg = await coordinator.request('user-click', { priority: 'foreground', timeoutMs: 100 }).acquired
- assert.ok(Date.now() - started < 80, 'foreground must not wait behind the background queue')
- assert.equal(coordinator.activeCount, 3)
-
- for (const request of queued) {
- request.cancel()
- }
-
- releaseFg()
-
- for (const release of bgRunning) {
- release()
- }
-
- await Promise.all(
- queued.map(request =>
- request.acquired.then(
- () => undefined,
- () => undefined
- )
- )
- )
- assert.equal(coordinator.activeCount, 0)
- assert.equal(coordinator.queuedCount, 0)
-})
-
-test('drain prefers a foreground waiter over an earlier background waiter', async () => {
- const coordinator = new LocalBackendSpawnCoordinator(1)
- const releaseHolder = await coordinator.acquire('holder')
- const background = coordinator.request('background', { priority: 'background' })
- const foreground = coordinator.request('foreground', { priority: 'foreground' })
- await flush()
- assert.equal(coordinator.queuedCount, 2)
-
- let backgroundEntered = false
- let foregroundEntered = false
-
- const backgroundGrant = background.acquired.then(release => {
- backgroundEntered = true
-
- return release
- })
-
- const foregroundGrant = foreground.acquired.then(release => {
- foregroundEntered = true
-
- return release
- })
-
- releaseHolder()
- await flush()
- assert.equal(foregroundEntered, true)
- assert.equal(backgroundEntered, false)
- assert.equal(coordinator.activeCount, 1)
-
- const releaseForeground = await foregroundGrant
- releaseForeground()
- const releaseBackground = await backgroundGrant
- assert.equal(backgroundEntered, true)
- releaseBackground()
- assert.equal(coordinator.activeCount, 0)
-})
-
-test('background slot-wait timeout is distinguishable; foreground keeps a user-facing message', async () => {
- const coordinator = new LocalBackendSpawnCoordinator(1)
- const releaseFirst = await coordinator.acquire('first')
-
- const background = coordinator.request('bg', { priority: 'background', timeoutMs: 10 })
- await assert.rejects(background.acquired, error => {
- assert.ok(error instanceof LocalBackendSlotWaitTimeoutError)
- assert.equal(error.name, 'LocalBackendSlotWaitTimeoutError')
- assert.equal(error.priority, 'background')
- assert.equal(error.silent, true)
- assert.match(error.message, /timed out while waiting for a free slot/)
- assert.match(error.message, /\(background\)/)
-
- return true
- })
-
- const foreground = coordinator.request('fg', { priority: 'foreground', timeoutMs: 10 })
- await assert.rejects(foreground.acquired, error => {
- assert.ok(error instanceof Error)
- assert.match(error.message, /timed out while waiting for a free slot/)
- assert.doesNotMatch(error.message, /\(background\)/)
- assert.notEqual(error.name, 'LocalBackendSlotWaitTimeoutError')
-
- return true
- })
-
- releaseFirst()
- assert.equal(coordinator.activeCount, 0)
-})
-
-test('request() reports whether the caller actually waited behind the queue', async () => {
- const coordinator = new LocalBackendSpawnCoordinator(3)
- const bg1 = coordinator.request('bg-1', { priority: 'background' })
- const bg2 = coordinator.request('bg-2', { priority: 'background' })
- const bgWait = coordinator.request('bg-3', { priority: 'background' })
- assert.equal(bg1.queued, false)
- assert.equal(bg2.queued, false)
- assert.equal(bgWait.queued, true)
-
- // The reserved slot is free: a foreground request is granted immediately
- // even though a background waiter is queued.
- const fg = coordinator.request('fg', { priority: 'foreground' })
- assert.equal(fg.queued, false)
- assert.equal(coordinator.activeCount, 3)
-
- bgWait.cancel()
- await bgWait.acquired.catch(() => undefined)
- ;(await fg.acquired)()
- ;(await bg1.acquired)()
- ;(await bg2.acquired)()
- assert.equal(coordinator.activeCount, 0)
-})
-
-test('promoting a queued background waiter lets it take the reserved foreground slot', async () => {
- const coordinator = new LocalBackendSpawnCoordinator(3)
- const bg1 = await coordinator.request('bg-1', { priority: 'background' }).acquired
- const bg2 = await coordinator.request('bg-2', { priority: 'background' }).acquired
- const queued = coordinator.request('same-bot', { priority: 'background' })
- await flush()
- assert.equal(coordinator.activeCount, 2)
- assert.equal(coordinator.queuedCount, 1)
-
- assert.equal(queued.promote('foreground'), true)
- const releasePromoted = await queued.acquired
- assert.equal(coordinator.activeCount, 3)
- assert.equal(coordinator.queuedCount, 0)
-
- releasePromoted()
- bg1()
- bg2()
- assert.equal(coordinator.activeCount, 0)
-})
diff --git a/apps/desktop/electron/pool-spawn-coordinator.ts b/apps/desktop/electron/pool-spawn-coordinator.ts
deleted file mode 100644
index 5f80af332d3..00000000000
--- a/apps/desktop/electron/pool-spawn-coordinator.ts
+++ /dev/null
@@ -1,272 +0,0 @@
-export type ReleaseLocalBackendSlot = () => void
-
-export type LocalBackendSpawnPriority = 'foreground' | 'background'
-
-export type LocalBackendSpawnRequest = {
- acquired: Promise<ReleaseLocalBackendSlot>
- cancel: () => boolean
- promote: (priority: LocalBackendSpawnPriority) => boolean
- /** False when the slot was granted without waiting behind the queue. */
- queued: boolean
-}
-
-type Waiter = {
- key: string
- priority: LocalBackendSpawnPriority
- resolve: (release: ReleaseLocalBackendSlot) => void
- reject: (error: Error) => void
- timer: ReturnType<typeof setTimeout> | null
-}
-
-const SLOT_WAIT_TIMEOUT_MESSAGE = (key: string) =>
- `Local backend start for "${key}" timed out while waiting for a free slot.`
-
-/**
- * Slot-wait timeout. Background hydrations set `silent` so call sites can fail
- * quiet instead of toasting a user-visible backend-start failure.
- */
-export class LocalBackendSlotWaitTimeoutError extends Error {
- readonly priority: LocalBackendSpawnPriority
- readonly silent: boolean
-
- constructor(key: string, priority: LocalBackendSpawnPriority) {
- const suffix = priority === 'background' ? ' (background)' : ''
- super(`${SLOT_WAIT_TIMEOUT_MESSAGE(key)}${suffix}`)
- this.name = 'LocalBackendSlotWaitTimeoutError'
- this.priority = priority
- this.silent = priority === 'background'
- }
-}
-
-export function isBackgroundSlotWaitTimeout(error: unknown): boolean {
- return error instanceof LocalBackendSlotWaitTimeoutError && error.silent
-}
-
-export async function releaseLocalBackendSlotAfterExit(
- release: ReleaseLocalBackendSlot,
- waitForExit: () => Promise<void>
-): Promise<void> {
- await waitForExit()
- release()
-}
-
-/**
- * Bounds the number of local profile backends that are starting or running.
- *
- * A lease is acquired immediately before local start work and is held until
- * the child exits or the start fails. Remote descriptors never call request().
- *
- * When the cap is at least 2, one slot is reserved for foreground (user-open)
- * requests so background roster hydration cannot occupy the whole pool.
- * Untagged acquire() is foreground, so existing cap tests still fill `limit`.
- */
-export class LocalBackendSpawnCoordinator {
- #limit: number
- #activeForeground = 0
- #activeBackground = 0
- #queue: Waiter[] = []
-
- constructor(limit: number) {
- if (!Number.isInteger(limit) || limit < 1) {
- throw new RangeError('Local backend spawn limit must be a positive integer.')
- }
-
- this.#limit = limit
- }
-
- get activeCount(): number {
- return this.#activeForeground + this.#activeBackground
- }
-
- get limit(): number {
- return this.#limit
- }
-
- /**
- * Adopt a new cap at runtime (the pool size is a live device preference).
- * Raising it drains waiters into the newly freed slots immediately; lowering
- * it never revokes a granted slot — the running backends simply stay over
- * the cap until they exit, and LRU eviction (main.ts) converges the pool.
- */
- setLimit(limit: number): void {
- if (!Number.isInteger(limit) || limit < 1) {
- throw new RangeError('Local backend spawn limit must be a positive integer.')
- }
-
- this.#limit = limit
- this.#drain()
- }
-
- get queuedCount(): number {
- return this.#queue.length
- }
-
- request(
- key: string,
- options: { timeoutMs?: number; priority?: LocalBackendSpawnPriority } = {}
- ): LocalBackendSpawnRequest {
- if (options.timeoutMs !== undefined && (!Number.isFinite(options.timeoutMs) || options.timeoutMs < 1)) {
- throw new RangeError('Local backend spawn timeout must be a positive number.')
- }
-
- const priority: LocalBackendSpawnPriority = options.priority === 'background' ? 'background' : 'foreground'
-
- if (this.#queue.length === 0 && this.#canGrant(priority)) {
- return {
- acquired: Promise.resolve(this.#grant(priority)),
- cancel: () => false,
- promote: () => false,
- queued: false
- }
- }
-
- let waiter!: Waiter
-
- const acquired = new Promise<ReleaseLocalBackendSlot>((resolve, reject) => {
- waiter = { key, priority, resolve, reject, timer: null }
- this.#queue.push(waiter)
-
- if (options.timeoutMs !== undefined) {
- waiter.timer = setTimeout(() => {
- this.#rejectWaiter(waiter, this.#timeoutError(waiter))
- }, options.timeoutMs)
- waiter.timer.unref?.()
- }
- })
-
- this.#drain()
-
- return {
- acquired,
- cancel: () =>
- this.#rejectWaiter(waiter, new Error(`Local backend start for "${key}" was cancelled while queued.`)),
- promote: (nextPriority: LocalBackendSpawnPriority) => this.#promoteWaiter(waiter, nextPriority),
- queued: this.#queue.includes(waiter)
- }
- }
-
- acquire(key: string): Promise<ReleaseLocalBackendSlot> {
- return this.request(key).acquired
- }
-
- #timeoutError(waiter: Waiter): Error {
- if (waiter.priority === 'background') {
- return new LocalBackendSlotWaitTimeoutError(waiter.key, 'background')
- }
-
- return new Error(SLOT_WAIT_TIMEOUT_MESSAGE(waiter.key))
- }
-
- #backgroundLimit(): number {
- return this.#limit >= 2 ? this.#limit - 1 : this.#limit
- }
-
- #canGrant(priority: LocalBackendSpawnPriority): boolean {
- if (this.activeCount >= this.#limit) {
- return false
- }
-
- if (priority === 'background' && this.#activeBackground >= this.#backgroundLimit()) {
- return false
- }
-
- return true
- }
-
- #promoteWaiter(waiter: Waiter, priority: LocalBackendSpawnPriority): boolean {
- if (!this.#queue.includes(waiter)) {
- return false
- }
-
- if (waiter.priority === priority) {
- return false
- }
-
- waiter.priority = priority
- this.#drain()
-
- return true
- }
-
- #rejectWaiter(waiter: Waiter, error: Error): boolean {
- const index = this.#queue.indexOf(waiter)
-
- if (index === -1) {
- return false
- }
-
- this.#queue.splice(index, 1)
- this.#clearTimer(waiter)
- waiter.reject(error)
-
- return true
- }
-
- #clearTimer(waiter: Waiter): void {
- if (waiter.timer) {
- clearTimeout(waiter.timer)
- waiter.timer = null
- }
- }
-
- #grant(priority: LocalBackendSpawnPriority): ReleaseLocalBackendSlot {
- if (priority === 'background') {
- this.#activeBackground += 1
- } else {
- this.#activeForeground += 1
- }
-
- let released = false
-
- return () => {
- if (released) {
- return
- }
-
- released = true
-
- if (priority === 'background') {
- this.#activeBackground -= 1
- } else {
- this.#activeForeground -= 1
- }
-
- this.#drain()
- }
- }
-
- #takeWaiter(priority: LocalBackendSpawnPriority): Waiter | undefined {
- const index = this.#queue.findIndex(waiter => waiter.priority === priority)
-
- if (index === -1) {
- return undefined
- }
-
- return this.#queue.splice(index, 1)[0]
- }
-
- /** Hand free slots to queued waiters. Foreground waiters always go first. */
- #drain(): void {
- while (this.#canGrant('foreground')) {
- const next = this.#takeWaiter('foreground')
-
- if (!next) {
- break
- }
-
- this.#clearTimer(next)
- next.resolve(this.#grant('foreground'))
- }
-
- while (this.#canGrant('background')) {
- const next = this.#takeWaiter('background')
-
- if (!next) {
- break
- }
-
- this.#clearTimer(next)
- next.resolve(this.#grant('background'))
- }
- }
-}
diff --git a/apps/desktop/electron/pool-stop.test.ts b/apps/desktop/electron/pool-stop.test.ts
deleted file mode 100644
index 55d6c40c879..00000000000
--- a/apps/desktop/electron/pool-stop.test.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-import assert from 'node:assert/strict'
-
-import { test } from 'vitest'
-
-import { createPoolStopper, type PoolStopEntry } from './pool-stop'
-
-// Pins the orphaned-backend class from #62721: fire-and-forget pool stops
-// (SIGTERM + immediate entry delete) dropped the process handle before the
-// child exited, so a slow/stuck backend survived detached under PID 1.
-
-interface Child {
- exited: boolean
- killed: boolean
-}
-
-function harness() {
- const pool = new Map<string, PoolStopEntry>()
- const events: string[] = []
- const exitResolvers = new Map<Child, () => void>()
-
- const stopper = createPoolStopper({
- pool,
- stopChild: child => {
- ;(child as Child).killed = true
- events.push('stop')
- },
- waitForExit: child =>
- new Promise<void>(resolve => {
- exitResolvers.set(child as Child, () => {
- ;(child as Child).exited = true
- events.push('exit')
- resolve()
- })
- })
- })
-
- function addChild(key: string): Child {
- const child: Child = { exited: false, killed: false }
-
- pool.set(key, { process: child })
-
- return child
- }
-
- return { addChild, events, exitResolvers, pool, stopper }
-}
-
-test('evicts the entry immediately but retains the handle until bounded exit', async () => {
- const { addChild, exitResolvers, pool, stopper } = harness()
- const child = addChild('selena')
-
- const stop = stopper.stop('selena')
-
- // No router may hand out the dying backend...
- assert.equal(pool.has('selena'), false)
- // ...but the stop is not done and the in-flight handle is discoverable.
- assert.equal(child.killed, true)
- assert.equal(stopper.inFlight('selena'), stop)
-
- exitResolvers.get(child)?.()
- await stop
-
- assert.equal(child.exited, true)
- assert.equal(stopper.inFlight('selena'), undefined)
-})
-
-test('concurrent stop requests share one in-flight teardown', async () => {
- const { addChild, events, exitResolvers, stopper } = harness()
- const child = addChild('selena')
-
- const first = stopper.stop('selena')
- const second = stopper.stop('selena')
-
- assert.equal(first, second)
-
- exitResolvers.get(child)?.()
- await first
-
- // One SIGTERM, one exit — not one per caller.
- assert.deepEqual(events, ['stop', 'exit'])
-})
-
-test('stop of an unknown key resolves without signalling anything', async () => {
- const { events, stopper } = harness()
-
- await stopper.stop('ghost')
-
- assert.deepEqual(events, [])
- assert.equal(stopper.inFlight('ghost'), undefined)
-})
-
-test('stopAll stops every pooled backend and resolves after all exits', async () => {
- const { addChild, exitResolvers, pool, stopper } = harness()
- const a = addChild('a')
- const b = addChild('b')
-
- let settled = false
-
- const all = stopper.stopAll().then(() => {
- settled = true
- })
-
- assert.equal(pool.size, 0)
- assert.equal(a.killed, true)
- assert.equal(b.killed, true)
-
- exitResolvers.get(a)?.()
- await Promise.resolve()
- assert.equal(settled, false, 'must wait for EVERY child, not the first')
-
- exitResolvers.get(b)?.()
- await all
- assert.equal(settled, true)
-})
-
-test('a respawn can await the in-flight stop before reusing the key', async () => {
- const { addChild, exitResolvers, stopper } = harness()
- const child = addChild('selena')
- const order: string[] = []
-
- void stopper.stop('selena')
-
- const respawn = (async () => {
- const dying = stopper.inFlight('selena')
-
- if (dying) {
- await dying
- }
-
- order.push('spawn')
- })()
-
- order.push('exit-signal')
- exitResolvers.get(child)?.()
- await respawn
-
- assert.deepEqual(order, ['exit-signal', 'spawn'])
-})
diff --git a/apps/desktop/electron/pool-stop.ts b/apps/desktop/electron/pool-stop.ts
deleted file mode 100644
index 767a65e1748..00000000000
--- a/apps/desktop/electron/pool-stop.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-/**
- * pool-stop.ts
- *
- * Bounded, deduplicated teardown for pooled profile backends.
- *
- * Idle reaping, LRU eviction, profile deletion, and app quit can all ask to
- * stop the same pooled backend, and historically each caller SIGTERM'd the
- * child and immediately deleted the pool entry. A child that did not exit
- * promptly lost its only handle and survived detached under PID 1 — a live
- * installation accumulated 41 orphaned profile backends this way.
- *
- * createPoolStopper() gives every caller the same contract instead:
- * - the pool entry is evicted immediately (no router hands out a dying
- * backend), but the stop promise keeps the process handle until the
- * bounded SIGTERM -> SIGKILL escalation in waitForExit resolves;
- * - concurrent stop requests for one key share the single in-flight stop;
- * - spawn paths can await inFlight(key) so a fresh child never overlaps a
- * dying one on the same HERMES_HOME.
- *
- * Extracted into a dependency-free module (same pattern as backend-child.ts /
- * pool-eviction.ts) so the dedup and handle-retention semantics are asserted
- * directly instead of grepping main.ts source text.
- */
-
-export interface PoolStopEntry {
- process?: unknown
-}
-
-export interface PoolStopperDeps {
- /** The live backend pool. Entries are evicted synchronously on stop. */
- pool: Map<string, PoolStopEntry>
- /** Signal the child (tree/group kill per platform). Synchronous. */
- stopChild: (child: unknown) => void
- /** Bounded wait: resolves when the child exits, escalating to SIGKILL. */
- waitForExit: (child: unknown) => Promise<void>
-}
-
-export interface PoolStopper {
- /** The in-flight stop for a key, if any — await before respawning it. */
- inFlight: (key: string) => Promise<void> | undefined
- /** Stop one pooled backend; concurrent calls share the same promise. */
- stop: (key: string) => Promise<void>
- /** Stop every pooled backend currently in the pool. */
- stopAll: () => Promise<void>
-}
-
-export function createPoolStopper(deps: PoolStopperDeps): PoolStopper {
- const stops = new Map<string, Promise<void>>()
-
- function stop(key: string): Promise<void> {
- const inFlight = stops.get(key)
-
- if (inFlight) {
- return inFlight
- }
-
- const entry = deps.pool.get(key)
-
- if (!entry) {
- return Promise.resolve()
- }
-
- // Evict now: routing must not hand out a dying backend. The stop promise
- // below retains the process handle until the bounded exit completes.
- deps.pool.delete(key)
-
- const stopping = (async () => {
- deps.stopChild(entry.process)
- await deps.waitForExit(entry.process)
- })().finally(() => {
- stops.delete(key)
- })
-
- stops.set(key, stopping)
-
- return stopping
- }
-
- return {
- inFlight: key => stops.get(key),
- stop,
- stopAll: async () => {
- await Promise.all([...deps.pool.keys()].map(stop))
- }
- }
-}
diff --git a/apps/desktop/electron/pool-touch-scope.test.ts b/apps/desktop/electron/pool-touch-scope.test.ts
deleted file mode 100644
index f21b13071ce..00000000000
--- a/apps/desktop/electron/pool-touch-scope.test.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { describe, expect, it } from 'vitest'
-
-import { poolTouchKeys } from './pool-touch-scope'
-
-describe('poolTouchKeys', () => {
- it('falls back from an explicit local registry scope to its delegated bare profile', () => {
- expect(poolTouchKeys('conn:local::research')).toEqual(['conn:local::research', 'research'])
- })
-
- it('does not alias non-local registry scopes', () => {
- expect(poolTouchKeys('conn:homelab::research')).toEqual(['conn:homelab::research'])
- })
-})
diff --git a/apps/desktop/electron/pool-touch-scope.ts b/apps/desktop/electron/pool-touch-scope.ts
deleted file mode 100644
index 3a6f943e2c0..00000000000
--- a/apps/desktop/electron/pool-touch-scope.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-export function poolTouchKeys(scope: unknown): string[] {
- const key = String(scope ?? '').trim()
-
- if (!key) {
- return []
- }
-
- const localPrefix = 'conn:local::'
-
- if (key.startsWith(localPrefix)) {
- const delegatedProfile = key.slice(localPrefix.length)
-
- if (delegatedProfile) {
- return [key, delegatedProfile]
- }
- }
-
- return [key]
-}
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index a4614c6f9ef..3e43012d3b9 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -18,14 +18,11 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
// Launch-flag fact: the app was started with --local, so the renderer may
// show the local-models surfaces. Static for the window's lifetime.
localModelsEnabled: launchFlags?.localModels === true,
- getConnection: (profile, opts) => ipcRenderer.invoke('hermes:connection', profile, opts),
+ getConnection: profile => ipcRenderer.invoke('hermes:connection', profile),
// Registry-scoped backend resolution: { connectionId, profile } → descriptor.
getConnectionFor: payload => ipcRenderer.invoke('hermes:connection:for', payload),
getProfileRoutes: profiles => ipcRenderer.invoke('hermes:plugin-profile-routes', profiles),
revalidateConnection: () => ipcRenderer.invoke('hermes:connection:revalidate'),
- touchBackend: profile => ipcRenderer.invoke('hermes:backend:touch', profile),
- getPoolLimits: () => ipcRenderer.invoke('hermes:pool-limits:get'),
- setPoolLimits: limits => ipcRenderer.invoke('hermes:pool-limits:set', limits),
getGatewayWsUrl: profile => ipcRenderer.invoke('hermes:gateway:ws-url', profile),
// Registry-scoped fresh WS URL: { connectionId, profile } → result shape of
// getGatewayWsUrl, minted against that connection's backend.
diff --git a/apps/desktop/electron/remote-liveness.ts b/apps/desktop/electron/remote-liveness.ts
index 91ad9959595..5d6dac505e7 100644
--- a/apps/desktop/electron/remote-liveness.ts
+++ b/apps/desktop/electron/remote-liveness.ts
@@ -189,10 +189,9 @@ export interface RevalidatePooledRemoteBackendsOptions<TConnection extends Remot
/**
* Probe pooled REMOTE descriptors and drop the dead ones.
*
- * A pooled entry backed by a remote host has no child process, so the 'exit'
- * handler that clears a dead local backend never fires, and the renderer's
- * keepalive touch keeps the idle reaper off it. Without this the pool serves a
- * descriptor for an unreachable host indefinitely.
+ * A pooled entry is a cached descriptor with no child process, so nothing
+ * signals its host's death. Without this the pool serves a descriptor for an
+ * unreachable host indefinitely.
*
* Entries share the primary's failure policy, keyed per base URL, so a profile
* pointing at the same host as another does not burn the streak twice as fast.
@@ -256,7 +255,7 @@ export interface RevalidateSuspectPooledRemoteBackendsOptions<TConnection extend
*
* After a sleep/wake or network restore every pooled SSH tunnel is suspect:
* the SSH master died with the network, but the local forward's descriptor is
- * still cached and the renderer keepalive keeps the idle reaper off it. Unlike
+ * still cached. Unlike
* the background policy in revalidatePooledRemoteBackends — which tolerates a
* failure streak because transient blips are common in steady state — a
* suspect descriptor that fails ONE bounded probe after resume is dead: retire
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 4f6d214ca1b..9ceaffeffcb 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
@@ -239,7 +239,6 @@ function fakeDesktop() {
}),
revalidateConnection: vi.fn(async () => ({ ok: true, rebuilt: false })),
onWindowStateChanged: vi.fn(() => () => undefined),
- touchBackend: vi.fn(async () => undefined),
profile: { get: vi.fn(async () => ({ profile: 'default' })) }
}
}
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 5f3096316d3..e7eca39ad92 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -35,8 +35,7 @@ import {
reconnectSecondaryGateways,
reportPrimaryGatewayState,
setPrimaryGateway,
- setPrimaryGatewayConnection,
- touchSecondaryGateways
+ setPrimaryGatewayConnection
} from '@/store/gateway'
import { registerGatewayReconnect } from '@/store/gateway-reconnect'
import {
@@ -48,12 +47,10 @@ import {
} from '@/store/gateway-switch'
import { checkLocalRuntimeUpdate, watchLocalRuntimeJobs } from '@/store/local-runtime-jobs'
import { notify, notifyError } from '@/store/notifications'
-import { loadPoolLimits } from '@/store/pool-limits'
import {
$activeGatewayProfile,
normalizeProfileKey,
- refreshActiveProfile,
- touchActiveGatewayBackend
+ refreshActiveProfile
} from '@/store/profile'
import {
$activeSessionId,
@@ -773,7 +770,7 @@ export function useGatewayBoot({
onActiveConnectionChanged: publish,
// Keep $activeGatewayProfile in lockstep with the registry's OWN record
// of which profile the active socket serves. The registry is the only
- // party that sees eviction fallbacks (idle reap, connection removal,
+ // party that sees eviction fallbacks (connection removal,
// profile delete → primary); before this mirror those fallbacks moved
// the SOCKET back to the primary while the profile atom kept naming the
// evicted bot. ensureGatewayProfile's "already active" fast path then
@@ -795,7 +792,7 @@ export function useGatewayBoot({
onActiveConnectionInvalidated: (fallbackProfile, invalidationEpoch) => {
$activeGatewayProfile.set(fallbackProfile)
// Bounded like every other getConnection() call in this file (#93454):
- // an eviction fallback (idle reap, connection removal, profile delete)
+ // an eviction fallback (connection removal, profile delete)
// must not latch the profile atom to a connection that never resolves
// if the main-process IPC round-trip wedges.
void withTimeout(
@@ -938,22 +935,11 @@ export function useGatewayBoot({
// this a socket dropped during sleep sits closed until the user clicks.
window.addEventListener('focus', onFocus)
- // Pool limits are main-process state; mirror them once for the Settings
- // rows and prewarmProfileBackend's saturation guard.
- void loadPoolLimits()
-
- // Keep live pool backends alive while this window is open (the main process
- // can't observe the direct renderer↔backend WS). No-op for the primary.
- const keepaliveTimer = setInterval(() => {
- touchActiveGatewayBackend()
- touchSecondaryGateways()
- }, 60_000)
-
// Bound concurrency cost to consumers: keep a background socket while its
// profile has a running (working) or blocked (needs-input) session, OR an
// open owner-routed tile (Bot chats stay on a secondary while chrome stays
// on the launch profile). Once the last consumer leaves, the socket drops
- // and its backend is free to idle-reap. The active profile is always spared.
+ // (the gateway behind it keeps running). The active profile is always spared.
// Do not key this off `entry.retained` — that flag only skips dispose-after-
// RPC; idle prune is what reclaims hover-warmed sockets after you leave.
const recomputeKeptGateways = () => {
@@ -1189,7 +1175,6 @@ export function useGatewayBoot({
clearReconnectTimer()
clearBootRetryTimer()
clearLivenessReprobeTimer()
- clearInterval(keepaliveTimer)
offWorking()
offAttention()
offActiveSession()
diff --git a/apps/desktop/src/app/session/hooks/branch-owner-routing.integration.test.ts b/apps/desktop/src/app/session/hooks/branch-owner-routing.integration.test.ts
index d4a8f0fb8ad..a7755ec313d 100644
--- a/apps/desktop/src/app/session/hooks/branch-owner-routing.integration.test.ts
+++ b/apps/desktop/src/app/session/hooks/branch-owner-routing.integration.test.ts
@@ -87,8 +87,7 @@ describe('branch owner routing (real router, faked transport)', () => {
return { connectionId, mode: 'remote', profile }
},
getGatewayWsUrlFor: async ({ connectionId, profile }: { connectionId: string; profile: string }) =>
- `ws://${connectionId}/gateway?profile=${profile}`,
- touchBackend: async () => undefined
+ `ws://${connectionId}/gateway?profile=${profile}`
}
})
diff --git a/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx b/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx
index f72609bebfd..2fadf9fd314 100644
--- a/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx
+++ b/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx
@@ -221,8 +221,7 @@ function installDesktop(): void {
: 9999
return { port, profile, token: `${connectionId}-${profile}-token`, wsUrl: `ws://127.0.0.1:${port}/ws` }
- }),
- touchBackend: vi.fn(async () => undefined)
+ })
}
}
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index ac8c5bdac64..4e2741b3c3d 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
@@ -1009,11 +1009,9 @@ export function useSessionActions({
// dial the owning backend without moving $activeGatewayProfile.
if ($showAllProfiles.get()) {
if (resolvedConnectionId) {
- await openGatewayForAgent(resolvedConnectionId, ownerRoute?.profile || sessionProfile || 'default', {
- spawnPriority: 'foreground'
- })
+ await openGatewayForAgent(resolvedConnectionId, ownerRoute?.profile || sessionProfile || 'default')
} else if (sessionProfile) {
- await openGatewayForProfile(normalizeProfileKey(sessionProfile), { spawnPriority: 'foreground' })
+ await openGatewayForProfile(normalizeProfileKey(sessionProfile))
}
} else if (resolvedConnectionId) {
await ensureGatewayAgent(resolvedConnectionId, ownerRoute?.profile || sessionProfile || 'default')
diff --git a/apps/desktop/src/app/settings/config-settings.tsx b/apps/desktop/src/app/settings/config-settings.tsx
index 73cb0d205b2..40a30662da9 100644
--- a/apps/desktop/src/app/settings/config-settings.tsx
+++ b/apps/desktop/src/app/settings/config-settings.tsx
@@ -45,7 +45,6 @@ import {
import { MemoryConnect } from './memory/connect'
import { ProviderConfigPanel } from './memory/provider-config-panel'
import { ModelSettings, ModelSettingsSkeleton } from './model-settings'
-import { PoolLimitsSetting } from './pool-limits-setting'
import { EmptyState, ListRow, SettingsContent, SettingsSkeleton, ToggleRow } from './primitives'
import { SettingsProfileScope } from './profile-scope'
import { QuickEntrySettings } from './quick-entry-settings'
@@ -406,7 +405,6 @@ function ConfigSettingsInner({
label={c.disableF12Title}
onChange={setDisableF12}
/>
- <PoolLimitsSetting />
<QuickEntrySettings />
</>
)}
diff --git a/apps/desktop/src/app/settings/pool-limits-setting.tsx b/apps/desktop/src/app/settings/pool-limits-setting.tsx
deleted file mode 100644
index 4db5ee8824d..00000000000
--- a/apps/desktop/src/app/settings/pool-limits-setting.tsx
+++ /dev/null
@@ -1,113 +0,0 @@
-import { useStore } from '@nanostores/react'
-import { useEffect, useState } from 'react'
-
-import { ListRow } from '@/app/settings/primitives'
-import { Input } from '@/components/ui/input'
-import { $poolLimits, loadPoolLimits, savePoolLimits } from '@/store/pool-limits'
-
-// Bounds imported from main's clamp module so the advertised input ranges
-// can never drift from what the pool actually enforces (review note on #92581).
-import { POOL_LIMITS_BOUNDS } from '../../../electron/pool-limits'
-
-const MAX_BACKENDS_MAX = POOL_LIMITS_BOUNDS.maxBackendsMax
-const IDLE_MS_MAX = POOL_LIMITS_BOUNDS.idleMsMax
-
-/** Settings → Advanced: warm-bot-backends count + backend idle timeout.
- * Device-local (not profile-scoped): the pool is sized once per machine and
- * changes apply live — main evicts/reaps to converge without a restart. */
-export function PoolLimitsSetting() {
- const limits = useStore($poolLimits)
- const [maxDraft, setMaxDraft] = useState(String(limits.maxBackends))
- const [idleDraft, setIdleDraft] = useState(String(limits.idleMs))
-
- useEffect(() => {
- void loadPoolLimits()
- }, [])
-
- useEffect(() => {
- setMaxDraft(String(limits.maxBackends))
- setIdleDraft(String(limits.idleMs))
- }, [limits])
-
- const commitMax = () => {
- const parsed = Number(maxDraft)
-
- if (!Number.isFinite(parsed) || parsed === limits.maxBackends) {
- setMaxDraft(String(limits.maxBackends))
-
- return
- }
-
- void savePoolLimits({ maxBackends: parsed })
- .then(() => undefined)
- .catch(() => setMaxDraft(String($poolLimits.get().maxBackends)))
- }
-
- const commitIdle = () => {
- const parsed = Number(idleDraft)
-
- if (!Number.isFinite(parsed) || parsed === limits.idleMs) {
- setIdleDraft(String(limits.idleMs))
-
- return
- }
-
- void savePoolLimits({ idleMs: parsed })
- .then(() => undefined)
- .catch(() => setIdleDraft(String($poolLimits.get().idleMs)))
- }
-
- return (
- <>
- <ListRow
- action={
- <div className="flex items-center gap-2">
- <Input
- aria-label="Warm bot backends"
- className="w-20"
- inputMode="numeric"
- max={MAX_BACKENDS_MAX}
- min={1}
- onBlur={commitMax}
- onChange={event => setMaxDraft(event.target.value)}
- onKeyDown={event => {
- if (event.key === 'Enter') {
- event.currentTarget.blur()
- }
- }}
- type="number"
- value={maxDraft}
- />
- </div>
- }
- description="How many bot backends stay running for instant switching. Higher = faster switches, more memory (~60MB per backend). Applies immediately."
- title="Warm Bot Backends"
- />
- <ListRow
- action={
- <div className="flex items-center gap-2">
- <Input
- aria-label="Backend idle timeout in milliseconds"
- className="w-28"
- inputMode="numeric"
- max={IDLE_MS_MAX}
- min={60_000}
- onBlur={commitIdle}
- onChange={event => setIdleDraft(event.target.value)}
- onKeyDown={event => {
- if (event.key === 'Enter') {
- event.currentTarget.blur()
- }
- }}
- type="number"
- value={idleDraft}
- />
- <span className="text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">ms</span>
- </div>
- }
- description="How long an unused bot backend stays warm before it is shut down. Raise this so bots you revisit every few minutes never pay a cold start."
- title="Backend Idle Timeout"
- />
- </>
- )
-}
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index 68a2ea86bd0..596b09cf060 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -1,8 +1,6 @@
import type { GatewayWsUrlResult } from '@hermes/shared'
import type { TranslucencyState } from '@hermes/shared/translucency'
-import type { PoolLimits } from '../electron/pool-limits'
-
import type { WakeIndicatorState } from './lib/wake-indicator'
import type {
PetOverlayBounds,
@@ -18,18 +16,14 @@ declare global {
interface Window {
hermesDesktop: {
// Resolve a backend connection. Omit `profile` (or pass the primary) for
- // the window's backend; pass a named profile to lazily spawn/reuse that
- // profile's backend from the pool.
- getConnection: (
- profile?: string | null,
- opts?: { priority?: 'foreground' | 'background' }
- ) => Promise<HermesConnection>
+ // the window's backend; pass a named profile to dial/reuse that profile's
+ // cached gateway descriptor.
+ getConnection: (profile?: string | null) => Promise<HermesConnection>
// Registry-scoped backend resolution: dial (connectionId, profile). An
// empty/local connectionId delegates to the legacy getConnection path.
getConnectionFor?: (payload: {
connectionId?: null | string
profile?: null | string
- priority?: 'foreground' | 'background'
}) => Promise<HermesConnection>
// Registry-scoped fresh WS URL (same result contract as getGatewayWsUrl).
getGatewayWsUrlFor?: (payload: {
@@ -49,17 +43,6 @@ declare global {
// self-heal via the child 'exit' handler). `rebuilt` is true when a stale
// remote cache was dropped.
revalidateConnection: () => Promise<{ ok: boolean; rebuilt: boolean }>
- // Keepalive: mark a pool profile backend as recently used so the idle
- // reaper spares it while its chat is active.
- touchBackend: (profile?: string | null) => Promise<{ ok: boolean }>
- // Pool sizing (Settings → Advanced): device-local, live-applied by the
- // main process. get resolves the limits currently in force; set applies
- // (and persists) new ones, evicting/reaping to converge immediately.
- getPoolLimits: () => Promise<PoolLimits>
- setPoolLimits: (limits: { maxBackends?: number; idleMs?: number }) => Promise<{
- ok: boolean
- limits: PoolLimits
- }>
getGatewayWsUrl: (profile?: null | string) => Promise<GatewayWsUrlResult>
// Open (or focus) a standalone OS window for a single chat session so
// the user can work with multiple chats side by side. Returns ok:false
diff --git a/apps/desktop/src/plugin-socket-scope.test.ts b/apps/desktop/src/plugin-socket-scope.test.ts
index c793ca6a175..e78eef2cd7c 100644
--- a/apps/desktop/src/plugin-socket-scope.test.ts
+++ b/apps/desktop/src/plugin-socket-scope.test.ts
@@ -63,8 +63,7 @@ beforeEach(() => {
getConnection,
getConnectionFor,
getGatewayWsUrl: vi.fn(async () => 'wss://pool.invalid/api/ws?ticket=fake'),
- getGatewayWsUrlFor: vi.fn(async () => 'wss://homelab.invalid/api/ws?ticket=fake'),
- touchBackend: vi.fn(async () => ({ ok: true }))
+ getGatewayWsUrlFor: vi.fn(async () => 'wss://homelab.invalid/api/ws?ticket=fake')
}
})
configureGatewayRegistry({ onEvent: vi.fn() })
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts
index f01cf6f1578..fe7f250d52e 100644
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@ -937,14 +937,11 @@ export const host = {
// not the registry-secondary path openGatewayForAgent takes for a 'local'
// connection id. Behavior for a plain local open is unchanged.
const dial = explicitRoute
- ? () =>
- openGatewayForAgent(explicitRoute.connectionId, explicitRoute.profile, {
- spawnPriority: 'foreground'
- })
+ ? () => openGatewayForAgent(explicitRoute.connectionId, explicitRoute.profile)
: plan.switchWorkspace
? () => ensureGatewayProfile(plan.switchWorkspace as string)
: plan.dialWithoutSwitching
- ? () => openGatewayForProfile(plan.dialWithoutSwitching as string, { spawnPriority: 'foreground' })
+ ? () => openGatewayForProfile(plan.dialWithoutSwitching as string)
: null
if (dial) {
diff --git a/apps/desktop/src/sdk/profile-routing.test.ts b/apps/desktop/src/sdk/profile-routing.test.ts
index ae9d54ec100..1cb1bb833dd 100644
--- a/apps/desktop/src/sdk/profile-routing.test.ts
+++ b/apps/desktop/src/sdk/profile-routing.test.ts
@@ -612,11 +612,7 @@ describe('profile-aware plugin session opens', () => {
await host.openSession('remote-chat', { route })
- expect(openGatewayForAgent).toHaveBeenCalledWith(
- 'source-a',
- 'default',
- expect.objectContaining({ spawnPriority: 'foreground' })
- )
+ expect(openGatewayForAgent).toHaveBeenCalledWith('source-a', 'default')
expect(ensureGatewayProfile).not.toHaveBeenCalled()
expect(setShowAllProfiles).toHaveBeenCalledWith(true)
expect($activeGatewayProfile.get()).toBe('remote-worker')
@@ -1167,10 +1163,7 @@ describe('profile-aware plugin session opens', () => {
})
expect(ensureGatewayProfile).not.toHaveBeenCalled()
- expect(openGatewayForProfile).toHaveBeenCalledWith(
- 'worker',
- expect.objectContaining({ spawnPriority: 'foreground' })
- )
+ expect(openGatewayForProfile).toHaveBeenCalledWith('worker')
expect(setShowAllProfiles).toHaveBeenCalledWith(true)
expect($activeGatewayProfile.get()).toBe('default')
})
@@ -1181,10 +1174,7 @@ describe('profile-aware plugin session opens', () => {
await host.openSession('bot-chat', { profile: 'worker' })
expect(ensureGatewayProfile).not.toHaveBeenCalled()
- expect(openGatewayForProfile).toHaveBeenCalledWith(
- 'worker',
- expect.objectContaining({ spawnPriority: 'foreground' })
- )
+ expect(openGatewayForProfile).toHaveBeenCalledWith('worker')
expect(setShowAllProfiles).toHaveBeenCalledWith(true)
expect($activeGatewayProfile.get()).toBe('default')
})
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..f9e0f3ec1db 100644
--- a/apps/desktop/src/store/gateway-activation-prune-lease.test.ts
+++ b/apps/desktop/src/store/gateway-activation-prune-lease.test.ts
@@ -66,8 +66,7 @@ function installDesktop(): void {
profile,
token: 'registry-token'
})),
- getGatewayWsUrlFor: vi.fn(async () => 'ws://127.0.0.1:6161/ws'),
- touchBackend: vi.fn(async () => undefined)
+ getGatewayWsUrlFor: vi.fn(async () => 'ws://127.0.0.1:6161/ws')
}
}
diff --git a/apps/desktop/src/store/gateway-connection-scope.test.ts b/apps/desktop/src/store/gateway-connection-scope.test.ts
index 5fb959a00b8..5afb4d71e17 100644
--- a/apps/desktop/src/store/gateway-connection-scope.test.ts
+++ b/apps/desktop/src/store/gateway-connection-scope.test.ts
@@ -72,8 +72,7 @@ function installDesktop(): void {
getGatewayWsUrlFor: vi.fn(
async ({ connectionId, profile }: { connectionId: string; profile: string }) =>
`wss://${connectionId}.invalid/api/ws?profile=${profile}`
- ),
- touchBackend: vi.fn(async () => undefined)
+ )
}
}
diff --git a/apps/desktop/src/store/gateway-foreground-retention.test.ts b/apps/desktop/src/store/gateway-foreground-retention.test.ts
index baf801bdf2c..30b5d9ef8d1 100644
--- a/apps/desktop/src/store/gateway-foreground-retention.test.ts
+++ b/apps/desktop/src/store/gateway-foreground-retention.test.ts
@@ -64,8 +64,7 @@ function installDesktop(): void {
getGatewayWsUrlFor: vi.fn(
async ({ connectionId, profile }: { connectionId: string; profile: string }) =>
`wss://${connectionId}.invalid/api/ws?profile=${profile}`
- ),
- touchBackend: vi.fn(async () => undefined)
+ )
}
}
diff --git a/apps/desktop/src/store/gateway-profile-request.test.ts b/apps/desktop/src/store/gateway-profile-request.test.ts
index b16cb95d293..33199317def 100644
--- a/apps/desktop/src/store/gateway-profile-request.test.ts
+++ b/apps/desktop/src/store/gateway-profile-request.test.ts
@@ -64,8 +64,7 @@ const {
function installDesktop(getConnection: ReturnType<typeof vi.fn>): void {
;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {
- getConnection,
- touchBackend: vi.fn(async () => undefined)
+ getConnection
}
}
@@ -208,8 +207,7 @@ describe('requestGatewayForAgent', () => {
;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {
getConnection: vi.fn(),
getConnectionFor,
- getGatewayWsUrlFor: vi.fn(async () => ({ ok: true as const, wsUrl: 'wss://remote.invalid/api/ws' })),
- touchBackend: vi.fn(async () => undefined)
+ getGatewayWsUrlFor: vi.fn(async () => ({ ok: true as const, wsUrl: 'wss://remote.invalid/api/ws' }))
}
await ensureGatewayForProfile('default')
@@ -246,8 +244,7 @@ describe('requestGatewayForAgent', () => {
;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {
getConnection: vi.fn(),
getConnectionFor,
- getGatewayWsUrlFor: vi.fn(async () => ({ ok: true as const, wsUrl: 'wss://remote.invalid/api/ws' })),
- touchBackend: vi.fn(async () => undefined)
+ getGatewayWsUrlFor: vi.fn(async () => ({ ok: true as const, wsUrl: 'wss://remote.invalid/api/ws' }))
}
await requestGatewayForAgent('remote-primary', 'research', 'session.resume', {
@@ -279,8 +276,7 @@ describe('requestGatewayForAgent', () => {
;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {
getConnection,
getConnectionFor,
- getGatewayWsUrlFor,
- touchBackend: vi.fn(async () => undefined)
+ getGatewayWsUrlFor
}
await ensureGatewayForProfile('default')
@@ -325,8 +321,7 @@ describe('requestGatewayForAgent', () => {
getGatewayWsUrlFor: vi.fn(async ({ connectionId, profile }) => ({
ok: true as const,
wsUrl: `ws://${connectionId}/${profile}`
- })),
- touchBackend: vi.fn(async () => undefined)
+ }))
}
await ensureGatewayForProfile('default')
@@ -353,8 +348,7 @@ describe('requestGatewayForAgent', () => {
getGatewayWsUrlFor: vi.fn(async ({ connectionId, profile }) => ({
ok: true as const,
wsUrl: `ws://${connectionId}/${profile}`
- })),
- touchBackend: vi.fn(async () => undefined)
+ }))
}
await openGatewayForAgent('source-a', 'research')
@@ -382,8 +376,7 @@ describe('requestGatewayForAgent', () => {
getGatewayWsUrlFor: vi.fn(async ({ connectionId, profile }) => ({
ok: true as const,
wsUrl: `ws://${connectionId}/${profile}`
- })),
- touchBackend: vi.fn(async () => undefined)
+ }))
}
await ensureGatewayForAgent('source-a', 'pinned')
@@ -419,8 +412,7 @@ describe('requestGatewayForAgent', () => {
getGatewayWsUrlFor: vi.fn(async ({ connectionId, profile }) => ({
ok: true as const,
wsUrl: `ws://${connectionId}/${profile}`
- })),
- touchBackend: vi.fn(async () => undefined)
+ }))
}
await ensureGatewayForProfile('default')
@@ -453,8 +445,7 @@ describe('requestGatewayForAgent', () => {
getGatewayWsUrlFor: vi.fn(async ({ connectionId, profile }) => ({
ok: true as const,
wsUrl: `ws://${connectionId}/${profile}`
- })),
- touchBackend: vi.fn(async () => undefined)
+ }))
}
await ensureGatewayForProfile('default')
@@ -482,8 +473,7 @@ describe('retainGatewayForAgent (#93602)', () => {
getGatewayWsUrlFor: vi.fn(async ({ connectionId, profile }) => ({
ok: true as const,
wsUrl: `ws://${connectionId}/${profile}`
- })),
- touchBackend: vi.fn(async () => undefined)
+ }))
}
}
@@ -578,8 +568,7 @@ describe('attached shared-remote group turns (#96493)', () => {
getGatewayWsUrlFor: vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({
ok: true as const,
wsUrl: `ws://${connectionId}/${profile}`
- })),
- touchBackend: vi.fn(async () => undefined)
+ }))
}
}
@@ -625,8 +614,7 @@ describe('attached shared-remote group turns (#96493)', () => {
getGatewayWsUrlFor: vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({
ok: true as const,
wsUrl: `ws://${connectionId}/${profile}`
- })),
- touchBackend: vi.fn(async () => undefined)
+ }))
}
await ensureGatewayForProfile('default')
@@ -645,8 +633,7 @@ describe('attached shared-remote group turns (#96493)', () => {
getConnectionFor: vi.fn(async () => {
throw new Error('Timed out connecting to profile "voter"')
}),
- getGatewayWsUrlFor: vi.fn(async () => ({ ok: true as const, wsUrl: 'ws://homelab/voter' })),
- touchBackend: vi.fn(async () => undefined)
+ getGatewayWsUrlFor: vi.fn(async () => ({ ok: true as const, wsUrl: 'ws://homelab/voter' }))
}
await ensureGatewayForProfile('default')
diff --git a/apps/desktop/src/store/gateway-spawn-priority.test.ts b/apps/desktop/src/store/gateway-spawn-priority.test.ts
deleted file mode 100644
index 58ea0a5eb28..00000000000
--- a/apps/desktop/src/store/gateway-spawn-priority.test.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-
-// #102281: a user-initiated open must reach Electron main as a FOREGROUND dial
-// on its FIRST IPC, not only on the secondary's connect. Every open first
-// probes the route (sharedPrimaryRoute / isAttachedSharedRemote) with
-// getConnection / getConnectionFor; if that probe is untagged, main starts the
-// spawn as a background slot wait and the click waits out the probe's 20s
-// timeout before anything promotes it.
-
-vi.mock('@/hermes', () => ({
- setApiRequestConnection: vi.fn(),
- HermesGateway: class {
- connectionState = 'closed'
- connect = async (): Promise<void> => {
- this.connectionState = 'open'
- }
- close = (): void => {
- this.connectionState = 'closed'
- }
- onEvent = vi.fn(() => () => {})
- onState = vi.fn(() => () => {})
- }
-}))
-vi.mock('@/store/session', () => ({ setConnection: vi.fn(), setGatewayState: vi.fn() }))
-vi.mock('@/store/notify-baseline', () => ({ markNativeNotifyBaseline: vi.fn() }))
-
-const {
- closeSecondaryGateways,
- configureGatewayRegistry,
- ensureGatewayForAgent,
- ensureGatewayForProfile,
- openGatewayForAgent,
- openGatewayForProfile,
- setPrimaryGateway
-} = await import('./gateway')
-
-const conn = {
- 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(): { getConnection: ReturnType<typeof vi.fn>; getConnectionFor: ReturnType<typeof vi.fn> } {
- const stub = {
- getConnection: vi.fn(async () => conn),
- getConnectionFor: vi.fn(async () => conn)
- }
-
- ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = stub
-
- return stub
-}
-
-function priorities(mock: ReturnType<typeof vi.fn>, pick: (args: unknown[]) => unknown): unknown[] {
- return mock.mock.calls.map(args => pick(args))
-}
-
-beforeEach(() => {
- configureGatewayRegistry({ onEvent: vi.fn() })
- setPrimaryGateway({ connectionState: 'open' } as never, 'default')
-})
-
-afterEach(() => {
- closeSecondaryGateways()
- vi.clearAllMocks()
- delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
-})
-
-describe('user opens dial main as foreground from the first IPC (#102281)', () => {
- it('ensureGatewayForProfile tags the route probe AND the connect dial', async () => {
- const desktop = installDesktop()
-
- await ensureGatewayForProfile('research')
-
- const seen = priorities(desktop.getConnection, args => (args[1] as { priority?: string } | undefined)?.priority)
- expect(seen.length).toBeGreaterThanOrEqual(2)
- expect(seen.every(priority => priority === 'foreground')).toBe(true)
- })
-
- it('openGatewayForProfile without a priority never tags a dial as foreground', async () => {
- const desktop = installDesktop()
-
- await openGatewayForProfile('research')
-
- const seen = priorities(desktop.getConnection, args => (args[1] as { priority?: string } | undefined)?.priority)
- expect(seen.length).toBeGreaterThanOrEqual(1)
- expect(seen.every(priority => priority === undefined)).toBe(true)
- })
-
- it('openGatewayForAgent forwards spawnPriority to every registry dial', async () => {
- const desktop = installDesktop()
-
- await openGatewayForAgent('homelab', 'research', { spawnPriority: 'foreground' })
-
- const seen = priorities(desktop.getConnectionFor, args => (args[0] as { priority?: string }).priority)
- expect(seen.length).toBeGreaterThanOrEqual(1)
- expect(seen.every(priority => priority === 'foreground')).toBe(true)
- })
-
- it('ensureGatewayForAgent is always a foreground open', async () => {
- const desktop = installDesktop()
-
- await ensureGatewayForAgent('homelab', 'research')
-
- const seen = priorities(desktop.getConnectionFor, args => (args[0] as { priority?: string }).priority)
- expect(seen.length).toBeGreaterThanOrEqual(1)
- expect(seen.every(priority => priority === 'foreground')).toBe(true)
- })
-})
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index 89fbf3b2cff..b824d3a74ae 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -21,26 +21,6 @@ import { stampSecondaryProfileOwner } from '@/store/session-event-provenance'
const normKey = (profile: string | null | undefined): string => (profile ?? '').trim() || 'default'
-// Spawn-slot priority handed to Electron main with every backend dial. A
-// user-initiated open is 'foreground' and may take the pool's reserved slot;
-// roster hydration, hover prewarm and untagged dials are 'background' — main's
-// default, so background dials keep the pre-priority IPC payload shape.
-type SpawnPriority = 'foreground' | 'background'
-
-function dialPriority(spawnPriority: SpawnPriority): { priority: 'foreground' } | Record<never, never> {
- return spawnPriority === 'foreground' ? { priority: 'foreground' } : {}
-}
-
-function dialProfile(
- desktop: NonNullable<typeof window.hermesDesktop>,
- profile: string,
- spawnPriority: SpawnPriority
-): Promise<HermesConnection> {
- return spawnPriority === 'foreground'
- ? desktop.getConnection(profile, { priority: 'foreground' })
- : desktop.getConnection(profile)
-}
-
// Read connection state through a call so TS control-flow analysis doesn't
// narrow the getter to a constant across guards (it genuinely changes).
const isOpen = (gateway: HermesGateway | null): boolean => gateway?.connectionState === 'open'
@@ -56,7 +36,7 @@ interface RegistryConfig {
/**
* Fires whenever applyActive() moves the active route to a (possibly
* different) profile — including registry-internal eviction fallbacks
- * (idle reap, connection removal, profile delete) that no renderer call
+ * (connection removal, profile delete) that no renderer call
* initiated. Consumers mirror this into $activeGatewayProfile so the
* published profile can never diverge from the socket actually selected
* (#89206: the stale-profile split-brain that stranded bot wake-ups).
@@ -327,11 +307,7 @@ function isPrimaryRegistryRoute(connectionId: null | string, profile: string): b
* dials a second WebSocket at the same Tailscale URL, which accept/closes in
* ~30ms (`messages=1`) and never runs `session.create` (#96493). Isolated
* SSH/pooled backends (`sharedRemote: false`) still get their own secondary. */
-async function isAttachedSharedRemote(
- connectionId: null | string,
- profile: string,
- spawnPriority: SpawnPriority = 'background'
-): Promise<boolean> {
+async function isAttachedSharedRemote(connectionId: null | string, profile: string): Promise<boolean> {
const id = String(connectionId ?? '').trim()
const key = normKey(profile)
@@ -351,7 +327,7 @@ async function isAttachedSharedRemote(
try {
const conn = await withTimeout(
- desktop.getConnectionFor({ connectionId: id, profile: key, ...dialPriority(spawnPriority) }),
+ desktop.getConnectionFor({ connectionId: id, profile: key }),
RECONNECT_ATTEMPT_TIMEOUT_MS,
`Timed out resolving shared-remote route for "${key}"`
)
@@ -518,7 +494,7 @@ function clearTimer(entry: Secondary): void {
}
}
-async function openSecondary(entry: Secondary, spawnPriority: SpawnPriority = 'background'): Promise<void> {
+async function openSecondary(entry: Secondary): Promise<void> {
const desktop = window.hermesDesktop
if (!desktop) {
@@ -526,20 +502,6 @@ async function openSecondary(entry: Secondary, spawnPriority: SpawnPriority = 'b
}
if (entry.connectPromise) {
- if (spawnPriority === 'foreground') {
- // Hydration may already own this dial as a background slot wait. Kick a
- // foreground IPC so main can promote it onto the reserved slot.
- void (
- entry.connectionId && desktop.getConnectionFor
- ? desktop.getConnectionFor({
- connectionId: entry.connectionId,
- profile: entry.profile,
- priority: 'foreground'
- })
- : desktop.getConnection(entry.profile, { priority: 'foreground' })
- ).catch(() => undefined)
- }
-
await entry.connectPromise
return
@@ -586,16 +548,12 @@ async function openSecondary(entry: Secondary, spawnPriority: SpawnPriority = 'b
const conn =
entry.connectionId && desktop.getConnectionFor
? await withTimeout(
- desktop.getConnectionFor({
- connectionId: entry.connectionId,
- profile: entry.profile,
- ...dialPriority(spawnPriority)
- }),
+ desktop.getConnectionFor({ connectionId: entry.connectionId, profile: entry.profile }),
RECONNECT_ATTEMPT_TIMEOUT_MS,
`Timed out connecting to profile "${entry.profile}"`
)
: await withTimeout(
- dialProfile(desktop, entry.profile, spawnPriority),
+ desktop.getConnection(entry.profile),
RECONNECT_ATTEMPT_TIMEOUT_MS,
`Timed out connecting to profile "${entry.profile}"`
)
@@ -648,8 +606,6 @@ async function openSecondary(entry: Secondary, spawnPriority: SpawnPriority = 'b
if (g.activeKey === entry.scope) {
publishActiveConnection(conn)
}
-
- void desktop.touchBackend?.(entry.scope).catch(() => undefined)
})()
entry.connectPromise = pending
@@ -803,7 +759,7 @@ function createSecondary(profile: string, connectionId: null | string = null): S
// the second dial fails (tunnel/token are per-backend) and the closed socket
// poisons the active gateway with "not connected" even though the primary is
// open right next to it.
-async function sharedPrimaryRoute(profile: string, spawnPriority: SpawnPriority = 'background'): Promise<boolean> {
+async function sharedPrimaryRoute(profile: string): Promise<boolean> {
const desktop = window.hermesDesktop
if (!desktop) {
@@ -815,11 +771,8 @@ async function sharedPrimaryRoute(profile: string, spawnPriority: SpawnPriority
// like any other failure, not hang the route decision forever, since
// every caller (gatewayForProfile → requestGatewayForProfile/Agent) awaits
// this before it can fall back to dialing a secondary.
- // This is the FIRST dial main sees for a user open, so it must already
- // carry the foreground priority — otherwise the spawn it starts queues as
- // background and the click waits out this probe before being promoted.
const conn = await withTimeout(
- dialProfile(desktop, profile, spawnPriority),
+ desktop.getConnection(profile),
RECONNECT_ATTEMPT_TIMEOUT_MS,
`Timed out resolving the shared-primary route for profile "${profile}"`
)
@@ -835,8 +788,7 @@ async function sharedPrimaryRoute(profile: string, spawnPriority: SpawnPriority
// request-scope flag; dedicated local/remote profiles use their pooled socket.
async function gatewayForProfile(
profile: string,
- leaseRequest = false,
- spawnPriority: SpawnPriority = 'background'
+ leaseRequest = false
): Promise<{ gateway: HermesGateway | null; key: string; release: () => void; scopeProfile: boolean }> {
const key = normKey(profile)
const noRelease = () => undefined
@@ -845,7 +797,7 @@ async function gatewayForProfile(
return { gateway: g.primaryGateway, key, release: noRelease, scopeProfile: false }
}
- if (await sharedPrimaryRoute(key, spawnPriority)) {
+ if (await sharedPrimaryRoute(key)) {
return { gateway: g.primaryGateway, key, release: noRelease, scopeProfile: true }
}
@@ -895,7 +847,7 @@ async function gatewayForProfile(
try {
if (!isOpen(entry.gateway)) {
- await openSecondary(entry, spawnPriority)
+ await openSecondary(entry)
}
} catch (error) {
release()
@@ -1085,10 +1037,9 @@ function drainPendingConnectionRedial(entry: Secondary): boolean {
/**
* 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
+ * are deliberately EXEMPT and get a no-op release: a relay pin would keep a
+ * local socket open past the point where retireLocalProfileGateways means to
+ * drop it (see that 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.
*/
@@ -1360,11 +1311,8 @@ function releaseTerminalTurnLease(scope: string, event: GatewayEvent): void {
// it. No scheduleReconnect on failure: a hover is speculative, so a dead
// backend must not start a background retry loop — the real switch owns retry
// and error UX. An already-open (or primary) profile is a no-op.
-export async function openGatewayForProfile(
- profile: string,
- { spawnPriority = 'background' }: { spawnPriority?: SpawnPriority } = {}
-): Promise<void> {
- await gatewayForProfile(profile, false, spawnPriority)
+export async function openGatewayForProfile(profile: string): Promise<void> {
+ await gatewayForProfile(profile, false)
}
// ── Connection-scoped agents (multi-source roster) ─────────────────────────
@@ -1384,18 +1332,15 @@ export async function openGatewayForProfile(
export async function openGatewayForAgent(
connectionId: null | string,
profile: string,
- {
- activationLease = false,
- spawnPriority = 'background'
- }: { activationLease?: boolean; spawnPriority?: SpawnPriority } = {}
+ { activationLease = false }: { activationLease?: boolean } = {}
): Promise<void> {
const scope = registryBackendScopeKey(connectionId, profile)
if (scope === normKey(profile) || isPrimaryRegistryRoute(connectionId, profile)) {
- return openGatewayForProfile(profile, { spawnPriority })
+ return openGatewayForProfile(profile)
}
- if (await isAttachedSharedRemote(connectionId, profile, spawnPriority)) {
+ if (await isAttachedSharedRemote(connectionId, profile)) {
if (!isOpen(g.primaryGateway)) {
throw new Error('Hermes gateway unavailable')
}
@@ -1422,7 +1367,7 @@ export async function openGatewayForAgent(
}
try {
- await openSecondary(entry, spawnPriority)
+ await openSecondary(entry)
} catch (error) {
if (activationLease) {
entry.activationLeaseUntil = 0
@@ -1449,7 +1394,7 @@ export async function ensureGatewayForAgent(
return !signal?.aborted
}
- if (await isAttachedSharedRemote(connectionId, profile, 'foreground')) {
+ if (await isAttachedSharedRemote(connectionId, profile)) {
return Boolean(isOpen(g.primaryGateway) && !signal?.aborted)
}
@@ -1478,7 +1423,7 @@ export async function ensureGatewayForAgent(
entry.reconnectAttempt = 0
try {
- await openSecondary(entry, 'foreground')
+ await openSecondary(entry)
} catch {
scheduleReconnect(entry)
}
@@ -1531,7 +1476,7 @@ export async function ensureGatewayForProfile(profile: string): Promise<void> {
// primary instead of dialing a doomed duplicate socket at the same
// descriptor — $activeGatewayProfile still moves to `key`, so request
// scoping and profile-aware surfaces behave identically.
- if (await sharedPrimaryRoute(key, 'foreground')) {
+ if (await sharedPrimaryRoute(key)) {
applyActive(g.primaryProfile, activationEpoch)
return
@@ -1555,7 +1500,7 @@ export async function ensureGatewayForProfile(profile: string): Promise<void> {
entry.reconnectAttempt = 0
try {
- await openSecondary(entry, 'foreground')
+ await openSecondary(entry)
} catch (error) {
// #81094: a failed secondary dial must NOT fall through to setActive()
// with a closed socket — that silently routes the user's messages to the
@@ -1650,36 +1595,6 @@ export function reconnectSecondaryGateways({ forceOpenSockets = false }: { force
}
}
-// How many non-primary backends currently hold an open socket. Hover-intent
-// prewarming consults this before spawning: a speculative spawn that pushes
-// the pool past its cap causes the Electron main to LRU-evict a warm backend
-// — often one the user is about to click — turning the prewarm into churn
-// (the #91545 evict/respawn cascade). The active gateway's backend is
-// primary-routed and never counts toward the pool cap.
-export function openSecondaryCount(): number {
- let count = 0
-
- for (const entry of g.secondaries.values()) {
- if (isOpen(entry.gateway)) {
- count += 1
- }
- }
-
- return count
-}
-
-// Keep the idle reaper from killing a backend we still need: ping every live
-// secondary. The active one is pinged separately (touchActiveGatewayBackend).
-export function touchSecondaryGateways(): void {
- const desktop = window.hermesDesktop
-
- for (const entry of g.secondaries.values()) {
- if (entry.wantOpen) {
- void desktop?.touchBackend?.(entry.scope).catch(() => undefined)
- }
- }
-}
-
// Tear a secondary down: stop its reconnect loop, detach listeners, close the
// socket. Caller handles removal from the map.
function disposeSecondary(entry: Secondary): void {
diff --git a/apps/desktop/src/store/pool-limits.ts b/apps/desktop/src/store/pool-limits.ts
deleted file mode 100644
index 71bd9e4ade4..00000000000
--- a/apps/desktop/src/store/pool-limits.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- * Pool limits — how many bot backends may stay spawned, and how long an
- * unused one survives before it is shut down.
- *
- * A device-local preference (each machine trades RAM against switching
- * speed for itself). The MAIN process is authoritative: it owns the pool
- * and the persisted copy, and applies a new max immediately by evicting
- * least-recently-used idle backends — no restart. This store mirrors the
- * live values for the Settings rows and feeds prewarmProfileBackend's
- * saturation guard.
- */
-
-import { atom } from 'nanostores'
-
-export interface PoolLimits {
- /** Max concurrently spawned non-primary profile backends. */
- maxBackends: number
- /** Idle lifetime of an unused pool backend, in milliseconds. */
- idleMs: number
-}
-
-export const POOL_LIMITS_DEFAULTS: PoolLimits = {
- maxBackends: 3,
- idleMs: 10 * 60_000
-}
-
-export const $poolLimits = atom<PoolLimits>({ ...POOL_LIMITS_DEFAULTS })
-
-/** Seed from main's authoritative state once at startup; no-op without the
- * bridge (web/older builds just keep the defaults for the UI). */
-export async function loadPoolLimits(): Promise<void> {
- try {
- const limits = await window.hermesDesktop?.getPoolLimits?.()
-
- if (limits) {
- $poolLimits.set(limits)
- }
- } catch {
- // Keep defaults — Settings rows still render and can retry on save.
- }
-}
-
-/** Push new limits to main; adopt the post-clamp values it reports. */
-export async function savePoolLimits(next: { maxBackends?: number; idleMs?: number }): Promise<void> {
- const current = $poolLimits.get()
-
- const optimistic: PoolLimits = {
- maxBackends: next.maxBackends ?? current.maxBackends,
- idleMs: next.idleMs ?? current.idleMs
- }
-
- // Optimistic paint, then honest reconciliation with the clamped result.
- $poolLimits.set(optimistic)
-
- try {
- const result = await window.hermesDesktop?.setPoolLimits?.(next)
-
- if (result?.limits) {
- $poolLimits.set(result.limits)
- }
- } catch {
- $poolLimits.set(current)
- throw new Error('Applying pool limits failed')
- }
-}
diff --git a/apps/desktop/src/store/profile.test.ts b/apps/desktop/src/store/profile.test.ts
index 33c95784274..e62dc86a851 100644
--- a/apps/desktop/src/store/profile.test.ts
+++ b/apps/desktop/src/store/profile.test.ts
@@ -9,7 +9,6 @@ import type { ProfileInfo } from '@/types/hermes'
const ensureGatewayForProfile = vi.fn(async () => undefined)
const ensureGatewayForAgent = vi.fn(async () => undefined)
const openGatewayForProfile = vi.fn(async (_profile: string) => undefined)
-const openSecondaryCount = vi.fn(() => 0)
const $gateway = atom<unknown>({ id: 'live-socket', connectionState: 'open' })
const resetStarmapGraph = vi.fn()
@@ -17,16 +16,8 @@ vi.mock('@/store/gateway', () => ({
$gateway,
ensureGatewayForAgent,
ensureGatewayForProfile,
- openGatewayForProfile,
- openSecondaryCount
+ openGatewayForProfile
}))
-// The pool-limits atom is profile.ts's live saturation signal — keep the real
-// one so tests can move the cap via the store, but stub its IPC bridge.
-vi.mock('@/store/pool-limits', async () => {
- const { atom } = await import('nanostores')
-
- return { $poolLimits: atom({ idleMs: 600_000, maxBackends: 3 }) }
-})
vi.mock('@/hermes', () => ({
getProfiles: vi.fn(async () => ({ profiles: [] })),
setApiRequestProfile: vi.fn()
@@ -43,8 +34,6 @@ const {
refreshProfiles
} = await import('./profile')
-const { $poolLimits } = await import('@/store/pool-limits')
-
const { $connection } = await import('./session')
const { invalidateProfileScopedQueries } = await import('@/lib/query-client')
const { getProfiles } = await import('@/hermes')
@@ -71,7 +60,6 @@ beforeEach(() => {
getConnection.mockReset()
ensureGatewayForProfile.mockClear()
openGatewayForProfile.mockClear()
- openSecondaryCount.mockReturnValue(0)
$gateway.set({ id: 'live-socket', connectionState: 'open' })
$activeGatewayProfile.set('default')
$connection.set(localConn())
@@ -186,43 +174,6 @@ describe('prewarmProfileBackend (hover-intent pool spawn)', () => {
expect(() => prewarmProfileBackend('warm-failing')).not.toThrow()
})
-
- it('skips pre-warm when the pool is saturated (#91545 evict/respawn cascade)', () => {
- // Every pool slot occupied: a speculative spawn would LRU-evict a warm
- // backend — often the one the user is about to click. Default limit 3,
- // 3 open secondaries → the next spawn would exceed the cap.
- openSecondaryCount.mockReturnValue(3)
-
- prewarmProfileBackend('warm-saturated')
-
- expect(openGatewayForProfile).not.toHaveBeenCalled()
- })
-
- it('pre-warms while pool slots are free', () => {
- openSecondaryCount.mockReturnValue(1)
-
- prewarmProfileBackend('warm-slot-free')
-
- expect(openGatewayForProfile).toHaveBeenCalledWith('warm-slot-free')
- })
-
- it('follows the live pool-limit atom, not a hard-coded cap', () => {
- // User raises Warm Bot Backends to 8 in Settings: prewarming must keep
- // working well past the old default of 3.
- openSecondaryCount.mockReturnValue(5)
- $poolLimits.set({ idleMs: 600_000, maxBackends: 8 })
-
- prewarmProfileBackend('warm-raised-cap')
-
- expect(openGatewayForProfile).toHaveBeenCalledWith('warm-raised-cap')
-
- // And lowering the cap re-engages the guard at the new boundary.
- $poolLimits.set({ idleMs: 600_000, maxBackends: 2 })
-
- prewarmProfileBackend('warm-lowered-cap')
-
- expect(openGatewayForProfile).not.toHaveBeenCalledWith('warm-lowered-cap')
- })
})
describe('refreshProfiles shared rail list (#49289)', () => {
diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.ts
index 44d4d6b1cad..53f6e2e8c05 100644
--- a/apps/desktop/src/store/profile.ts
+++ b/apps/desktop/src/store/profile.ts
@@ -21,11 +21,9 @@ import {
ensureGatewayForAgent,
ensureGatewayForProfile,
openGatewayForAgent,
- openGatewayForProfile,
- openSecondaryCount
+ openGatewayForProfile
} from '@/store/gateway'
import { notifyError } from '@/store/notifications'
-import { $poolLimits } from '@/store/pool-limits'
import { notifyRemoteOverrideAuthFailure } from '@/store/profile-remote-override'
import { clearComposerSelectionOwner, setComposerSelectionOwner, setConnection } from '@/store/session'
import type { SessionOwnerRoute } from '@/store/session-request-router'
@@ -246,7 +244,7 @@ export async function switchProfile(name: string): Promise<void> {
// to the primary (window) backend's profile on boot. The gateway registry
// mirrors its own route into this atom via the onActiveRouteChanged callback
// (wired in use-gateway-boot's configureGatewayRegistry), so registry-internal
-// eviction fallbacks (idle reap, connection removal, profile delete) can never
+// eviction fallbacks (connection removal, profile delete) can never
// leave this naming a profile the active socket no longer serves (#89206).
export const $activeGatewayProfile = atom<string>('default')
@@ -397,17 +395,17 @@ export const $gatewaySwapTarget = atom<string | null>(null)
export const $hydrationSyncProfile = atom<string | null>(null)
// ── Hover-intent backend pre-warm ───────────────────────────────────────────
-// A cold switch to a profile whose pool backend isn't running pays the full
-// spawn (Python boot + port announce + readiness probe — measured ~2.5-3s)
-// plus the socket connect before the sidebar can repopulate. The pointer
-// entering a profile square in the rail signals the switch a few hundred ms
-// before the click lands, so we run the same spawn + connect chain then
-// (openGatewayForProfile — without activating). `ensureBackend` in the
-// Electron main is idempotent (a pooled profile returns its existing
-// connectionPromise), so the real switch joins the in-flight work instead of
-// duplicating it — and a pre-warm for an already-open profile is a no-op.
-// Throttled per profile so drive-by hovers can't spam spawn attempts; failures
-// stay silent here and surface on the real switch, which owns retry/error UX.
+// A cold switch to a profile whose gateway descriptor isn't cached pays the
+// `hermes gateway ensure` round-trip plus the socket connect before the sidebar
+// can repopulate. The pointer entering a profile square in the rail signals the
+// switch a few hundred ms before the click lands, so we run the same dial +
+// connect chain then (openGatewayForProfile — without activating).
+// `ensureBackend` in the Electron main is idempotent (a cached profile returns
+// its existing connectionPromise), so the real switch joins the in-flight work
+// instead of duplicating it — and a pre-warm for an already-open profile is a
+// no-op. Throttled per profile so drive-by hovers can't spam dial attempts;
+// failures stay silent here and surface on the real switch, which owns
+// retry/error UX.
const PREWARM_MIN_INTERVAL_MS = 60_000
const prewarmedAt = new Map<string, number>()
@@ -425,17 +423,6 @@ export function prewarmProfileBackend(name: string): void {
return
}
- // Prewarm/cap harmony (#91545): the pool caps spawned backends at the
- // configured max, and a spawn over the cap LRU-evicts the warmest idle
- // backend. A hover sweep across the rail therefore evicted backends for
- // profiles the user was about to click — prewarming caused the exact churn
- // it exists to prevent. Skip speculative spawns once every pool slot is
- // occupied by an open socket; the real click still spawns on demand, it
- // just doesn't get a head start.
- if (openSecondaryCount() + 1 > $poolLimits.get().maxBackends) {
- return
- }
-
prewarmedAt.set(key, now)
openGatewayForProfile(key).catch(() => undefined)
}
@@ -603,10 +590,7 @@ export async function openGatewayAgent(connectionId: string, profile: string): P
return
}
- await openGatewayForAgent(connection, normalizeProfileKey(profile), {
- activationLease: true,
- spawnPriority: 'foreground'
- })
+ await openGatewayForAgent(connection, normalizeProfileKey(profile), { activationLease: true })
}
// Activate a connection-scoped agent's gateway — the (connectionId, profile)
@@ -996,13 +980,3 @@ export const $profileCreateRequest = atom(0)
export function requestProfileCreate(): void {
$profileCreateRequest.set($profileCreateRequest.get() + 1)
}
-
-// Keepalive ping for the active pool backend so the main-process idle reaper
-// (which can't see the direct renderer↔backend WS) spares it. No-op for the
-// primary/default backend, which is never pooled.
-export function touchActiveGatewayBackend(): void {
- // Always ping: the main process no-ops for non-pool (primary) backends, so we
- // don't need to know which profile is primary from here.
- const target = normalizeProfileKey($activeGatewayProfile.get())
- void window.hermesDesktop?.touchBackend?.(target).catch(() => undefined)
-}
diff --git a/apps/desktop/src/store/session-request-router.test.ts b/apps/desktop/src/store/session-request-router.test.ts
index 8c3261b402e..39822b84e27 100644
--- a/apps/desktop/src/store/session-request-router.test.ts
+++ b/apps/desktop/src/store/session-request-router.test.ts
@@ -91,8 +91,7 @@ function installDesktop(): void {
port: connectionId === 'source-a' ? 6161 : 6262,
profile,
token: `${connectionId}-token`
- })),
- touchBackend: vi.fn(async () => undefined)
+ }))
}
}
diff --git a/website/docs/user-guide/multi-connection-desktop.md b/website/docs/user-guide/multi-connection-desktop.md
index e8c3ddcafb4..3cdff0dbf7d 100644
--- a/website/docs/user-guide/multi-connection-desktop.md
+++ b/website/docs/user-guide/multi-connection-desktop.md
@@ -177,9 +177,10 @@ The union roster is what multi-gateway surfaces (and the built-in
live on the machine that owns the profile, exactly as if you were using
that instance directly.
-Each `(connection, profile)` pair gets its own backend and socket, pooled
-with the same idle-reaping as local per-profile backends — background agents
-keep streaming while you look at another gateway.
+Each `(connection, profile)` pair gets its own socket, and Desktop caches the
+gateway descriptor it dialed so the next open joins the same connection —
+background agents keep streaming while you look at another gateway. Nothing is
+spawned or reaped on your behalf: each gateway owns its own lifetime.
Approval buttons route back to the session's owning backend, not whichever
profile is currently selected. For a local secondary profile, Desktop can use