Skip to content

The agent that grows with you

fix(desktop): confirm detached updater spawn before quitting for hand-off (#66753)

Tekniumac2e4207c11b
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 9f2b3c9f26f..8743f3fab4d 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -231,6 +231,7 @@ import { readLiveUpdateMarker, updateHandoffConflict, writeUpdateMarker } from '
import { isOfficialSshRemote, OFFICIAL_REPO_HTTPS_URL } from './update-remote'
import {
collectRelaunchArgs,
+ observeUpdaterHandoff,
resolvePosixScriptHandoff,
resolveStagedUpdaterBinary,
resolveUpdateScriptHandoff,
@@ -3485,10 +3486,33 @@ async function applyUpdates(opts = {}) {
// appears), THEN quit to release the venv shim. The updater rebuilds and
// relaunches us when it's done. (#50419 — a 600ms quit looked like a crash
// and lured users into the #50238 relaunch loop.)
+ //
+ // The dwell doubles as the hand-off settle window (#66753): watch the
+ // detached child for an async spawn `error` (ENOENT/EACCES) or an early
+ // non-zero/signal exit. On failure, DON'T quit — the user would be left
+ // with no app, no updater, and no evidence. Restart our backend and
+ // surface the error instead. The pre-written marker names the dead child
+ // pid, so readLiveUpdateMarker self-heals it; no cleanup needed.
+ const dwellStartedAt = Date.now()
+ const handoffOutcome = await observeUpdaterHandoff(child, UPDATE_HANDOFF_DWELL_MS)
+
+ if (!handoffOutcome.ok) {
+ const message = `Update failed to start: ${handoffOutcome.message}. Hermes will keep running — try again, or run \`hermes update\` from a terminal.`
+
+ rememberLog(`[updates] hand-off not viable, aborting quit: ${handoffOutcome.message}`)
+ emitUpdateProgress({ stage: 'error', message, percent: null })
+ startHermes().catch(() => {})
+
+ return { ok: false, error: 'updater-spawn-failed', message }
+ }
+
isQuittingForHandoff = true
- setTimeout(() => {
- app.quit()
- }, UPDATE_HANDOFF_DWELL_MS)
+ setTimeout(
+ () => {
+ app.quit()
+ },
+ Math.max(0, UPDATE_HANDOFF_DWELL_MS - (Date.now() - dwellStartedAt))
+ )
return { ok: true, handedOff: true, updater }
} finally {
@@ -3578,11 +3602,26 @@ async function handOffWindowsBootstrapRecovery(reason) {
)
// Same dwell as the in-app update hand-off (#50419): give the updater's
// window time to appear before we vanish, so the recovery doesn't look like
- // a crash and provoke a mid-recovery relaunch.
+ // a crash and provoke a mid-recovery relaunch. The dwell doubles as the
+ // hand-off settle window (#66753): a spawn error or early updater death
+ // returns false so the caller falls through to its next recovery path
+ // instead of quitting into nothing.
+ const dwellStartedAt = Date.now()
+ const handoffOutcome = await observeUpdaterHandoff(child, UPDATE_HANDOFF_DWELL_MS)
+
+ if (!handoffOutcome.ok) {
+ rememberLog(`[bootstrap] recovery hand-off not viable, staying alive: ${handoffOutcome.message}`)
+
+ return false
+ }
+
isQuittingForHandoff = true
- setTimeout(() => {
- app.quit()
- }, UPDATE_HANDOFF_DWELL_MS)
+ setTimeout(
+ () => {
+ app.quit()
+ },
+ Math.max(0, UPDATE_HANDOFF_DWELL_MS - (Date.now() - dwellStartedAt))
+ )
return true
}
@@ -3788,10 +3827,30 @@ async function applyUpdatesPosixHandoff(opts: any) {
percent: 100
})
+ // Settle window (#66753): the reported macOS failure mode is exactly this
+ // path — the app quits, bash/posix.sh dies early (or was never spawnable),
+ // and the user is left with no app, no updater, and no relaunch. Watch the
+ // child through the dwell; on spawn error or early death, stay alive and
+ // surface the failure instead of quitting into nothing.
+ const dwellStartedAt = Date.now()
+ const handoffOutcome = await observeUpdaterHandoff(child, UPDATE_HANDOFF_DWELL_MS)
+
+ if (!handoffOutcome.ok) {
+ const message = `Update failed to start: ${handoffOutcome.message}. Hermes will keep running — try again, or run \`hermes update\` from a terminal.`
+
+ rememberLog(`[updates] posix hand-off not viable, aborting quit: ${handoffOutcome.message}`)
+ emitUpdateProgress({ stage: 'error', message, percent: null })
+
+ return { ok: false, error: 'updater-spawn-failed', message }
+ }
+
isQuittingForHandoff = true
- setTimeout(() => {
- app.quit()
- }, UPDATE_HANDOFF_DWELL_MS)
+ setTimeout(
+ () => {
+ app.quit()
+ },
+ Math.max(0, UPDATE_HANDOFF_DWELL_MS - (Date.now() - dwellStartedAt))
+ )
return { ok: true, handedOff: true, updater: handoff.scriptPath }
}
diff --git a/apps/desktop/electron/updater-process.test.ts b/apps/desktop/electron/updater-process.test.ts
index dbf3a765f79..96fc1de2c87 100644
--- a/apps/desktop/electron/updater-process.test.ts
+++ b/apps/desktop/electron/updater-process.test.ts
@@ -7,6 +7,7 @@ import { test } from 'vitest'
import {
collectRelaunchArgs,
MARKER_SELF_ADOPT_EPOCH_MS,
+ observeUpdaterHandoff,
resolvePosixScriptHandoff,
resolveStagedUpdaterBinary,
resolveUpdateScriptHandoff,
@@ -309,3 +310,153 @@ test('sandboxFallbackFromEnv: ELECTRON_DISABLE_SANDBOX / --no-sandbox opt out',
assert.equal(sandboxFallbackFromEnv({ ELECTRON_DISABLE_SANDBOX: '0' }, []), false)
assert.equal(sandboxFallbackFromEnv({}, []), false)
})
+
+// ── observeUpdaterHandoff (#66753) ──────────────────────────────────────────
+
+class FakeChild {
+ pid = 1234
+ listeners = new Map<string, Array<(...args: unknown[]) => void>>()
+ removed: string[] = []
+
+ unref() {}
+
+ once(event: string, listener: (...args: unknown[]) => void) {
+ const arr = this.listeners.get(event) ?? []
+
+ arr.push(listener)
+ this.listeners.set(event, arr)
+
+ return this
+ }
+
+ removeListener(event: string, _listener: (...args: unknown[]) => void) {
+ this.removed.push(event)
+
+ return this
+ }
+
+ emit(event: string, ...args: unknown[]) {
+ for (const listener of this.listeners.get(event) ?? []) {
+ listener(...args)
+ }
+ }
+}
+
+function manualTimer() {
+ const pending: Array<() => void> = []
+
+ return {
+ deps: {
+ setTimeoutFn: (callback: () => void, _ms: number) => {
+ pending.push(callback)
+
+ return 0
+ },
+ clearTimeoutFn: () => {}
+ },
+ fire: () => {
+ for (const callback of pending.splice(0)) {
+ callback()
+ }
+ }
+ }
+}
+
+test('observeUpdaterHandoff reports a spawn error instead of settling ok', async () => {
+ const child = new FakeChild()
+ const timer = manualTimer()
+ const outcomePromise = observeUpdaterHandoff(child, 2500, timer.deps)
+
+ const err: Error & { code?: string } = new Error('spawn ENOENT')
+
+ err.code = 'ENOENT'
+ child.emit('error', err)
+
+ const outcome = await outcomePromise
+
+ assert.equal(outcome.ok, false)
+ assert.equal(outcome.reason, 'spawn-error')
+ assert.match(outcome.message ?? '', /ENOENT/)
+})
+
+test('observeUpdaterHandoff reports a non-zero early exit', async () => {
+ const child = new FakeChild()
+ const timer = manualTimer()
+ const outcomePromise = observeUpdaterHandoff(child, 2500, timer.deps)
+
+ child.emit('exit', 127, null)
+
+ const outcome = await outcomePromise
+
+ assert.equal(outcome.ok, false)
+ assert.equal(outcome.reason, 'early-exit')
+ assert.equal(outcome.code, 127)
+})
+
+test('observeUpdaterHandoff reports a signal death inside the window', async () => {
+ const child = new FakeChild()
+ const timer = manualTimer()
+ const outcomePromise = observeUpdaterHandoff(child, 2500, timer.deps)
+
+ child.emit('exit', null, 'SIGTERM')
+
+ const outcome = await outcomePromise
+
+ assert.equal(outcome.ok, false)
+ assert.equal(outcome.reason, 'early-exit')
+ assert.equal(outcome.signal, 'SIGTERM')
+})
+
+test('observeUpdaterHandoff accepts a clean exit 0 (Windows cmd start wrapper)', async () => {
+ const child = new FakeChild()
+ const timer = manualTimer()
+ const outcomePromise = observeUpdaterHandoff(child, 2500, timer.deps)
+
+ child.emit('exit', 0, null)
+
+ const outcome = await outcomePromise
+
+ assert.equal(outcome.ok, true)
+ assert.equal(outcome.code, 0)
+})
+
+test('observeUpdaterHandoff settles ok when the child survives the window', async () => {
+ const child = new FakeChild()
+ const timer = manualTimer()
+ const outcomePromise = observeUpdaterHandoff(child, 2500, timer.deps)
+
+ timer.fire()
+
+ const outcome = await outcomePromise
+
+ assert.equal(outcome.ok, true)
+ assert.equal(outcome.reason, undefined)
+ // Listeners must be detached so a post-quit late exit can't fire them.
+ assert.deepEqual(child.removed.sort(), ['error', 'exit'])
+})
+
+test('observeUpdaterHandoff ignores events after the first settle', async () => {
+ const child = new FakeChild()
+ const timer = manualTimer()
+ const outcomePromise = observeUpdaterHandoff(child, 2500, timer.deps)
+
+ child.emit('exit', 1, null)
+ child.emit('error', new Error('late'))
+ timer.fire()
+
+ const outcome = await outcomePromise
+
+ assert.equal(outcome.ok, false)
+ assert.equal(outcome.reason, 'early-exit')
+})
+
+test('observeUpdaterHandoff settles ok for children without an event interface', async () => {
+ const timer = manualTimer()
+ const outcomePromise = observeUpdaterHandoff({ pid: 1, unref: () => {} }, 2500, timer.deps)
+
+ timer.fire()
+
+ const outcome = await outcomePromise
+
+ assert.equal(outcome.ok, true)
+})
diff --git a/apps/desktop/electron/updater-process.ts b/apps/desktop/electron/updater-process.ts
index ad6ae0d9f07..4cbb96247fb 100644
--- a/apps/desktop/electron/updater-process.ts
+++ b/apps/desktop/electron/updater-process.ts
@@ -318,3 +318,116 @@ export function spawnUpdaterProcess(
return child
}
+
+export interface UpdaterHandoffOutcome {
+ ok: boolean
+ /** Set when ok is false. */
+ reason?: 'spawn-error' | 'early-exit'
+ /** Human-readable detail for logs (never contains argv secrets). */
+ message?: string
+ /** Exit code when the child exited inside the settle window. */
+ code?: number | null
+ /** Signal when the child was killed inside the settle window. */
+ signal?: string | null
+}
+
+export interface ObserveUpdaterHandoffDeps {
+ setTimeoutFn?: (callback: () => void, ms: number) => unknown
+ clearTimeoutFn?: (timer: unknown) => void
+}
+
+/**
+ * Watch a just-spawned detached updater for the duration of the quit dwell
+ * and report whether the hand-off actually became viable (#66753).
+ *
+ * Before this, the Desktop called `unref()` and quit after a fixed dwell
+ * without ever observing the child's async `error` event (ENOENT/EACCES —
+ * Node reports exec failures asynchronously) or an early `exit`. A failed
+ * spawn therefore looked identical to a successful one: the app vanished, no
+ * updater appeared, and nothing relaunched. Worse, an unhandled `'error'`
+ * event on the detached child would crash the Electron main process outright.
+ *
+ * Success is: no `error` event AND either the child survives the settle
+ * window or it exits 0 inside it (the Windows `cmd start` wrapper exits 0
+ * immediately by design — see wrapHandoffForDetachedConsole). Failure is a
+ * spawn `error`, a non-zero exit, or a signal death inside the window.
+ *
+ * Children that expose no event interface (bare test doubles) settle as ok
+ * after the window — the observation is a best-effort hardening, never a new
+ * way to wedge an update.
+ */
+export function observeUpdaterHandoff(
+ child: UpdaterChild,
+ settleMs: number,
+ deps: ObserveUpdaterHandoffDeps = {}
+): Promise<UpdaterHandoffOutcome> {
+ const setTimeoutFn = deps.setTimeoutFn ?? setTimeout
+ const clearTimeoutFn =
+ deps.clearTimeoutFn ?? ((timer: unknown) => clearTimeout(timer as ReturnType<typeof setTimeout>))
+
+ const observable = child as UpdaterChild & {
+ once?: (event: string, listener: (...args: unknown[]) => void) => unknown
+ removeListener?: (event: string, listener: (...args: unknown[]) => void) => unknown
+ }
+
+ if (typeof observable.once !== 'function') {
+ return new Promise(resolve => {
+ setTimeoutFn(() => resolve({ ok: true }), settleMs)
+ })
+ }
+
+ return new Promise(resolve => {
+ let settled = false
+
+ const finish = (outcome: UpdaterHandoffOutcome) => {
+ if (settled) {
+ return
+ }
+
+ settled = true
+ clearTimeoutFn(timer)
+ observable.removeListener?.('error', onError)
+ observable.removeListener?.('exit', onExit)
+ resolve(outcome)
+ }
+
+ const onError = (...args: unknown[]) => {
+ const error = args[0] as (Error & { code?: string }) | undefined
+
+ finish({
+ ok: false,
+ reason: 'spawn-error',
+ message: `updater spawn failed: ${error?.code || error?.message || 'unknown error'}`
+ })
+ }
+
+ const onExit = (...args: unknown[]) => {
+ const code = args[0] as number | null
+ const signal = args[1] as string | null
+
+ if (signal || (typeof code === 'number' && code !== 0)) {
+ finish({
+ ok: false,
+ reason: 'early-exit',
+ message: signal
+ ? `updater died from signal ${signal} before the settle window elapsed`
+ : `updater exited ${code} before the settle window elapsed`,
+ code: code ?? null,
+ signal: signal ?? null
+ })
+
+ return
+ }
+
+ // Clean exit 0 inside the window is expected for wrapper shapes
+ // (cmd.exe `start` on Windows exits immediately after launching the
+ // real script in its own console).
+ finish({ ok: true, code: code ?? 0, signal: null })
+ }
+
+ const timer = setTimeoutFn(() => finish({ ok: true }), settleMs)
+
+ observable.once('error', onError)
+ observable.once('exit', onExit)
+ })
+}