The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(desktop): drop the dead local-backend slot coordinator wiring in main.ts
Tekniumb87ab0673414
diff --git a/apps/desktop/electron/backend-dial-claim.test.ts b/apps/desktop/electron/backend-dial-claim.test.tsindex 30c7e8195c3..3562ecb59ad 100644--- a/apps/desktop/electron/backend-dial-claim.test.ts+++ b/apps/desktop/electron/backend-dial-claim.test.ts@@ -129,7 +129,7 @@ describe('main.ts wiring for #90812', () => {const body = mainSource.slice(handlerStart, handlerStart + 1200)expect(body).toContain('backendDialClaims.run(')- expect(body).toContain('ensureBackend(profile, { spawnPriority })')+ expect(body).toContain('ensureBackend(profile)')})it('routes the registry-scoped dial IPC through the claim keyed by backendScopeKey(connectionId, profile)', () => {@@ -139,7 +139,7 @@ describe('main.ts wiring for #90812', () => {expect(body).toContain('const scopeKey = backendScopeKey(id, profile)')expect(body).toContain('backendDialClaims.run(scopeKey, ')- expect(body).toContain("ensureRegistryBackend(id, profile, '', { spawnPriority })")+ expect(body).toContain('ensureRegistryBackend(id, profile)')})// The four IPC/probe surfaces below call ensureRegistryBackend()/ensureBackend()diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex fcc91dc065f..8436ea940ed 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -289,13 +289,6 @@ import {} from './plugin-profile-routes'import { selectPoolEvictions } from './pool-eviction'import { clampPoolLimits, parsePoolLimits, POOL_LIMITS_DEFAULTS } from './pool-limits'-import {- isBackgroundSlotWaitTimeout,- LocalBackendSpawnCoordinator,- type LocalBackendSpawnPriority,- type LocalBackendSpawnRequest,- releaseLocalBackendSlotAfterExit-} from './pool-spawn-coordinator'import { createPoolStopper } from './pool-stop'import { poolTouchKeys } from './pool-touch-scope'import { createKeepAwake } from './power-save'@@ -1490,77 +1483,12 @@ let desktopLogFlushTimer = nulllet desktopLogFlushPromise = Promise.resolve()let poolLimits = readPersistedPoolLimits()-// Hard cap on local backends that are starting OR running (the LRU eviction-// above is soft — it spares keepalive-fresh entries). Follows the live-// preference: setPoolLimits() pushes a new max into the coordinator.-const localBackendSpawnCoordinator = new LocalBackendSpawnCoordinator(poolLimits.maxBackends)-// How long a spawn may wait for a free local slot. Must stay under the-// renderer's BACKEND_BOOT_WAIT_TIMEOUT_MS (45s, src/lib/with-timeout.ts) so-// the queued ticket fails before the renderer does and the user sees why.-const POOL_SLOT_WAIT_MS = 30_000--function spawnPriorityFrom(value: unknown): LocalBackendSpawnPriority {- return value === 'foreground' ? 'foreground' : 'background'-}--// Foreground intent for a dial whose pool entry does not exist yet: a user-// click that joins an in-flight backendDialClaims claim never re-enters-// ensureBackend(), and the claim owner may still be awaiting poolStopper /-// registry resolution before backendPool.set(). The local spawn takes the mark-// right before its slot request; the IPC handler that set it clears it once-// the claim settles, so a dial that never reaches a slot request (primary-// route, remote scope, a guard rejection) cannot leave it for a later-// hydration spawn of the same key to pick up.-const pendingForegroundSpawns = new Set<string>()--function takeForegroundSpawn(...poolKeys: string[]): boolean {- let marked = false-- for (const poolKey of poolKeys) {- marked = pendingForegroundSpawns.delete(poolKey) || marked- }-- return marked-}--// Upgrade a pooled entry (running, spawning, or queued for a slot) to-// foreground so a queued slot wait can take the reserved foreground slot.-function promotePoolEntry(entry: any): void {- entry.spawnPriority = 'foreground'- entry.localBackendSpawnRequest?.promote?.('foreground')-}-// Land a spawn failure in desktop.log. A background slot-wait timeout is-// routine under a saturated pool (the next hydration pass retries), so it is-// logged as such instead of as a backend-start failure.+// Land a spawn failure in desktop.log.function logPoolSpawnFailure(label: string, error: unknown): void {- if (isBackgroundSlotWaitTimeout(error)) {- rememberLog(`Profile backend ${label} slot wait timed out (background); will retry on the next hydration`)- } else {- rememberLog(- `Hermes backend for profile ${label} failed to start: ${error instanceof Error ? error.message : String(error)}`- )- }-}--// Apply foreground intent to the dial claim for `scopeKey`: an entry already-// in the pool is promoted directly, otherwise the intent is marked for the-// spawn the claim owner is about to start. Returns the cleanup that clears a-// mark the dial never consumed.-function applySpawnPriority(scopeKey: string, spawnPriority: LocalBackendSpawnPriority): () => void {- if (spawnPriority !== 'foreground') {- return () => undefined- }-- const existing = backendPool.get(scopeKey)-- if (existing) {- promotePoolEntry(existing)- } else {- pendingForegroundSpawns.add(scopeKey)- }-- return () => void pendingForegroundSpawns.delete(scopeKey)+ rememberLog(+ `Hermes backend for profile ${label} failed to start: ${error instanceof Error ? error.message : String(error)}`+ )}function poolMaxBackends() {@@ -1580,7 +1508,6 @@ function poolIdleMs() {function setPoolLimits(raw) {poolLimits = clampPoolLimits(raw)persistPoolLimits(poolLimits)- localBackendSpawnCoordinator.setLimit(poolLimits.maxBackends)evictLruPoolBackends(poolMaxBackends())startPoolIdleReaper()@@ -11484,9 +11411,8 @@ async function forgetLocalGatewayDescriptor(profile) {}}-async function ensureBackend(profile, opts: { spawnPriority?: LocalBackendSpawnPriority } = {}) {+async function ensureBackend(profile) {const key = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()- const spawnPriority = spawnPriorityFrom(opts.spawnPriority)profileDeletionGate.assertCanStart(key)@@ -11519,10 +11445,6 @@ async function ensureBackend(profile, opts: { spawnPriority?: LocalBackendSpawnPif (existing) {existing.lastActiveAt = Date.now()- if (spawnPriority === 'foreground') {- promotePoolEntry(existing)- }-const connection = await existing.connectionPromisesetWslBridgeProfileState(key, connection.mode !== 'remote')@@ -11537,11 +11459,7 @@ async function ensureBackend(profile, opts: { spawnPriority?: LocalBackendSpawnPtoken: null,connectionPromise: null,lastActiveAt: Date.now(),- remoteBaseUrl: null,- releaseLocalBackendSlot: null,- localBackendSlotKey: null,- localBackendSpawnRequest: null,- spawnPriority+ remoteBaseUrl: null}entry.connectionPromise = spawnPoolBackend(key, entry).catch(async error => {@@ -11572,10 +11490,8 @@ async function ensureBackend(profile, opts: { spawnPriority?: LocalBackendSpawnPasync function ensureRegistryBackend(connectionId,profile,- managedUpdateCorrelation = '',- opts: { spawnPriority?: LocalBackendSpawnPriority } = {}+ managedUpdateCorrelation = '') {- const spawnPriority = spawnPriorityFrom(opts.spawnPriority)const registry = readDesktopConnectionsRegistry()const id = String(connectionId || '').trim() || registry.primaryconst source = registry.connections.find(c => c.id === id)@@ -11632,7 +11548,7 @@ async function ensureRegistryBackend(const primary = await reuseMatchingPrimarySshBackend({connectionId: id,effectiveFingerprint: resolveRegistryEffectiveFingerprint,- ensurePrimary: () => ensureBackend(profile, { spawnPriority }),+ ensurePrimary: () => ensureBackend(profile),profile,registry,source@@ -11683,7 +11599,7 @@ async function ensureRegistryBackend(})if (localRoute.delegate) {- return ensureBackend(profile, { spawnPriority })+ return ensureBackend(profile)}const stoppingLocal = poolStopper.inFlight(localRoute.poolKey)@@ -11697,10 +11613,6 @@ async function ensureRegistryBackend(if (existingLocal) {existingLocal.lastActiveAt = Date.now()- if (spawnPriority === 'foreground') {- promotePoolEntry(existingLocal)- }-return existingLocal.connectionPromise}@@ -11712,11 +11624,7 @@ async function ensureRegistryBackend(token: null,connectionPromise: null,lastActiveAt: Date.now(),- remoteBaseUrl: null,- releaseLocalBackendSlot: null,- localBackendSlotKey: null,- localBackendSpawnRequest: null,- spawnPriority+ remoteBaseUrl: null}localEntry.connectionPromise = spawnPoolBackend(profileKey, localEntry, {@@ -12460,27 +12368,8 @@ function startPoolIdleReaper() {}}-function releaseLocalBackendSlot(entry: any) {- if (!entry) {- return- }-- const release = entry.releaseLocalBackendSlot- const request = entry.localBackendSpawnRequest as LocalBackendSpawnRequest | null- entry.releaseLocalBackendSlot = null- entry.localBackendSlotKey = null- entry.localBackendSpawnRequest = null-- if (release) {- release()- } else {- request?.cancel()- }-}-function assertPoolEntryStillOwned(poolKey: string, entry: any) {if (backendPool.get(poolKey) !== entry) {- releaseLocalBackendSlot(entry)throw new Error(`Profile backend start for "${poolKey}" was cancelled before spawn.`)}}@@ -12500,19 +12389,16 @@ function teardownFailedLocalBackend(poolKey: string, entry: any): Promise<void>const child = entry.process- const teardown = releaseLocalBackendSlotAfterExit(- () => releaseLocalBackendSlot(entry),- async () => {- stopBackendChild(child)- await waitForBackendExit(child)-- if (child && child.exitCode === null && child.signalCode === null) {- throw new Error(`Profile backend for "${poolKey}" did not exit; keeping the local slot occupied.`)- }+ const teardown = (async () => {+ stopBackendChild(child)+ await waitForBackendExit(child)- releaseBackendChild(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.@@ -12593,9 +12479,7 @@ const poolStopper = createPoolStopper({})async function stopPoolBackend(profile: string) {- const entry = backendPool.get(profile)await poolStopper.stop(profile)- releaseLocalBackendSlot(entry)}async function teardownPoolBackendAndWait(profile) {@@ -12603,9 +12487,7 @@ async function teardownPoolBackendAndWait(profile) {}async function stopAllPoolBackends() {- const entries = [...backendPool.values()]await poolStopper.stopAll()- entries.forEach(releaseLocalBackendSlot)}const backendShutdown = createBackendShutdownCoordinator(async () => {@@ -14434,26 +14316,14 @@ function createWindow() {})}-ipcMain.handle('hermes:connection', async (_event, profile, extra) => {+ipcMain.handle('hermes:connection', async (_event, profile) => {// Coalesce concurrent renderer dials for one profile scope (#90812): the// renderer-side reconnect lock is per-window, so two windows waking at once// both land here. The claim key mirrors ensureBackend()'s own profile// normalization so every spelling of the primary coalesces onto one dial.const profileKey = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()- // A user click may join an in-flight hydration claim; the foreground intent- // is applied to that claim so its slot wait can take the reserved slot.- const spawnPriority = spawnPriorityFrom(extra?.priority)-const scopeKey = backendScopeKey(null, profileKey)- const clearSpawnPriority = applySpawnPriority(scopeKey, spawnPriority)-- let connection-- try {- connection = await backendDialClaims.run(scopeKey, () => ensureBackend(profile, { spawnPriority }))- } finally {- clearSpawnPriority()- }+ const connection = await backendDialClaims.run(scopeKey, () => ensureBackend(profile))const connectionId = resolvedConnectionId(readDesktopConnectionsRegistry(), connection)@@ -14465,24 +14335,15 @@ ipcMain.handle('hermes:connection', async (_event, profile, extra) => {// forces a genuinely-local child when the v1 global mode is remote (the// registry 'local' entry always means this machine).ipcMain.handle('hermes:connection:for', async (_event, payload) => {- const { connectionId, profile, priority } = payload && typeof payload === 'object' ? (payload as any) : ({} as any)+ const { connectionId, profile } = payload && typeof payload === 'object' ? (payload as any) : ({} as any)const registry = readDesktopConnectionsRegistry()const id = String(connectionId || '').trim() || registry.primary- const spawnPriority = spawnPriorityFrom(priority)// Same single-owner claim as 'hermes:connection', keyed by the composite// (connectionId, profile) scope (#90812): concurrent registry dials for one// scope share the first spawn instead of bootstrapping duplicate remotes.const scopeKey = backendScopeKey(id, profile)- const clearSpawnPriority = applySpawnPriority(scopeKey, spawnPriority)-- let connection-- try {- connection = await backendDialClaims.run(scopeKey, () => ensureRegistryBackend(id, profile, '', { spawnPriority }))- } finally {- clearSpawnPriority()- }+ const connection = await backendDialClaims.run(scopeKey, () => ensureRegistryBackend(id, profile))return { ...connection, connectionId: id, registryScoped: true }})diff --git a/apps/desktop/electron/pool-spawn-coordinator.test.ts b/apps/desktop/electron/pool-spawn-coordinator.test.tsindex b7cf4ee30ec..e55c1921d49 100644--- a/apps/desktop/electron/pool-spawn-coordinator.test.ts+++ b/apps/desktop/electron/pool-spawn-coordinator.test.ts@@ -1,8 +1,5 @@import assert from 'node:assert/strict'import { spawn } from 'node:child_process'-import fs from 'node:fs'-import path from 'node:path'-import { fileURLToPath } from 'node:url'import { test } from 'vitest'@@ -500,43 +497,3 @@ test('promoting a queued background waiter lets it take the reserved foregroundbg2()assert.equal(coordinator.activeCount, 0)})--// ── main.ts wiring ──────────────────────────────────────────────────────────-// The coordinator is only as good as the timeout main.ts hands it. A queued-// ticket that outlives the renderer's backend-boot budget holds the pool key-// hostage: the renderer has already reported "backend didn't come up", and-// every later click on that profile joins the stale wait instead of failing-// fast with a reason.-{- const here = path.dirname(fileURLToPath(import.meta.url))- const mainSource = fs.readFileSync(path.join(here, 'main.ts'), 'utf8').replace(/\r\n/g, '\n')-- const withTimeoutSource = fs- .readFileSync(path.join(here, '..', 'src', 'lib', 'with-timeout.ts'), 'utf8')- .replace(/\r\n/g, '\n')-- test('main.ts bounds the slot wait below the renderer backend-boot budget', () => {- const slotWait = Number(/const POOL_SLOT_WAIT_MS = ([\d_]+)/.exec(mainSource)?.[1]?.replace(/_/g, ''))-- const bootBudget = Number(- /export const BACKEND_BOOT_WAIT_TIMEOUT_MS = ([\d_]+)/.exec(withTimeoutSource)?.[1]?.replace(/_/g, '')- )-- assert.ok(Number.isFinite(slotWait) && slotWait > 0, 'POOL_SLOT_WAIT_MS must be a literal in main.ts')- assert.ok(Number.isFinite(bootBudget), 'BACKEND_BOOT_WAIT_TIMEOUT_MS must be a literal')- assert.ok(slotWait < bootBudget, `slot wait ${slotWait}ms must be below the boot budget ${bootBudget}ms`)- assert.match(- mainSource,- /localBackendSpawnCoordinator\.request\(poolKey, \{\s*timeoutMs: POOL_SLOT_WAIT_MS,\s*priority: spawnPriority\s*\}\)/- )- assert.doesNotMatch(mainSource, /request\(poolKey, \{ timeoutMs: POOL_IDLE_MS \}\)/)- })-- test('main.ts pushes the live pool max into the coordinator when the preference changes', () => {- // Pool sizing is a live device preference (#92581); the hard cap must- // follow it, otherwise raising the max in Settings would leave spawns- // queued behind the launch-time value.- assert.match(mainSource, /new LocalBackendSpawnCoordinator\(poolLimits\.maxBackends\)/)- assert.match(mainSource, /localBackendSpawnCoordinator\.setLimit\(poolLimits\.maxBackends\)/)- })-}