The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(desktop): delete pool-era backend modules only tests imported
Tekniumfad246a91075
diff --git a/apps/desktop/electron/backend-discovery.test.ts b/apps/desktop/electron/backend-discovery.test.tsdeleted file mode 100644index 593595370a2..00000000000--- a/apps/desktop/electron/backend-discovery.test.ts+++ /dev/null@@ -1,703 +0,0 @@-import assert from 'node:assert/strict'-import { type ChildProcess, spawn } from 'node:child_process'-import fs from 'node:fs'-import http from 'node:http'-import os from 'node:os'-import path from 'node:path'--import { test } from 'vitest'--import { spawnOrAttach } from './backend-discovery'-import { resolveServedDashboardToken } from './dashboard-token'-import { attachOrReserveSpawn, attachToHostBackend, HOST_IDENTITY_RETRY_MS } from './host-backend-attach'-import { claimHostSpawnGate } from './host-spawn-gate'-import { runPrimaryBackendStartup } from './primary-backend-startup'--const LEDGER = JSON.stringify([- {- argv: 'hermes serve --host 127.0.0.1 --port 0',- create_time: 1_000,- host: '127.0.0.1',- install: 'abc',- pid: 4711,- port: 65_238,- profile: 'ops',- purpose: 'serve',- registered_at: 2_000- }-])--function attachDeps(ledger: string | null) {- return {- log: () => {},- probeWebSocket: async () => ({ ok: true }),- readLedger: () => ledger,- resolveServedToken: async () => 'served-token',- waitForReady: async () => undefined- }-}--/**- * Multiplex-only invariant: a backend already running on the HOST is THE- * backend — even one registered by another profile. Startup attaches to it and- * spawns nothing.- */-test('a running backend record makes startup attach and spawn zero processes', async () => {- let spawns = 0-- const setup = await runPrimaryBackendStartup({- assertCurrentAttempt: () => {},- attachHostBackend: () => attachToHostBackend({ isolated: false, ledgerPath: '/ledger.json' }, attachDeps(LEDGER)),- connectRemote: async () => ({ mode: 'remote' }),- ensureLocalRuntime: async backend => backend,- prepareLocalBackend: () => {- spawns += 1-- return { label: 'spawned' }- },- resolveRemote: async () => null,- waitForDecision: async () => 'continue-local' as const,- waitForLocalStart: async () => undefined- })-- assert.equal(setup.kind, 'attached')- assert.equal(spawns, 0, 'startup must not prepare/spawn a backend when the host already has one')- assert.deepEqual(setup.kind === 'attached' ? setup.attached : null, {- baseUrl: 'http://127.0.0.1:65238',- pid: 4711,- port: 65238,- token: 'served-token',- wsUrl: 'ws://127.0.0.1:65238/api/ws?token=served-token'- })-})--/** The only case that may start a process: the host has no backend. */-test('no backend record spawns exactly one backend', async () => {- let spawns = 0-- const setup = await runPrimaryBackendStartup({- assertCurrentAttempt: () => {},- attachHostBackend: () => attachToHostBackend({ isolated: false, ledgerPath: '/ledger.json' }, attachDeps(null)),- connectRemote: async () => ({ mode: 'remote' }),- ensureLocalRuntime: async backend => backend,- prepareLocalBackend: () => {- spawns += 1-- return { label: 'spawned' }- },- resolveRemote: async () => null,- waitForDecision: async () => 'continue-local' as const,- waitForLocalStart: async () => undefined- })-- assert.equal(setup.kind, 'local')- assert.equal(spawns, 1)-})--/**- * `serve --isolated` is another client's backend (Desktop SSH mode from a- * different machine). It is live, loopback and serves a valid token, but it is- * not this host's shared backend: attaching to it strands this app on- * whatever code that client started, across our own updates.- */-test('an isolated serve record is never attached; startup spawns its own backend', async () => {- const isolatedOnly = JSON.stringify([{ ...JSON.parse(LEDGER)[0], isolated: true }])- let spawns = 0-- const setup = await runPrimaryBackendStartup({- assertCurrentAttempt: () => {},- attachHostBackend: () =>- attachToHostBackend({ isolated: false, ledgerPath: '/ledger.json' }, attachDeps(isolatedOnly)),- connectRemote: async () => ({ mode: 'remote' }),- ensureLocalRuntime: async backend => backend,- prepareLocalBackend: () => {- spawns += 1-- return { label: 'spawned' }- },- resolveRemote: async () => null,- waitForDecision: async () => 'continue-local' as const,- waitForLocalStart: async () => undefined- })-- assert.equal(setup.kind, 'local')- assert.equal(spawns, 1)-})--test('an ordinary serve is still attached when an isolated one is newer', async () => {- const [ordinary] = JSON.parse(LEDGER)-- const ledger = JSON.stringify([- ordinary,- { ...ordinary, isolated: true, pid: 5150, port: 61_000, registered_at: ordinary.registered_at + 1 }- ])-- const attached = await attachToHostBackend({ isolated: false, ledgerPath: '/ledger.json' }, attachDeps(ledger))-- assert.equal(attached?.pid, 4711)-})--/** A record that fails validation is not a backend: fall through to spawning. */-test('a record whose backend rejects the session token does not attach', async () => {- const attached = await attachToHostBackend(- { isolated: false, ledgerPath: '/ledger.json' },- { ...attachDeps(LEDGER), probeWebSocket: async () => ({ ok: false, reason: 'unauthorized' }) }- )-- assert.equal(attached, null)-})--/** A process that loses the atomic gate race waits for the winner's backend. */-test('a lost spawn-gate race attaches instead of spawning a second backend', async () => {- let ledger: string | null = null- let takeAttempts = 0-- const outcome = await attachOrReserveSpawn(- { isolated: false, ledgerPath: '/ledger.json' },- { ...attachDeps(null), readLedger: () => ledger },- {- now: () => 0,- read: () => null,- take: () => {- takeAttempts += 1-- return null- },- sleep: async () => {- ledger = LEDGER- }- },- { pollMs: 0, waitBudgetMs: 1 }- )-- assert.equal(takeAttempts, 1)- assert.equal('attached' in outcome, true)-})--/** Gate creation is exclusive and an old release cannot remove a replacement. */-test('only one process owns the spawn gate file', () => {- const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-spawn-gate-'))- const gatePath = path.join(directory, 'gate.json')-- try {- const releaseFirst = claimHostSpawnGate(gatePath, {- claim: 'first',- pid: 1,- startedAt: 1- })-- const releaseLoser = claimHostSpawnGate(gatePath, {- claim: 'loser',- pid: 2,- startedAt: 2- })-- assert.equal(typeof releaseFirst, 'function')- assert.equal(releaseLoser, null)-- fs.unlinkSync(gatePath)-- const releaseReplacement = claimHostSpawnGate(gatePath, {- claim: 'replacement',- pid: 3,- startedAt: 3- })-- releaseFirst?.()-- assert.equal(typeof releaseReplacement, 'function')- assert.equal(fs.existsSync(gatePath), true)- releaseReplacement?.()- } finally {- fs.rmSync(directory, { force: true, recursive: true })- }-})--/** A crashed owner cannot leave every later launch waiting on an orphan. */-test('a stale spawn gate is reclaimed before taking ownership', () => {- const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-spawn-gate-stale-'))- const gatePath = path.join(directory, 'gate.json')-- try {- fs.writeFileSync(gatePath, JSON.stringify({ claim: 'crashed', pid: 10, startedAt: 1 }))-- const release = claimHostSpawnGate(gatePath, {- claim: 'replacement',- isOwnerAlive: () => false,- now: 2,- pid: 20,- staleAfterMs: 60_000,- startedAt: 2- })-- assert.equal(typeof release, 'function')- assert.deepEqual(JSON.parse(fs.readFileSync(gatePath, 'utf8')), {- claim: 'replacement',- pid: 20,- startedAt: 2- })- release?.()- } finally {- fs.rmSync(directory, { force: true, recursive: true })- }-})--/** Discovery takes over a crashed owner immediately instead of polling for a minute. */-test('a crashed spawn-gate owner is reclaimed without waiting', async () => {- const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-spawn-gate-crashed-'))- const gatePath = path.join(directory, 'gate.json')- let sleeps = 0-- try {- fs.writeFileSync(gatePath, JSON.stringify({ claim: 'crashed', pid: 10, startedAt: 1 }))-- const outcome = await attachOrReserveSpawn(- { isolated: false, ledgerPath: '/ledger.json' },- attachDeps(null),- {- now: () => 2,- read: () => null,- take: () =>- claimHostSpawnGate(gatePath, {- claim: 'replacement',- isOwnerAlive: () => false,- now: 2,- pid: 20,- staleAfterMs: 60_000,- startedAt: 2- }),- sleep: async () => {- sleeps += 1- }- },- { pollMs: 0, waitBudgetMs: 1 }- )-- assert.equal('reservation' in outcome, true)- assert.equal(sleeps, 0)-- if ('reservation' in outcome) {- outcome.reservation.release()- }- } finally {- fs.rmSync(directory, { force: true, recursive: true })- }-})--/** Recovery must not replace a live owner merely because a contender exists. */-test('a live spawn gate is not reclaimed', () => {- const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-spawn-gate-live-'))- const gatePath = path.join(directory, 'gate.json')-- try {- const liveRecord = JSON.stringify({ claim: 'live', pid: 10, startedAt: 1 })- fs.writeFileSync(gatePath, liveRecord)-- const release = claimHostSpawnGate(gatePath, {- claim: 'contender',- isOwnerAlive: () => true,- now: 2,- pid: 20,- staleAfterMs: 60_000,- startedAt: 2- })-- assert.equal(release, null)- assert.equal(fs.readFileSync(gatePath, 'utf8'), liveRecord)- } finally {- fs.rmSync(directory, { force: true, recursive: true })- }-})--/**- * Post-update relaunch: the previous backend published a session token, but- * GET / withholds it. Refusing that record and spawning another is the- * "did not publish a session token" hand-off failure.- */-test('a relaunch adopts a backend that published a session token instead of spawning another', async () => {- const logs: string[] = []- const token = 'published-session-token'- let spawns = 0-- const setup = await runPrimaryBackendStartup({- assertCurrentAttempt: () => {},- attachHostBackend: () =>- attachToHostBackend({ isolated: false, ledgerPath: '/ledger.json' }, {- ...attachDeps(LEDGER),- log: message => {- logs.push(message)- },- probeWebSocket: async wsUrl => {- assert.match(wsUrl, /token=published-session-token/)-- return { ok: true }- },- publishedTokenFor: () => token,- resolveServedToken: async () => null- } as Parameters<typeof attachToHostBackend>[1]),- connectRemote: async () => ({ mode: 'remote' }),- ensureLocalRuntime: async backend => backend,- prepareLocalBackend: () => {- spawns += 1-- return { label: 'spawned' }- },- resolveRemote: async () => null,- waitForDecision: async () => 'continue-local' as const,- waitForLocalStart: async () => undefined- })-- assert.equal(setup.kind, 'attached')- assert.equal(spawns, 0, 'a published session token must be adopted, not replaced by a second backend')- assert.equal(- logs.some(line => line.includes('did not publish a session token')),- false- )- assert.equal(setup.kind === 'attached' ? setup.attached.token : null, token)-})--test('a published token the websocket rejects is not adopted', async () => {- let probed = 0-- const attached = await attachToHostBackend({ isolated: false, ledgerPath: '/ledger.json' }, {- ...attachDeps(LEDGER),- probeWebSocket: async () => {- probed += 1-- return { ok: false, reason: 'unauthorized' }- },- publishedTokenFor: () => 'published-session-token',- resolveServedToken: async () => null- } as Parameters<typeof attachToHostBackend>[1])-- assert.equal(attached, null)- assert.equal(probed, 1)-})--/**- * #123586: the ledger survives the process it describes, so after any- * shutdown the newest record points at a dead PID. Attaching to it dials a- * port nobody listens on and burns the wait budget (a squatted port can burn- * all of it); a PID that is gone must decide `spawn` before any network I/O.- */-test('a record whose pid is dead decides spawn instead of attach', () => {- const decision = spawnOrAttach({- isolated: false,- isPidAlive: () => false,- records: JSON.parse(LEDGER)- } as Parameters<typeof spawnOrAttach>[0])-- assert.deepEqual(decision, { action: 'spawn', reason: 'no-running-backend' })-})--test('a dead pid is skipped before any network probe runs', async () => {- let servedTokenCalls = 0- let readyCalls = 0- let probeCalls = 0-- const attached = await attachToHostBackend({ isolated: false, ledgerPath: '/ledger.json' }, {- ...attachDeps(LEDGER),- isPidAlive: () => false,- probeWebSocket: async () => {- probeCalls += 1-- return { ok: true }- },- resolveServedToken: async () => {- servedTokenCalls += 1-- return 'served-token'- },- waitForReady: async () => {- readyCalls += 1- }- } as Parameters<typeof attachToHostBackend>[1])-- assert.equal(attached, null)- assert.equal(servedTokenCalls, 0, 'a dead pid must not be probed over HTTP')- assert.equal(readyCalls, 0)- assert.equal(probeCalls, 0)-})--test('a dead newest record falls through to a live older one', async () => {- const [ordinary] = JSON.parse(LEDGER)- const probedPorts: number[] = []-- const ledger = JSON.stringify([- ordinary,- { ...ordinary, pid: 5150, port: 61_000, registered_at: ordinary.registered_at - 1 }- ])-- const attached = await attachToHostBackend({ isolated: false, ledgerPath: '/ledger.json' }, {- ...attachDeps(ledger),- isPidAlive: (pid: number) => pid !== 4711,- resolveServedToken: async (baseUrl: string) => {- probedPorts.push(Number(new URL(baseUrl).port))-- return 'served-token'- }- } as Parameters<typeof attachToHostBackend>[1])-- assert.equal(attached?.pid, 5150)- assert.deepEqual(probedPorts, [61_000], 'only the live record may be dialled')-})--test('a live pid still attaches (liveness gate must not break the hot path)', async () => {- const attached = await attachToHostBackend({ isolated: false, ledgerPath: '/ledger.json' }, {- ...attachDeps(LEDGER),- isPidAlive: () => true- } as Parameters<typeof attachToHostBackend>[1])-- assert.equal(attached?.pid, 4711)-})--// A real `hermes serve` stand-in: serves its session token at GET / and its-// boot commit on the public GET /api/health (omitted when `commit` is null,-// i.e. a backend predating the field).-const FAKE_BACKEND = `-const http = require('node:http')-const commit = process.argv[1] === '-' ? undefined : process.argv[1]-http.createServer((req, res) => {- if (req.url === '/api/health') {- res.setHeader('content-type', 'application/json')- return res.end(JSON.stringify({ ok: true, version: '0.21.5', commit }))- }- res.end('<script>window.__HERMES_SESSION_TOKEN__ = "tok-' + process.pid + '"</script>')-}).listen(0, '127.0.0.1', function () { process.stdout.write(this.address().port + '\\n') })-`--async function startFakeBackend(commit: null | string): Promise<{ child: ChildProcess; pid: number; port: number }> {- const child = spawn(process.execPath, ['-e', FAKE_BACKEND, commit ?? '-'], { stdio: ['ignore', 'pipe', 'inherit'] })-- const port = await new Promise<number>((resolve, reject) => {- child.once('error', reject)- child.stdout!.once('data', chunk => resolve(Number(String(chunk).trim())))- })-- return { child, pid: child.pid!, port }-}--async function attachAmongRealBackends(- backends: { commit: null | string; registeredAt: number }[],- expectedCommit: null | string-) {- const started = await Promise.all(backends.map(backend => startFakeBackend(backend.commit)))- const logs: string[] = []-- try {- const ledger = JSON.stringify(- started.map(({ pid, port }, index) => ({- host: '127.0.0.1',- pid,- port,- purpose: 'serve',- registered_at: backends[index].registeredAt- }))- )-- const attached = await attachToHostBackend(- { isolated: false, ledgerPath: '/ledger.json' },- {- expectedCodeIdentity: async () => expectedCommit,- log: message => logs.push(message),- probeWebSocket: async () => ({ ok: true }),- readLedger: () => ledger,- resolveServedToken: baseUrl => resolveServedDashboardToken(baseUrl, ''),- waitForReady: async () => undefined- }- )-- return { attached, logs, started }- } finally {- started.forEach(({ child }) => child.kill())- }-}--const OLD_COMMIT = 'a'.repeat(40)-const NEW_COMMIT = 'b'.repeat(40)--/**- * V15: a CLI/launchd `hermes serve` that survived an update keeps running the- * OLD code and answers 503 "Restart required"; re-attaching it on every- * Restart wedges the app. Attach skips it — even as the newest record — and- * takes the backend that booted from this Desktop's checkout.- */-test('attach skips a running backend on other code and takes the one matching this checkout', async () => {- const { attached, logs, started } = await attachAmongRealBackends(- [- { commit: OLD_COMMIT, registeredAt: 2_000 },- { commit: NEW_COMMIT, registeredAt: 1_000 }- ],- NEW_COMMIT- )-- assert.equal(attached?.pid, started[1].pid)- assert.equal(attached?.token, `tok-${started[1].pid}`)- assert.ok(- logs.some(line => line.includes(`runs code ${OLD_COMMIT}, this Desktop expects ${NEW_COMMIT}; not attaching`)),- logs.join('\n')- )-})--test('no backend on this checkout means spawn; unknown own identity keeps token-only attach', async () => {- const mismatched = [- { commit: OLD_COMMIT, registeredAt: 2_000 },- // Predates the `commit` field: older code by construction.- { commit: null, registeredAt: 1_000 }- ]-- const refused = await attachAmongRealBackends(mismatched, NEW_COMMIT)-- assert.equal(refused.attached, null)- assert.ok(- refused.logs.some(line => line.includes('runs code of unknown version')),- refused.logs.join('\n')- )-- const unknownOwn = await attachAmongRealBackends(mismatched, null)-- assert.equal(unknownOwn.attached?.pid, unknownOwn.started[0].pid)-})--/**- * A ready backend on this checkout whose /api/health is briefly unavailable is- * still ours: startup retries it and attaches, never spawning a second one.- */-test('a transient identity read failure retries the running backend instead of spawning beside it', async () => {- let healthReads = 0-- const server = http.createServer((req, res) => {- if (req.url !== '/api/health') {- return res.end('<script>window.__HERMES_SESSION_TOKEN__ = "tok-slow"</script>')- }-- healthReads += 1- res.statusCode = healthReads <= 2 ? 503 : 200- res.end(JSON.stringify({ commit: NEW_COMMIT }))- })-- const port = await new Promise<number>(resolve =>- server.listen(0, '127.0.0.1', () => resolve((server.address() as { port: number }).port))- )-- let takes = 0-- try {- const ledger = JSON.stringify([{ host: '127.0.0.1', pid: process.pid, port, purpose: 'serve', registered_at: 1 }])-- const outcome = await attachOrReserveSpawn(- { isolated: false, ledgerPath: '/ledger.json' },- {- expectedCodeIdentity: async () => NEW_COMMIT,- log: () => {},- probeWebSocket: async () => ({ ok: true }),- readLedger: () => ledger,- resolveServedToken: baseUrl => resolveServedDashboardToken(baseUrl, ''),- waitForReady: async () => undefined- },- {- now: () => 0,- read: () => null,- take: () => {- takes += 1-- return () => {}- },- sleep: async () => {}- },- { pollMs: 0, waitBudgetMs: 1 }- )-- assert.equal('attached' in outcome && outcome.attached.token, 'tok-slow')- assert.equal(takes, 0, 'no spawn reservation may be taken beside a ready backend')- } finally {- server.close()- }-})--/**- * An identity that stays unreadable for the whole wait budget is "unknown",- * never a mismatch: startup keeps the token-validated attach instead of- * spawning a second backend beside a correct but slow one.- */-test('an identity unreadable for the whole budget keeps the token attach, never a second backend', async () => {- let clock = 0- let takes = 0- const ledger = JSON.stringify([{ host: '127.0.0.1', pid: 4711, port: 65_238, purpose: 'serve', registered_at: 1 }])-- const outcome = await attachOrReserveSpawn(- { isolated: false, ledgerPath: '/ledger.json' },- {- ...attachDeps(ledger),- backendCodeIdentity: async () => {- throw new Error('The operation was aborted due to timeout')- },- expectedCodeIdentity: async () => NEW_COMMIT- },- {- now: () => clock,- read: () => null,- take: () => {- takes += 1-- return () => {}- },- sleep: async ms => {- clock += ms- }- },- { pollMs: 500, waitBudgetMs: 2_000 }- )-- assert.equal('attached' in outcome && outcome.attached.token, 'served-token')- assert.equal(takes, 0, 'no spawn reservation may be taken beside a ready backend of unknown identity')-})--/**- * A token-valid ready backend with a persistently unreadable identity attaches- * within a few seconds, not the whole spawn-gate wait, and the local commit- * (`git rev-parse HEAD`) is resolved once per call, not once per retry round.- */-test('a persistently unreadable identity attaches by token within its short retry budget', async () => {- let clock = 0- let headReads = 0- const ledger = JSON.stringify([{ host: '127.0.0.1', pid: 4711, port: 65_238, purpose: 'serve', registered_at: 1 }])-- const outcome = await attachOrReserveSpawn(- { isolated: false, ledgerPath: '/ledger.json' },- {- ...attachDeps(ledger),- backendCodeIdentity: async () => {- throw new Error('The operation was aborted due to timeout')- },- expectedCodeIdentity: async () => {- headReads += 1-- return NEW_COMMIT- }- },- { now: () => clock, read: () => null, take: () => () => {}, sleep: async ms => void (clock += ms) }- )-- assert.equal('attached' in outcome && outcome.attached.token, 'served-token')- assert.ok(clock <= HOST_IDENTITY_RETRY_MS, `attached after ${clock} ms, budget ${HOST_IDENTITY_RETRY_MS} ms`)- assert.equal(headReads, 1, 'the expected commit is resolved once per attach call')-})--test('a definitive non-matching commit is still refused after the budget', async () => {- let clock = 0- const ledger = JSON.stringify([{ host: '127.0.0.1', pid: 4711, port: 65_238, purpose: 'serve', registered_at: 1 }])-- const outcome = await attachOrReserveSpawn(- { isolated: false, ledgerPath: '/ledger.json' },- {- ...attachDeps(ledger),- backendCodeIdentity: async () => OLD_COMMIT,- expectedCodeIdentity: async () => NEW_COMMIT- },- { now: () => clock, read: () => null, take: () => () => {}, sleep: async ms => void (clock += ms) },- { pollMs: 500, waitBudgetMs: 2_000 }- )-- assert.equal('reservation' in outcome, true)-})diff --git a/apps/desktop/electron/backend-discovery.ts b/apps/desktop/electron/backend-discovery.tsindex 07b269ba6da..4f23ec9d3b1 100644--- a/apps/desktop/electron/backend-discovery.ts+++ b/apps/desktop/electron/backend-discovery.ts@@ -29,9 +29,6 @@ export interface HostBackendRecord {registeredAt: number}-export type SpawnOrAttachDecision =- { action: 'attach'; record: HostBackendRecord } | { action: 'spawn'; reason: 'isolated' | 'no-running-backend' }-/** Filename the CLI writes under the machine Hermes root. */export const SPAWN_LEDGER_FILENAME = 'spawn-ledger.json'@@ -109,69 +106,3 @@ export function parseSpawnLedger(contents: unknown): HostBackendRecord[] {return records}--/**- * The attach-first decision: one running backend on the host means attach and- * spawn nothing. `isolated` is the deliberate escape hatch (see- * `HERMES_DESKTOP_ISOLATED_BACKEND` in main.ts) and wins over every record.- *- * Newest registration first, so a host that briefly holds a stale record and a- * fresh one tries the live one before falling back.- *- * `isPidAlive` skips records whose backend is already gone (#123586): the- * ledger survives the process it describes, so after any shutdown the newest- * record points at a dead PID and dialling its port only burns the wait- * budget. Absent the probe, every record is assumed live (today's behaviour).- *- * ponytail: PID-only check — a reused PID still faces the HTTP probe and the- * session-token handshake below, which stay the boundary that validates a- * record. Read the other end's start time too if a same-PID impostor ever- * attaches in the wild (no stdlib way to ask another PID's create_time).- */-export function spawnOrAttach({- isolated = false,- records = [],- isPidAlive-}: {- isolated?: boolean- records?: HostBackendRecord[]- isPidAlive?: (pid: number) => boolean-}): SpawnOrAttachDecision {- if (isolated) {- return { action: 'spawn', reason: 'isolated' }- }-- const live = isPidAlive ? records.filter(record => isPidAlive(record.pid)) : records- const [newest] = [...live].sort((left, right) => right.registeredAt - left.registeredAt)-- return newest ? { action: 'attach', record: newest } : { action: 'spawn', reason: 'no-running-backend' }-}--/** The loopback base URL for a discovered record. */-export function recordBaseUrl(record: HostBackendRecord): string {- return `http://127.0.0.1:${record.port}`-}--export interface HostSpawnGateState {- ownerAlive: boolean- startedAt: number-}--/**- * Cross-process spawn race: two apps starting at once both see an empty ledger- * and would each spawn a backend. The loser of the gate waits and re-runs- * discovery instead.- *- * A gate whose owner is gone, or one older than `staleAfterMs`, is taken over —- * a crashed spawner must never wedge every later launch.- */-export function classifyHostSpawnGate(- state: HostSpawnGateState | null,- { now, staleAfterMs }: { now: number; staleAfterMs: number }-): 'take' | 'wait' {- if (!state || !state.ownerAlive || now - state.startedAt >= staleAfterMs) {- return 'take'- }-- return 'wait'-}diff --git a/apps/desktop/electron/backend-env.test.ts b/apps/desktop/electron/backend-env.test.tsindex fbbd82858e5..95ac34b2aac 100644--- a/apps/desktop/electron/backend-env.test.ts+++ b/apps/desktop/electron/backend-env.test.ts@@ -10,7 +10,6 @@ import {buildDesktopBackendEnv,normalizeHermesHomeRoot,pathEnvKey,- pooledProfileBackendEnv,POSIX_SANE_PATH_ENTRIES,profileBackendParentEnv} from './backend-env'@@ -275,62 +274,3 @@ test('Windows matches profile homes and dotenv names case-insensitively', () =>assert.deepEqual(scoped('default'), currentEnv)assert.deepEqual(scoped('urbot'), { HERMES_HOME: currentEnv.HERMES_HOME, Path: 'C:\\Windows' })})--test('a pooled profile backend drops the launch profile TERMINAL_CWD (#87584)', () => {- withHermesRoot(ROOT_SCOPE_FILES, root => {- // The Desktop env carries the app-global cwd (resolveHermesCwd) and the- // runtime may add its own; both name the LAUNCH profile's workspace.- const env = pooledProfileBackendEnv({- hermesHome: root,- profile: 'urbot',- currentEnv: { ...ROOT_LAUNCHED_ENV, TERMINAL_CWD: '/source/launch-workspace' },- backendEnv: { TERMINAL_CWD: '/stale/runtime-workspace', KEEP_BACKEND: '1' },- platform: 'linux'- })-- assert.equal(env.TERMINAL_CWD, undefined)- assert.equal(env.HERMES_HOME, root, 'the child resolves --profile under the Desktop-resolved root')- assert.equal(env.KEEP_BACKEND, '1')- // The named-profile dotenv scrub (#68367) still applies on top.- assert.equal(env.TLON_SHIP_CODE, undefined)- assert.equal(env.OP_SERVICE_ACCOUNT_TOKEN, undefined)- assert.equal(env.OPENROUTER_API_KEY, 'shell-key')- })-})--test('a pooled backend removes case-insensitive TERMINAL_CWD on Windows', () => {- withHermesRoot(ROOT_SCOPE_FILES, root => {- const env = pooledProfileBackendEnv({- hermesHome: root,- profile: 'urbot',- currentEnv: { Path: 'C:\\Windows', Terminal_Cwd: 'C:\\source\\workspace' },- backendEnv: { terminal_cwd: 'C:\\backend' },- platform: 'win32'- })-- assert.equal(env.Terminal_Cwd, undefined)- assert.equal(env.terminal_cwd, undefined)- assert.equal(env.Path, 'C:\\Windows')- })-})--test('the launch profile pooled backend keeps its TERMINAL_CWD', () => {- withHermesRoot(ROOT_SCOPE_FILES, root => {- // profile 'default' targets the root home: no dotenv scrub, and the pin- // survives only when the caller (main.ts) provides it — the pooled helper- // itself never stamps one, it only strips inherited/global values.- const env = pooledProfileBackendEnv({- hermesHome: root,- profile: 'default',- currentEnv: { TERMINAL_CWD: '/launch-workspace', PATH: '/usr/bin' },- platform: 'linux'- })-- assert.equal(- env.TERMINAL_CWD,- undefined,- 'the pooled helper never carries the global pin; main.ts owns that decision'- )- assert.equal(env.PATH, '/usr/bin')- })-})diff --git a/apps/desktop/electron/backend-env.ts b/apps/desktop/electron/backend-env.tsindex 9498da88c51..792290a9953 100644--- a/apps/desktop/electron/backend-env.ts+++ b/apps/desktop/electron/backend-env.ts@@ -244,61 +244,12 @@ function buildDesktopBackendEnv({}}-/**- * Spawn env for a POOLED per-profile backend (`spawnPoolBackend`).- *- * TERMINAL_CWD is the LAUNCH profile's resolved workspace. A pooled child- * serves ANOTHER profile (`--profile X`): stamping the app-global cwd makes- * that profile's placeholder/unset `terminal.cwd` sessions inherit the launch- * (or another) profile's workspace (#87584). Drop TERMINAL_CWD from the- * inherited env AND from any runtime-provided mapping (case-insensitively on- * Windows); the `--profile` child re-resolves its own cwd from its profile- * config, the same way a standalone `hermes -p X serve` would. The launch- * profile's own (primary) backend keeps the pin in main.ts.- */-function pooledProfileBackendEnv({- hermesHome,- profile,- currentEnv = process.env,- backendEnv = {},- platform = process.platform,- fsModule = fs,- pathModule = pathModuleForPlatform(platform)-}: any = {}) {- const parent = profileBackendParentEnv({ hermesHome, profile, currentEnv, platform, fsModule, pathModule })- const fold = platform === 'win32' ? (value: string) => value.toUpperCase() : (value: string) => value- const isTerminalCwd = (key: string) => fold(key) === 'TERMINAL_CWD'-- const env = { ...parent }-- for (const key of Object.keys(env)) {- if (isTerminalCwd(key)) {- delete env[key]- }- }-- // The resolved root, not process.env's: on Windows it can come from the user- // registry, and the --profile child resolves its home under it.- env.HERMES_HOME = hermesHome-- for (const [key, value] of Object.entries(backendEnv || {})) {- if (isTerminalCwd(key)) {- continue- }-- env[key] = value- }-- return env-}-export {appendUniquePathEntries,buildDesktopBackendEnv,delimiterForPlatform,normalizeHermesHomeRoot,pathEnvKey,- pooledProfileBackendEnv,POSIX_SANE_PATH_ENTRIES,profileBackendParentEnv,storeFirstPathdiff --git a/apps/desktop/electron/backend-exit-recovery.test.ts b/apps/desktop/electron/backend-exit-recovery.test.tsdeleted file mode 100644index 0d0a0a18e54..00000000000--- a/apps/desktop/electron/backend-exit-recovery.test.ts+++ /dev/null@@ -1,187 +0,0 @@-import assert from 'node:assert/strict'--import { test } from 'vitest'--import { createBackendConnectionState } from './backend-connection-state'-import { createBackendExitRecoveryLatch } from './backend-exit-recovery'--type Child = { pid: number }--// Mirrors main.ts::runHermesStart's exit handler: the slot state the handler-// reads when the child's exit is classified as stale (#112344).-function slotState(state: ReturnType<typeof createBackendConnectionState<Child, unknown>>, extra = {}) {- return {- hasCurrentOwner: state.getProcess() !== null || state.getPromise() !== null,- hasPendingStart: false,- intentionalTeardown: false,- ...extra- }-}--test('a stale exit that leaves the primary slot empty is claimed once, then re-armed by the next ready backend', () => {- const state = createBackendConnectionState<Child, unknown>()- const latch = createBackendExitRecoveryLatch()- const attempt = state.startAttempt()- state.setPromise(attempt, Promise.resolve({ mode: 'local' }))- const owner = state.attachProcess(attempt, { pid: 100 })!-- // The slot is emptied (invalidate without a follow-up start, or the child's- // own `error` handler cleared it first) and only THEN the exit lands.- state.invalidate()- assert.equal(state.clearForCurrentProcess(owner), false, 'exit is classified stale')-- // Base behaviour was "log and return" here; the supervisor now owns the respawn.- assert.equal(latch.claim(slotState(state)), true)- // A second stale event for the same empty slot (error + exit pair) coalesces.- assert.equal(latch.claim(slotState(state)), false)-- // The replacement becomes ready: the latch re-arms for the next death.- latch.reset()- assert.equal(latch.claim(slotState(state)), true)-})--test('a stale exit is not claimed while the slot has an owner, a start is pending, or teardown is intentional', () => {- const state = createBackendConnectionState<Child, unknown>()- const latch = createBackendExitRecoveryLatch()- const first = state.startAttempt()- state.setPromise(first, Promise.resolve({ mode: 'local' }))- const oldOwner = state.attachProcess(first, { pid: 100 })!-- // Re-home: invalidate, then a replacement attempt publishes before the old exit lands.- state.invalidate()- const replacement = state.startAttempt()- state.setPromise(replacement, new Promise(() => {}))- assert.equal(state.clearForCurrentProcess(oldOwner), false)- assert.equal(latch.claim(slotState(state)), false, 'published replacement attempt owns the slot')-- // A remote descriptor with no child process is still an owner.- const remote = createBackendConnectionState<Child, unknown>()- const remoteAttempt = remote.startAttempt()- remote.setPromise(remoteAttempt, Promise.resolve({ mode: 'remote' }))- assert.equal(latch.claim(slotState(remote)), false)-- const empty = createBackendConnectionState<Child, unknown>()- assert.equal(latch.claim(slotState(empty, { hasPendingStart: true })), false)- assert.equal(latch.claim(slotState(empty, { intentionalTeardown: true })), false)- // Nothing above consumed the latch.- assert.equal(latch.claim(slotState(empty)), true)-})--test('a backend that dies after every ready is respawned at most maxRespawns times per window, then reported as crash-looping', () => {- let clock = 1_000- const latch = createBackendExitRecoveryLatch({ maxRespawns: 3, windowMs: 120_000, now: () => clock })- const empty = { hasCurrentOwner: false, hasPendingStart: false, intentionalTeardown: false }-- // ready -> dies -> respawn, three times within the window.- for (let i = 0; i < 3; i++) {- assert.equal(latch.claim(empty), true, `respawn ${i + 1}`)- assert.equal(latch.isCrashLooping(), false)- latch.reset()- clock += 5_000- }-- // The fourth death inside the window is a crash loop: no respawn.- assert.equal(latch.claim(empty), false)- assert.equal(latch.isCrashLooping(), true)-- // Once the window has passed the supervisor may try again.- clock += 120_000- assert.equal(latch.claim(empty), true)- assert.equal(latch.isCrashLooping(), false)-})--test('a claimed recovery that fails before ready can retry within the same crash-loop budget', () => {- let clock = 1_000- const latch = createBackendExitRecoveryLatch({ maxRespawns: 3, windowMs: 120_000, now: () => clock })- const empty = { hasCurrentOwner: false, hasPendingStart: false, intentionalTeardown: false }-- assert.equal(latch.claim(empty), true, 'ready backend death grants the first recovery')- clock += 1_000- assert.equal(latch.retryAfterFailedStart(empty), true, 'pre-ready failure grants a bounded retry')- clock += 1_000- assert.equal(latch.retryAfterFailedStart(empty), true, 'the final budgeted retry is still admitted')- clock += 1_000- assert.equal(latch.retryAfterFailedStart(empty), false, 'a fourth recovery attempt is refused')- assert.equal(latch.isCrashLooping(), true)-})--test('a failed recovery does not release its claim while another owner/start or teardown is present', () => {- const latch = createBackendExitRecoveryLatch()- const empty = { hasCurrentOwner: false, hasPendingStart: false, intentionalTeardown: false }-- assert.equal(latch.claim(empty), true)- assert.equal(latch.retryAfterFailedStart({ ...empty, hasPendingStart: true }), false)- assert.equal(latch.claim(empty), false, 'the pending-start refusal preserves the original claim')-- latch.reset()- assert.equal(latch.claim(empty), true)- assert.equal(latch.retryAfterFailedStart({ ...empty, hasCurrentOwner: true }), false)- assert.equal(latch.claim(empty), false, 'the current-owner refusal preserves the original claim')-- latch.reset()- assert.equal(latch.claim(empty), true)- assert.equal(latch.retryAfterFailedStart({ ...empty, intentionalTeardown: true }), false)- assert.equal(latch.claim(empty), false, 'intentional teardown does not re-arm recovery')-})--test('an attached backend torn down as unexpected (dead or drifted token) is claimed and a respawn is scheduled (#121988)', () => {- const state = createBackendConnectionState<Child, unknown>()- const latch = createBackendExitRecoveryLatch()- const attempt = state.startAttempt()- // An attached backend spawns no child (main.ts: "Nothing was spawned, so- // there is no child to own"); the slot holds only the resolved connection.- state.setPromise(attempt, Promise.resolve({ mode: 'local', attached: true }))-- // Mirrors startAttachedBackendMonitor's catch handler: invalidate the slot,- // then immediately try to claim the respawn in the same tick.- state.invalidate()- assert.equal(- latch.claim(slotState(state)),- true,- 'an unexpected attach teardown must not read as intentional, or the respawn is silently dropped'- )-- // The bug this guards: invalidating through a path that also marks the- // teardown intentional (as `invalidatePrimaryConnection()` does, for the- // deliberate re-home/quit/config-apply cases) makes the very next claim()- // above refuse the respawn, leaving the app with no backend.- const otherState = createBackendConnectionState<Child, unknown>()- const otherLatch = createBackendExitRecoveryLatch()- const otherAttempt = otherState.startAttempt()- otherState.setPromise(otherAttempt, Promise.resolve({ mode: 'local', attached: true }))- otherState.invalidate()- assert.equal(- otherLatch.claim(slotState(otherState, { intentionalTeardown: true })),- false,- 'marking an unexpected attach teardown intentional would silently drop the respawn'- )-})--test('a failed start that owns no recovery claim is not re-armed and spends no budget', () => {- let clock = 1_000- const latch = createBackendExitRecoveryLatch({ maxRespawns: 3, windowMs: 120_000, now: () => clock })- const empty = { hasCurrentOwner: false, hasPendingStart: false, intentionalTeardown: false }-- // Nothing claimed yet (fresh latch): a pre-ready failure of a user-driven- // start is not the supervisor's retry to take.- assert.equal(latch.retryAfterFailedStart(empty), false, 'fresh latch has no claim to re-arm')- assert.equal(latch.isCrashLooping(), false)-- // A ready backend released the claim: a later failed start still owns nothing.- assert.equal(latch.claim(empty), true)- latch.reset()- clock += 1_000- assert.equal(latch.retryAfterFailedStart(empty), false, 'reset() leaves nothing to re-arm')- assert.equal(latch.isCrashLooping(), false)-- // Neither refusal consumed the window: the remaining two grants are intact.- clock += 1_000- assert.equal(latch.claim(empty), true, 'second respawn')- latch.reset()- clock += 1_000- assert.equal(latch.claim(empty), true, 'third respawn')- latch.reset()- clock += 1_000- assert.equal(latch.claim(empty), false, 'fourth is the real budget exhaustion')- assert.equal(latch.isCrashLooping(), true)-})diff --git a/apps/desktop/electron/backend-exit-recovery.ts b/apps/desktop/electron/backend-exit-recovery.tsdeleted file mode 100644index a97a217e16a..00000000000--- a/apps/desktop/electron/backend-exit-recovery.ts+++ /dev/null@@ -1,97 +0,0 @@-/**- * Supervisor decision for a primary backend child's post-ready exit (#112344).- *- * The child's `exit` handler classifies the exit as "current" (this child- * still owned the connection slot) or "stale" (the slot was already cleared- * or moved on). A stale exit is normally harmless: a replacement owns the- * slot or a start is already in flight. But the same classification also- * fires when the slot was emptied and NOTHING followed — the connection was- * invalidated without a replacement start, or the child's own `error`- * handler cleared the slot first — and then the UI keeps running with no- * engine until the user relaunches the app (9 h observed).- *- * `claim` answers "does the supervisor own the respawn for this exit?" from- * the primary slot's state alone. Pool children never enter the decision:- * they do not own the window backend and must not suppress its recovery.- */-export type BackendExitRecoveryState = {- /** A live primary (local child or remote descriptor) or a published attempt still holds the slot. */- hasCurrentOwner: boolean- /** startHermes() is running but has not published its attempt yet. */- hasPendingStart: boolean- /** The slot was emptied on purpose (re-home, quit, hand-off, latched boot failure). */- intentionalTeardown: boolean-}--export type BackendExitRecoveryOptions = {- /** Respawns the supervisor grants per `windowMs` before it stops and lets the user relaunch. */- maxRespawns?: number- windowMs?: number- now?: () => number-}--export function createBackendExitRecoveryLatch({- maxRespawns = 3,- windowMs = 120_000,- now = Date.now-}: BackendExitRecoveryOptions = {}) {- let claimed = false- let respawnedAt: number[] = []- let crashLooping = false-- const blocked = (state: BackendExitRecoveryState) =>- state.hasCurrentOwner || state.hasPendingStart || state.intentionalTeardown-- const claim = (state: BackendExitRecoveryState): boolean => {- if (claimed || blocked(state)) {- return false- }-- const at = now()- respawnedAt = respawnedAt.filter(t => at - t < windowMs)- crashLooping = respawnedAt.length >= maxRespawns-- if (crashLooping) {- return false- }-- respawnedAt.push(at)- claimed = true-- return true- }-- return {- /**- * True exactly once per empty slot; `reset()` when a backend becomes ready- * again. A backend that dies again shortly after every ready re-arms the- * latch each time, so the grant is also bounded: more than `maxRespawns`- * within `windowMs` is a crash loop, and the supervisor stops respawning- * (`isCrashLooping()`) instead of cycling child + error toast forever.- */- claim,- /**- * Re-arm only the recovery attempt that already owns this latch and failed- * before reaching ready. A concurrent owner/start or intentional teardown- * keeps the existing claim intact; its eventual ready transition owns the- * normal reset. A real retry consumes the same crash-loop budget as every- * other supervisor respawn.- */- retryAfterFailedStart(state: BackendExitRecoveryState): boolean {- if (!claimed || blocked(state)) {- return false- }-- claimed = false-- return claim(state)- },- /** True when the last claim attempt was refused because the respawn budget for the window is spent. */- isCrashLooping(): boolean {- return crashLooping- },- reset(): void {- claimed = false- }- }-}diff --git a/apps/desktop/electron/dashboard-web-dist.test.ts b/apps/desktop/electron/dashboard-web-dist.test.tsdeleted file mode 100644index 69832d548a1..00000000000--- a/apps/desktop/electron/dashboard-web-dist.test.ts+++ /dev/null@@ -1,95 +0,0 @@-import assert from 'node:assert/strict'-import fs from 'node:fs'-import os from 'node:os'-import path from 'node:path'--import { test } from 'vitest'--import { resolveDashboardWebDist } from './dashboard-web-dist'--function touchIndex(dir) {- fs.mkdirSync(dir, { recursive: true })- fs.writeFileSync(path.join(dir, 'index.html'), '<!doctype html>')-}--function withTempRoot(fn) {- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-dashboard-web-dist-'))-- try {- return fn(root)- } finally {- fs.rmSync(root, { recursive: true, force: true })- }-}--test('desktop-spawned dashboard resolves hermes_cli/web_dist, not Desktop renderer dist', () => {- withTempRoot(root => {- const activeHermesRoot = path.join(root, 'hermes-agent')-- const desktopDist = path.join(- activeHermesRoot,- 'apps',- 'desktop',- 'release',- 'win-unpacked',- 'resources',- 'app.asar.unpacked',- 'dist'- )-- const dashboardDist = path.join(activeHermesRoot, 'hermes_cli', 'web_dist')- touchIndex(desktopDist)- touchIndex(dashboardDist)- assert.equal(- resolveDashboardWebDist({- activeHermesRoot,- appRoot: path.join(activeHermesRoot, 'apps', 'desktop'),- env: {}- }),- dashboardDist- )- })-})--test('explicit dashboard dist override wins when it exists', () => {- withTempRoot(root => {- const override = path.join(root, 'custom-dashboard-dist')- touchIndex(override)- assert.equal(- resolveDashboardWebDist({- activeHermesRoot: path.join(root, 'hermes-agent'),- env: { HERMES_DESKTOP_DASHBOARD_WEB_DIST: override }- }),- override- )- })-})--test('missing dashboard bundle falls back to canonical path for a clear child error', () => {- withTempRoot(root => {- const activeHermesRoot = path.join(root, 'hermes-agent')- assert.equal(- resolveDashboardWebDist({ activeHermesRoot, env: {} }),- path.join(activeHermesRoot, 'hermes_cli', 'web_dist')- )- })-})--test('appRoot candidate is used when it has a dashboard bundle and activeHermesRoot does not', () => {- withTempRoot(root => {- const activeHermesRoot = path.join(root, 'active-install')- const sourceRoot = path.join(root, 'source-checkout')- const appRoot = path.join(sourceRoot, 'apps', 'desktop')- const appRootDashboard = path.resolve(appRoot, '..', '..', 'hermes_cli', 'web_dist')- fs.mkdirSync(activeHermesRoot, { recursive: true })- touchIndex(appRootDashboard)- assert.equal(- resolveDashboardWebDist({- activeHermesRoot,- appRoot,- env: {}- }),- appRootDashboard- )- })-})diff --git a/apps/desktop/electron/dashboard-web-dist.ts b/apps/desktop/electron/dashboard-web-dist.tsdeleted file mode 100644index 9ec9b62edd1..00000000000--- a/apps/desktop/electron/dashboard-web-dist.ts+++ /dev/null@@ -1,67 +0,0 @@-import fs from 'node:fs'-import path from 'node:path'--function directoryExists(dir) {- try {- return fs.statSync(dir).isDirectory()- } catch {- return false- }-}--function hasDashboardBundle(dir) {- try {- return fs.statSync(path.join(dir, 'index.html')).isFile()- } catch {- return false- }-}--/**- * Resolve the web bundle served by `hermes dashboard` / `hermes serve` when it- * is spawned by Desktop as the local backend.- *- * This must be the dashboard bundle (`hermes_cli/web_dist`), not the Electron- * renderer bundle (`apps/desktop/dist` or the packaged `app.asar.unpacked/dist`).- * The Electron renderer is loaded by BrowserWindow from file://; the dashboard- * backend is also reachable in a normal browser, where serving the Desktop- * renderer produces a broken page (`Desktop IPC bridge is unavailable`).- */-function resolveDashboardWebDist(options: any = {}) {- const env = options.env || process.env- const override = env.HERMES_DESKTOP_DASHBOARD_WEB_DIST-- if (override && directoryExists(path.resolve(override))) {- return path.resolve(override)- }-- const candidates = []-- if (options.activeHermesRoot) {- candidates.push(path.join(options.activeHermesRoot, 'hermes_cli', 'web_dist'))- }-- if (options.appRoot) {- // Dev/source layout: <repo>/apps/desktop/electron/main.ts has APP_ROOT at- // <repo>/apps/desktop. Packaged layout can put APP_ROOT under resources/app.asar;- // this candidate is harmless there and useful in tests/source checkouts.- candidates.push(path.resolve(options.appRoot, '..', '..', 'hermes_cli', 'web_dist'))- }-- for (const candidate of candidates) {- if (hasDashboardBundle(candidate)) {- return candidate- }- }-- // Fall back to the canonical active install path even if it does not exist so- // the child `hermes dashboard --skip-build` fails with its explicit missing- // dist error instead of silently serving the wrong Desktop bundle.- if (options.activeHermesRoot) {- return path.join(options.activeHermesRoot, 'hermes_cli', 'web_dist')- }-- return path.resolve('hermes_cli', 'web_dist')-}--export { resolveDashboardWebDist }diff --git a/apps/desktop/electron/host-backend-attach.ts b/apps/desktop/electron/host-backend-attach.tsdeleted file mode 100644index d323ee775cd..00000000000--- a/apps/desktop/electron/host-backend-attach.ts+++ /dev/null@@ -1,374 +0,0 @@-// Attach to the host's running Hermes backend (multiplex-only, Desktop half).-//-// `backend-discovery.ts` owns the pure decision; this module performs the IO-// ladder around it: read the machine-root ledger, validate a candidate at the-// boundary that actually matters (HTTP readiness → served session token →-// WebSocket auth), and hold a host-level gate so two apps starting at once-// produce one backend instead of two.-//-// Every dependency is injected so the ladder runs in a test without Electron.--import {- classifyHostSpawnGate,- type HostBackendRecord,- parseSpawnLedger,- recordBaseUrl,- SPAWN_LEDGER_FILENAME,- spawnOrAttach-} from './backend-discovery'--/** A gate held longer than this belongs to a spawner that never finished. */-export const HOST_SPAWN_GATE_STALE_MS = 60_000--/**- * How long a ready backend whose identity is unreadable is re-read before the- * token attach. A slow /api/health is ours far more often than not, so it gets- * a few retries, not the whole spawn-gate budget: a token-valid backend must- * not hold startup for a minute.- */-export const HOST_IDENTITY_RETRY_MS = 3_000--export interface AttachedBackend {- baseUrl: string- pid: number- port: number- token: string- wsUrl: string-}--export interface HostBackendAttachDeps {- /** Read the ledger file; return null when it is missing/unreadable. */- readLedger: (path: string) => string | null- /** Resolve the token the backend actually serves at `GET /`. */- resolveServedToken: (baseUrl: string) => Promise<string | null>- /**- * Session token the backend published for this record when `GET /` withholds- * it. Absent readers keep the dashboard-HTML-only handshake.- */- publishedTokenFor?: (record: HostBackendRecord) => string | null- /** Reject unless the backend answers its readiness probe. */- waitForReady: (baseUrl: string, token: string) => Promise<unknown>- /** Reject unless `/api/ws` accepts the token — the leg the renderer uses. */- probeWebSocket: (wsUrl: string) => Promise<{ ok: boolean; reason?: string }>- /**- * PID liveness probe (real: `isPidAliveWindows`). Records whose backend is- * already gone are skipped before any network I/O (#123586). Absent, every- * record is probed as before.- */- isPidAlive?: (pid: number) => boolean- /**- * Commit this Desktop would spawn its own backend from (the checkout HEAD).- * A backend that booted from other code — a CLI/launchd `hermes serve` that- * outlived an update — answers 503 "Restart required" forever, and Restart- * would re-attach it, so it is skipped. Absent or null (packaged/non-git- * install): the token-only handshake, as before.- */- expectedCodeIdentity?: () => Promise<string | null>- /**- * Boot commit a backend reports; defaults to {@link fetchBackendCodeIdentity}.- * Null = the backend answered without one; a rejection = it could not be read.- */- backendCodeIdentity?: (baseUrl: string) => Promise<string | null>- log: (message: string) => void-}--/**- * The commit a backend booted from: `commit` on the public `GET /api/health`,- * resolved once at import (`get_version_info` is cached), so an update moving- * the checkout underneath the process does not change it. Null only when the- * backend answered and predates the field; a timeout, network error, non-2xx- * or unparsable body rejects, because a slow backend is not a different one.- */-export async function fetchBackendCodeIdentity(baseUrl: string, timeoutMs = 3000): Promise<string | null> {- const response = await fetch(`${baseUrl}/api/health`, { signal: AbortSignal.timeout(timeoutMs) })-- if (!response.ok) {- throw new Error(`/api/health answered ${response.status}`)- }-- const body: unknown = await response.json()-- return body && typeof body === 'object' && 'commit' in body ? nonemptyToken(String(body.commit ?? '')) : null-}--/** A ready backend whose identity could not be read yet: neither attach nor spawn beside it. */-const UNCONFIRMED = 'unconfirmed'--/** The commit this Desktop would spawn its backend from: its checkout's HEAD, or null off git. */-export async function checkoutHeadIdentity(- root: string,- isGitCheckout: (root: string) => boolean,- git: (args: string[], options: { cwd: string; timeoutMs: number }) => Promise<{ code: number | null; stdout: string }>-): Promise<string | null> {- if (!isGitCheckout(root)) {- return null- }-- const head = await git(['rev-parse', 'HEAD'], { cwd: root, timeoutMs: 5000 })-- return head.code === 0 ? head.stdout.trim() || null : null-}--export function spawnLedgerPath(hermesHomeRoot: string, join: (...parts: string[]) => string): string {- return join(hermesHomeRoot, SPAWN_LEDGER_FILENAME)-}--function wsUrlFor(baseUrl: string, token: string): string {- return `${baseUrl.replace(/^http/, 'ws')}/api/ws?token=${encodeURIComponent(token)}`-}--function nonemptyToken(value: string | null | undefined): string | null {- const token = String(value ?? '').trim()-- return token || null-}--/**- * Validate one candidate all the way to a usable connection, or return null.- *- * A failed rung is not an error: it means this record is not the backend we can- * use, and the caller falls through to the next rung (another record, then- * spawning). Only a *validated* candidate is ever returned.- */-async function validate(- record: HostBackendRecord,- deps: HostBackendAttachDeps,- expectedCommit: string | null,- unreadableIdentity: 'unconfirmed' | 'token-attach'-): Promise<AttachedBackend | null | typeof UNCONFIRMED> {- const baseUrl = recordBaseUrl(record)- const servedToken = nonemptyToken(await deps.resolveServedToken(baseUrl).catch(() => null))- let publishedToken: string | null = null-- if (!servedToken && deps.publishedTokenFor) {- try {- publishedToken = nonemptyToken(deps.publishedTokenFor(record))- } catch {- publishedToken = null- }- }-- const token = servedToken || publishedToken-- if (!token) {- deps.log(`[attach] ${baseUrl} (pid ${record.pid}) did not publish a session token; not attaching`)-- return null- }-- try {- await deps.waitForReady(baseUrl, token)- } catch (error) {- deps.log(`[attach] ${baseUrl} (pid ${record.pid}) is not ready: ${(error as Error).message}`)-- return null- }-- if (expectedCommit) {- // Unknown backend identity is a mismatch: a backend predating the field is- // older code by construction.- const resolve = deps.backendCodeIdentity ?? fetchBackendCodeIdentity- let theirs: string | null-- try {- theirs = nonemptyToken(await resolve(baseUrl))- } catch (error) {- deps.log(- `[attach] ${baseUrl} (pid ${record.pid}) is ready but its code identity is unreadable: ${(error as Error).message}`- )-- if (unreadableIdentity === 'unconfirmed') {- return UNCONFIRMED- }-- // Retries exhausted: an unreadable identity is still not a mismatch, so- // keep the token-validated attach rather than spawn a second backend.- theirs = expectedCommit- }-- if (theirs?.toLowerCase() !== expectedCommit.toLowerCase()) {- deps.log(- `[attach] ${baseUrl} (pid ${record.pid}) runs ${theirs ? `code ${theirs}` : 'code of unknown version'}, ` +- `this Desktop expects ${expectedCommit}; not attaching`- )-- return null- }- }-- const wsUrl = wsUrlFor(baseUrl, token)- const probe = await deps.probeWebSocket(wsUrl).catch(error => ({ ok: false, reason: error.message }))-- if (!probe.ok) {- deps.log(`[attach] ${baseUrl} (pid ${record.pid}) rejected the session token on /api/ws: ${probe.reason}`)-- return null- }-- return { baseUrl, pid: record.pid, port: record.port, token, wsUrl }-}--/**- * Discover and attach to the host's running backend.- *- * Returns null when the host has none (or the escape hatch is set), which is- * the caller's signal to spawn exactly one.- */-export async function attachToHostBackend(- options: { isolated: boolean; ledgerPath: string },- deps: HostBackendAttachDeps-): Promise<AttachedBackend | null> {- const found = await findHostBackend(options, deps, await expectedCommitFor(deps))-- return found === UNCONFIRMED ? null : found-}--/** Resolved once per attach call: `git rev-parse HEAD` must not run per retry round. */-async function expectedCommitFor(deps: HostBackendAttachDeps): Promise<string | null> {- return nonemptyToken(await deps.expectedCodeIdentity?.().catch(() => null))-}--async function findHostBackend(- { isolated, ledgerPath }: { isolated: boolean; ledgerPath: string },- deps: HostBackendAttachDeps,- expectedCommit: string | null,- unreadableIdentity: 'unconfirmed' | 'token-attach' = 'unconfirmed'-): Promise<AttachedBackend | null | typeof UNCONFIRMED> {- const records = parseSpawnLedger(deps.readLedger(ledgerPath))- const decision = spawnOrAttach({ isolated, records, isPidAlive: deps.isPidAlive })-- if (decision.action === 'spawn') {- if (decision.reason === 'isolated') {- deps.log('[attach] HERMES_DESKTOP_ISOLATED_BACKEND is set; spawning a dedicated backend')- }-- return null- }-- // Newest first, then the rest: a stale record must not cost us a live one.- // Dead PIDs are skipped here too, so the fallback rung never dials a port- // whose owner is already gone (#123586).- const ordered = [- decision.record,- ...records.filter(- candidate => candidate !== decision.record && (!deps.isPidAlive || deps.isPidAlive(candidate.pid))- )- ]-- let unconfirmed = false-- for (const record of ordered) {- const attached = await validate(record, deps, expectedCommit, unreadableIdentity)-- if (attached === UNCONFIRMED) {- unconfirmed = true- } else if (attached) {- deps.log(- `[attach] attached to the running Hermes backend on ${attached.baseUrl} ` +- `(pid ${attached.pid}, registered by profile "${record.profile || 'default'}"); spawning nothing`- )-- return attached- }- }-- return unconfirmed ? UNCONFIRMED : null-}--export interface HostSpawnGateDeps {- now: () => number- /** Read the gate record; null when absent, unreadable, or its owner is gone. */- read: () => { ownerAlive: boolean; startedAt: number } | null- /** Atomically claim the gate; null means another process won the race. */- take: () => (() => void) | null- sleep: (ms: number) => Promise<void>-}--export interface SpawnReservation {- release: () => void-}--/**- * Attach to the host backend, or come back holding the host spawn gate.- *- * Two apps launching at once both find an empty ledger; without a gate they- * each spawn a backend and the host ends up with two. The loser waits for the- * winner's backend to register and attaches to it instead. The wait is bounded- * and a gate whose owner died is taken over, so a crashed spawner cannot wedge- * every later launch — worst case we spawn, which is today's behaviour.- *- * The caller MUST release the reservation once its spawn is ready or has- * failed; the ledger entry only appears after the new backend binds.- */-export async function attachOrReserveSpawn(- options: { isolated: boolean; ledgerPath: string },- deps: HostBackendAttachDeps,- gate: HostSpawnGateDeps,- { pollMs = 500, waitBudgetMs = HOST_SPAWN_GATE_STALE_MS }: { pollMs?: number; waitBudgetMs?: number } = {}-): Promise<{ attached: AttachedBackend } | { reservation: SpawnReservation }> {- const expectedCommit = await expectedCommitFor(deps)- let found = await findHostBackend(options, deps, expectedCommit)-- if (found && found !== UNCONFIRMED) {- return { attached: found }- }-- if (options.isolated) {- return { reservation: { release: () => {} } }- }-- const deadline = gate.now() + waitBudgetMs- // An unreadable identity gets its own short budget, counted from first sight.- let identityDeadline = found === UNCONFIRMED ? gate.now() + HOST_IDENTITY_RETRY_MS : Infinity-- while (gate.now() < (found === UNCONFIRMED ? Math.min(deadline, identityDeadline) : deadline)) {- const gateState = gate.read()-- // A ready backend we could not identify may well be ours: re-read it- // instead of spawning a second one beside it.- if (- found !== UNCONFIRMED &&- classifyHostSpawnGate(gateState, {- now: gate.now(),- staleAfterMs: HOST_SPAWN_GATE_STALE_MS- }) === 'take'- ) {- const release = gate.take()-- if (release) {- return { reservation: { release } }- }- }-- deps.log(- found === UNCONFIRMED- ? '[attach] retrying the running backend whose code identity was unreadable before spawning another'- : '[attach] another app is starting the host backend; waiting for it instead of spawning a second one'- )- await gate.sleep(pollMs)-- found = await findHostBackend(options, deps, expectedCommit)-- if (found && found !== UNCONFIRMED) {- return { attached: found }- }-- if (found === UNCONFIRMED) {- identityDeadline = Math.min(identityDeadline, gate.now() + HOST_IDENTITY_RETRY_MS)- }- }-- // Only a definitive non-matching commit is a mismatch: a ready backend whose- // identity stayed unreadable for its whole retry budget keeps the token attach.- if (found === UNCONFIRMED) {- found = await findHostBackend(options, deps, expectedCommit, 'token-attach')-- if (found && found !== UNCONFIRMED) {- return { attached: found }- }- }-- // Preserve the bounded startup fallback when a stale/unreadable gate cannot- // be claimed. The no-op reservation owns no file and therefore removes none.- return { reservation: { release: gate.take() ?? (() => {}) } }-}diff --git a/apps/desktop/electron/host-backend-singleton.ts b/apps/desktop/electron/host-backend-singleton.tsindex 0450eb5585c..bd239305b8c 100644--- a/apps/desktop/electron/host-backend-singleton.ts+++ b/apps/desktop/electron/host-backend-singleton.ts@@ -1,9 +1,9 @@// Multiplex-only, Desktop half: ONE `hermes serve` per HOST serves every// profile, so a local profile never gets a backend process of its own.//-// `backend-discovery.ts` + `host-backend-attach.ts` made the PRIMARY backend-// attach to a backend the host is already running. This module removes the-// other producer of `hermes serve` children: the per-profile backend pool.+// The PRIMARY attaches to the host's running gateway through+// `hermes gateway ensure` (local-gateway.ts). This module removes the other+// producer of local backend children: the per-profile backend pool.// Every local profile now resolves onto the same host backend and carries its// own `profile` on the wire — the server binds a SESSION to a profile home// (`session.create {profile}` -> `profile_home`) and a sessionless RPC to thediff --git a/apps/desktop/electron/host-published-token.test.ts b/apps/desktop/electron/host-published-token.test.tsdeleted file mode 100644index b13b69007eb..00000000000--- a/apps/desktop/electron/host-published-token.test.ts+++ /dev/null@@ -1,152 +0,0 @@-import assert from 'node:assert/strict'-import { createHash } from 'node:crypto'-import fs from 'node:fs'-import os from 'node:os'-import path from 'node:path'--import { test } from 'vitest'--import { attachToHostBackend } from './host-backend-attach'-import { lookupPublishedSessionToken, publishedTokenForRecord } from './host-published-token'--const RECORD = {- createTime: 1_000,- host: '127.0.0.1',- pid: 4711,- port: 65_238,- profile: 'ops',- purpose: 'serve',- registeredAt: 2_000-}--function fingerprint(token: string): string {- return createHash('sha256').update(token, 'utf8').digest('hex').slice(0, 16)-}--function publication(role: string, token: string, overrides: Record<string, unknown> = {}) {- return {- recordText: JSON.stringify({- createTime: 1_000,- host: '127.0.0.1',- pid: 4711,- port: 65_238,- protocolVersion: 1,- role,- tokenFingerprint: fingerprint(token),- ...overrides- }),- role,- token- }-}--test('a desktop-serve publication matches the ledger record by pid, port, and fingerprint', () => {- const token = 'published-session-token'-- assert.equal(publishedTokenForRecord(RECORD, [publication('desktop-serve', token)]), token)- assert.equal(- publishedTokenForRecord(RECORD, [publication('desktop-serve', token, { tokenFingerprint: '0'.repeat(16) })]),- null- )- assert.equal(publishedTokenForRecord(RECORD, [publication('desktop-serve', token, { pid: 99 })]), null)- assert.equal(publishedTokenForRecord(RECORD, [publication('gateway', token)]), null)-})--test('lookup adopts an owner-only desktop-serve token and ignores a world-readable one', () => {- const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-host-token-'))- const token = 'published-session-token'-- const record = {- createTime: 1_000,- host: '127.0.0.1',- pid: 4711,- port: 65_238,- protocolVersion: 1,- role: 'desktop-serve',- tokenFingerprint: fingerprint(token)- }-- fs.chmodSync(directory, 0o700)- fs.writeFileSync(path.join(directory, 'host-desktop-serve.json'), JSON.stringify(record), { mode: 0o600 })- fs.writeFileSync(path.join(directory, 'host-desktop-serve.token'), `${token}\n`, { mode: 0o600 })-- const env = { home: os.homedir(), lockDir: directory, platform: process.platform }-- const io = {- lstat: (target: string) => fs.lstatSync(target),- readFile: (target: string) => fs.readFileSync(target, 'utf8'),- uid: typeof process.getuid === 'function' ? process.getuid() : null- }-- assert.equal(lookupPublishedSessionToken(RECORD, env, io), token)-- fs.chmodSync(path.join(directory, 'host-desktop-serve.token'), 0o644)- assert.equal(process.platform === 'win32' ? token : null, lookupPublishedSessionToken(RECORD, env, io))- fs.rmSync(directory, { recursive: true, force: true })-})--test('a withheld dashboard token adopts the on-disk published token instead of spawning', async () => {- const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-host-token-'))- const token = 'published-session-token'-- fs.chmodSync(directory, 0o700)- fs.writeFileSync(- path.join(directory, 'host-desktop-serve.json'),- JSON.stringify({- host: '127.0.0.1',- pid: 4711,- port: 65_238,- protocolVersion: 1,- role: 'desktop-serve',- tokenFingerprint: fingerprint(token)- }),- { mode: 0o600 }- )- fs.writeFileSync(path.join(directory, 'host-desktop-serve.token'), token, { mode: 0o600 })-- const logs: string[] = []-- const attached = await attachToHostBackend(- { isolated: false, ledgerPath: '/ledger.json' },- {- log: message => {- logs.push(message)- },- probeWebSocket: async wsUrl => {- assert.match(wsUrl, /token=published-session-token/)-- return { ok: true }- },- publishedTokenFor: record =>- lookupPublishedSessionToken(- record,- { home: os.homedir(), lockDir: directory, platform: process.platform },- {- lstat: target => fs.lstatSync(target),- readFile: target => fs.readFileSync(target, 'utf8'),- uid: typeof process.getuid === 'function' ? process.getuid() : null- }- ),- readLedger: () =>- JSON.stringify([- {- host: '127.0.0.1',- pid: 4711,- port: 65_238,- profile: 'ops',- purpose: 'dashboard',- registered_at: 2_000- }- ]),- resolveServedToken: async () => null,- waitForReady: async () => undefined- }- )-- assert.equal(attached?.token, token)- assert.equal(- logs.some(line => line.includes('did not publish a session token')),- false- )- fs.rmSync(directory, { recursive: true, force: true })-})diff --git a/apps/desktop/electron/host-published-token.ts b/apps/desktop/electron/host-published-token.tsdeleted file mode 100644index 73027aaa95f..00000000000--- a/apps/desktop/electron/host-published-token.ts+++ /dev/null@@ -1,179 +0,0 @@-// Session token published by a Hermes backend for same-user attach.-//-// `GET /` withholds `window.__HERMES_SESSION_TOKEN__` when the dashboard is-// auth-gated. The backend still writes the live token next to its host-// rendezvous record (`gateway/host_rendezvous.py`): `host-serve.token` for the-// machine owner, `host-desktop-serve.token` for a Desktop-spawned child. The-// post-update relaunch has to adopt that token instead of logging "did not-// publish a session token" and spawning a second backend.--import { createHash } from 'node:crypto'-import path from 'node:path'--import type { HostBackendRecord } from './backend-discovery'--const HOST_PROTOCOL_VERSION = 1-const PUBLISHED_ROLES = ['serve', 'desktop-serve'] as const--export interface PublishedHostToken {- recordText: string- role: string- token: string-}--export interface HostTokenStat {- isDirectory: () => boolean- isFile: () => boolean- isSymbolicLink: () => boolean- mode: number- uid: number-}--export interface HostTokenIo {- lstat: (target: string) => HostTokenStat- readFile: (target: string) => string- uid: number | null-}--export interface HostRendezvousEnv {- home: string- lockDir?: string- platform: string- stateHome?: string-}--export function hostRendezvousDirectory(env: HostRendezvousEnv): string {- const override = String(env.lockDir || '').trim()-- if (override) {- return path.resolve(override)- }-- const stateHomeEnv = String(env.stateHome || '').trim()-- const stateHome =- stateHomeEnv && path.isAbsolute(stateHomeEnv) ? stateHomeEnv : path.join(env.home, '.local', 'state')-- return path.join(stateHome, 'hermes', 'gateway-locks')-}--function tokenFingerprint(token: string): string {- return createHash('sha256').update(token, 'utf8').digest('hex').slice(0, 16)-}--function isPrivateEntry(stat: HostTokenStat, platform: string, uid: number | null): boolean {- if (stat.isSymbolicLink()) {- return false- }-- if (platform === 'win32') {- return true- }-- if ((stat.mode & 0o077) !== 0) {- return false- }-- return uid === null || stat.uid === uid-}--function tokenForPublication(record: HostBackendRecord, publication: PublishedHostToken): string | null {- if (!PUBLISHED_ROLES.includes(publication.role as (typeof PUBLISHED_ROLES)[number])) {- return null- }-- let parsed: unknown-- try {- parsed = JSON.parse(publication.recordText)- } catch {- return null- }-- if (!parsed || typeof parsed !== 'object') {- return null- }-- const payload = parsed as Record<string, unknown>- const token = publication.token.trim()- const fingerprint = String(payload.tokenFingerprint ?? '')-- if (- payload.role !== publication.role ||- payload.protocolVersion !== HOST_PROTOCOL_VERSION ||- payload.pid !== record.pid ||- payload.port !== record.port ||- !token ||- !/^[0-9a-f]{16}$/.test(fingerprint) ||- tokenFingerprint(token) !== fingerprint- ) {- return null- }-- return token-}--/** The published token that belongs to this ledger record, or null. */-export function publishedTokenForRecord(record: HostBackendRecord, publications: PublishedHostToken[]): string | null {- for (const publication of publications) {- const token = tokenForPublication(record, publication)-- if (token) {- return token- }- }-- return null-}--/** Read owner-only host-serve and host-desktop-serve token pairs. Never throws. */-export function readPublishedHostTokens(directory: string, io: HostTokenIo, platform: string): PublishedHostToken[] {- try {- const directoryStat = io.lstat(directory)-- if (!directoryStat.isDirectory() || !isPrivateEntry(directoryStat, platform, io.uid)) {- return []- }- } catch {- return []- }-- const publications: PublishedHostToken[] = []-- for (const role of PUBLISHED_ROLES) {- const recordPath = path.join(directory, `host-${role}.json`)- const tokenPath = path.join(directory, `host-${role}.token`)-- try {- const recordStat = io.lstat(recordPath)- const tokenStat = io.lstat(tokenPath)-- if (- !recordStat.isFile() ||- !tokenStat.isFile() ||- !isPrivateEntry(recordStat, platform, io.uid) ||- !isPrivateEntry(tokenStat, platform, io.uid)- ) {- continue- }-- publications.push({- recordText: io.readFile(recordPath),- role,- token: io.readFile(tokenPath)- })- } catch {- continue- }- }-- return publications-}--export function lookupPublishedSessionToken(- record: HostBackendRecord,- env: HostRendezvousEnv,- io: HostTokenIo-): string | null {- return publishedTokenForRecord(record, readPublishedHostTokens(hostRendezvousDirectory(env), io, env.platform))-}diff --git a/apps/desktop/electron/host-spawn-gate.ts b/apps/desktop/electron/host-spawn-gate.tsdeleted file mode 100644index 7d30ef9e0f6..00000000000--- a/apps/desktop/electron/host-spawn-gate.ts+++ /dev/null@@ -1,132 +0,0 @@-import crypto from 'node:crypto'-import fs from 'node:fs'--interface HostSpawnGateClaim {- claim?: string- isOwnerAlive?: (pid: number) => boolean- now?: number- pid?: number- staleAfterMs?: number- startedAt?: number-}--interface HostSpawnGateRecord {- claim: string- pid: number- startedAt: number-}--function ownerIsAlive(pid: number): boolean {- try {- process.kill(pid, 0)-- return true- } catch {- return false- }-}--function parseRecord(contents: string): HostSpawnGateRecord | null {- try {- const record = JSON.parse(contents)-- if (- typeof record?.claim !== 'string' ||- !record.claim ||- !Number.isInteger(record.pid) ||- record.pid <= 0 ||- !Number.isFinite(record.startedAt)- ) {- return null- }-- return record- } catch {- return null- }-}--function createClaim(gatePath: string, record: HostSpawnGateRecord): boolean {- try {- fs.writeFileSync(gatePath, JSON.stringify(record), {- flag: 'wx',- mode: 0o600- })-- return true- } catch {- return false- }-}--/**- * Atomically claim the host-level backend spawn gate.- *- * Exclusive creation makes one contender win when several Desktop processes- * start together. The release checks its opaque claim before unlinking, so a- * delayed cleanup cannot remove a later process's gate.- */-export function claimHostSpawnGate(- gatePath: string,- {- pid = process.pid,- startedAt = Date.now(),- claim = crypto.randomUUID(),- now = Date.now(),- staleAfterMs,- isOwnerAlive = ownerIsAlive- }: HostSpawnGateClaim = {}-): (() => void) | null {- const record = { claim, pid, startedAt }-- if (!createClaim(gatePath, record)) {- if (staleAfterMs === undefined) {- return null- }-- let staleContents: string-- try {- staleContents = fs.readFileSync(gatePath, 'utf8')- } catch {- return null- }-- const staleRecord = parseRecord(staleContents)-- const reclaimable =- staleRecord === null || !isOwnerAlive(staleRecord.pid) || now - staleRecord.startedAt >= staleAfterMs-- if (!reclaimable) {- return null- }-- try {- // Re-read immediately before unlinking so a replacement claim is not- // removed using a decision made about the old owner.- if (fs.readFileSync(gatePath, 'utf8') !== staleContents) {- return null- }-- fs.unlinkSync(gatePath)- } catch {- return null- }-- if (!createClaim(gatePath, record)) {- return null- }- }-- return () => {- try {- const record = JSON.parse(fs.readFileSync(gatePath, 'utf8'))-- if (record?.claim === claim) {- fs.unlinkSync(gatePath)- }- } catch {- // Already gone, unreadable, or replaced.- }- }-}diff --git a/tests/hermes_cli/test_web_routers_status_health.py b/tests/hermes_cli/test_web_routers_status_health.pyindex 0108e1dfbc4..d6413db0372 100644--- a/tests/hermes_cli/test_web_routers_status_health.py+++ b/tests/hermes_cli/test_web_routers_status_health.py@@ -1,8 +1,8 @@"""``GET /api/health`` ``commit`` contract (review G4).-Desktop's host-backend-attach.ts (``fetchBackendCodeIdentity``) reads ``commit`` from the public-health probe and refuses to attach to a backend whose BOOT commit differs from its checkout, so a-``serve`` that outlived ``hermes update`` is never re-adopted. The field must always be present+The public health probe reports the backend's BOOT ``commit`` so an attaching client can refuse a+backend whose boot commit differs from its checkout: a ``serve`` that outlived ``hermes update``+is never re-adopted. The field must always be present(``null`` off git) and must come from ``get_version_info().commit``."""@@ -32,5 +32,5 @@ def test_health_reports_the_boot_commit_from_version_info(monkeypatch, commit):assert response.status_code == 200body = response.json()assert body["ok"] is True- assert "commit" in body, "host-backend-attach.ts keys the attach decision on this field"+ assert "commit" in body, "attaching clients key the boot-identity decision on this field"assert body["commit"] == commit