Skip to content

The agent that grows with you

fix(desktop): claim the host spawn gate atomically

wangtaof0c447bd7a2c
diff --git a/apps/desktop/electron/backend-discovery.test.ts b/apps/desktop/electron/backend-discovery.test.ts
index 395c4cf9488..969bbfc9cd1 100644
--- a/apps/desktop/electron/backend-discovery.test.ts
+++ b/apps/desktop/electron/backend-discovery.test.ts
@@ -1,8 +1,12 @@
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 { attachToHostBackend } from './host-backend-attach'
+import { attachOrReserveSpawn, attachToHostBackend } from './host-backend-attach'
+import { claimHostSpawnGate } from './host-spawn-gate'
import { runPrimaryBackendStartup } from './primary-backend-startup'
const LEDGER = JSON.stringify([
@@ -139,6 +143,168 @@ test('a record whose backend rejects the session token does not attach', async (
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
diff --git a/apps/desktop/electron/host-backend-attach.ts b/apps/desktop/electron/host-backend-attach.ts
index b7f095f5977..44a603f4529 100644
--- a/apps/desktop/electron/host-backend-attach.ts
+++ b/apps/desktop/electron/host-backend-attach.ts
@@ -151,8 +151,8 @@ export interface HostSpawnGateDeps {
now: () => number
/** Read the gate record; null when absent, unreadable, or its owner is gone. */
read: () => { ownerAlive: boolean; startedAt: number } | null
- /** Claim the gate for this process; returns the release. */
- take: () => () => void
+ /** Atomically claim the gate; null means another process won the race. */
+ take: () => (() => void) | null
sleep: (ms: number) => Promise<void>
}
@@ -184,23 +184,39 @@ export async function attachOrReserveSpawn(
return { attached }
}
- if (!options.isolated) {
- const deadline = gate.now() + waitBudgetMs
+ if (options.isolated) {
+ return { reservation: { release: () => {} } }
+ }
- while (
- gate.now() < deadline &&
- classifyHostSpawnGate(gate.read(), { now: gate.now(), staleAfterMs: HOST_SPAWN_GATE_STALE_MS }) === 'wait'
- ) {
- deps.log('[attach] another app is starting the host backend; waiting for it instead of spawning a second one')
- await gate.sleep(pollMs)
+ const deadline = gate.now() + waitBudgetMs
- const late = await attachToHostBackend(options, deps)
+ while (gate.now() < deadline) {
+ const gateState = gate.read()
+
+ if (
+ classifyHostSpawnGate(gateState, {
+ now: gate.now(),
+ staleAfterMs: HOST_SPAWN_GATE_STALE_MS
+ }) === 'take'
+ ) {
+ const release = gate.take()
- if (late) {
- return { attached: late }
+ if (release) {
+ return { reservation: { release } }
}
}
+
+ deps.log('[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)
+
+ if (late) {
+ return { attached: late }
+ }
}
- return { reservation: { release: gate.take() } }
+ // 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-spawn-gate.ts b/apps/desktop/electron/host-spawn-gate.ts
new file mode 100644
index 00000000000..7d30ef9e0f6
--- /dev/null
+++ b/apps/desktop/electron/host-spawn-gate.ts
@@ -0,0 +1,132 @@
+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/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index c7b96649160..8cf587193f5 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -296,11 +296,13 @@ import {
import {
type AttachedBackend,
attachOrReserveSpawn,
+ HOST_SPAWN_GATE_STALE_MS,
spawnLedgerPath,
type SpawnReservation
} from './host-backend-attach'
import { assertNoSecondLocalBackend, assertNotPassiveSpawn } from './host-backend-singleton'
import { lookupPublishedSessionToken } from './host-published-token'
+import { claimHostSpawnGate } from './host-spawn-gate'
import { requestHudClose } from './hud-close'
import { cursorPointInWindow } from './hud-cursor'
import { startHudGameOverlayWatch } from './hud-game-overlay'
@@ -12661,24 +12663,10 @@ function hostSpawnGateDeps() {
return null
}
},
- take: () => {
- const gatePath = hostSpawnGatePath()
-
- try {
- fs.writeFileSync(gatePath, JSON.stringify({ pid: process.pid, startedAt: Date.now() }), { mode: 0o600 })
- } catch {
- // A gate we cannot write is a race we cannot win; spawning anyway is
- // exactly today's behaviour, so never fail boot over it.
- }
-
- return () => {
- try {
- fs.unlinkSync(gatePath)
- } catch {
- // Already gone / never written.
- }
- }
- },
+ take: () =>
+ claimHostSpawnGate(hostSpawnGatePath(), {
+ staleAfterMs: HOST_SPAWN_GATE_STALE_MS
+ }),
sleep: (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))
}
}