Skip to content

The agent that grows with you

fix(desktop): await LRU teardown before queued wake

Mabolla919dea902029
diff --git a/apps/desktop/electron/pool-eviction.test.ts b/apps/desktop/electron/pool-eviction.test.ts
index 4ad3c3fc0de..486729114ef 100644
--- a/apps/desktop/electron/pool-eviction.test.ts
+++ b/apps/desktop/electron/pool-eviction.test.ts
@@ -11,7 +11,7 @@ import assert from 'node:assert/strict'
import { test } from 'vitest'
-import { selectPoolEvictions } from './pool-eviction'
+import { evictPoolEntries, selectPoolEvictions } from './pool-eviction'
const NOW = 1_000_000
// Mirrors main.ts POOL_KEEPALIVE_FRESH_MS (4 minutes — see #95189).
@@ -85,6 +85,39 @@ test('descriptor-only pools never evict', () => {
assert.deepEqual(selectPoolEvictions(entries, 2, NOW, FRESH_MS), [])
})
+test('making room waits for every selected backend to finish stopping', async () => {
+ let releaseStop!: () => void
+
+ const stopGate = new Promise<void>(resolve => {
+ releaseStop = resolve
+ })
+
+ const stopped: string[] = []
+ let settled = false
+
+ const entries: [string, ReturnType<typeof spawned>][] = [
+ ['oldest', spawned(500_000)],
+ ['fresh', spawned(1_000)]
+ ]
+
+ const eviction = evictPoolEntries(entries, 1, NOW, FRESH_MS, async key => {
+ stopped.push(key)
+ await stopGate
+ }).then(keys => {
+ settled = true
+
+ return keys
+ })
+
+ await Promise.resolve()
+ assert.deepEqual(stopped, ['oldest'])
+ assert.equal(settled, false, 'a replacement must not race the exiting child for its slot')
+
+ releaseStop()
+ assert.deepEqual(await eviction, ['oldest'])
+ assert.equal(settled, true)
+})
+
// ── #95189 — Keepalive-fresh window must tolerate transient missed pings ──
// Symptom: gateway restarts every ~2 minutes on WSL2. Root cause: the renderer
// pings every 60s; the LRU cap declared a backend "stale" if `lastActiveAt`
diff --git a/apps/desktop/electron/pool-eviction.ts b/apps/desktop/electron/pool-eviction.ts
index 628a3311993..e17b17ffdca 100644
--- a/apps/desktop/electron/pool-eviction.ts
+++ b/apps/desktop/electron/pool-eviction.ts
@@ -56,3 +56,26 @@ export function selectPoolEvictions<K>(
return evictions
}
+
+/**
+ * Evict enough stale spawned backends to make room, and do not report the
+ * room as available until every selected child has actually exited.
+ *
+ * Selection and teardown deliberately live in one helper: callers that fire
+ * stopBackend() without awaiting it can enqueue a replacement while the old
+ * child still owns its hard spawn slot. Under a restore stampede that race
+ * turns successful LRU selection into a 30-second queue timeout.
+ */
+export async function evictPoolEntries<K>(
+ entries: Iterable<[K, PoolEvictionEntry]>,
+ keep: number,
+ now: number,
+ freshMs: number,
+ stopBackend: (key: K) => Promise<void>
+): Promise<K[]> {
+ const evictions = selectPoolEvictions(entries, keep, now, freshMs)
+
+ await Promise.all(evictions.map(key => stopBackend(key)))
+
+ return evictions
+}