The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): serialize idle reclamation and release slots on real exit
brooklyn!768e5c2af366
diff --git a/apps/desktop/electron/backend-child.ts b/apps/desktop/electron/backend-child.tsindex 398d779f831..3e52df08d62 100644--- a/apps/desktop/electron/backend-child.ts+++ b/apps/desktop/electron/backend-child.ts@@ -52,8 +52,8 @@ export interface KillableChild extends BackendProcessRoot {export interface WaitableChild extends KillableChild {exitCode: number | nullsignalCode: string | null- once: (event: 'exit', listener: () => void) => unknown- removeListener: (event: 'exit', listener: () => void) => unknown+ once: (event: 'exit' | 'error', listener: () => void) => unknown+ removeListener: (event: 'exit' | 'error', listener: () => void) => unknown}/** Graceful exit, SIGKILL escalation, then a bounded wait for the escalation. */@@ -106,10 +106,16 @@ export async function waitForBackendExit(child.kill('SIGKILL')}} catch {- return+ // A failed signal may mean the child is gone, but only exit proves it.}await wait(1000)++ if (!exited()) {+ throw new Error(+ `Backend child${child.pid ? ` (PID ${child.pid})` : ''} did not exit after SIGKILL; retaining ownership.`+ )+ }}/**diff --git a/apps/desktop/electron/backend-exit.test.ts b/apps/desktop/electron/backend-exit.test.tsindex 4380dc8c984..35e1de13214 100644--- a/apps/desktop/electron/backend-exit.test.ts+++ b/apps/desktop/electron/backend-exit.test.ts@@ -11,8 +11,16 @@ test('backend exit escalation remains bounded when no exit or close arrives', astry {const child = Object.assign(new EventEmitter(), { exitCode: null, signalCode: null, kill: vi.fn() })const waiting = waitForBackendExit(child, { forceKillProcessTree: () => {} }, 20)++ const outcome = waiting.then(+ () => null,+ error => error+ )+await vi.advanceTimersByTimeAsync(1020)- await waiting+ assert.match(String(await outcome), /did not exit/)+ assert.equal(child.exitCode, null)+ assert.equal(child.signalCode, null)assert.equal(child.kill.mock.calls.length, 1)assert.equal(child.kill.mock.calls[0][0], 'SIGKILL')assert.equal(child.listenerCount('exit'), 0)@@ -21,3 +29,29 @@ test('backend exit escalation remains bounded when no exit or close arrives', asvi.useRealTimers()}})++test('a failed escalation is not evidence that the child exited', async () => {+ vi.useFakeTimers()++ try {+ const child = Object.assign(new EventEmitter(), {+ exitCode: null,+ signalCode: null,+ kill: () => {+ throw new Error('signal denied')+ }+ })++ const outcome = waitForBackendExit(child, { forceKillProcessTree: () => {} }, 20).then(+ () => null,+ error => error+ )++ await vi.advanceTimersByTimeAsync(1020)+ assert.match(String(await outcome), /did not exit/)+ assert.equal(child.listenerCount('exit'), 0)+ assert.equal(vi.getTimerCount(), 0)+ } finally {+ vi.useRealTimers()+ }+})diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 72fc855ad4b..febdad1286f 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -301,9 +301,9 @@ import {localRouteFallbackProfiles,undialedSshRouteSeeds} from './plugin-profile-routes'-import { evictPoolEntries } from './pool-eviction'import { clampPoolLimits, parsePoolLimits, POOL_LIMITS_DEFAULTS } from './pool-limits'import { createPoolRetirer } from './pool-retire'+import { createPoolRetirementClient } from './pool-retire-http'import {BackgroundSlotRetryBackoff,BackgroundSlotRetryDeferredError,@@ -312,6 +312,7 @@ import {LocalBackendSpawnCoordinator,type LocalBackendSpawnPriority,type LocalBackendSpawnRequest,+ registerLocalBackendExitFinalizer,releaseLocalBackendSlotAfterExit} from './pool-spawn-coordinator'import { createPoolStopper } from './pool-stop'@@ -1630,6 +1631,12 @@ function logPoolSpawnFailure(label: string, error: unknown): void {// 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 {+ // The renderer's socket-close event may beat its parking IPC. Main owns+ // this fence too, so that race cannot resurrect the retired generation.+ for (const key of poolTouchKeys(scopeKey)) {+ poolRetirer.assertCanOpen(key, spawnPriority)+ }+if (spawnPriority !== 'foreground') {return () => undefined}@@ -11474,6 +11481,7 @@ async function ensureBackend(profile, opts: { passive?: boolean; spawnPriority?:localBackendLifecycle.assertCanStart()const key = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()const spawnPriority = spawnPriorityFrom(opts.spawnPriority)+ poolRetirer.assertCanOpen(key, spawnPriority)const passive = Boolean(opts.passive)profileDeletionGate.assertCanStart(key)@@ -12451,16 +12459,7 @@ function touchPoolBackend(profile, options: { activeTurn?: boolean } = {}) {// was merely idle past the keepalive window. Descriptors are still reclaimed// by the idle reaper.async function evictLruPoolBackends(keep) {- return evictPoolEntries(- backendPool.entries(),- Math.max(0, keep),- Date.now(),- POOL_KEEPALIVE_FRESH_MS,- async profile => {- rememberLog(`Evicting idle profile backend "${profile}" (LRU cap ${poolMaxBackends()})`)- await stopPoolBackend(profile)- }- )+ return poolRetirer.evictTo(Math.max(0, keep), POOL_KEEPALIVE_FRESH_MS)}function startPoolIdleReaper() {@@ -12473,8 +12472,12 @@ function startPoolIdleReaper() {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)+ // Remote descriptors hold no child/slot. Local children require the+ // same admission authority as foreground and LRU reclamation.+ const retiring = entry.process+ ? poolRetirer.retireIdle(profile, poolIdleMs())+ : stopPoolBackend(profile)+ void retiring.catch(error => rememberLog(`Pool idle retirement failed: ${String(error)}`))}}@@ -12542,11 +12545,6 @@ function teardownFailedLocalBackend(poolKey: string, entry: any): Promise<void>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.`)- }-releaseBackendChild(child)})@@ -12618,23 +12616,8 @@ 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- }-+ // The arbiter subscribes to the actual coordinator queue, so a later+ // foreground promotion receives reclamation too, not just fresh starts.const spawnRequest = localBackendSpawnCoordinator.request(poolKey, {timeoutMs: POOL_SLOT_WAIT_MS,priority: spawnPriority@@ -12643,12 +12626,6 @@ 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)`@@ -12773,6 +12750,7 @@ async function runPoolBackendStart(profile, entry, opts: { forceLocal?: boolean;entry.process = childentry.token = token+ registerLocalBackendExitFinalizer(backendPool, poolKey, entry, () => releaseLocalBackendSlot(entry))// Buffer stdout+stderr from the instant of spawn (#93608): an early crash's// traceback must survive into the claim error and the before-ready exit// message instead of a bare exit code. rememberLog attaches later, after@@ -12780,32 +12758,14 @@ async function runPoolBackendStart(profile, entry, opts: { forceLocal?: boolean;const outputTail = createBackendOutputTail()outputTail.attach(child)- // Start watching for the READY announcement BEFORE any await (#60323):- // stdout is already flowing into the tail, and Node streams never replay- // consumed chunks to late listeners — a sentinel printed while- // claimBackendChild runs would otherwise be lost forever, timing out a- // healthy backend. The tail-buffer accessor covers any residual gap.- const portAnnouncement = waitForDashboardPortAnnouncement(child, {- bufferedOutput: () => outputTail.text(),- describeOutputTail: () => outputTail.describe(),- readyFile- })-- // Mark handled so an early rejection (child dies during the claim) can't- // surface as an unhandled rejection before the Promise.race below attaches.- portAnnouncement.catch(() => {})- await claimBackendChild(child, `${backend.command} ${backend.args.join(' ')}`, profile, backendNonce, outputTail)- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })-- child.stdout.on('data', rememberLog)- child.stderr.on('data', rememberLog)-let ready = falselet rejectStart = nullconst startFailed = new Promise((_resolve, reject) => {rejectStart = reject})+ // Exit/error can now arrive while the ownership claim is still pending.+ startFailed.catch(() => {})child.once('error', error => {rememberLog(`Hermes backend for profile "${profile}" failed to start: ${error.message}`)@@ -12818,13 +12778,8 @@ async function runPoolBackendStart(profile, entry, opts: { forceLocal?: boolean;})child.once('exit', (code, signal) => {rememberLog(formatBackendExitLine(`Hermes backend for profile "${profile}" exited`, code, signal, outputTail))- releaseLocalBackendSlot(entry)releaseBackendChild(child)- if (backendPool.get(poolKey) === entry) {- backendPool.delete(poolKey)- }-if (!ready) {rejectStart?.(new Error(@@ -12834,7 +12789,23 @@ async function runPoolBackendStart(profile, entry, opts: { forceLocal?: boolean;}})- // Discover the ephemeral port the child bound to+ // Start watching for the READY announcement BEFORE any await (#60323):+ // stdout is already flowing into the tail, and Node streams never replay+ // consumed chunks to late listeners — a sentinel printed while+ // claimBackendChild runs would otherwise be lost forever, timing out a+ // healthy backend. The tail-buffer accessor covers any residual gap.+ const portAnnouncement = waitForDashboardPortAnnouncement(child, {+ bufferedOutput: () => outputTail.text(),+ describeOutputTail: () => outputTail.describe(),+ readyFile+ })+ portAnnouncement.catch(() => {})+ await claimBackendChild(child, `${backend.command} ${backend.args.join(' ')}`, profile, backendNonce, outputTail)+ assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })++ child.stdout.on('data', rememberLog)+ child.stderr.on('data', rememberLog)+const port = await Promise.race([portAnnouncement, startFailed])assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })@@ -12908,31 +12879,19 @@ const poolStopper = createPoolStopper({}})-async function stopPoolBackend(profile: string) {+function stopPoolBackend(profile: string): Promise<void> {const entry = backendPool.get(profile)- await poolStopper.stop(profile)- 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- })+ const stopping = releaseLocalBackendSlotAfterExit(+ () => releaseLocalBackendSlot(entry),+ () => poolStopper.stop(profile)+ )+ // Fire-and-forget callers still need diagnostics; awaiters receive the+ // rejection, while physical ownership and the exit finalizer remain live.+ void stopping.catch(error => {+ rememberLog(`Profile backend "${profile}" stop failed: ${error instanceof Error ? error.message : String(error)}`)+ })- return body?.idle === true ? true : body?.idle === false ? false : null- } catch {- return null- }+ return stopping}// Tell every window the pooled backend under `poolKey` is being retired so the@@ -12948,13 +12907,15 @@ function broadcastPoolBackendRetiring(poolKey: string) {}}-const poolRetirer = createPoolRetirer<any>({+const poolRetirer = createPoolRetirer({pool: backendPool,- probeIdle: (_key, entry) => probePoolBackendIdle(entry),+ coordinator: localBackendSpawnCoordinator,+ ...createPoolRetirementClient(fetchJson),stopBackend: stopPoolBackend,onRetiring: broadcastPoolBackendRetiring,log: rememberLog})+localBackendLifecycle.signal.addEventListener('abort', poolRetirer.dispose, { once: true })async function teardownPoolBackendAndWait(profile) {await Promise.all(localProfilePoolKeys(profile).map(key => stopPoolBackend(key)))diff --git a/apps/desktop/electron/pool-child-exit.test.ts b/apps/desktop/electron/pool-child-exit.test.tsnew file mode 100644index 00000000000..e86933cb653--- /dev/null+++ b/apps/desktop/electron/pool-child-exit.test.ts@@ -0,0 +1,141 @@+import assert from 'node:assert/strict'+import { spawn } from 'node:child_process'+import { EventEmitter } from 'node:events'+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { test, vi } from 'vitest'++import { stopBackendChild, type WaitableChild, waitForBackendExit } from './backend-child'+import { createLocalBackendLifecycle } from './local-backend-lifecycle'+import {+ LocalBackendSpawnCoordinator,+ registerLocalBackendExitFinalizer,+ releaseLocalBackendSlotAfterExit+} from './pool-spawn-coordinator'+import { createPoolStopper } from './pool-stop'++test('bounded stop retains a live child and its slot until late exit, without evicting a successor', async () => {+ vi.useFakeTimers()++ try {+ // A child that acknowledges signals without exiting exercises the otherwise+ // unprovable OS failure path; the waiter, stopper, lifecycle and allocator are real.+ const child = Object.assign(new EventEmitter(), {+ exitCode: null as number | null,+ signalCode: null as string | null,+ kill: vi.fn()+ })++ const deps = { forceKillProcessTree: () => {} }++ const lifecycle = createLocalBackendLifecycle<WaitableChild>({+ stopChild: child => stopBackendChild(child, deps),+ waitForExit: child => waitForBackendExit(child, deps, 20),+ cancelSetup: () => {}+ })++ const coordinator = new LocalBackendSpawnCoordinator(1)+ const release = await coordinator.acquire('profile')+ const entry = { process: lifecycle.spawn(() => child) }+ const pool = new Map<string, { process: WaitableChild | null }>([['profile', entry]])+ child.once('exit', () => lifecycle.release(child))+ registerLocalBackendExitFinalizer(pool, 'profile', entry, release)++ const stopper = createPoolStopper({+ pool,+ stopChild: child => stopBackendChild(child as WaitableChild, deps),+ waitForExit: child => waitForBackendExit(child as WaitableChild, deps, 20)+ })++ const next = coordinator.request('profile')+ const stopping = releaseLocalBackendSlotAfterExit(release, () => stopper.stop('profile'))++ const outcome = stopping.then(+ () => null,+ error => error+ )++ await vi.advanceTimersByTimeAsync(1020)+ assert.match(String(await outcome), /did not exit/)+ assert.equal(lifecycle.hasPending(), true, 'bounded failure must retain physical ownership')+ assert.equal(coordinator.activeCount, 1)+ assert.equal(coordinator.queuedCount, 1, 'timeout is not a free slot')++ // A replacement routing generation may already be waiting for the old lease.+ const successor = { process: null }+ pool.set('profile', successor)+ child.signalCode = 'SIGKILL'+ child.emit('exit', null, child.signalCode)+ const releaseNext = await next.acquired+ assert.equal(lifecycle.hasPending(), false)+ assert.equal(pool.get('profile'), successor)+ assert.equal(coordinator.activeCount, 1)+ assert.equal(coordinator.queuedCount, 0)++ child.emit('exit', null, child.signalCode)+ await releaseLocalBackendSlotAfterExit(release, () => waitForBackendExit(child, deps, 20))+ assert.equal(coordinator.activeCount, 1, 'old exit and cleanup cannot release the successor lease')+ assert.equal(child.listenerCount('exit'), 0)+ assert.equal(vi.getTimerCount(), 0)+ releaseNext()+ assert.equal(coordinator.activeCount, 0)+ } finally {+ vi.useRealTimers()+ }+})++test('real spawn failures finalize before a pending identity claim settles', async () => {+ const home = mkdtempSync(join(tmpdir(), 'pool-child-exit-'))++ try {+ // Exercise both an early crash and spawn's no-PID error (which has no exit event).+ for (const command of [process.execPath, join(home, 'missing-backend')]) {+ const coordinator = new LocalBackendSpawnCoordinator(1)+ const release = await coordinator.acquire('profile')++ const child = spawn(command, ['-e', 'process.exit(17)'], {+ env: { ...process.env, HERMES_HOME: home },+ stdio: 'ignore'+ })++ const entry = { process: child }+ const pool = new Map([['profile', entry]])++ const ended = new Promise<void>(resolve => {+ child.once('exit', () => resolve())+ child.once('error', () => resolve())+ })++ registerLocalBackendExitFinalizer(pool, 'profile', entry, release)+ let finishClaim!: () => void++ const claim = new Promise<void>(resolve => {+ finishClaim = resolve+ })++ let claimSettled = false++ const claimed = claim.then(() => {+ claimSettled = true+ })++ await ended+ assert.equal(claimSettled, false)+ assert.equal(coordinator.activeCount, 0, 'early failure must not wait for the identity claim')+ assert.equal(pool.has('profile'), false)++ const releaseNext = await coordinator.acquire('profile')+ finishClaim()+ await claimed+ await releaseLocalBackendSlotAfterExit(release, () =>+ waitForBackendExit(child, { forceKillProcessTree: () => {} }, 20)+ )+ assert.equal(coordinator.activeCount, 1, 'late failed-start cleanup owns only the old lease')+ releaseNext()+ }+ } finally {+ rmSync(home, { recursive: true, force: true })+ }+})diff --git a/apps/desktop/electron/pool-reclamation.test.ts b/apps/desktop/electron/pool-reclamation.test.tsnew file mode 100644index 00000000000..80df7a891d3--- /dev/null+++ b/apps/desktop/electron/pool-reclamation.test.ts@@ -0,0 +1,111 @@+import assert from 'node:assert/strict'++import { test, vi } from 'vitest'++import { createPoolRetirer, type PoolRetireEntry } from './pool-retire'+import { LocalBackendSpawnCoordinator } from './pool-spawn-coordinator'++function harness() {+ const coordinator = new LocalBackendSpawnCoordinator(3)+ const pool = new Map<string, PoolRetireEntry>()+ const releases = new Map<string, () => void>()+ const exits = new Map<string, () => void>()+ const stopped: string[] = []+ const cancelled: string[] = []+ const prepared: string[] = []+ let prepare = async (key: string) => `${key}-permit`++ const retirer = createPoolRetirer({+ pool,+ coordinator,+ prepare: async key => {+ prepared.push(key)++ return prepare(key)+ },+ commit: async () => true,+ cancel: async key => { cancelled.push(key) },+ stopBackend: key => new Promise<void>(resolve => {+ stopped.push(key)+ pool.delete(key)+ exits.set(key, () => {+ releases.get(key)?.()+ resolve()+ })+ }),+ })++ async function seed() {+ for (const [index, key] of ['a', 'b', 'c'].entries()) {+ releases.set(key, await coordinator.acquire(key))+ pool.set(key, { process: {}, lastActiveAt: index })+ }+ }++ return { coordinator, pool, releases, exits, stopped, cancelled, prepared, retirer, seed,+ setPrepare: (fn: typeof prepare) => { prepare = fn } }+}++test('reclamation sequences every foreground waiter, including an already queued background promotion', async () => {+ const h = harness()+ await h.seed()+ const first = h.coordinator.request('d', { priority: 'foreground' })+ const second = h.coordinator.request('e', { priority: 'background' })+ second.promote('foreground')+ let granted = 0+ void first.acquired.then(() => { granted += 1 }).catch(() => undefined)+ void second.acquired.then(() => { granted += 1 }).catch(() => undefined)++ try {+ await vi.waitFor(() => assert.deepEqual(h.stopped, ['a']), { timeout: 2000 })+ assert.equal(h.coordinator.activeCount, 3, 'a signal does not release a slot')+ assert.equal(granted, 0)+ assert.throws(() => h.retirer.assertCanOpen('a', 'background'), /retired/i)+ assert.doesNotThrow(() => h.retirer.assertCanOpen('a', 'foreground'))+ h.exits.get('a')!()+ await vi.waitFor(() => assert.deepEqual(h.stopped, ['a', 'b']))+ assert.equal(granted, 1)+ h.exits.get('b')!()+ await Promise.all([first.acquired, second.acquired])+ assert.equal(granted, 2)+ assert.equal(h.coordinator.queuedCount, 0)+ } finally {+ void first.acquired.catch(() => undefined)+ void second.acquired.catch(() => undefined)+ first.cancel()+ second.cancel()+ h.retirer.dispose?.()+ }+})++test('withdrawn demand or replaced candidates cancel prepared authority without stopping a resident', async () => {+ for (const change of ['capacity', 'withdrawal', 'identity'] as const) {+ const h = harness()+ await h.seed()+ let finishPrepare!: (value: string) => void+ h.setPrepare(() => new Promise(resolve => { finishPrepare = resolve }))+ const ticket = h.coordinator.request('d', { priority: 'foreground' })+ void ticket.acquired.catch(() => undefined)++ try {+ await vi.waitFor(() => assert.ok(finishPrepare), { timeout: 2000 })++ if (change === 'capacity') {+ h.releases.get('c')!()+ h.pool.delete('c')+ } else if (change === 'withdrawal') {+ ticket.cancel()+ } else {+ h.pool.set('a', { process: {}, lastActiveAt: 100 })+ ticket.cancel()+ }++ finishPrepare('a-permit')+ await vi.waitFor(() => assert.deepEqual(h.cancelled, ['a']))+ assert.deepEqual(h.stopped, [])+ } finally {+ ticket.cancel()+ h.retirer.dispose?.()+ }+ }+})diff --git a/apps/desktop/electron/pool-retire-http.ts b/apps/desktop/electron/pool-retire-http.tsnew file mode 100644index 00000000000..c102906213b--- /dev/null+++ b/apps/desktop/electron/pool-retire-http.ts@@ -0,0 +1,53 @@+interface PoolBackend {+ process?: unknown+ port?: number | null+ token?: string | null+}++interface RetirementReply {+ ok?: boolean+ idle?: boolean | null+ token?: string+}++type RequestJson = (+ url: string,+ token: string,+ options: { method: string; body: Record<string, string>; timeoutMs: number }+) => Promise<unknown>++/** Use the app's authenticated transport, never a descriptor's remote URL. */+export function createPoolRetirementClient(requestJson: RequestJson) {+ async function request(entry: PoolBackend, action: string, token?: string): Promise<RetirementReply | null> {+ if (!entry.process || !entry.port || !entry.token) {+ return null+ }++ try {+ return await requestJson(`http://127.0.0.1:${entry.port}/api/health/retirement`, entry.token, {+ method: 'POST',+ body: { action, ...(token ? { token } : {}) },+ timeoutMs: 3000,+ }) as RetirementReply | null+ } catch {+ // An older runtime, transport failure or unreadable reply grants no+ // authority. Prepared permits expire; committed ones remain recoverable+ // through idempotent prepare/commit on this exact backend generation.+ return null+ }+ }++ return {+ prepare: async (_key: string, entry: PoolBackend): Promise<string | null> => {+ const reply = await request(entry, 'prepare')++ return reply?.ok === true && reply.idle === true && typeof reply.token === 'string' && reply.token+ ? reply.token : null+ },+ commit: async (_key: string, entry: PoolBackend, token: string): Promise<boolean> =>+ (await request(entry, 'commit', token))?.ok === true,+ cancel: async (_key: string, entry: PoolBackend, token: string): Promise<void> => {+ await request(entry, 'cancel', token)+ },+ }+}diff --git a/apps/desktop/electron/pool-retire.test.ts b/apps/desktop/electron/pool-retire.test.tsindex 847ca539f2c..0fbf63c5a0d 100644--- a/apps/desktop/electron/pool-retire.test.ts+++ b/apps/desktop/electron/pool-retire.test.ts@@ -2,190 +2,62 @@ import assert from 'node:assert/strict'import { test } from 'vitest'-import { createPoolRetirer, type IdleVerdict, type PoolRetireEntry, selectRetirementCandidates } from './pool-retire'+import { createPoolRetirer, 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]+test('idle and LRU retirement require backend authority, unchanged identity and current eligibility', async () => {+ for (const path of ['idle', 'lru'] as const) {+ for (const outcome of ['busy', 'unknown', 'expired', 'replaced', 'fresh', 'idle'] as const) {+ const entry: PoolRetireEntry = { process: {}, lastActiveAt: 1 }+ const pool = new Map([['a', entry]])+ const cancelled: string[] = []+ const stopped: string[] = []+ const events: string[] = []++ const retirer = createPoolRetirer({+ pool,+ coordinator: new LocalBackendSpawnCoordinator(3),+ prepare: async () => {+ if (outcome === 'replaced') {pool.set('a', { process: {}, lastActiveAt: 1 })}++ if (outcome === 'fresh') {entry.lastActiveAt = Date.now()}++ return outcome === 'busy' || outcome === 'unknown' ? null : 'permit'+ },+ commit: async () => {+ events.push('commit')++ return outcome !== 'expired'+ },+ cancel: async key => { cancelled.push(key) },+ onRetiring: () => { events.push('park') },+ stopBackend: async key => { events.push('stop'); stopped.push(key); pool.delete(key) },+ })++ try {+ if (path === 'idle') {await retirer.retireIdle('a', 1000)}+ else {await retirer.evictTo(0, 1000)}++ assert.deepEqual(stopped, outcome === 'idle' ? ['a'] : [], `${path}: ${outcome}`)++ if (outcome === 'idle') {assert.deepEqual(events, ['commit', 'park', 'stop'])}++ if (['expired', 'replaced', 'fresh'].includes(outcome)) {assert.deepEqual(cancelled, ['a'])}+ } finally {+ retirer.dispose()}-- 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')+test('candidate selection excludes processless descriptors, renderer-leased work and queued target scopes', () => {+ const pool = new Map<string, PoolRetireEntry>([+ ['fresh', { process: {}, lastActiveAt: 100 }],+ ['old', { process: {}, lastActiveAt: 1 }],+ ['busy', { process: {}, lastActiveAt: 0, activeTurn: true }],+ ['descriptor', { process: null }],+ ['target', { process: {}, lastActiveAt: 0 }],])- 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'])+ assert.deepEqual(selectRetirementCandidates(pool, new Set(['target'])).map(([key]) => key), ['old', 'fresh'])})diff --git a/apps/desktop/electron/pool-retire.ts b/apps/desktop/electron/pool-retire.tsindex 8fde7ce9992..276910d6687 100644--- a/apps/desktop/electron/pool-retire.ts+++ b/apps/desktop/electron/pool-retire.ts@@ -1,88 +1,23 @@-// 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.+import type { LocalBackendSpawnCoordinator } from './pool-spawn-coordinator'export interface PoolRetireEntry {- /** Renderer-published prompt-turn lease (`touchBackend(scope, { activeTurn })`). Undefined = unknown. */+ /** An early veto only; backend admission owns the proof. */activeTurn?: booleanlastActiveAt?: null | numberprocess?: 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. */+ coordinator: LocalBackendSpawnCoordinator+ prepare: (key: string, entry: E) => Promise<string | null>+ commit: (key: string, entry: E, token: string) => Promise<boolean>+ cancel: (key: string, entry: E, token: string) => Promise<void>stopBackend: (key: string) => Promise<void>- /** Fires before the stop so the renderer parks the scope instead of redialing. */onRetiring?: (key: string) => voidlog?: (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>@@ -92,122 +27,145 @@ export function selectRetirementCandidates<K, E extends PoolRetireEntry>(.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+/** One arbiter owns foreground recovery, idle reaping and stale LRU eviction.+ * A permit freezes backend admission; a GET snapshot never authorizes a kill.+ * Credit: @bounce12340's occupied-not-busy diagnosis, @austinpickett's parking,+ * @chelsealong's backend-work proof and @sharkenstein3d's shared stop boundary.+ */+export function createPoolRetirer<E extends PoolRetireEntry>(deps: PoolRetirerDeps<E>) {+ let serial: Promise<unknown> = Promise.resolve()+ let scheduled = false+ let disposed = false+ const retiredScopes = new Set<string>()+ let retry: ReturnType<typeof setTimeout> | undefined+ const report = (error: unknown) => deps.log?.(`Pool retirement failed: ${String(error)}`)++ function enqueue<T>(work: () => Promise<T>): Promise<T> {+ const result = serial.then(work)+ serial = result.catch(report)++ return result+ }- const log = (message: string) => deps.log?.(message)+ const needsCapacity = () => !disposed && deps.coordinator.foregroundWaiters.size > 0 &&+ deps.coordinator.activeCount >= deps.coordinator.limit- // 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+ async function retire(key: string, entry: E, needed: () => boolean): Promise<boolean> {+ const eligible = () => !disposed && deps.pool.get(key) === entry && entry.activeTurn !== true && needed()- function makeRetirement(key: string, entry: E, release: () => void): PoolRetirement {- let committed: Promise<boolean> | null = null+ if (!entry.process || !eligible()) {+ return false+ }- return {- key,- commit: () => {- if (committed) {- return committed- }+ const token = await deps.prepare(key, entry)- 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()- }- }+ if (!token) {+ return false}- }- async function prepare(waiterKey: string, release: () => void): Promise<PoolRetirement | null> {- const candidates = selectRetirementCandidates(deps.pool.entries(), new Set([waiterKey]))+ let committed = false- for (const [key, entry] of candidates) {- const verdict = await deps.probeIdle(key, entry)+ try {+ // A different resident may have exited, the waiter withdrawn, or this+ // key acquired a new generation while the HTTP prepare was outstanding.+ if (!eligible()) {+ return false+ }- if (verdict !== true) {- log(`Pool resident "${key}" not retirable for a foreground dial (idle=${String(verdict)})`)+ committed = await deps.commit(key, entry, token)- continue+ if (!committed || deps.pool.get(key) !== entry) {+ return false}- // 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- }+ // Commit is irreversible: admission remains closed even if capacity or+ // renderer intent changes now. Park before signalling the exact child.+ retiredScopes.add(key)+ deps.onRetiring?.(key)+ await deps.stopBackend(key)- return makeRetirement(key, entry, release)+ return true+ } finally {+ if (!committed) {+ await deps.cancel(key, entry, token).catch(report)+ }}-- return null}- return {- retireForForeground: waiterKey => {- if (inFlight) {- return inFlight- }-- let released = false- let run: Promise<PoolRetirement | null> | null = null+ async function reclaim(): Promise<void> {+ while (needsCapacity()) {+ let retired = false+ const candidates = selectRetirementCandidates(deps.pool, deps.coordinator.foregroundWaiters)- const release = () => {- if (released) {+ for (const [key, entry] of candidates) {+ if (!needsCapacity()) {return}- released = true+ if (await retire(key, entry, needsCapacity)) {+ retired = true- if (inFlight === run) {- inFlight = null+ break}}- run = prepare(waiterKey, release).then(- retirement => {- if (!retirement) {- release()- }-- return retirement- },- error => {- release()- throw error- }- )+ if (!retired) {+ return+ }+ }+ }++ function wake(): void {+ if (scheduled || disposed) {+ return+ }++ clearTimeout(retry)+ scheduled = true+ void enqueue(reclaim).catch(report).finally(() => {+ scheduled = false- inFlight = run+ // Busy work may finish without a renderer touch (cron / side agents).+ // The coordinator's existing ticket deadline bounds these retries.+ if (needsCapacity()) {+ retry = setTimeout(wake, 1000)+ retry.unref?.()+ }+ })+ }++ const unsubscribe = deps.coordinator.onChange(wake)++ return {+ wake,+ assertCanOpen: (key: string, priority: 'foreground' | 'background') => {+ if (priority === 'foreground') {+ retiredScopes.delete(key)+ } else if (retiredScopes.has(key)) {+ throw new Error(`Backend for "${key}" was retired; open it explicitly to reconnect.`)+ }+ },+ retireIdle: (key: string, idleMs: number) => enqueue(async () => {+ const entry = deps.pool.get(key)++ return entry ? retire(key, entry, () => Date.now() - (entry.lastActiveAt || 0) > idleMs) : false+ }),+ evictTo: (keep: number, freshMs: number) => enqueue(async () => {+ const retired: string[] = []+ const overCap = () => [...deps.pool.values()].filter(entry => entry.process).length > Math.max(0, keep)++ for (const [key, entry] of selectRetirementCandidates(deps.pool, deps.coordinator.foregroundWaiters)) {+ if (await retire(key, entry, () => overCap() && Date.now() - (entry.lastActiveAt || 0) > freshMs)) {+ retired.push(key)+ }+ }- return run+ return retired+ }),+ dispose: () => {+ disposed = true+ clearTimeout(retry)+ unsubscribe()},- inFlight: () => inFlight !== null}}diff --git a/apps/desktop/electron/pool-spawn-coordinator.ts b/apps/desktop/electron/pool-spawn-coordinator.tsindex 18516eac7c5..48d0f792154 100644--- a/apps/desktop/electron/pool-spawn-coordinator.ts+++ b/apps/desktop/electron/pool-spawn-coordinator.ts@@ -1,3 +1,5 @@+import type { WaitableChild } from './backend-child'+export type ReleaseLocalBackendSlot = () => voidexport type LocalBackendSpawnPriority = 'foreground' | 'background'@@ -94,6 +96,38 @@ export class BackgroundSlotRetryBackoff {}}+/** Register at spawn, before claiming ownership or awaiting readiness. */+export function registerLocalBackendExitFinalizer<Entry extends { process: WaitableChild | null }>(+ pool: Map<string, Entry>,+ key: string,+ entry: Entry,+ release: ReleaseLocalBackendSlot+): void {+ const child = entry.process++ const finalize = () => {+ child?.removeListener('exit', finalize)+ child?.removeListener('error', spawnFailed)++ if (pool.get(key) === entry) {+ pool.delete(key)+ }++ release()+ }++ const spawnFailed = () => {+ // Failed spawn has no PID and emits error, but never exit. A signal error+ // against an existing child is not evidence of exit and must keep its slot.+ if (!child?.pid) {+ finalize()+ }+ }++ child?.once('exit', finalize)+ child?.once('error', spawnFailed)+}+export async function releaseLocalBackendSlotAfterExit(release: ReleaseLocalBackendSlot,waitForExit: () => Promise<void>@@ -117,6 +151,23 @@ export class LocalBackendSpawnCoordinator {#activeForeground = 0#activeBackground = 0#queue: Waiter[] = []+ #listeners = new Set<() => void>()++ get foregroundWaiters(): ReadonlySet<string> {+ return new Set(this.#queue.filter(waiter => waiter.priority === 'foreground').map(waiter => waiter.key))+ }++ onChange(listener: () => void): () => void {+ this.#listeners.add(listener)++ return () => { this.#listeners.delete(listener) }+ }++ #changed(): void {+ for (const listener of this.#listeners) {+ listener()+ }+ }constructor(limit: number) {if (!Number.isInteger(limit) || limit < 1) {@@ -250,6 +301,7 @@ export class LocalBackendSpawnCoordinator {this.#queue.splice(index, 1)this.#clearTimer(waiter)waiter.reject(error)+ this.#changed()return true}@@ -320,5 +372,7 @@ export class LocalBackendSpawnCoordinator {this.#clearTimer(next)next.resolve(this.#grant('background'))}++ this.#changed()}}diff --git a/apps/desktop/electron/pool-stop.test.ts b/apps/desktop/electron/pool-stop.test.tsindex 1d759cef8a8..b1024f4de2f 100644--- a/apps/desktop/electron/pool-stop.test.ts+++ b/apps/desktop/electron/pool-stop.test.ts@@ -1,4 +1,5 @@import assert from 'node:assert/strict'+import { EventEmitter } from 'node:events'import { test } from 'vitest'@@ -220,3 +221,22 @@ test('a respawn can await the in-flight stop before reusing the key', async () =assert.deepEqual(order, ['exit-signal', 'spawn'])})++test('failed teardown blocks same-profile respawn until the actual late exit', async () => {+ const child = Object.assign(new EventEmitter(), { exitCode: null, signalCode: null })+ const pool = new Map([['profile', { process: child }]])+ const stopper = createPoolStopper({+ pool,+ stopChild: () => {},+ waitForExit: async () => { throw new Error('child did not exit') }+ })+ const stopping = stopper.stop('profile')++ await assert.rejects(stopping, /did not exit/)+ assert.equal(stopper.inFlight('profile'), stopping)+ assert.equal(stopper.hasPending(), true)+ await assert.rejects(stopper.stop('profile'), /did not exit/)+ child.emit('exit')+ assert.equal(stopper.inFlight('profile'), undefined)+ assert.equal(stopper.hasPending(), false)+})diff --git a/apps/desktop/electron/pool-stop.ts b/apps/desktop/electron/pool-stop.tsindex 7215d11c1af..047974dcb68 100644--- a/apps/desktop/electron/pool-stop.ts+++ b/apps/desktop/electron/pool-stop.ts@@ -22,6 +22,8 @@* directly instead of grepping main.ts source text.*/+import type { WaitableChild } from './backend-child'+export interface PoolStopEntry {process?: unknown}@@ -71,14 +73,29 @@ export function createPoolStopper(deps: PoolStopperDeps): PoolStopper {// below retains the process handle until the bounded exit completes.deps.pool.delete(key)+ const clear = () => {+ if (stops.get(key) === stopping) {+ stops.delete(key)+ }+ }const stopping = (async () => {deps.stopChild(entry.process)await deps.waitForExit(entry.process)if (deps.afterStop) {await deps.afterStop(key)}- })().finally(() => {- stops.delete(key)+ })().then(clear, error => {+ const child = entry.process as Partial<WaitableChild> | undefined++ if (child?.once && child.exitCode === null && child.signalCode === null) {+ // Keep rejecting reuse of this profile while the old child is alive.+ // The real late exit, not the teardown deadline, releases this fence.+ child.once('exit', clear)+ } else {+ clear()+ }++ throw error})stops.set(key, stopping)diff --git a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts b/apps/desktop/src/store/gateway-connection-lifecycle.test.tsindex 9bc77685eb1..f5f595d5db9 100644--- a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts+++ b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts@@ -764,6 +764,14 @@ describe('cooperative pool retirement (supersedes #104871)', () => {getConnectionFor.mock.calls.slice(0, dialsBefore).filter(([args]) => args.profile === 'bot-a').length)+ // Ambient hydration and relay/status RPCs must not undo the park either.+ const { requestGatewayForAgent } = await import('./gateway')+ const parkedDials = getConnectionFor.mock.calls.length+ await expect(openGatewayForAgent('local', 'bot-a')).rejects.toThrow(/retired/i)+ await expect(requestGatewayForAgent('local', 'bot-a', 'session.list')).rejects.toThrow(/retired/i)+ await expect(retainGatewayForAgent('local', 'bot-a')).rejects.toThrow(/retired/i)+ expect(getConnectionFor.mock.calls.length).toBe(parkedDials)+// Parked ≠ evicted: the entry survives for its tile, and an explicit open// (a click on the bot) is the one thing that re-arms and redials it.const before = getConnectionFor.mock.calls.lengthdiff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex d8e3608418a..3ff6186c4cb 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -369,6 +369,11 @@ async function isAttachedSharedRemote(): Promise<boolean> {const id = String(connectionId ?? '').trim()const key = normKey(profile)+ const parked = g.secondaries.get(registryBackendScopeKey(connectionId, key))++ if (parked?.retiredByPool) {+ rearmSecondary(parked, spawnPriority)+ }if (!id || !g.primaryConnectionId || id !== g.primaryConnectionId) {return false@@ -720,7 +725,11 @@ function isStalledDialError(error: unknown): boolean {return message.includes('timed out while waiting for a free slot')}-function rearmSecondary(entry: Secondary): void {+function rearmSecondary(entry: Secondary, priority: SpawnPriority = 'foreground'): void {+ if (entry.retiredByPool && priority !== 'foreground') {+ throw new Error(`Backend for "${entry.profile}" was retired; open it explicitly to reconnect.`)+ }+entry.wantOpen = trueentry.stalledDials = 0entry.retiredByPool = false@@ -926,6 +935,11 @@ async function gatewayForProfile(): Promise<{ gateway: HermesGateway | null; key: string; release: () => void; scopeProfile: boolean }> {const key = normKey(profile)const noRelease = () => undefined+ const parked = g.secondaries.get(key)++ if (parked?.retiredByPool) {+ rearmSecondary(parked, spawnPriority)+ }if (key === g.primaryProfile) {return { gateway: g.primaryGateway, key, release: noRelease, scopeProfile: false }@@ -950,7 +964,7 @@ async function gatewayForProfile(entry.retained = true}- rearmSecondary(entry)+ rearmSecondary(entry, spawnPriority)if (leaseRequest) {entry.activeRequests += 1@@ -1086,7 +1100,7 @@ export async function requestGatewayForAgent<T>(entry.retained = true}- rearmSecondary(entry)+ rearmSecondary(entry, spawnPriority)entry.activeRequests += 1try {@@ -1285,7 +1299,7 @@ export async function retainGatewayForAgent(entry.retained = true}- rearmSecondary(entry)+ rearmSecondary(entry, spawnPriority)entry.activeRequests += 1let released = false@@ -1532,7 +1546,7 @@ export async function openGatewayForAgent(const entry = g.secondaries.get(scope) ?? createSecondary(profile, connectionId)entry.retained = true- rearmSecondary(entry)+ rearmSecondary(entry, spawnPriority)if (activationLease) {// Stays held after a successful open: the activation that follows releases