The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): a ready backend with a briefly unreadable identity is retried, never doubled (review desk-identity-transient-mismatch)
Tekniumd1429fb013e2
diff --git a/apps/desktop/electron/backend-discovery.test.ts b/apps/desktop/electron/backend-discovery.test.tsindex 8bce1630c2f..d9dae184dc7 100644--- a/apps/desktop/electron/backend-discovery.test.ts+++ b/apps/desktop/electron/backend-discovery.test.ts@@ -1,6 +1,7 @@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'@@ -548,9 +549,68 @@ test('no backend on this checkout means spawn; unknown own identity keeps token-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'))+ 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()+ }+})diff --git a/apps/desktop/electron/host-backend-attach.ts b/apps/desktop/electron/host-backend-attach.tsindex 91408606568..ae89eaec5ef 100644--- a/apps/desktop/electron/host-backend-attach.ts+++ b/apps/desktop/electron/host-backend-attach.ts@@ -56,7 +56,10 @@ export interface HostBackendAttachDeps {* install): the token-only handshake, as before.*/expectedCodeIdentity?: () => Promise<string | null>- /** Boot commit a backend reports; defaults to {@link fetchBackendCodeIdentity}. */+ /**+ * 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}@@ -64,20 +67,25 @@ export interface HostBackendAttachDeps {/*** 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.+ * 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> {- try {- const response = await fetch(`${baseUrl}/api/health`, { signal: AbortSignal.timeout(timeoutMs) })- const body: unknown = response.ok ? await response.json() : null+ const response = await fetch(`${baseUrl}/api/health`, { signal: AbortSignal.timeout(timeoutMs) })- return body && typeof body === 'object' && 'commit' in body ? nonemptyToken(String(body.commit ?? '')) : null- } catch {- return null+ 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'+export function spawnLedgerPath(hermesHomeRoot: string, join: (...parts: string[]) => string): string {return join(hermesHomeRoot, SPAWN_LEDGER_FILENAME)}@@ -103,7 +111,7 @@ async function validate(record: HostBackendRecord,deps: HostBackendAttachDeps,expectedCommit: string | null-): Promise<AttachedBackend | null> {+): Promise<AttachedBackend | null | typeof UNCONFIRMED> {const baseUrl = recordBaseUrl(record)const servedToken = nonemptyToken(await deps.resolveServedToken(baseUrl).catch(() => null))let publishedToken: string | null = null@@ -136,7 +144,17 @@ async function validate(// 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))+ 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}`+ )++ return UNCONFIRMED+ }if (theirs?.toLowerCase() !== expectedCommit.toLowerCase()) {deps.log(@@ -167,9 +185,18 @@ async function validate(* the caller's signal to spawn exactly one.*/export async function attachToHostBackend(- { isolated, ledgerPath }: { isolated: boolean; ledgerPath: string },+ options: { isolated: boolean; ledgerPath: string },deps: HostBackendAttachDeps): Promise<AttachedBackend | null> {+ const found = await findHostBackend(options, deps)++ return found === UNCONFIRMED ? null : found+}++async function findHostBackend(+ { isolated, ledgerPath }: { isolated: boolean; ledgerPath: string },+ deps: HostBackendAttachDeps+): Promise<AttachedBackend | null | typeof UNCONFIRMED> {const records = parseSpawnLedger(deps.readLedger(ledgerPath))const decision = spawnOrAttach({ isolated, records, isPidAlive: deps.isPidAlive })@@ -192,11 +219,14 @@ export async function attachToHostBackend(]const expectedCommit = nonemptyToken(await deps.expectedCodeIdentity?.().catch(() => null))+ let unconfirmed = falsefor (const record of ordered) {const attached = await validate(record, deps, expectedCommit)- if (attached) {+ 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`@@ -206,7 +236,7 @@ export async function attachToHostBackend(}}- return null+ return unconfirmed ? UNCONFIRMED : null}export interface HostSpawnGateDeps {@@ -240,10 +270,10 @@ export async function attachOrReserveSpawn(gate: HostSpawnGateDeps,{ pollMs = 500, waitBudgetMs = HOST_SPAWN_GATE_STALE_MS }: { pollMs?: number; waitBudgetMs?: number } = {}): Promise<{ attached: AttachedBackend } | { reservation: SpawnReservation }> {- const attached = await attachToHostBackend(options, deps)+ let found = await findHostBackend(options, deps)- if (attached) {- return { attached }+ if (found && found !== UNCONFIRMED) {+ return { attached: found }}if (options.isolated) {@@ -255,7 +285,10 @@ export async function attachOrReserveSpawn(while (gate.now() < 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@@ -268,13 +301,17 @@ export async function attachOrReserveSpawn(}}- deps.log('[attach] another app is starting the host backend; waiting for it instead of spawning a second one')+ 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)- const late = await attachToHostBackend(options, deps)+ found = await findHostBackend(options, deps)- if (late) {- return { attached: late }+ if (found && found !== UNCONFIRMED) {+ return { attached: found }}}