The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): cooperative pool retirement for foreground dials behind an admission fence
Austin Pickett5fef73015a4a
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 3718ac358d7..72fc855ad4b 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -303,6 +303,7 @@ import {} from './plugin-profile-routes'import { evictPoolEntries } from './pool-eviction'import { clampPoolLimits, parsePoolLimits, POOL_LIMITS_DEFAULTS } from './pool-limits'+import { createPoolRetirer } from './pool-retire'import {BackgroundSlotRetryBackoff,BackgroundSlotRetryDeferredError,@@ -12419,13 +12420,21 @@ 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) {+// It also reports whether a prompt turn currently leases the backend: a+// foreground dial that must retire a resident skips leased ones early. That+// flag is an optimisation, never the proof — the backend probe is (see+// pool-retire.ts). Shape from #104871 by @bounce12340.+function touchPoolBackend(profile, options: { activeTurn?: boolean } = {}) {for (const key of poolTouchKeys(profile)) {const entry = backendPool.get(key)if (entry) {entry.lastActiveAt = Date.now()+ if (typeof options.activeTurn === 'boolean') {+ entry.activeTurn = options.activeTurn+ }+return}}@@ -12609,6 +12618,23 @@ async function runPoolBackendStart(profile, entry, opts: { forceLocal?: boolean;throw new BackgroundSlotRetryDeferredError(profile)}+ // Trigger point (from #104871): a foreground dial against a full pool may+ // retire ONE resident the backend proves idle. Prepare it BEFORE taking a+ // ticket so the request below sits at the queue head when the slot frees;+ // commit AFTER so nothing that was not already waiting can take that slot.+ // Null (nothing provably idle) falls through to the ordinary bounded wait.+ const retirement =+ spawnPriority === 'foreground' && localBackendSpawnCoordinator.activeCount >= poolMaxBackends()+ ? await poolRetirer.retireForForeground(poolKey)+ : null++ try {+ assertPoolEntryStillOwned(poolKey, entry)+ } catch (error) {+ retirement?.abandon()+ throw error+ }+const spawnRequest = localBackendSpawnCoordinator.request(poolKey, {timeoutMs: POOL_SLOT_WAIT_MS,priority: spawnPriority@@ -12617,6 +12643,12 @@ async function runPoolBackendStart(profile, entry, opts: { forceLocal?: boolean;entry.localBackendSlotKey = poolKeyentry.localBackendSpawnRequest = spawnRequest+ // The slot is released by the retired child's real exit (stopPoolBackend →+ // releaseLocalBackendSlot), never here; this only starts the teardown.+ void retirement?.commit().catch(error => {+ rememberLog(`Pool retirement for "${poolKey}" failed: ${error instanceof Error ? error.message : String(error)}`)+ })+if (spawnRequest.queued) {rememberLog(`Profile backend "${profile}" waiting for a free local slot (${localBackendSpawnCoordinator.activeCount}/${poolMaxBackends()} busy, ${localBackendSpawnCoordinator.queuedCount} queued)`@@ -12882,6 +12914,48 @@ async function stopPoolBackend(profile: string) {releaseLocalBackendSlot(entry)}+// Backend-proven idleness for cooperative retirement (pool-retire.ts). Only+// the child's own ledgers count: `/api/health/idle` reads running sessions,+// running cron jobs (HERMES_DESKTOP=1 runs the in-process ticker) and prompts+// waiting on a human. A runtime predating the route 404s, a probe error or an+// unreadable ledger reads as null; both are "busy" to the retirer.+async function probePoolBackendIdle(entry: any): Promise<boolean | null> {+ if (!entry?.process || !entry.port || !entry.token) {+ return null+ }++ try {+ const body: any = await fetchJson(`http://127.0.0.1:${entry.port}/api/health/idle`, entry.token, {+ timeoutMs: 3_000+ })++ return body?.idle === true ? true : body?.idle === false ? false : null+ } catch {+ return null+ }+}++// Tell every window the pooled backend under `poolKey` is being retired so the+// renderer parks that scope (wantOpen=false) instead of redialing into the+// slot it just vacated. Fired BEFORE the SIGTERM (pool-retire.ts contract).+function broadcastPoolBackendRetiring(poolKey: string) {+ for (const win of BrowserWindow.getAllWindows()) {+ const { webContents } = win++ if (webContents && !webContents.isDestroyed()) {+ webContents.send('hermes:pool:retiring', { poolKey })+ }+ }+}++const poolRetirer = createPoolRetirer<any>({+ pool: backendPool,+ probeIdle: (_key, entry) => probePoolBackendIdle(entry),+ stopBackend: stopPoolBackend,+ onRetiring: broadcastPoolBackendRetiring,+ log: rememberLog+})+async function teardownPoolBackendAndWait(profile) {await Promise.all(localProfilePoolKeys(profile).map(key => stopPoolBackend(key)))}@@ -15271,8 +15345,8 @@ function revalidateSuspectPoolAfterResume() {)}-ipcMain.handle('hermes:backend:touch', async (_event, profile) => {- touchPoolBackend(profile)+ipcMain.handle('hermes:backend:touch', async (_event, profile, options) => {+ touchPoolBackend(profile, options)return { ok: true }})diff --git a/apps/desktop/electron/pool-retire.test.ts b/apps/desktop/electron/pool-retire.test.tsnew file mode 100644index 00000000000..847ca539f2c--- /dev/null+++ b/apps/desktop/electron/pool-retire.test.ts@@ -0,0 +1,191 @@+import assert from 'node:assert/strict'++import { test } from 'vitest'++import { createPoolRetirer, type IdleVerdict, type PoolRetireEntry, selectRetirementCandidates } from './pool-retire'+import { LocalBackendSpawnCoordinator } from './pool-spawn-coordinator'++// Bug class (supersedes #104871): a foreground open against a full 3-slot pool+// waited 30s and timed out because every resident was keepalive-fresh but+// idle. The salvage rotates ONE resident out — provably idle by the backend's+// own ledgers, behind an admission fence, with the identity rechecked after+// every await, and the slot released only by the real child exit.++const NOW = 1_000_000++interface Entry extends PoolRetireEntry {+ process: { pid: number } | null+}++const resident = (idleMs: number, extra: Partial<Entry> = {}): Entry => ({+ process: { pid: 100 + idleMs },+ lastActiveAt: NOW - idleMs,+ ...extra+})++function harness(verdicts: Record<string, IdleVerdict | IdleVerdict[]>) {+ const pool = new Map<string, Entry>()+ const probes: string[] = []+ const stopped: string[] = []+ const retiring: string[] = []+ const exitResolvers = new Map<string, () => void>()+ const coordinator = new LocalBackendSpawnCoordinator(3)+ const releases = new Map<string, () => void>()++ const retirer = createPoolRetirer<Entry>({+ pool,+ probeIdle: async key => {+ probes.push(key)+ const scripted = verdicts[key]++ if (Array.isArray(scripted)) {+ return scripted.length > 1 ? (scripted.shift() as IdleVerdict) : scripted[0]+ }++ return scripted ?? null+ },+ // Mirrors stopPoolBackend: the entry leaves the pool now, SIGTERM is+ // synchronous, and the slot is released only after the child's real exit.+ stopBackend: key =>+ new Promise<void>(resolve => {+ stopped.push(key)+ pool.delete(key)+ exitResolvers.set(key, () => {+ releases.get(key)?.()+ resolve()+ })+ }),+ onRetiring: key => retiring.push(key)+ })++ // Fill the coordinator like three spawned residents would.+ async function seed(...keys: string[]) {+ for (const key of keys) {+ releases.set(key, await coordinator.acquire(key))+ }+ }++ return { pool, probes, stopped, retiring, exitResolvers, coordinator, retirer, seed }+}++test('selector: LRU among spawned residents, skipping renderer-leased turns and the waiter itself', () => {+ const entries: [string, Entry][] = [+ ['pinned-old', resident(300_000)],+ ['mid-turn', resident(900_000, { activeTurn: true })],+ ['fresh', resident(1_000)],+ ['descriptor', { process: null, lastActiveAt: NOW - 999_999 }],+ ['unknown-activity', resident(600_000, { activeTurn: undefined })],+ ['waiter', resident(999_999)]+ ]++ assert.deepEqual(+ selectRetirementCandidates(entries, new Set(['waiter'])).map(([key]) => key),+ ['unknown-activity', 'pinned-old', 'fresh']+ )+})++test('fence: two concurrent foreground dials share one retirement and exactly one ticket gets the slot', async () => {+ const h = harness({ 'bot-a': true, 'bot-b': true })+ h.pool.set('bot-a', resident(300_000))+ h.pool.set('bot-b', resident(200_000))+ h.pool.set('bot-c', resident(1_000, { activeTurn: true }))+ await h.seed('bot-a', 'bot-b', 'bot-c')+ assert.equal(h.coordinator.activeCount, 3)++ // Two clicks land in the same tick.+ const [first, second] = await Promise.all([+ h.retirer.retireForForeground('new-1'),+ h.retirer.retireForForeground('new-2')+ ])++ assert.ok(first && second)+ assert.equal(first.key, 'bot-a')+ assert.equal(second, first, 'the second dial shares the first retirement, it does not start its own')+ assert.deepEqual(h.probes, ['bot-a'], 'one probe, not one per dial')++ // Trigger point contract: each waiter queues BEFORE the stop so the freed+ // slot cannot be taken by anything that was not already waiting.+ const ticket1 = h.coordinator.request('new-1', { priority: 'foreground', timeoutMs: 10_000 })+ const ticket2 = h.coordinator.request('new-2', { priority: 'foreground', timeoutMs: 10_000 })+ assert.equal(ticket1.queued, true)++ const commits = Promise.all([first.commit(), second.commit()])+ await Promise.resolve()+ assert.deepEqual(h.retiring, ['bot-a'], 'renderer told once, before the stop')+ assert.deepEqual(h.stopped, ['bot-a'], 'exactly one SIGTERM')+ assert.equal(h.pool.has('bot-a'), false)++ // The lease is still held until the child actually exits.+ assert.equal(h.coordinator.activeCount, 3)+ let granted = 0+ void ticket1.acquired.then(() => (granted += 1))+ void ticket2.acquired.then(() => (granted += 1)).catch(() => undefined)+ await new Promise(resolve => setTimeout(resolve, 5))+ assert.equal(granted, 0, 'no slot before the real exit')++ h.exitResolvers.get('bot-a')?.()+ assert.deepEqual(await commits, [true, true])+ await new Promise(resolve => setTimeout(resolve, 5))+ assert.equal(granted, 1, 'exactly one waiter gets the freed slot')+ assert.equal(h.coordinator.queuedCount, 1)+ assert.equal(h.retirer.inFlight(), false, 'the fence lifts once the retirement settled')++ ticket2.cancel()+})++test('identity: the recheck aborts when the entry was swapped or leased a turn while the probe was in flight', async () => {+ const h = harness({ 'bot-a': true, 'bot-b': true })+ const original = resident(300_000)+ h.pool.set('bot-a', original)+ h.pool.set('bot-b', resident(100_000))++ const retirement = await h.retirer.retireForForeground('new')+ assert.equal(retirement?.key, 'bot-a')++ // Between prepare and commit (the waiter is queueing), a respawn replaced+ // bot-a's entry under the same key. The stale retirement must not kill it.+ h.pool.set('bot-a', resident(0))+ assert.equal(await retirement!.commit(), false)+ assert.deepEqual(h.stopped, [])+ assert.deepEqual(h.retiring, [])+ assert.equal(h.retirer.inFlight(), false)++ // Same shape for a renderer turn lease published after the probe answered.+ const h2 = harness({ 'bot-a': true })+ const entry = resident(300_000)+ h2.pool.set('bot-a', entry)+ const r2 = await h2.retirer.retireForForeground('new')+ entry.activeTurn = true+ assert.equal(await r2!.commit(), false)+ assert.deepEqual(h2.stopped, [])+})++test('fail closed: idle null (older runtime / probe error) and cron-running are ineligible; no candidate falls through to the queue', async () => {+ const h = harness({+ 'old-runtime': null, // 404 from a backend predating /api/health/idle+ 'cron-mid-run': false, // turn_in_flight() saw a running cron job+ 'probe-error': null+ })++ h.pool.set('old-runtime', resident(500_000))+ h.pool.set('cron-mid-run', resident(400_000))+ h.pool.set('probe-error', resident(300_000))++ assert.equal(await h.retirer.retireForForeground('new'), null)+ assert.deepEqual(h.probes.sort(), ['cron-mid-run', 'old-runtime', 'probe-error'])+ assert.deepEqual(h.stopped, [])+ assert.equal(h.retirer.inFlight(), false, 'a null result releases the fence for the next dial')+})++test('a renderer activeTurn:false is not proof: the backend re-probe before SIGTERM wins', async () => {+ // Renderer says idle; the backend says a turn started (a messaging-platform+ // turn, a cron fire) between the selection probe and the commit re-probe.+ const h = harness({ 'bot-a': [true, false] })+ h.pool.set('bot-a', resident(300_000, { activeTurn: false }))++ const retirement = await h.retirer.retireForForeground('new')+ assert.equal(retirement?.key, 'bot-a')+ assert.equal(await retirement!.commit(), false)+ assert.deepEqual(h.stopped, [])+ assert.deepEqual(h.probes, ['bot-a', 'bot-a'])+})diff --git a/apps/desktop/electron/pool-retire.ts b/apps/desktop/electron/pool-retire.tsnew file mode 100644index 00000000000..8fde7ce9992--- /dev/null+++ b/apps/desktop/electron/pool-retire.ts@@ -0,0 +1,213 @@+// Cooperative retirement of a provably idle pooled backend for a foreground dial.+//+// The local pool caps spawned `hermes serve` children (3 by default) and a+// child's hard slot lease lives exactly as long as the child. The renderer+// keeps every open socket's entry keepalive-fresh (60s touch), so LRU eviction+// and the idle reaper — both keyed off lastActiveAt — never free a slot held by+// a bot tile that is merely pinned. Occupied is not busy: two pinned residents+// plus one foreground resident fill the pool and the fourth foreground open+// waits 30s for a slot that nothing will release, then times out.+//+// This module lets a foreground dial retire ONE resident, under these rules:+//+// * Proof comes from the backend. Every candidate is probed+// (`/api/health/idle`: running sessions + running cron jobs + prompts+// waiting on a human) and only `true` is idle. `false` and `null` (an older+// runtime, a probe error, an unreadable ledger) are both busy. The+// renderer-published `activeTurn` lease is an early skip, never the proof —+// it cannot see cron fires or messaging turns on a pooled backend.+// * Admission fence. Concurrent foreground dials share one retirement; the+// coordinator hands the freed slot to whichever ticket queued first.+// * Identity is rechecked after every await (`pool.get(key) === entry`), and+// the candidate is re-probed immediately before SIGTERM: a turn may have+// started while the waiter queued.+// * The slot is released only by the caller's `stopBackend`, i.e. after the+// child has actually exited (stopPoolBackend → releaseLocalBackendSlot).+// Nothing here touches the lease.+// * `onRetiring(key)` fires before the stop so the renderer can park the+// scope instead of redialing into the slot it just vacated.+//+// Pure/DI-testable like pool-spawn-coordinator.ts and pool-stop.ts. Trigger+// point (foreground dial at activeCount >= cap, before coordinator.request)+// and the LRU-among-eligible selector shape are from #104871 by @bounce12340.++export interface PoolRetireEntry {+ /** Renderer-published prompt-turn lease (`touchBackend(scope, { activeTurn })`). Undefined = unknown. */+ activeTurn?: boolean+ lastActiveAt?: null | number+ process?: unknown+}++/** true = the backend proved it is idle; false = busy; null = cannot prove (treated as busy). */+export type IdleVerdict = boolean | null++export interface PoolRetirerDeps<E extends PoolRetireEntry> {+ pool: Map<string, E>+ /** Ask the backend itself. Must never throw; map every failure to null. */+ probeIdle: (key: string, entry: E) => Promise<IdleVerdict>+ /** Bounded teardown; resolves only after the child has actually exited and its slot was released. */+ stopBackend: (key: string) => Promise<void>+ /** Fires before the stop so the renderer parks the scope instead of redialing. */+ onRetiring?: (key: string) => void+ log?: (message: string) => void+}++export interface PoolRetirement {+ key: string+ /**+ * Final identity + idle recheck, then stop. Resolves true when the child was+ * retired (after its real exit), false when the recheck aborted. Idempotent:+ * every foreground dial sharing this retirement gets the same promise.+ */+ commit: () => Promise<boolean>+ /** Release the fence without stopping anything (the caller failed before it could queue). */+ abandon: () => void+}++export interface PoolRetirer {+ /**+ * Find a resident this foreground dial may retire. Resolves null when no+ * candidate can prove idle (the dial falls through to the ordinary slot+ * queue). While a retirement is being prepared or committed, every caller+ * shares it.+ */+ retireForForeground: (waiterKey: string) => Promise<PoolRetirement | null>+ /** Test/diagnostic: whether a retirement is in flight. */+ inFlight: () => boolean+}++/**+ * Spawned residents a foreground dial may consider, least-recently-used first.+ * Entries without a child (descriptors, spawns still queued) hold no slot;+ * entries the renderer reports as mid-turn are skipped early; the waiter's own+ * key is never a candidate. Unknown activity (`activeTurn` undefined) stays+ * eligible — the backend probe decides, not the renderer.+ */+export function selectRetirementCandidates<K, E extends PoolRetireEntry>(+ entries: Iterable<[K, E]>,+ exclude: ReadonlySet<K>+): [K, E][] {+ return [...entries]+ .filter(([key, entry]) => Boolean(entry.process) && entry.activeTurn !== true && !exclude.has(key))+ .sort((a, b) => (a[1].lastActiveAt || 0) - (b[1].lastActiveAt || 0))+}++export function createPoolRetirer<E extends PoolRetireEntry>(deps: PoolRetirerDeps<E>): PoolRetirer {+ let inFlight: Promise<PoolRetirement | null> | null = null++ const log = (message: string) => deps.log?.(message)++ // Still the same live entry, and the renderer has not leased a turn since.+ const stillRetirable = (key: string, entry: E): boolean =>+ deps.pool.get(key) === entry && entry.activeTurn !== true++ function makeRetirement(key: string, entry: E, release: () => void): PoolRetirement {+ let committed: Promise<boolean> | null = null++ return {+ key,+ commit: () => {+ if (committed) {+ return committed+ }++ committed = (async () => {+ try {+ // Re-probe right before the stop: the waiter's request() is queued+ // by now, so whatever this proves holds for the slot handoff.+ const verdict = await deps.probeIdle(key, entry)++ if (verdict !== true || !stillRetirable(key, entry)) {+ log(`Pool retirement of "${key}" aborted: backend no longer provably idle`)++ return false+ }++ deps.onRetiring?.(key)+ log(`Retiring provably idle profile backend "${key}" for a foreground dial`)+ // stopBackend must SIGTERM synchronously on entry (pool-stop.ts does):+ // no await sits between the recheck above and the signal.+ await deps.stopBackend(key)++ return true+ } finally {+ release()+ }+ })()++ return committed+ },+ abandon: () => {+ if (!committed) {+ release()+ }+ }+ }+ }++ async function prepare(waiterKey: string, release: () => void): Promise<PoolRetirement | null> {+ const candidates = selectRetirementCandidates(deps.pool.entries(), new Set([waiterKey]))++ for (const [key, entry] of candidates) {+ const verdict = await deps.probeIdle(key, entry)++ if (verdict !== true) {+ log(`Pool resident "${key}" not retirable for a foreground dial (idle=${String(verdict)})`)++ continue+ }++ // Identity recheck after the await: a reaper, a delete, or an exit may+ // have replaced or removed the entry while the probe was in flight.+ if (!stillRetirable(key, entry)) {+ continue+ }++ return makeRetirement(key, entry, release)+ }++ return null+ }++ return {+ retireForForeground: waiterKey => {+ if (inFlight) {+ return inFlight+ }++ let released = false+ let run: Promise<PoolRetirement | null> | null = null++ const release = () => {+ if (released) {+ return+ }++ released = true++ if (inFlight === run) {+ inFlight = null+ }+ }++ run = prepare(waiterKey, release).then(+ retirement => {+ if (!retirement) {+ release()+ }++ return retirement+ },+ error => {+ release()+ throw error+ }+ )++ inFlight = run++ return run+ },+ inFlight: () => inFlight !== null+ }+}diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex bdc375f3c86..ac579c66133 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -32,7 +32,7 @@ contextBridge.exposeInMainWorld('hermesDesktop', {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),+ touchBackend: (profile, options) => ipcRenderer.invoke('hermes:backend:touch', profile, options),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),@@ -516,6 +516,15 @@ contextBridge.exposeInMainWorld('hermesDesktop', {return () => ipcRenderer.removeListener('hermes:backend-exit', listener)},+ // Cooperative pool retirement (main → renderer): the pooled backend under+ // `poolKey` is being stopped for a foreground open. Park that scope; do not+ // redial into the slot it vacated.+ onPoolBackendRetiring: callback => {+ const listener = (_event, payload) => callback(payload)+ ipcRenderer.on('hermes:pool:retiring', listener)++ return () => ipcRenderer.removeListener('hermes:pool:retiring', listener)+ },// Soft gateway-mode apply finished tearing down the primary backend. Renderer// should wipe session lists + re-dial without a window reload.onConnectionApplied: callback => {diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex ebf15fe9ac3..34f15f1ebf9 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -52,8 +52,10 @@ declare global {// 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 }>+ // reaper spares it while its chat is active. `activeTurn` reports whether+ // a prompt turn leases the backend (early skip for cooperative+ // retirement; the backend probe is the proof).+ touchBackend: (profile?: string | null, options?: { activeTurn?: boolean }) => 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.@@ -542,6 +544,9 @@ declare global {) => () => voidonPreviewFileChanged: (callback: (payload: HermesPreviewFileChanged) => void) => () => voidonBackendExit: (callback: (payload: BackendExit) => void) => () => void+ // Cooperative pool retirement: main is stopping the pooled backend under+ // `poolKey` for a foreground open. The renderer parks that scope.+ onPoolBackendRetiring?: (callback: (payload: { poolKey: string }) => void) => () => void// Soft gateway-mode apply: primary backend was torn down without a window// reload. Wipe session lists (skeletons) and re-dial.onConnectionApplied?: (callback: () => void) => () => void