The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(desktop): exercise native retirement against live serve children
brooklyn!36842e639a17
diff --git a/apps/desktop/electron/pool-retirement-live-fixture/README.md b/apps/desktop/electron/pool-retirement-live-fixture/README.mdnew file mode 100644index 00000000000..98857d5c50d--- /dev/null+++ b/apps/desktop/electron/pool-retirement-live-fixture/README.md@@ -0,0 +1,59 @@+# Native pool retirement integration++From `apps/desktop`, after installing the repository-pinned Node dependencies and a+Hermes Python environment (including the serve dependencies):++```sh+HERMES_TEST_REAL_SERVE=1 \+HERMES_TEST_PYTHON=/absolute/path/to/venv/bin/python \+HERMES_TEST_ELECTRON=/absolute/path/to/native/electron \+node ../../node_modules/vitest/vitest.mjs run \+ --config electron/pool-retirement-live-fixture/vitest.config.ts+```++`HERMES_TEST_ELECTRON` is optional when Electron resolves from the desktop/root+Node installation. Point it at the native executable, not `electron/cli.js`.+The Python interpreter supplies dependencies; imports use this checkout's source.+The test is opt-in and POSIX-only (real process-group signals), not a Windows proof.+No full Electron app or Vite renderer build is required. Esbuild bundles only the+fixture entry points and their production imports into a fresh temporary directory.++## What it proves++- Native Electron's browser/main process imports production `pool-retire.ts`,+ `pool-spawn-coordinator.ts`, `pool-retire-http.ts`, and `backend-child.ts`.+- Three actual isolated Python children run headless `start_server(..., port=0)`.+ The oldest is busy with a real scheduler-dispatched, `no_agent=True` cron script:+ no fake running ledger, inference responses, or provider/model calls.+- Real session-token-authenticated HTTP covers busy refusal, unauthenticated refusal,+ prepare/cancel/reprepare, invalid-token commit refusal, commit recovery, and the+ committed fence's refusal to cancel. No retirement response is mocked.+- At cap three, a direct foreground waiter plus an already-queued background ticket+ promoted to foreground both obtain live successors. Renderer activity flags are+ false and timestamps recent: backend-only cron work still vetoes retirement.+- A fixture lifespan barrier holds each real idle child alive after SIGTERM.+ Neither its lease nor successor capacity is released during that barrier.+ The event receipt asserts commit → park → signal → held shutdown → actual exit →+ lease release → acquisition → successor spawn, and OS liveness is false at release.+- A hidden, sandboxed native renderer imports the real `src/store/gateway.ts` and+ `HermesGateway`. It opens four actual WebSockets (legacy and registry-local scopes+ for both idle children). Main sends retirement over fixture IPC before signalling.+ Both scopes stay parked after socket closure and ordinary/forced wake sweeps;+ no new descriptor request is made. Renderer Node integration is disabled.+- The cron process and script remain alive and its heartbeat advances after both+ retirements. Releasing the script completes the real job and restores HTTP idle.+- Cleanup waits for every owned backend exit and verifies the coordinator has zero+ live leases. The temporary HOME, per-child HERMES_HOME, Electron userData,+ sessionData, config/cache, random auth tokens, and OS-assigned ports are isolated.+ The launch environment is allowlisted; no real credentials are copied.++The JSON stdout receipt includes actual PIDs, ephemeral ports, HTTP outcomes, event+ordering, maximum live child count, renderer parking, and cleanup status. Failed+runs additionally report child output. The launcher captures the process handle+before exit. Keeping a `window-all-closed` listener is essential: otherwise native+Electron may exit while asynchronous cleanup is still writing the receipt.++This is a live seam integration test, **not** a full `main.ts` startup/onboarding+or application-window E2E. Descriptor/retirement IPC and shutdown pacing are fixture+wiring. The retirement arbiter, HTTP protocol, OS child exit, scheduler, renderer+parking, and WebSocket connections are real production implementations.diff --git a/apps/desktop/electron/pool-retirement-live-fixture/cron_work.py b/apps/desktop/electron/pool-retirement-live-fixture/cron_work.pynew file mode 100644index 00000000000..2c2705ff416--- /dev/null+++ b/apps/desktop/electron/pool-retirement-live-fixture/cron_work.py@@ -0,0 +1,20 @@+"""A local-only script actually dispatched by Hermes' no-agent cron scheduler."""++import json+import os+from pathlib import Path+import time++home = Path.cwd()+(home / "cron-started").write_text(json.dumps({"pid": os.getpid()}))+deadline = time.monotonic() + 150+while not (home / "finish-cron").exists():+ if time.monotonic() > deadline:+ raise RuntimeError("Native fixture did not release its cron work")+ # Atomic heartbeat: the test observes work continuing after both retirements.+ temporary = home / "cron-heartbeat.tmp"+ temporary.write_text(str(time.monotonic_ns()))+ temporary.replace(home / "cron-heartbeat")+ time.sleep(0.05)+(home / "cron-finished").write_text("completed")+print("Native retirement cron completed without a model call")diff --git a/apps/desktop/electron/pool-retirement-live-fixture/main.ts b/apps/desktop/electron/pool-retirement-live-fixture/main.tsnew file mode 100644index 00000000000..c0fb81509e9--- /dev/null+++ b/apps/desktop/electron/pool-retirement-live-fixture/main.ts@@ -0,0 +1,340 @@+import assert from 'node:assert/strict'+import { type ChildProcessWithoutNullStreams, spawn } from 'node:child_process'+import { randomUUID } from 'node:crypto'+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { setTimeout as delay } from 'node:timers/promises'++import { app, BrowserWindow, ipcMain } from 'electron'++import { stopBackendChild, waitForBackendExit } from '../backend-child'+import { createPoolRetirer } from '../pool-retire'+import { createPoolRetirementClient } from '../pool-retire-http'+import { LocalBackendSpawnCoordinator, type LocalBackendSpawnRequest, registerLocalBackendExitFinalizer } from '../pool-spawn-coordinator'++interface Resident {+ process: ChildProcessWithoutNullStreams+ home: string+ token: string+ port: number | null+ activeTurn: boolean+ lastActiveAt: number+ output: string+}+interface Receipt {+ event: string+ key?: string+ pid?: number+ active: number+ live: number+ [detail: string]: unknown+}++const [root, repo, python, fixture] = process.argv.slice(2)+assert.ok(root && repo && python && fixture)+assert.equal(process.type, 'browser')+assert.ok(process.versions.electron)+app.setPath('userData', join(root, 'user-data'))+app.setPath('sessionData', join(root, 'session-data'))+app.commandLine.appendSwitch('disable-background-networking')+// Cleanup owns app exit even after destroying the last hidden fixture window.+app.on('window-all-closed', () => {})+const coordinator = new LocalBackendSpawnCoordinator(3)+const pool = new Map<string, Resident>()+const children = new Map<string, Resident>()+const live = new Set<number>()+const receipts: Receipt[] = []+const retired: string[] = []+const opened: string[] = []+const errors: string[] = []+const tickets: LocalBackendSpawnRequest[] = []+let maxLiveServeChildren = 0+let busyCronSurvived = false+let finishing = false+let retirer: ReturnType<typeof createPoolRetirer<Resident>> | undefined+let window: BrowserWindow | undefined+let descriptorCalls = 0+let rendererParking: { parked: Record<string, string[]>; redials: number; open: number } | undefined++const stopDeps = { forceKillProcessTree: () => { throw new Error('POSIX fixture only') } }++const record = (event: string, key?: string, details: Record<string, unknown> = {}) => {+ receipts.push({ event, key, active: coordinator.activeCount, live: live.size, ...details })+}++const alive = (pid: number) => {+ try { process.kill(pid, 0);++ return true } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ESRCH') {return false}+ throw error+ }+}++async function until(description: string, predicate: () => boolean | Promise<boolean>, timeoutMs = 30_000) {+ const deadline = Date.now() + timeoutMs++ while (!await predicate()) {+ if (Date.now() > deadline) {+ throw new Error(`Timed out: ${description}\n${JSON.stringify(receipts)}\n${[...children].map(([key, entry]) => `${key}: ${entry.output}`).join('\n')}`)+ }++ await delay(30)+ }+}++async function http(entry: Resident, route: string, body?: Record<string, string>, token = entry.token) {+ const response = await fetch(`http://127.0.0.1:${entry.port}${route}`, {+ method: body ? 'POST' : 'GET', headers: {+ 'Content-Type': 'application/json', ...(token ? { 'X-Hermes-Session-Token': token } : {}),+ }, ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(5000),+ })++ return { status: response.status, body: await response.json() as Record<string, unknown> }+}++const client = createPoolRetirementClient(async (url, token, options) => {+ const response = await fetch(url, { method: options.method,+ headers: { 'X-Hermes-Session-Token': token, 'Content-Type': 'application/json' },+ body: JSON.stringify(options.body), signal: AbortSignal.timeout(options.timeoutMs) })++ const reply = await response.json() as Record<string, unknown>+ record('http', undefined, { action: options.body.action, status: response.status, ok: reply.ok, idle: reply.idle })++ if (!response.ok) {throw new Error(`Retirement HTTP ${response.status}: ${JSON.stringify(reply)}`)}++ return reply+})++async function spawnResident(key: string, release: () => void): Promise<Resident> {+ const home = join(root, key, '.hermes')+ mkdirSync(home, { recursive: true })+ writeFileSync(join(home, 'config.yaml'), 'cron:\n script_timeout: 160\n')+ const token = randomUUID()++ const child = spawn(python, ['-u', join(fixture, 'serve.py'), repo, key], {+ cwd: join(root, key), detached: true, stdio: 'pipe',+ env: { ...process.env, HOME: join(root, key), USERPROFILE: join(root, key), HERMES_HOME: home,+ HERMES_DESKTOP: '1', HERMES_SERVE_HEADLESS: '1', HERMES_DASHBOARD_SESSION_TOKEN: token,+ PYTHONUNBUFFERED: '1', PYTHONDONTWRITEBYTECODE: '1', PYTHONNOUSERSITE: '1',+ // Environment contains only the launch allowlist and fixture values.+ },+ })++ const entry: Resident = { process: child, home,+ token, port: null, activeTurn: false,+ // All residents are renderer-occupied/recent; backend-only work is the authority.+ lastActiveAt: Date.now(), output: '' }++ children.set(key, entry)+ pool.set(key, entry)+ child.on('error', error => { entry.output += String(error) })+ child.stdout.on('data', chunk => { entry.output += String(chunk) })+ child.stderr.on('data', chunk => { entry.output += String(chunk) })+ child.once('exit', (code, signal) => {+ live.delete(child.pid!)+ record('exit', key, { pid: child.pid, code, signal })+ })+ registerLocalBackendExitFinalizer(pool, key, entry, () => {+ record('release', key, { pid: child.pid, osAlive: alive(child.pid!) })+ release()+ })+ await new Promise<void>((resolveSpawn, reject) => {+ child.once('spawn', resolveSpawn)+ child.once('error', error => { release(); reject(error) })+ })+ live.add(child.pid!)+ maxLiveServeChildren = Math.max(maxLiveServeChildren, live.size)+ record('spawn', key, { pid: child.pid })+ assert.ok(live.size <= coordinator.limit, 'Live OS children exceeded the pool cap')+ await until(`${key} HERMES_BACKEND_READY`, () => {+ if (child.exitCode !== null || child.signalCode !== null) {throw new Error(`${key} exited before ready:\n${entry.output}`)}+ const match = entry.output.match(/HERMES_BACKEND_READY[^\n]*port=(\d+)/)++ if (match) {entry.port = Number(match[1])}++ return Boolean(match)+ }, 60_000)+ record('ready', key, { pid: child.pid, port: entry.port })++ return entry+}++async function run() {+ const cron = await spawnResident('cron-busy', await coordinator.acquire('cron-busy'))+ const idleA = await spawnResident('idle-a', await coordinator.acquire('idle-a'))+ await spawnResident('idle-b', await coordinator.acquire('idle-b'))+ assert.equal(coordinator.activeCount, 3)+ const cronPid = JSON.parse(readFileSync(join(cron.home, 'cron-started'), 'utf8')).pid as number+ assert.ok(alive(cronPid), 'A real no-agent cron script must be running')+ const heartbeat = readFileSync(join(cron.home, 'cron-heartbeat'), 'utf8')+ assert.equal((await http(cron, '/api/health/idle')).body.idle, false)+ assert.equal(await client.prepare('cron-busy', cron), null, 'Backend-only cron vetoes retirement')+ const unauthenticated = await http(idleA, '/api/health/retirement', { action: 'prepare' }, '')+ assert.equal(unauthenticated.status, 401)+ assert.equal(unauthenticated.body.token, undefined)+ const firstPermit = await client.prepare('idle-a', idleA)+ assert.ok(firstPermit, 'Live idle backend must implement POST prepare')+ assert.equal(await client.commit('idle-a', idleA, 'not-the-permit'), false)+ await client.cancel('idle-a', idleA, firstPermit)+ const nextPermit = await client.prepare('idle-a', idleA)+ assert.ok(nextPermit && nextPermit !== firstPermit, 'Cancel must reopen admission and revoke the old token')+ await client.cancel('idle-a', idleA, nextPermit)++ ipcMain.handle('retirement-fixture:descriptor', (_event, key: string) => {+ descriptorCalls += 1+ record('descriptor', key)+ const entry = children.get(key)+ assert.ok(entry?.port, `No real backend for ${key}`)++ return { mode: 'local', authMode: 'token', profile: key, token: entry.token,+ baseUrl: `http://127.0.0.1:${entry.port}`,+ wsUrl: `ws://127.0.0.1:${entry.port}/api/ws?token=${encodeURIComponent(entry.token)}` }+ })+ window = new BrowserWindow({ show: false, webPreferences: {+ preload: join(root, 'preload.cjs'), contextIsolation: true, nodeIntegration: false,+ sandbox: true, backgroundThrottling: false,+ } })+ await window.loadFile(join(root, 'renderer.html'))+ assert.equal(await window.webContents.executeJavaScript('window.poolRetirementRenderer.open()'), 4,+ 'Real renderer opens legacy and registry WebSockets for both idle children')+ const dialsBeforeRetirement = descriptorCalls++ retirer = createPoolRetirer<Resident>({ pool, coordinator,+ prepare: async (key, entry) => {+ const token = await client.prepare(key, entry)+ record(token ? 'prepared' : 'busy', key)++ return token+ },+ commit: async (key, entry, token) => {+ const committed = await client.commit(key, entry, token)++ if (committed) {+ assert.equal(await client.prepare(key, entry), token, 'A lost commit reply must recover the committed permit')+ assert.equal((await http(entry, '/api/health/retirement', { action: 'cancel', token })).body.ok, false,+ 'Committed retirement cannot reopen admission')+ record('committed', key)+ }++ return committed+ },+ cancel: client.cancel,+ onRetiring: key => {+ retired.push(key)+ record('park', key)+ window!.webContents.send('retirement-fixture:retiring', key)+ },+ stopBackend: async key => {+ const entry = pool.get(key)!+ record('signal', key)+ const acquiredBefore = opened.length+ stopBackendChild(entry.process, stopDeps)+ const exit = waitForBackendExit(entry.process, stopDeps, 15_000)+ await until(`${key} real SIGTERM shutdown barrier`, () => entry.output.includes('RETIREMENT_SHUTDOWN_STARTED'))+ assert.ok(alive(entry.process.pid!))+ assert.equal(entry.process.exitCode, null)+ assert.equal(entry.process.signalCode, null)+ assert.equal(coordinator.activeCount, 3, 'SIGTERM is not free capacity')+ assert.equal(opened.length, acquiredBefore, 'A successor must remain queued throughout real shutdown')+ record('shutdown-held', key)+ writeFileSync(join(entry.home, 'allow-exit'), '')+ await exit+ assert.equal(alive(entry.process.pid!), false)+ },+ log: message => { errors.push(message) },+ })+ const direct = coordinator.request('foreground-d', { timeoutMs: 45_000, priority: 'foreground' })+ const promoted = coordinator.request('promoted-e', { timeoutMs: 45_000, priority: 'background' })+ tickets.push(direct, promoted)+ assert.equal(direct.queued, true)+ assert.equal(promoted.queued, true)+ assert.equal(promoted.promote('foreground'), true)+ assert.deepEqual([...coordinator.foregroundWaiters], ['foreground-d', 'promoted-e'])+ record('waiters', undefined, { keys: [...coordinator.foregroundWaiters] })+ await Promise.all(([['foreground-d', direct], ['promoted-e', promoted]] as const).map(async ([name, ticket]) => {+ const release = await ticket.acquired+ opened.push(name)+ record('acquired', name)+ await spawnResident(name, release)+ }))+ assert.deepEqual(errors, [])+ assert.deepEqual(retired, ['idle-a', 'idle-b'])+ assert.equal(coordinator.queuedCount, 0)+ assert.equal(coordinator.activeCount, 3)++ for (const [oldKey, newKey] of [['idle-a', 'foreground-d'], ['idle-b', 'promoted-e']]) {+ const index = (event: string, key: string) => receipts.findIndex(receipt => receipt.event === event && receipt.key === key)+ assert.ok(index('committed', oldKey) < index('park', oldKey))+ assert.ok(index('park', oldKey) < index('signal', oldKey))+ assert.ok(index('signal', oldKey) < index('shutdown-held', oldKey))+ assert.ok(index('shutdown-held', oldKey) < index('exit', oldKey))+ assert.ok(index('exit', oldKey) < index('release', oldKey))+ assert.ok(index('release', oldKey) < index('acquired', newKey))+ assert.ok(index('acquired', newKey) < index('spawn', newKey))+ }++ assert.ok(receipts.filter(receipt => receipt.event === 'release').every(receipt => receipt.osAlive === false))+ assert.ok(alive(cron.process.pid!) && alive(cronPid))+ assert.equal((await http(cron, '/api/health/idle')).body.idle, false)+ await until('cron made progress after reclamation', () => readFileSync(join(cron.home, 'cron-heartbeat'), 'utf8') !== heartbeat)+ assert.equal(retired.includes('cron-busy'), false)+ busyCronSurvived = true+ const parked = await window.webContents.executeJavaScript('window.poolRetirementRenderer.wake()')+ rendererParking = { ...parked, redials: descriptorCalls - dialsBeforeRetirement }+ assert.deepEqual(rendererParking?.parked['idle-a'], ['idle-a', 'conn:local::idle-a'])+ assert.deepEqual(rendererParking?.parked['idle-b'], ['idle-b', 'conn:local::idle-b'])+ assert.equal(rendererParking?.open, 0)+ assert.equal(rendererParking?.redials, 0, 'Socket close and wake sweeps must not redial parked scopes')+ record('renderer-parked', undefined, rendererParking)+ writeFileSync(join(cron.home, 'finish-cron'), '')+ await until('real cron completed and released backend activity', async () =>+ existsSync(join(cron.home, 'cron-finished')) && !alive(cronPid) && (await http(cron, '/api/health/idle')).body.idle === true)+ record('cron-completed', 'cron-busy', { pid: cronPid })+}++async function finish(error?: unknown) {+ if (finishing) {return}+ finishing = true+ retirer?.dispose()++ for (const ticket of tickets) {ticket.cancel()}+ let cleanupError: unknown++ try {+ if (window && !window.isDestroyed()) {window.destroy()}++ for (const entry of children.values()) {+ writeFileSync(join(entry.home, 'finish-cron'), '')+ writeFileSync(join(entry.home, 'allow-exit'), '')+ }++ const cron = children.get('cron-busy')++ if (cron && existsSync(join(cron.home, 'cron-started'))) {+ const pid = JSON.parse(readFileSync(join(cron.home, 'cron-started'), 'utf8')).pid as number+ await until('cron script cleanup', () => !alive(pid), 5000).catch(() => { process.kill(pid, 'SIGKILL') })+ }++ await Promise.all([...children.values()].map(async entry => {+ stopBackendChild(entry.process, stopDeps)+ await waitForBackendExit(entry.process, stopDeps, 5000)+ }))+ assert.equal(live.size, 0)+ assert.equal(coordinator.activeCount, 0)+ } catch (caught) { cleanupError = caught }++ const failure = error || cleanupError+ writeFileSync(join(root, 'result.json'), JSON.stringify({+ ok: !failure, error: failure ? String((failure as Error).stack || failure) : undefined,+ cleanupError: cleanupError ? String(cleanupError) : undefined, cleanedUp: !cleanupError,+ electronVersion: process.versions.electron, processType: process.type,+ capacity: coordinator.limit, maxLiveServeChildren, retired, opened, busyCronSurvived,+ rendererParking, receipts,+ ...(failure ? { backendOutput: Object.fromEntries([...children].map(([key, entry]) => [key, entry.output])) } : {}),+ }, null, 2))+ app.exit(failure ? 1 : 0)+}++process.once('SIGTERM', () => { void finish(new Error('Native fixture interrupted')) })+app.whenReady().then(run).then(() => finish(), finish)diff --git a/apps/desktop/electron/pool-retirement-live-fixture/preload.ts b/apps/desktop/electron/pool-retirement-live-fixture/preload.tsnew file mode 100644index 00000000000..fed40a8f8ec--- /dev/null+++ b/apps/desktop/electron/pool-retirement-live-fixture/preload.ts@@ -0,0 +1,12 @@+import { contextBridge, ipcRenderer } from 'electron'++// Deliberate fixture IPC only; the renderer still uses production gateway/WS code.+contextBridge.exposeInMainWorld('hermesDesktop', {+ getConnection: (profile: string) => ipcRenderer.invoke('retirement-fixture:descriptor', profile),+ getConnectionFor: ({ profile }: { profile: string }) => ipcRenderer.invoke('retirement-fixture:descriptor', profile),+})+contextBridge.exposeInMainWorld('retirementFixture', {+ onRetiring: (handler: (key: string) => void) => {+ ipcRenderer.on('retirement-fixture:retiring', (_event, key: string) => handler(key))+ },+})diff --git a/apps/desktop/electron/pool-retirement-live-fixture/serve.py b/apps/desktop/electron/pool-retirement-live-fixture/serve.pynew file mode 100644index 00000000000..a3e88aab4da--- /dev/null+++ b/apps/desktop/electron/pool-retirement-live-fixture/serve.py@@ -0,0 +1,61 @@+"""Real serve entry with observable, bounded shutdown and real no-agent cron work.++Only lifecycle pacing is fixture-owned. HTTP routes, admission, scheduler dispatch,+cron ledgers, session-token auth, and uvicorn shutdown are production code.+"""++import asyncio+from contextlib import asynccontextmanager+from datetime import datetime, timezone+import os+from pathlib import Path+import shutil+import sys+import time++# The installed interpreter supplies dependencies, never the implementation.+sys.path.insert(0, sys.argv[1])+home = Path(os.environ["HERMES_HOME"])+assert home.is_relative_to(Path(os.environ["HOME"]))++if sys.argv[2] == "cron-busy":+ from cron.jobs import create_job+ from cron.scheduler import tick++ scripts = home / "scripts"+ scripts.mkdir(parents=True)+ shutil.copyfile(Path(__file__).with_name("cron_work.py"), scripts / "cron_work.py")+ job = create_job(+ prompt=None, schedule=datetime.now(timezone.utc).isoformat(),+ name="Native pool retirement work", script="cron_work.py", no_agent=True,+ deliver="local", repeat=1, workdir=str(home),+ )+ tick(verbose=False, sync=False)+ deadline = time.monotonic() + 30+ while not (home / "cron-started").exists():+ if time.monotonic() > deadline:+ raise RuntimeError(f"Real cron job {job['id']} did not start")+ time.sleep(0.03)+ print("RETIREMENT_CRON_STARTED", flush=True)++from hermes_cli.web_server import app, start_server++original_lifespan = app.router.lifespan_context+++@asynccontextmanager+async def observed_lifespan(application):+ async with original_lifespan(application):+ yield+ # Hold the real process after SIGTERM, not a fake exit promise. This+ # makes premature lease release observable even on a fast workstation.+ print("RETIREMENT_SHUTDOWN_STARTED", flush=True)+ deadline = time.monotonic() + 12+ while not (home / "allow-exit").exists():+ if time.monotonic() > deadline:+ raise RuntimeError("Native parent did not release shutdown barrier")+ await asyncio.sleep(0.03)+++app.router.lifespan_context = observed_lifespan+start_server(host="127.0.0.1", port=0, open_browser=False, headless=True)diff --git a/apps/desktop/electron/pool-retirement-live-fixture/vitest.config.ts b/apps/desktop/electron/pool-retirement-live-fixture/vitest.config.tsnew file mode 100644index 00000000000..1bce7a7ef0c--- /dev/null+++ b/apps/desktop/electron/pool-retirement-live-fixture/vitest.config.ts@@ -0,0 +1,9 @@+import { fileURLToPath } from 'node:url'++import { defineConfig } from 'vitest/config'++// Targeted native seam proof: no unrelated renderer Vite plugins or full app build.+export default defineConfig({+ root: fileURLToPath(new URL('../../', import.meta.url)),+ test: { environment: 'node', include: ['electron/pool-retirement-live.test.ts'] },+})diff --git a/apps/desktop/electron/pool-retirement-live.test.ts b/apps/desktop/electron/pool-retirement-live.test.tsnew file mode 100644index 00000000000..5479ee37c6b--- /dev/null+++ b/apps/desktop/electron/pool-retirement-live.test.ts@@ -0,0 +1,101 @@+/** Native Electron main -> real headless serve, without an app/renderer build.+ * Opt in with HERMES_TEST_REAL_SERVE=1; see pool-retirement-live-fixture/README.md.+ */+import assert from 'node:assert/strict'+import { type ChildProcess, spawn } from 'node:child_process'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { createRequire } from 'node:module'+import { tmpdir } from 'node:os'+import { dirname, join, resolve } from 'node:path'+import { fileURLToPath } from 'node:url'++import { build } from 'esbuild'+import { test } from 'vitest'++const require = createRequire(import.meta.url)++const desktop = resolve(dirname(fileURLToPath(import.meta.url)), '..')+const repo = resolve(desktop, '../..')+const fixture = join(desktop, 'electron/pool-retirement-live-fixture')++function isolatedEnv(root: string): NodeJS.ProcessEnv {+ const env: NodeJS.ProcessEnv = {}++ // Allowlist rather than trying to enumerate provider secrets and overrides.+ for (const name of ['PATH', 'SystemRoot', 'WINDIR', 'DISPLAY', 'WAYLAND_DISPLAY', 'XDG_RUNTIME_DIR']) {+ if (process.env[name]) {env[name] = process.env[name]}+ }++ return { ...env, HOME: root, USERPROFILE: root, HERMES_HOME: join(root, '.hermes'),+ XDG_CONFIG_HOME: join(root, 'config'), XDG_CACHE_HOME: join(root, 'cache'),+ TMPDIR: root, TEMP: root, TMP: root, TZ: 'UTC', LANG: 'C.UTF-8',+ HERMES_DESKTOP_CDP_PORT: 'off', HERMES_DESKTOP_USER_DATA_DIR: join(root, 'user-data') }+}++function waitForExit(child: ChildProcess, timeoutMs: number): Promise<number | null> {+ return new Promise((resolveExit, reject) => {+ const timer = setTimeout(() => reject(new Error('Native retirement fixture timed out')), timeoutMs)+ child.once('error', error => { clearTimeout(timer); reject(error) })+ child.once('exit', code => { clearTimeout(timer); resolveExit(code) })+ })+}++test.skipIf(process.env.HERMES_TEST_REAL_SERVE !== '1' || process.platform === 'win32')(+ 'native retirement preserves backend-only cron and hands both waiters capacity only after real child exit',+ async () => {+ const python = process.env.HERMES_TEST_PYTHON+ assert.ok(python && existsSync(python), 'Set HERMES_TEST_PYTHON to an installed Hermes Python environment')+ const electron = process.env.HERMES_TEST_ELECTRON || require('electron') as string+ assert.ok(existsSync(electron), 'HERMES_TEST_ELECTRON must name a real native Electron executable')+ const root = mkdtempSync(join(tmpdir(), 'hermes-pool-retirement-live-'))+ const resultPath = join(root, 'result.json')+ let child: ChildProcess | undefined+ let output = ''++ try {+ mkdirSync(join(root, '.hermes'))+ const bundle = join(root, 'main.cjs')+ await build({ entryPoints: [join(fixture, 'main.ts')], outfile: bundle,+ bundle: true, platform: 'node', format: 'cjs', target: 'node22', external: ['electron'] })+ await build({ entryPoints: [join(fixture, 'preload.ts')], outfile: join(root, 'preload.cjs'),+ bundle: true, platform: 'node', format: 'cjs', external: ['electron'] })+ await build({ entryPoints: [join(desktop, 'src/test/pool-retirement-renderer.ts')], outfile: join(root, 'renderer.js'),+ bundle: true, platform: 'browser', format: 'iife',+ alias: { '@': join(desktop, 'src'), '@hermes/shared': join(repo, 'apps/shared/src') },+ define: { 'import.meta.env': '{}', 'import.meta.hot': 'undefined' } })+ writeFileSync(join(root, 'renderer.html'), '<!doctype html><meta charset="utf-8"><title>Retirement seam fixture</title><script src="./renderer.js"></script>')+ child = spawn(electron, [bundle, root, repo, python, fixture], {+ cwd: root, env: isolatedEnv(root), stdio: ['ignore', 'pipe', 'pipe'],+ })+ // Capture the OS handle now; do not ask a disposed Electron dispatcher after quit.+ child.stdout!.on('data', chunk => { output += String(chunk) })+ child.stderr!.on('data', chunk => { output += String(chunk) })+ const code = await waitForExit(child, 180_000)+ assert.ok(existsSync(resultPath), `No native result (exit ${code}):\n${output}`)+ const result = JSON.parse(readFileSync(resultPath, 'utf8'))+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`)+ assert.equal(code, 0, `${result.error || 'Native fixture failed'}\n${output}`)+ assert.equal(result.ok, true)+ assert.ok(result.electronVersion, 'Must run native Electron, not ELECTRON_RUN_AS_NODE')+ assert.equal(result.processType, 'browser')+ assert.equal(result.maxLiveServeChildren, result.capacity)+ assert.deepEqual(result.retired, ['idle-a', 'idle-b'])+ assert.deepEqual(result.opened, ['foreground-d', 'promoted-e'])+ assert.equal(result.busyCronSurvived, true)+ assert.equal(result.rendererParking.redials, 0)+ assert.deepEqual(result.rendererParking.parked['idle-a'], ['idle-a', 'conn:local::idle-a'])+ assert.deepEqual(result.rendererParking.parked['idle-b'], ['idle-b', 'conn:local::idle-b'])+ assert.equal(result.cleanedUp, true)+ } finally {+ if (child && child.exitCode === null && child.signalCode === null) {+ child.kill('SIGTERM')+ await waitForExit(child, 15_000).catch(async () => {+ child!.kill('SIGKILL')+ await waitForExit(child!, 5000)+ })+ }++ rmSync(root, { recursive: true, force: true })+ }+ }, 210_000,+)diff --git a/apps/desktop/src/test/pool-retirement-renderer.ts b/apps/desktop/src/test/pool-retirement-renderer.tsnew file mode 100644index 00000000000..5e7bc58c623--- /dev/null+++ b/apps/desktop/src/test/pool-retirement-renderer.ts@@ -0,0 +1,38 @@+import {+ closeSecondaryGateways, configureGatewayRegistry, openGatewayForAgent,+ openGatewayForProfile, openSecondaryCount, parkSecondariesForRetiredBackend,+ reconnectSecondaryGateways,+} from '../store/gateway'++const parked: Record<string, string[]> = {}+const scopes = new Set(['idle-a', 'conn:local::idle-a', 'idle-b', 'conn:local::idle-b'])+configureGatewayRegistry({ onEvent: () => {}, foregroundScopes: () => scopes })++interface FixtureWindow extends Window {+ retirementFixture: { onRetiring: (handler: (key: string) => void) => void }+}+;(window as unknown as FixtureWindow).retirementFixture.onRetiring(key => {+ parked[key] = parkSecondariesForRetiredBackend(key)+})++const api = {+ async open() {+ for (const key of ['idle-a', 'idle-b']) {+ await openGatewayForProfile(key)+ await openGatewayForAgent('local', key)+ }++ return openSecondaryCount()+ },+ async wake() {+ reconnectSecondaryGateways()+ reconnectSecondaryGateways({ forceOpenSockets: true })+ // Observe past the normal first reconnect timer, not only its microtask.+ await new Promise(resolve => setTimeout(resolve, 2500))++ return { parked, open: openSecondaryCount() }+ },+ close: closeSecondaryGateways,+}++Object.assign(window, { poolRetirementRenderer: api })