The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): attach only to a host backend booted from this checkout
Teknium55b51fa8ad82
diff --git a/apps/desktop/electron/backend-discovery.test.ts b/apps/desktop/electron/backend-discovery.test.tsindex f66861767d2..8bce1630c2f 100644--- a/apps/desktop/electron/backend-discovery.test.ts+++ b/apps/desktop/electron/backend-discovery.test.ts@@ -1,4 +1,5 @@import assert from 'node:assert/strict'+import { type ChildProcess, spawn } from 'node:child_process'import fs from 'node:fs'import os from 'node:os'import path from 'node:path'@@ -6,6 +7,7 @@ import path from 'node:path'import { test } from 'vitest'import { spawnOrAttach } from './backend-discovery'+import { resolveServedDashboardToken } from './dashboard-token'import { attachOrReserveSpawn, attachToHostBackend } from './host-backend-attach'import { claimHostSpawnGate } from './host-spawn-gate'import { runPrimaryBackendStartup } from './primary-backend-startup'@@ -447,3 +449,108 @@ test('a live pid still attaches (liveness gate must not break the hot path)', asassert.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)+})diff --git a/apps/desktop/electron/host-backend-attach.ts b/apps/desktop/electron/host-backend-attach.tsindex ccb756c8534..91408606568 100644--- a/apps/desktop/electron/host-backend-attach.ts+++ b/apps/desktop/electron/host-backend-attach.ts@@ -48,9 +48,36 @@ export interface HostBackendAttachDeps {* 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}. */+ 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 when the+ * backend predates the field or does not answer.+ */+export async function fetchBackendCodeIdentity(baseUrl: string, timeoutMs = 3000): Promise<string | null> {+ try {+ const response = await fetch(`${baseUrl}/api/health`, { signal: AbortSignal.timeout(timeoutMs) })+ const body: unknown = response.ok ? await response.json() : null++ return body && typeof body === 'object' && 'commit' in body ? nonemptyToken(String(body.commit ?? '')) : null+ } catch {+ return null+ }+}+export function spawnLedgerPath(hermesHomeRoot: string, join: (...parts: string[]) => string): string {return join(hermesHomeRoot, SPAWN_LEDGER_FILENAME)}@@ -72,7 +99,11 @@ function nonemptyToken(value: string | null | undefined): string | null {* 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): Promise<AttachedBackend | null> {+async function validate(+ record: HostBackendRecord,+ deps: HostBackendAttachDeps,+ expectedCommit: string | null+): Promise<AttachedBackend | null> {const baseUrl = recordBaseUrl(record)const servedToken = nonemptyToken(await deps.resolveServedToken(baseUrl).catch(() => null))let publishedToken: string | null = null@@ -101,6 +132,22 @@ async function validate(record: HostBackendRecord, deps: HostBackendAttachDeps):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+ const theirs = nonemptyToken(await resolve(baseUrl).catch(() => null))++ 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 }))@@ -144,8 +191,10 @@ export async function attachToHostBackend()]+ const expectedCommit = nonemptyToken(await deps.expectedCodeIdentity?.().catch(() => null))+for (const record of ordered) {- const attached = await validate(record, deps)+ const attached = await validate(record, deps, expectedCommit)if (attached) {deps.log(diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex f98793129c2..9c7dd53430f 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -12796,6 +12796,20 @@ function hostBackendAttachDeps() {// Skip ledger records whose backend is already gone before dialling// anything: the ledger survives the process it describes (#123586).isPidAlive: isPidAliveWindows,+ // Attach only to a backend booted from this checkout's HEAD: a CLI/launchd+ // serve that outlived an update answers 503 "Restart required", and Restart+ // would re-adopt the same stale process forever.+ expectedCodeIdentity: async () => {+ const root = resolveUpdateRoot()++ if (!isGitCheckout(root)) {+ return null+ }++ const head = await execGit(resolveGitBinary(), ['rev-parse', 'HEAD'], { cwd: root, timeoutMs: 5000 })++ return head.code === 0 ? head.stdout.trim() || null : null+ },log: rememberLog,readLedger: (target: string) => {try {diff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.pyindex 9579be47df0..c3f7eb2c53f 100644--- a/hermes_cli/web_routers/status.py+++ b/hermes_cli/web_routers/status.py@@ -115,9 +115,15 @@ async def get_ssh_ownership(request: Request):@router.get("/api/health")async def get_health():- """Lightweight process liveness for desktop/backend readiness probes."""+ """Lightweight process liveness for desktop/backend readiness probes.++ ``commit`` is the code this process BOOTED from (``get_version_info`` is cached at+ ``web_server`` import): Desktop refuses to attach to a backend whose commit differs from+ its checkout, so a serve that outlived ``hermes update`` is never re-adopted.+ """info = get_version_info()return {"ok": True, "version": info.base_version, "displayVersion": info.display_version,+ "commit": info.commit,"auth_required": bool(getattr(app.state, "auth_required", False))}