Skip to content

The agent that grows with you

fix(desktop): supervisor owns the respawn when a backend exit empties the primary slot

teknium1d9277fe0aea8
diff --git a/apps/desktop/electron/backend-claim.test.ts b/apps/desktop/electron/backend-claim.test.ts
index 5efca30f765..2572e15ee4f 100644
--- a/apps/desktop/electron/backend-claim.test.ts
+++ b/apps/desktop/electron/backend-claim.test.ts
@@ -137,32 +137,18 @@ test('attach tolerates a child with missing stdio streams', () => {
// --- formatBackendExitLine ---------------------------------------------------
-test('exit line carries the buffered tail next to the exit code', () => {
+test('exit line carries the buffered tail next to the exit code, preferring the signal', () => {
const tail = createBackendOutputTail(64)
tail.append('Traceback (most recent call last):\n')
- const line = formatBackendExitLine('Ignoring stale Hermes backend exit', 1, null, tail)
-
- assert.equal(line, 'Ignoring stale Hermes backend exit (1)\nRecent backend output:\nTraceback (most recent call last):')
-})
-
-test('exit line prefers the signal over the code, matching the old shape', () => {
- const tail = createBackendOutputTail(64)
- tail.append('bye\n')
-
- const line = formatBackendExitLine('Hermes backend exited', 1, 'SIGTERM', tail)
-
- assert.equal(line, 'Hermes backend exited (SIGTERM)\nRecent backend output:\nbye')
+ assert.equal(
+ formatBackendExitLine('Ignoring stale Hermes backend exit', 1, null, tail),
+ 'Ignoring stale Hermes backend exit (1)\nRecent backend output:\nTraceback (most recent call last):'
+ )
+ assert.equal(formatBackendExitLine('Hermes backend exited', null, 'SIGTERM', tail), 'Hermes backend exited (SIGTERM)\nRecent backend output:\nTraceback (most recent call last):')
})
-test('exit line stays byte-identical to the legacy shape when the tail is empty', () => {
- const line = formatBackendExitLine('Hermes backend exited', 0, null, createBackendOutputTail(64))
-
- assert.equal(line, 'Hermes backend exited (0)')
-})
-
-test('exit line tolerates a missing tail', () => {
- const line = formatBackendExitLine('Hermes backend exited', 1, null, null)
-
- assert.equal(line, 'Hermes backend exited (1)')
+test('exit line stays byte-identical to the legacy shape when the tail is empty or missing', () => {
+ assert.equal(formatBackendExitLine('Hermes backend exited', 0, null, createBackendOutputTail(64)), 'Hermes backend exited (0)')
+ assert.equal(formatBackendExitLine('Hermes backend exited', 1, null, null), 'Hermes backend exited (1)')
})
diff --git a/apps/desktop/electron/backend-exit-recovery.test.ts b/apps/desktop/electron/backend-exit-recovery.test.ts
new file mode 100644
index 00000000000..696d2f8d094
--- /dev/null
+++ b/apps/desktop/electron/backend-exit-recovery.test.ts
@@ -0,0 +1,68 @@
+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)
+})
diff --git a/apps/desktop/electron/backend-exit-recovery.ts b/apps/desktop/electron/backend-exit-recovery.ts
new file mode 100644
index 00000000000..fa5177f570d
--- /dev/null
+++ b/apps/desktop/electron/backend-exit-recovery.ts
@@ -0,0 +1,44 @@
+/**
+ * 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 function createBackendExitRecoveryLatch() {
+ let claimed = false
+
+ return {
+ /** True exactly once per empty slot; `reset()` when a backend becomes ready again. */
+ claim(state: BackendExitRecoveryState): boolean {
+ if (claimed || state.hasCurrentOwner || state.hasPendingStart || state.intentionalTeardown) {
+ return false
+ }
+
+ claimed = true
+
+ return true
+ },
+ reset(): void {
+ claimed = false
+ }
+ }
+}
diff --git a/apps/desktop/electron/backend-stale-exit-recovery.test.ts b/apps/desktop/electron/backend-stale-exit-recovery.test.ts
deleted file mode 100644
index 6fcb21e5202..00000000000
--- a/apps/desktop/electron/backend-stale-exit-recovery.test.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import assert from 'node:assert/strict'
-import { test } from 'vitest'
-
-import { claimStaleBackendExitRecovery } from './backend-stale-exit-recovery'
-
-test('current owner exit is eligible for recovery', () => {
- assert.equal(claimStaleBackendExitRecovery({ hasCurrentProcess: false, hasPendingStart: false, intentionalTeardown: false, recoveryClaimed: false }), true)
-})
-
-test('stale exit with a new owner is ignored', () => {
- assert.equal(claimStaleBackendExitRecovery({ hasCurrentProcess: true, hasPendingStart: false, intentionalTeardown: false, recoveryClaimed: false }), false)
-})
-
-test('stale exit with an empty state recovers once', () => {
- const state = { hasCurrentProcess: false, hasPendingStart: false, intentionalTeardown: false, recoveryClaimed: false }
- assert.equal(claimStaleBackendExitRecovery(state), true)
- assert.equal(claimStaleBackendExitRecovery(state), false)
-})
-
-test('stale exit during intentional teardown does not recover', () => {
- assert.equal(claimStaleBackendExitRecovery({ hasCurrentProcess: false, hasPendingStart: false, intentionalTeardown: true, recoveryClaimed: false }), false)
-})
-
-test('double stale exits coalesce to one recovery', () => {
- const state = { hasCurrentProcess: false, hasPendingStart: false, intentionalTeardown: false, recoveryClaimed: false }
- assert.equal([claimStaleBackendExitRecovery(state), claimStaleBackendExitRecovery(state)].filter(Boolean).length, 1)
-})
-
-test('current exit while a replacement start is pending does not recover again', () => {
- assert.equal(claimStaleBackendExitRecovery({ hasCurrentProcess: false, hasPendingStart: true, intentionalTeardown: false, recoveryClaimed: false }), false)
-})
diff --git a/apps/desktop/electron/backend-stale-exit-recovery.ts b/apps/desktop/electron/backend-stale-exit-recovery.ts
deleted file mode 100644
index de38ee2b257..00000000000
--- a/apps/desktop/electron/backend-stale-exit-recovery.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-export type StaleExitRecoveryState = {
- hasCurrentProcess: boolean
- hasPendingStart: boolean
- intentionalTeardown: boolean
- recoveryClaimed: boolean
-}
-
-export function claimStaleBackendExitRecovery(state: StaleExitRecoveryState): boolean {
- if (state.hasCurrentProcess || state.hasPendingStart || state.intentionalTeardown || state.recoveryClaimed) return false
- state.recoveryClaimed = true
- return true
-}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index b90e0ab69ca..ae84def052e 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -30,7 +30,6 @@ import {
} from 'electron'
import { classifyActiveRuntime } from './active-runtime-state'
-import { claimStaleBackendExitRecovery } from './backend-stale-exit-recovery'
import {
destroyKeepaliveAgents,
downloadAgentFor,
@@ -62,6 +61,7 @@ import { dashboardFallbackArgs } from './backend-command'
import { createBackendConnectionState } from './backend-connection-state'
import { BackendDialClaims } from './backend-dial-claim'
import { buildDesktopBackendEnv, hermesManagedNodePathEntries, normalizeHermesHomeRoot } from './backend-env'
+import { createBackendExitRecoveryLatch } from './backend-exit-recovery'
import { isReauthRequiredError, waitForHermesReady } from './backend-health'
import { backendCommandMatches, createBackendOwnership, createBackendShutdownCoordinator } from './backend-ownership'
import { canImportHermesCli, PROBE_TIMEOUT_MS, shouldTrustHermesOverride, verifyHermesCli } from './backend-probes'
@@ -1468,7 +1468,14 @@ const backendDialClaims = new BackendDialClaims()
// True while connection-config:apply soft-rehomes the primary — suppresses the
// backend-exit toast so an intentional kill doesn't look like a crash.
let softRehomeInProgress = false
-let staleExitRecoveryClaimed = false
+// Primary-slot bookkeeping for the exit supervisor (#112344). `primaryStartsInFlight`
+// counts startHermes() calls that have not settled; `primaryRecoverySuppressed`
+// is set by every intentional invalidate of the slot and cleared by the next
+// startHermes(), so the dying child's stale exit never respawns behind a
+// re-home, a quit, or a latched boot failure.
+let primaryStartsInFlight = 0
+let primaryRecoverySuppressed = false
+const primaryExitRecovery = createBackendExitRecoveryLatch()
// Additional per-profile backends, keyed by profile name. The PRIMARY backend
// (the desktop's launch profile) stays managed by backendConnectionState +
// startHermes(); this pool only holds EXTRA profile
@@ -11328,7 +11335,7 @@ function resetHermesConnection({ soft = false } = {}) {
remoteLiveness.clear()
// The next startHermes() re-reads active-profile.json for its launch profile.
primaryProfilePin.clear()
- const hermesProcess = backendConnectionState.invalidate()
+ const hermesProcess = invalidatePrimaryConnection()
stopBackendChild(hermesProcess)
if (!soft) {
@@ -11336,6 +11343,14 @@ function resetHermesConnection({ soft = false } = {}) {
}
}
+// Every deliberate emptying of the primary slot goes through here so the
+// dying child's stale exit reads as intentional (see primaryRecoverySuppressed).
+function invalidatePrimaryConnection() {
+ primaryRecoverySuppressed = true
+
+ return backendConnectionState.invalidate()
+}
+
// Re-home the primary backend: reset connection state, then wait for the live
// dashboard process to actually exit (SIGKILL after 5s) so the next
// startHermes() spawns fresh instead of racing the dying one. Shared by the
@@ -12952,27 +12967,46 @@ async function prepareProfileRenameRequest(request) {
}
function startHermes() {
- return localBackendLifecycle.start(runHermesStart)
+ primaryRecoverySuppressed = false
+ primaryStartsInFlight += 1
+
+ const start = localBackendLifecycle.start(runHermesStart)
+
+ const releaseStart = () => {
+ primaryStartsInFlight -= 1
+ }
+
+ void start.then(releaseStart, releaseStart)
+
+ return start
}
+// A ready primary child died. When its exit leaves the primary slot with no
+// owner and no start in flight (outside an intentional teardown), the
+// supervisor owns the respawn (#112344): the stale-classified exit used to
+// "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 } = {}) {
if (!ready) {
return false
}
- if (claimStaleBackendExitRecovery({
- hasCurrentProcess: backendConnectionState.getProcess() !== null,
- hasPendingStart: backendConnectionState.getPendingPromise() !== null || localBackendLifecycle.hasPending(),
- intentionalTeardown: softRehomeInProgress || isQuittingForHandoff || backendShutdown.hasStarted(),
- recoveryClaimed: staleExitRecoveryClaimed
- })) {
- staleExitRecoveryClaimed = true
- sendBackendExit({ code, signal, ...(error ? { error } : {}) })
- startHermes().catch(() => {})
- return true
+ const claimed = primaryExitRecovery.claim({
+ hasCurrentOwner: backendConnectionState.getProcess() !== null || backendConnectionState.getPromise() !== null,
+ hasPendingStart: primaryStartsInFlight > 0,
+ intentionalTeardown: primaryRecoverySuppressed || isQuittingForHandoff || backendShutdown.hasStarted()
+ })
+
+ if (!claimed) {
+ return false
}
- return false
+ rememberLog('[supervisor] backend exit left no primary owner and no start in flight; respawning')
+ sendBackendExit({ code, signal, ...(error ? { error } : {}) })
+ startHermes().catch(respawnError => rememberLog(`[supervisor] backend respawn failed: ${respawnError.message}`))
+
+ return true
}
async function runHermesStart() {
@@ -13333,7 +13367,7 @@ async function runHermesStart() {
await Promise.race([waitForHermes(baseUrl, token), backendStartFailed])
backendConnectionState.assertCurrentAttempt(connectionAttempt)
backendReady = true
- staleExitRecoveryClaimed = false
+ primaryExitRecovery.reset()
backendStartFailure = null
const authToken = await adoptServedDashboardToken(baseUrl, token, {
@@ -13389,7 +13423,7 @@ async function runHermesStart() {
throw error
}
- const failedProcess = backendConnectionState.invalidate()
+ const failedProcess = invalidatePrimaryConnection()
stopBackendChild(failedProcess)
if (error instanceof FirstRunSetupResetError) {