Skip to content

The agent that grows with you

feat(desktop): attach to the running host backend instead of spawning a second one

teknium125d88ad0c44c
diff --git a/apps/desktop/electron/backend-discovery.test.ts b/apps/desktop/electron/backend-discovery.test.ts
new file mode 100644
index 00000000000..b9c755a2e39
--- /dev/null
+++ b/apps/desktop/electron/backend-discovery.test.ts
@@ -0,0 +1,98 @@
+import assert from 'node:assert/strict'
+
+import { test } from 'vitest'
+
+import { attachToHostBackend } from './host-backend-attach'
+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)
+})
+
+/** 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)
+})
diff --git a/apps/desktop/electron/backend-discovery.ts b/apps/desktop/electron/backend-discovery.ts
new file mode 100644
index 00000000000..b8ea59dbe2a
--- /dev/null
+++ b/apps/desktop/electron/backend-discovery.ts
@@ -0,0 +1,160 @@
+// Host-level backend discovery — the Desktop half of multiplex-only.
+//
+// Exactly ONE `hermes serve` runs per HOST and multiplexes every profile, so
+// Desktop must ATTACH to a backend that is already listening and spawn only
+// when the host has none. A backend registered by another profile is still THE
+// backend: refusing it is what produced a second process per profile.
+//
+// Nothing new has to be published for this. The backend already writes a
+// machine-root `spawn-ledger.json` entry AFTER its socket binds
+// (`hermes_cli/process_identity.py::register_self`, called from
+// `web_server.py` with `detail={host, port, profile}`), and an ungated
+// loopback backend serves its session token at `GET /`
+// (`window.__HERMES_SESSION_TOKEN__`, `web_server_dashboard.py`). The ledger is
+// DISCOVERY ONLY — a record is never trusted as proof of a usable backend; the
+// HTTP probe and the token handshake are the boundary that validates it.
+//
+// These helpers are pure / dependency-injected so the decision is testable
+// without Electron.
+
+/** Ledger record for a backend that might be attachable. */
+export interface HostBackendRecord {
+ createTime: number | null
+ /** Bind host as recorded; `0.0.0.0`/`::`/empty all dial back on loopback. */
+ host: string
+ pid: number
+ port: number
+ profile: string
+ purpose: string
+ 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'
+
+/** Ledger purposes that denote a JSON-RPC/WebSocket backend we can attach to. */
+const ATTACHABLE_PURPOSES = new Set(['dashboard', 'serve'])
+
+/** Bind hosts reachable from this machine over loopback. */
+const LOOPBACK_DIALABLE = new Set(['', '0.0.0.0', '127.0.0.1', '::', '::1', 'localhost'])
+
+function asInteger(value: unknown): number | null {
+ return Number.isInteger(value) ? Number(value) : null
+}
+
+/**
+ * Attachable backend records from the raw `spawn-ledger.json` text.
+ *
+ * A record without a bound port predates the structured detail (or belongs to
+ * a purpose that never binds) and is skipped: a port is the whole point.
+ * Unreadable/corrupt JSON yields `[]` — discovery degrades to "spawn", never
+ * to a wrong attach.
+ */
+export function parseSpawnLedger(contents: unknown): HostBackendRecord[] {
+ let parsed: unknown
+
+ try {
+ parsed = JSON.parse(String(contents ?? ''))
+ } catch {
+ return []
+ }
+
+ if (!Array.isArray(parsed)) {
+ return []
+ }
+
+ const records: HostBackendRecord[] = []
+
+ for (const value of parsed) {
+ if (!value || typeof value !== 'object') {
+ continue
+ }
+
+ const entry = value as Record<string, unknown>
+ const pid = asInteger(entry.pid)
+ const port = asInteger(entry.port)
+ const purpose = String(entry.purpose ?? '')
+ const host = String(entry.host ?? '')
+
+ if (
+ pid === null ||
+ pid <= 0 ||
+ port === null ||
+ port <= 0 ||
+ port > 65535 ||
+ !ATTACHABLE_PURPOSES.has(purpose) ||
+ !LOOPBACK_DIALABLE.has(host.toLowerCase())
+ ) {
+ continue
+ }
+
+ records.push({
+ createTime: typeof entry.create_time === 'number' ? entry.create_time : null,
+ host,
+ pid,
+ port,
+ profile: String(entry.profile ?? ''),
+ purpose,
+ registeredAt: typeof entry.registered_at === 'number' ? entry.registered_at : 0
+ })
+ }
+
+ 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.
+ */
+export function spawnOrAttach({
+ isolated = false,
+ records = []
+}: {
+ isolated?: boolean
+ records?: HostBackendRecord[]
+}): SpawnOrAttachDecision {
+ if (isolated) {
+ return { action: 'spawn', reason: 'isolated' }
+ }
+
+ const [newest] = [...records].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/host-backend-attach.ts b/apps/desktop/electron/host-backend-attach.ts
new file mode 100644
index 00000000000..180abcbc54e
--- /dev/null
+++ b/apps/desktop/electron/host-backend-attach.ts
@@ -0,0 +1,185 @@
+// 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
+
+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>
+ /** 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 }>
+ log: (message: string) => void
+}
+
+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)}`
+}
+
+/**
+ * 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): Promise<AttachedBackend | null> {
+ const baseUrl = recordBaseUrl(record)
+
+ const token = await deps.resolveServedToken(baseUrl).catch(() => null)
+
+ 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
+ }
+
+ 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(
+ { isolated, ledgerPath }: { isolated: boolean; ledgerPath: string },
+ deps: HostBackendAttachDeps
+): Promise<AttachedBackend | null> {
+ const records = parseSpawnLedger(deps.readLedger(ledgerPath))
+ const decision = spawnOrAttach({ isolated, records })
+
+ 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.
+ const ordered = [decision.record, ...records.filter(candidate => candidate !== decision.record)]
+
+ for (const record of ordered) {
+ const attached = await validate(record, deps)
+
+ 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 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
+ /** Claim the gate for this process; returns the release. */
+ take: () => () => void
+ 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 attached = await attachToHostBackend(options, deps)
+
+ if (attached) {
+ return { attached }
+ }
+
+ if (!options.isolated) {
+ const deadline = gate.now() + waitBudgetMs
+
+ 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 late = await attachToHostBackend(options, deps)
+
+ if (late) {
+ return { attached: late }
+ }
+ }
+ }
+
+ return { reservation: { release: gate.take() } }
+}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 9808fdd9048..ea3c70a6b3d 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -171,7 +171,7 @@ import {
} from './connection-registry'
import type { RosterProfileMetadata } from './connection-registry'
import { describeCrashReason, installCrashForensics } from './crash-forensics'
-import { adoptServedDashboardToken } from './dashboard-token'
+import { adoptServedDashboardToken, resolveServedDashboardToken } from './dashboard-token'
import { loadOrCreateInstallationId, sshOwnershipId } from './desktop-installation'
import { formatDesktopLogLine } from './desktop-log-line'
import {
@@ -254,6 +254,7 @@ import {
tightenSecretFileMode,
writeSecretFileAtomic
} from './hardening'
+import { type AttachedBackend, attachOrReserveSpawn, spawnLedgerPath, type SpawnReservation } from './host-backend-attach'
import { requestHudClose } from './hud-close'
import { cursorPointInWindow } from './hud-cursor'
import { startHudGameOverlayWatch } from './hud-game-overlay'
@@ -1601,7 +1602,7 @@ function persistPoolLimits(limits) {
// readPersistedPoolLimits() call below, because that call logs during module
// evaluation; declaring these later crashed launch with `undefined.push` in
// the packaged build (esbuild lowers the TDZ to undefined instead of throwing).
-const hermesLog = []
+const hermesLog: string[] = []
let desktopLogBuffer = ''
let desktopLogFlushTimer = null
let desktopLogFlushPromise = Promise.resolve()
@@ -12948,6 +12949,137 @@ async function prepareProfileRenameRequest(request) {
})
}
+// ── Attach-first: one backend per HOST (multiplex-only) ───────────────────
+// Escape hatch: a dedicated, private backend for this app instead of the host's.
+const ISOLATED_BACKEND = process.env.HERMES_DESKTOP_ISOLATED_BACKEND === '1'
+const ATTACHED_LIVENESS_POLL_MS = 15_000
+let attachedBackendMonitor: NodeJS.Timeout | null = null
+let hostSpawnReservation: SpawnReservation | null = null
+
+function stopAttachedBackendMonitor() {
+ if (attachedBackendMonitor) {
+ clearInterval(attachedBackendMonitor)
+ attachedBackendMonitor = null
+ }
+}
+
+/**
+ * An attached backend has no child process, so `child.exit` can never drive
+ * recovery. Poll its readiness instead; a backend that dies under us
+ * invalidates the connection and hands the respawn to the same supervisor path
+ * a dead child would (which re-runs discovery and spawns, since the host now
+ * has no backend).
+ */
+function startAttachedBackendMonitor(attached: AttachedBackend) {
+ stopAttachedBackendMonitor()
+
+ attachedBackendMonitor = setInterval(() => {
+ void waitForHermes(attached.baseUrl, attached.token, undefined, 'token', {}).catch(() => {
+ stopAttachedBackendMonitor()
+ rememberLog(`[attach] attached backend on ${attached.baseUrl} (pid ${attached.pid}) is gone; recovering`)
+ invalidatePrimaryConnection()
+ scheduleUnexpectedPrimaryRecovery({ error: 'The Hermes backend this app attached to exited.', ready: true })
+ })
+ }, ATTACHED_LIVENESS_POLL_MS)
+
+ attachedBackendMonitor.unref?.()
+}
+
+/** Discover and attach to the host's running backend; null means "spawn one". */
+function attachToRunningHostBackend(): Promise<AttachedBackend | null> {
+ const options = { isolated: ISOLATED_BACKEND, ledgerPath: spawnLedgerPath(HERMES_HOME, path.join) }
+
+ return attachOrReserveSpawn(options, hostBackendAttachDeps(), hostSpawnGateDeps())
+ .then(outcome => {
+ if ('attached' in outcome) {
+ releaseHostSpawnReservation()
+
+ return outcome.attached
+ }
+
+ hostSpawnReservation = outcome.reservation
+
+ return null
+ })
+ .catch(error => {
+ // Discovery must never be able to block boot: fall through to spawning.
+ rememberLog(`[attach] host backend discovery failed (${error.message}); spawning our own`)
+
+ return null
+ })
+}
+
+function hostBackendAttachDeps() {
+ return {
+ log: rememberLog,
+ readLedger: (target: string) => {
+ try {
+ return fs.readFileSync(target, 'utf8')
+ } catch {
+ return null
+ }
+ },
+ probeWebSocket: (wsUrl: string) => probeGatewayWebSocket(wsUrl, { WebSocketImpl: globalThis.WebSocket }),
+ resolveServedToken: (baseUrl: string) => resolveServedDashboardToken(baseUrl, ''),
+ waitForReady: (baseUrl: string, token: string) => waitForHermes(baseUrl, token, undefined, 'token', {})
+ }
+}
+
+function hostSpawnGatePath() {
+ return path.join(HERMES_HOME, 'desktop-backend-spawn.json')
+}
+
+function hostSpawnGateDeps() {
+ return {
+ now: () => Date.now(),
+ read: () => {
+ try {
+ const record = JSON.parse(fs.readFileSync(hostSpawnGatePath(), 'utf8'))
+ const owner = Number(record?.pid)
+
+ if (!Number.isInteger(owner) || owner <= 0) {
+ return null
+ }
+
+ // A gate whose owner is gone is no gate at all.
+ try {
+ process.kill(owner, 0)
+ } catch {
+ return null
+ }
+
+ return { ownerAlive: true, startedAt: Number(record?.startedAt) || 0 }
+ } catch {
+ 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.
+ }
+ }
+ },
+ sleep: (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))
+ }
+}
+
+function releaseHostSpawnReservation() {
+ hostSpawnReservation?.release()
+ hostSpawnReservation = null
+}
+
function startHermes() {
primaryRecoverySuppressed = false
primaryStartsInFlight += 1
@@ -12969,7 +13101,12 @@ function startHermes() {
// "log and return", and recovery then hinged on the renderer noticing its
// socket drop — a 9 h engine-less window when it did not. Pool children are
// deliberately not consulted: they never own the window backend.
-function scheduleUnexpectedPrimaryRecovery({ code = null, signal = null, error = null, ready = false } = {}) {
+function scheduleUnexpectedPrimaryRecovery({
+ code = null,
+ signal = null,
+ error = null,
+ ready = false
+}: { code?: number | null; error?: string | null; ready?: boolean; signal?: string | null } = {}) {
if (!ready) {
return false
}
@@ -13138,6 +13275,7 @@ async function runHermesStart() {
const setup = await runPrimaryBackendStartup({
signal: localBackendLifecycle.signal,
assertCurrentAttempt: () => backendConnectionState.assertCurrentAttempt(connectionAttempt),
+ attachHostBackend: attachToRunningHostBackend,
connectRemote,
ensureLocalRuntime: backend =>
ensureRuntime(backend, () => backendConnectionState.assertCurrentAttempt(connectionAttempt)),
@@ -13171,9 +13309,42 @@ async function runHermesStart() {
return setup.connection
}
+ // Multiplex-only: a backend was already running on this host and we attached
+ // to it. Nothing was spawned, so there is no child to own — liveness is
+ // polled instead (startAttachedBackendMonitor).
+ if (setup.kind === 'attached') {
+ const attached = setup.attached
+
+ setWslBridgeProfileState(primaryProfile, true)
+ startAttachedBackendMonitor(attached)
+
+ updateBootProgress({
+ phase: 'backend.ready',
+ message: 'Attached to the running Hermes backend',
+ progress: 94,
+ running: true,
+ error: null
+ })
+
+ return {
+ baseUrl: attached.baseUrl,
+ mode: 'local',
+ source: 'local',
+ authMode: 'token',
+ attached: true,
+ token: attached.token,
+ profile: primaryProfile,
+ wsUrl: attached.wsUrl,
+ logs: hermesLog.slice(-80),
+ ...getWindowState()
+ }
+ }
+
// Local WSL backend — paths are bridgeable.
setWslBridgeProfileState(primaryProfile, true)
+ stopAttachedBackendMonitor()
+
const backend = setup.backend
// Route old runtimes (no `serve`) through the legacy `dashboard --no-open`.
backend.args = await getBackendArgsForRuntime(backend)
@@ -13359,6 +13530,9 @@ async function runHermesStart() {
await Promise.race([waitForHermes(baseUrl, token), backendStartFailed])
backendConnectionState.assertCurrentAttempt(connectionAttempt)
backendReady = true
+ // The host now has a bound, registered backend: the next launcher will
+ // discover and attach to it, so the spawn gate is done.
+ releaseHostSpawnReservation()
primaryExitRecovery.reset()
backendStartFailure = null
@@ -13411,6 +13585,8 @@ async function runHermesStart() {
...getWindowState()
}
})().catch(async error => {
+ releaseHostSpawnReservation()
+
if (!backendConnectionState.clearPromiseForAttempt(connectionAttempt)) {
throw error
}
diff --git a/apps/desktop/electron/primary-backend-startup.ts b/apps/desktop/electron/primary-backend-startup.ts
index e319b9b2407..6f57d819bd9 100644
--- a/apps/desktop/electron/primary-backend-startup.ts
+++ b/apps/desktop/electron/primary-backend-startup.ts
@@ -1,9 +1,14 @@
import { runBackendStartStep } from './backend-start-cancellation'
import type { FirstRunSetupDecision } from './first-run-setup-gate'
-export interface PrimaryBackendStartupOptions<Backend, RuntimeBackend, Remote, Connection> {
+export interface PrimaryBackendStartupOptions<Backend, RuntimeBackend, Remote, Connection, Attached> {
assertCurrentAttempt: () => void
signal?: AbortSignal
+ /**
+ * Multiplex-only: attach to the backend already running on this HOST.
+ * Resolves null when the host has none, which is the only case that spawns.
+ */
+ attachHostBackend?: () => Promise<Attached | null>
connectRemote: (remote: Remote) => Promise<Connection>
ensureLocalRuntime: (backend: Backend) => Promise<RuntimeBackend>
prepareLocalBackend: () => Backend | Promise<Backend>
@@ -12,8 +17,10 @@ export interface PrimaryBackendStartupOptions<Backend, RuntimeBackend, Remote, C
waitForLocalStart: () => Promise<unknown>
}
-export type PrimaryBackendStartupResult<RuntimeBackend, Connection> =
- { kind: 'local'; backend: RuntimeBackend } | { kind: 'remote'; connection: Connection }
+export type PrimaryBackendStartupResult<RuntimeBackend, Connection, Attached = never> =
+ | { kind: 'attached'; attached: Attached }
+ | { kind: 'local'; backend: RuntimeBackend }
+ | { kind: 'remote'; connection: Connection }
interface ResolvedPrimaryRemote {
authMode?: 'oauth' | 'token'
@@ -81,8 +88,9 @@ export class FirstRunSetupResetError extends Error {
// test: an already-saved remote wins immediately; otherwise update exclusion
// and local backend resolution happen before the setup gate, and a remote Apply
// re-resolves persisted config without ever entering ensureRuntime/bootstrap.
-export async function runPrimaryBackendStartup<Backend, RuntimeBackend, Remote, Connection>({
+export async function runPrimaryBackendStartup<Backend, RuntimeBackend, Remote, Connection, Attached = never>({
assertCurrentAttempt,
+ attachHostBackend,
connectRemote,
ensureLocalRuntime,
prepareLocalBackend,
@@ -90,8 +98,8 @@ export async function runPrimaryBackendStartup<Backend, RuntimeBackend, Remote,
waitForDecision,
waitForLocalStart,
signal
-}: PrimaryBackendStartupOptions<Backend, RuntimeBackend, Remote, Connection>): Promise<
- PrimaryBackendStartupResult<RuntimeBackend, Connection>
+}: PrimaryBackendStartupOptions<Backend, RuntimeBackend, Remote, Connection, Attached>): Promise<
+ PrimaryBackendStartupResult<RuntimeBackend, Connection, Attached>
> {
const step = async <T>(run: () => T | Promise<T>) => {
const result = await runBackendStartStep(signal, run)
@@ -108,6 +116,15 @@ export async function runPrimaryBackendStartup<Backend, RuntimeBackend, Remote,
await step(waitForLocalStart)
+ // Multiplex-only: one backend per HOST. Attach before resolving a runtime or
+ // entering the first-run gate — a machine with a live backend is, by
+ // definition, already set up, and the runtime resolve is only needed to spawn.
+ const attached = attachHostBackend ? await step(attachHostBackend) : null
+
+ if (attached) {
+ return { kind: 'attached', attached }
+ }
+
const backend = await step(prepareLocalBackend)
const decision = await step(() => waitForDecision(backend))