The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Refuse missing snapshots and retain slots through late claims
ethernet9e8557b78ca6
diff --git a/apps/desktop/electron/backend-stop-overlap.test.ts b/apps/desktop/electron/backend-stop-overlap.test.tsindex 09eaca82ad0..2cd57774bc9 100644--- a/apps/desktop/electron/backend-stop-overlap.test.ts+++ b/apps/desktop/electron/backend-stop-overlap.test.ts@@ -6,7 +6,13 @@ import { test } from 'vitest'import { stopBackendChild, waitForBackendExit } from './backend-child'import { createLocalBackendLifecycle } from './local-backend-lifecycle'-import { releaseLocalBackendSlotAfterExit } from './pool-spawn-coordinator'+import {+ assertPoolEntryStillOwned,+ type LocalBackendSlotEntry,+ LocalBackendSpawnCoordinator,+ releaseLocalBackendSlot,+ releaseLocalBackendSlotAfterExit+} from './pool-spawn-coordinator'import { createPoolStopper } from './pool-stop'test.skipIf(process.platform === 'win32')(@@ -87,3 +93,91 @@ test.skipIf(process.platform === 'win32')(}})++test.skipIf(process.platform === 'win32')(+ 'a claim completed after eviction retains its live child capacity',+ async (): Promise<void> => {+ const slots = new LocalBackendSpawnCoordinator(1)+ const signal = new AbortController().signal+ const unspawned: LocalBackendSlotEntry = { releaseLocalBackendSlot: await slots.acquire('not-spawned') }+ assert.throws((): void => assertPoolEntryStillOwned('not-spawned', unspawned, new Map(), signal))+ assert.equal(slots.activeCount, 0, 'pre-spawn cancellation releases its reservation')++ const physical = {+ forceKillProcessTree: (): never => {+ throw new Error('POSIX test')+ }+ }++ const lifecycle = createLocalBackendLifecycle<ChildProcess>({+ cancelSetup: (): void => {},+ stopChild: (child: ChildProcess): void => stopBackendChild(child, physical),+ waitForExit: (child: ChildProcess): Promise<void> => waitForBackendExit(child, physical)+ })++ const release = await slots.acquire('claiming')++ const child = lifecycle.spawn((): ChildProcess =>+ spawn(+ process.execPath,+ [+ '-e',+ `+ process.on('SIGTERM', () => process.send('stopping'));+ process.on('message', () => process.exit(0));+ setInterval(() => {}, 1000);+ process.send('ready');+ `+ ],+ { detached: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] }+ )+ )++ child.once('exit', (): boolean => lifecycle.release(child))+ const entry = { process: child, releaseLocalBackendSlot: release }+ const entries = new Map([['claiming', entry]])+ const pool = createPoolStopper({ pool: entries, stopChild: lifecycle.stop })+ let finishClaim!: () => void++ const claim = new Promise<void>((resolve: () => void): void => {+ finishClaim = resolve+ })++ const starting = claim.then((): void => assertPoolEntryStillOwned('claiming', entry, entries, signal))+ const rejected = assert.rejects(starting, /cancelled/)++ try {+ await once(child, 'message')+ const signalled = once(child, 'message')++ const eviction = releaseLocalBackendSlotAfterExit(+ (): void => releaseLocalBackendSlot(entry),+ (): Promise<void> => pool.stop('claiming')+ )++ await signalled+ finishClaim()+ await rejected+ assert.equal(child.exitCode, null)+ assert.equal(child.signalCode, null)+ assert.ok(pool.inFlight('claiming'))+ assert.equal(slots.activeCount, 1, 'the post-claim guard must not release a live child slot')+ const replacement = slots.request('different-profile')+ assert.equal(replacement.queued, true)+ child.send('exit')+ await eviction+ const releaseReplacement = await replacement.acquired+ assert.equal(child.exitCode, 0)+ releaseReplacement()+ assert.equal(slots.activeCount, 0)+ } finally {+ finishClaim()+ await rejected++ if (child.exitCode === null && child.signalCode === null) {+ child.kill('SIGKILL')+ await once(child, 'exit')+ }+ }+ }+)diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex a735fc591a8..1d373321618 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -310,10 +310,11 @@ import {import { selectPoolEvictions } from './pool-eviction'import { clampPoolLimits, parsePoolLimits, POOL_LIMITS_DEFAULTS } from './pool-limits'import {+ assertPoolEntryStillOwned,isBackgroundSlotWaitTimeout,LocalBackendSpawnCoordinator,type LocalBackendSpawnPriority,- type LocalBackendSpawnRequest,+ releaseLocalBackendSlot,releaseLocalBackendSlotAfterExit} from './pool-spawn-coordinator'import { createPoolStopper } from './pool-stop'@@ -11742,31 +11743,6 @@ 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): void {- if (localBackendLifecycle.signal.aborted || backendPool.get(poolKey) !== entry) {- releaseLocalBackendSlot(entry)- throw new Error(`Profile backend start for "${poolKey}" was cancelled before spawn.`)- }-}-const failedLocalBackendTeardowns = new WeakMap<object, Promise<void>>()function teardownFailedLocalBackend(poolKey: string, entry: any): Promise<void> {@@ -11805,7 +11781,11 @@ function teardownFailedLocalBackend(poolKey: string, entry: any): Promise<void>// entry means THIS machine regardless of the v1 routing table); `opts.poolKey`// is the backendPool key when it differs from the profile name (composite// registry scopes) so the exit/error cleanup evicts the right entry.-async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; poolKey?: string } = {}) {+async function spawnPoolBackend(+ profile: string,+ entry: any,+ opts: { forceLocal?: boolean; poolKey?: string } = {}+): Promise<Awaited<ReturnType<typeof backendConnectionState.getPromise>>> {const poolKey = opts.poolKey || profileawait reapOrphanedBackendsOnce()@@ -11848,7 +11828,7 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; poconst spawnPriority: LocalBackendSpawnPriority = spawnPriorityFrom(entry.spawnPriority)- assertPoolEntryStillOwned(poolKey, entry)+ assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)const spawnRequest = localBackendSpawnCoordinator.request(poolKey, {timeoutMs: POOL_SLOT_WAIT_MS,@@ -11877,7 +11857,7 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; poentry.localBackendSpawnRequest = null}- assertPoolEntryStillOwned(poolKey, entry)+ assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)const token = crypto.randomBytes(32).toString('base64url')@@ -11929,7 +11909,7 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; poconst parentStartMarker = await desktopParentStartMarker()const backendNonce = crypto.randomBytes(16).toString('hex')const parentIdentityEnv = parentWatchdogEnv(process.pid, parentStartMarker, backendNonce)- assertPoolEntryStillOwned(poolKey, entry)+ assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)const child = spawnOwnedBackend(backend.command,@@ -11984,7 +11964,7 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; po// 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)+ assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)child.stdout.on('data', rememberLog)child.stderr.on('data', rememberLog)diff --git a/apps/desktop/electron/pool-spawn-coordinator.ts b/apps/desktop/electron/pool-spawn-coordinator.tsindex 5f80af332d3..11c9c8a69f9 100644--- a/apps/desktop/electron/pool-spawn-coordinator.ts+++ b/apps/desktop/electron/pool-spawn-coordinator.ts@@ -42,6 +42,47 @@ export function isBackgroundSlotWaitTimeout(error: unknown): boolean {return error instanceof LocalBackendSlotWaitTimeoutError && error.silent}+export interface LocalBackendSlotEntry {+ process?: unknown+ releaseLocalBackendSlot?: ReleaseLocalBackendSlot | null+ localBackendSlotKey?: string | null+ localBackendSpawnRequest?: LocalBackendSpawnRequest | null+}++export function releaseLocalBackendSlot(entry: LocalBackendSlotEntry | undefined): void {+ if (!entry) {+ return+ }++ const release = entry.releaseLocalBackendSlot+ const request = entry.localBackendSpawnRequest+ entry.releaseLocalBackendSlot = null+ entry.localBackendSlotKey = null+ entry.localBackendSpawnRequest = null++ if (release) {+ release()+ } else {+ request?.cancel()+ }+}++export function assertPoolEntryStillOwned(+ poolKey: string,+ entry: LocalBackendSlotEntry,+ pool: ReadonlyMap<string, LocalBackendSlotEntry>,+ signal: AbortSignal+): void {+ if (signal.aborted || pool.get(poolKey) !== entry) {+ // A post-claim cancellation still owns a child. Its exit releases capacity.+ if (!entry.process) {+ releaseLocalBackendSlot(entry)+ }++ throw new Error(`Profile backend start for "${poolKey}" was cancelled during start.`)+ }+}+export async function releaseLocalBackendSlotAfterExit(release: ReleaseLocalBackendSlot,waitForExit: () => Promise<void>@@ -54,7 +95,8 @@ export async function releaseLocalBackendSlotAfterExit(* Bounds the number of local profile backends that are starting or running.** A lease is acquired immediately before local start work and is held until- * the child exits or the start fails. Remote descriptors never call request().+ * the child exits, or a start is cancelled before spawn. Remote descriptors+ * never call request().** When the cap is at least 2, one slot is reserved for foreground (user-open)* requests so background roster hydration cannot occupy the whole pool.diff --git a/apps/desktop/electron/updater/state-db-preflight.test.ts b/apps/desktop/electron/updater/state-db-preflight.test.tsindex 8f6a42fcc26..ab5267225de 100644--- a/apps/desktop/electron/updater/state-db-preflight.test.ts+++ b/apps/desktop/electron/updater/state-db-preflight.test.ts@@ -86,3 +86,23 @@ with sqlite3.connect(sys.argv[1]) as c:fs.rmSync(home, { recursive: true, force: true })}})++test('an older selected checkout without the snapshot helper refuses before backend stop', (): void => {+ const oldRoot: string = fs.mkdtempSync(path.join(os.tmpdir(), 'old-preflight-'))+ let stopped = false++ try {+ assert.throws((): void => {+ preflightStateDb({+ python: process.env.HERMES_PYTHON || 'python3',+ script: path.join(oldRoot, 'hermes_cli', 'backup_sqlite.py'),+ home: oldRoot,+ log: (): void => {}+ })+ stopped = true+ }, /snapshot|pre-flight/)+ assert.equal(stopped, false)+ } finally {+ fs.rmSync(oldRoot, { recursive: true, force: true })+ }+})diff --git a/apps/desktop/electron/updater/state-db-preflight.ts b/apps/desktop/electron/updater/state-db-preflight.tsindex d7c0b5ca626..bbc8ffdf615 100644--- a/apps/desktop/electron/updater/state-db-preflight.ts+++ b/apps/desktop/electron/updater/state-db-preflight.ts@@ -11,13 +11,11 @@ interface StateDbPreflight {// Synchronous by design: the caller must not stop the backend before the snapshot.export function preflightStateDb({ python, script, home, log }: StateDbPreflight): void {- if (!python) {- log('[updates] state.db pre-flight unavailable: Python not found')-- return- }-try {+ if (!python) {+ throw new Error('Python not found')+ }+const result: string = execFileSync(python,['-I', '-S', script, home],@@ -26,6 +24,11 @@ export function preflightStateDb({ python, script, home, log }: StateDbPreflightlog(`[updates] state.db pre-flight: ${result.trim()}`)} catch (error: unknown) {- log(`[updates] state.db pre-flight failed: ${error instanceof Error ? error.message : String(error)}`)+ const message =+ `state.db pre-flight failed: ${error instanceof Error ? error.message : String(error)}. ` ++ 'Update cancelled before backend shutdown. Update the selected installation with its hermes update command, then retry.'++ log(`[updates] ${message}`)+ throw new Error(message, { cause: error })}}