Skip to content

The agent that grows with you

fix(desktop): retain and cancel owned backend lifecycle work

brooklyn!8607d6a52a2b
diff --git a/apps/desktop/electron/backend-child.ts b/apps/desktop/electron/backend-child.ts
index df720be5916..398d779f831 100644
--- a/apps/desktop/electron/backend-child.ts
+++ b/apps/desktop/electron/backend-child.ts
@@ -46,7 +46,70 @@ export interface BackendProcessRoot {
export interface KillableChild extends BackendProcessRoot {
killed?: boolean
- kill: (signal: string) => void
+ kill: (signal: NodeJS.Signals) => void
+}
+
+export interface WaitableChild extends KillableChild {
+ exitCode: number | null
+ signalCode: string | null
+ once: (event: 'exit', listener: () => void) => unknown
+ removeListener: (event: 'exit', listener: () => void) => unknown
+}
+
+/** Graceful exit, SIGKILL escalation, then a bounded wait for the escalation. */
+export async function waitForBackendExit(
+ child: WaitableChild | null | undefined,
+ deps: StopBackendChildDeps,
+ timeoutMs = 5000
+): Promise<void> {
+ if (!child || child.exitCode !== null || child.signalCode !== null) {
+ return
+ }
+
+ const exited = () => child.exitCode !== null || child.signalCode !== null
+
+ const wait = (delay: number) =>
+ new Promise<void>(resolve => {
+ if (exited()) {
+ resolve()
+
+ return
+ }
+
+ const finish = () => {
+ clearTimeout(timer)
+ child.removeListener('exit', finish)
+ resolve()
+ }
+
+ const timer = setTimeout(finish, delay)
+ child.once('exit', finish)
+ })
+
+ await wait(timeoutMs)
+
+ if (exited()) {
+ return
+ }
+
+ try {
+ if ((deps.isWindows ?? process.platform === 'win32') && Number.isInteger(child.pid)) {
+ deps.forceKillProcessTree(child.pid as number)
+ } else if (Number.isInteger(child.pid)) {
+ try {
+ const killGroup = deps.killGroup ?? ((pid, signal) => process.kill(pid, signal))
+ killGroup(-(child.pid as number), 'SIGKILL')
+ } catch {
+ child.kill('SIGKILL')
+ }
+ } else {
+ child.kill('SIGKILL')
+ }
+ } catch {
+ return
+ }
+
+ await wait(1000)
}
/**
diff --git a/apps/desktop/electron/backend-connection-state.test.ts b/apps/desktop/electron/backend-connection-state.test.ts
index ce9dd2fded1..55ee25856e1 100644
--- a/apps/desktop/electron/backend-connection-state.test.ts
+++ b/apps/desktop/electron/backend-connection-state.test.ts
@@ -105,3 +105,19 @@ test('an invalidated attempt cannot attach a late-spawned process', () => {
assert.equal(state.attachProcess(staleAttempt, { id: 'late' }), null)
assert.equal(state.getProcess(), null)
})
+
+test('distinguishes a pending connection attempt from a cached settled descriptor', async () => {
+ const state = createBackendConnectionState<FakeProcess, string>()
+ const connection = deferred<string>()
+ const attempt = state.startAttempt()
+
+ state.setPromise(attempt, connection.promise)
+ assert.equal(state.getPendingPromise(), connection.promise)
+
+ connection.resolve('https://remote.example')
+ await connection.promise
+ await Promise.resolve()
+
+ assert.equal(state.getPromise(), connection.promise)
+ assert.equal(state.getPendingPromise(), null)
+})
diff --git a/apps/desktop/electron/backend-connection-state.ts b/apps/desktop/electron/backend-connection-state.ts
index d20165db851..fdbe6dea263 100644
--- a/apps/desktop/electron/backend-connection-state.ts
+++ b/apps/desktop/electron/backend-connection-state.ts
@@ -12,6 +12,7 @@ export function createBackendConnectionState<TProcess, TConnection>() {
let generation = 0
let process: TProcess | null = null
let promise: Promise<TConnection> | null = null
+ let pendingPromise: Promise<TConnection> | null = null
return {
startAttempt(): BackendConnectionAttempt<TConnection> {
@@ -25,6 +26,20 @@ export function createBackendConnectionState<TProcess, TConnection>() {
attempt.promise = nextPromise
promise = nextPromise
+ pendingPromise = nextPromise
+
+ void nextPromise.then(
+ () => {
+ if (attempt.generation === generation && promise === nextPromise) {
+ pendingPromise = null
+ }
+ },
+ () => {
+ if (attempt.generation === generation && promise === nextPromise) {
+ pendingPromise = null
+ }
+ }
+ )
return true
},
@@ -53,6 +68,7 @@ export function createBackendConnectionState<TProcess, TConnection>() {
process = null
promise = null
+ pendingPromise = null
return true
},
@@ -63,6 +79,7 @@ export function createBackendConnectionState<TProcess, TConnection>() {
}
promise = null
+ pendingPromise = null
return true
},
@@ -75,12 +92,17 @@ export function createBackendConnectionState<TProcess, TConnection>() {
return promise
},
+ getPendingPromise(): Promise<TConnection> | null {
+ return pendingPromise
+ },
+
invalidate(): TProcess | null {
const currentProcess = process
generation += 1
process = null
promise = null
+ pendingPromise = null
return currentProcess
}
diff --git a/apps/desktop/electron/backend-exit.test.ts b/apps/desktop/electron/backend-exit.test.ts
new file mode 100644
index 00000000000..4380dc8c984
--- /dev/null
+++ b/apps/desktop/electron/backend-exit.test.ts
@@ -0,0 +1,23 @@
+import assert from 'node:assert/strict'
+import { EventEmitter } from 'node:events'
+
+import { test, vi } from 'vitest'
+
+import { waitForBackendExit } from './backend-child'
+
+test('backend exit escalation remains bounded when no exit or close arrives', async () => {
+ vi.useFakeTimers()
+
+ try {
+ const child = Object.assign(new EventEmitter(), { exitCode: null, signalCode: null, kill: vi.fn() })
+ const waiting = waitForBackendExit(child, { forceKillProcessTree: () => {} }, 20)
+ await vi.advanceTimersByTimeAsync(1020)
+ await waiting
+ assert.equal(child.kill.mock.calls.length, 1)
+ assert.equal(child.kill.mock.calls[0][0], 'SIGKILL')
+ assert.equal(child.listenerCount('exit'), 0)
+ assert.equal(vi.getTimerCount(), 0)
+ } finally {
+ vi.useRealTimers()
+ }
+})
diff --git a/apps/desktop/electron/backend-ownership.test.ts b/apps/desktop/electron/backend-ownership.test.ts
index 54baa744208..1c1593ee77c 100644
--- a/apps/desktop/electron/backend-ownership.test.ts
+++ b/apps/desktop/electron/backend-ownership.test.ts
@@ -319,8 +319,8 @@ test('shutdown coordinator returns one promise and awaits teardown exactly once'
assert.equal(first, second)
assert.equal(coordinator.hasStarted(), true)
- await Promise.resolve()
assert.equal(teardown.mock.calls.length, 1)
+ assert.equal(coordinator.isPending(), true)
let finished = false
first.then(() => {
@@ -332,6 +332,7 @@ test('shutdown coordinator returns one promise and awaits teardown exactly once'
completion.resolve()
await second
assert.equal(finished, true)
+ assert.equal(coordinator.isPending(), false)
assert.equal(coordinator.run(), first)
})
diff --git a/apps/desktop/electron/backend-ownership.ts b/apps/desktop/electron/backend-ownership.ts
index 3ef1080f0eb..06aa8be9163 100644
--- a/apps/desktop/electron/backend-ownership.ts
+++ b/apps/desktop/electron/backend-ownership.ts
@@ -320,17 +320,36 @@ export function backendCommandMatches(command: unknown): boolean {
/** Coordinates all quit paths so asynchronous backend teardown runs once. */
export function createBackendShutdownCoordinator(teardown: () => Promise<void> | void) {
let completion: Promise<void> | undefined
+ let settled = false
return {
run(): Promise<void> {
if (!completion) {
- completion = Promise.resolve().then(teardown)
+ try {
+ // Invoke synchronously so no-wait quit paths still invalidate cached
+ // connection state and stop timers before Electron exits.
+ completion = Promise.resolve(teardown())
+ } catch (error) {
+ completion = Promise.reject(error)
+ }
+
+ void completion.then(
+ () => {
+ settled = true
+ },
+ () => {
+ settled = true
+ }
+ )
}
return completion
},
hasStarted(): boolean {
return completion !== undefined
+ },
+ isPending(): boolean {
+ return completion !== undefined && !settled
}
}
}
diff --git a/apps/desktop/electron/backend-start-cancellation.ts b/apps/desktop/electron/backend-start-cancellation.ts
new file mode 100644
index 00000000000..f833a864bd8
--- /dev/null
+++ b/apps/desktop/electron/backend-start-cancellation.ts
@@ -0,0 +1,24 @@
+/** Cancel a startup wait, and check ownership before invoking its continuation. */
+export async function runBackendStartStep<T>(signal: AbortSignal | undefined, run: () => T | Promise<T>): Promise<T> {
+ signal?.throwIfAborted()
+
+ if (!signal) {
+ return run()
+ }
+
+ let onAbort: () => void = () => {}
+
+ const cancelled = new Promise<never>((_resolve, reject) => {
+ onAbort = () => reject(signal.reason)
+ signal.addEventListener('abort', onAbort, { once: true })
+ })
+
+ try {
+ const result = await Promise.race([run(), cancelled])
+ signal.throwIfAborted()
+
+ return result
+ } finally {
+ signal.removeEventListener('abort', onAbort)
+ }
+}
diff --git a/apps/desktop/electron/local-backend-lifecycle.test.ts b/apps/desktop/electron/local-backend-lifecycle.test.ts
new file mode 100644
index 00000000000..7485c1e8c97
--- /dev/null
+++ b/apps/desktop/electron/local-backend-lifecycle.test.ts
@@ -0,0 +1,180 @@
+import assert from 'node:assert/strict'
+import { spawn } from 'node:child_process'
+import { once } from 'node:events'
+
+import { test, vi } from 'vitest'
+
+import { createFirstRunSetupGate } from './first-run-setup-gate'
+import { createLocalBackendLifecycle } from './local-backend-lifecycle'
+import { runPrimaryBackendStartup } from './primary-backend-startup'
+import { createQuitTeardownCoordinator } from './quit-teardown'
+
+function deferred() {
+ let resolve!: () => void
+
+ const promise = new Promise<void>(done => {
+ resolve = done
+ })
+
+ return { promise, resolve }
+}
+
+test('shutdown joins a removed start and prevents its late spawn', async () => {
+ const resume = deferred()
+ const spawn = vi.fn(() => ({}))
+
+ const lifecycle = createLocalBackendLifecycle({
+ stopChild: () => {},
+ waitForExit: async () => {},
+ cancelSetup: () => {}
+ })
+
+ const start = lifecycle.start(async () => {
+ await resume.promise
+ lifecycle.spawn(spawn)
+ })
+
+ void start.catch(() => {})
+ await Promise.resolve()
+ assert.equal(lifecycle.hasPending(), true)
+ const shutdown = lifecycle.shutdown()
+ resume.resolve()
+ await shutdown
+ await assert.rejects(start)
+ assert.equal(spawn.mock.calls.length, 0)
+ await assert.rejects(lifecycle.start(async () => {}))
+})
+
+test('shutdown retains a child before asynchronous claim and joins an earlier stop', async () => {
+ const exit = deferred()
+ const stopChild = vi.fn()
+ const lifecycle = createLocalBackendLifecycle({ stopChild, waitForExit: () => exit.promise, cancelSetup: () => {} })
+ const child = lifecycle.spawn(() => ({}))
+ const stopping = lifecycle.stop(child)
+ let done = false
+
+ const shutdown = lifecycle.shutdown().then(() => {
+ done = true
+ })
+
+ await Promise.resolve()
+ assert.equal(done, false)
+ assert.equal(stopChild.mock.calls.length, 1)
+ exit.resolve()
+ await Promise.all([shutdown, stopping])
+})
+
+test('shutdown is bounded even if startup ignores cancellation', async () => {
+ vi.useFakeTimers()
+
+ try {
+ const lifecycle = createLocalBackendLifecycle({
+ stopChild: () => {},
+ waitForExit: async () => {},
+ cancelSetup: () => {},
+ timeoutMs: 20
+ })
+
+ void lifecycle.start(() => new Promise(() => {}))
+ await Promise.resolve()
+ const shutdown = lifecycle.shutdown()
+ await vi.advanceTimersByTimeAsync(20)
+ await shutdown
+ assert.throws(() => lifecycle.spawn(() => ({})))
+ assert.equal(vi.getTimerCount(), 0)
+ } finally {
+ vi.useRealTimers()
+ }
+})
+
+test('the quit barrier cancels real first-run startup and waits for both local and SSH drains', async () => {
+ const gate = createFirstRunSetupGate({ stuckAfterMs: 0 })
+ const localExit = deferred()
+ const sshExit = deferred()
+ const finalQuit = vi.fn()
+ const install = vi.fn(async () => ({}))
+
+ const lifecycle = createLocalBackendLifecycle({
+ stopChild: () => {},
+ waitForExit: () => localExit.promise,
+ cancelSetup: () => gate.resetForRetry()
+ })
+
+ lifecycle.spawn(() => ({}))
+
+ const startup = lifecycle.start(() =>
+ runPrimaryBackendStartup({
+ signal: lifecycle.signal,
+ resolveRemote: async () => null,
+ connectRemote: async () => ({}),
+ waitForLocalStart: async () => {},
+ prepareLocalBackend: () => ({ kind: 'bootstrap-needed' }),
+ waitForDecision: backend => gate.wait(backend),
+ ensureLocalRuntime: install
+ })
+ )
+
+ void startup.catch(() => {})
+
+ for (let i = 0; i < 30; i++) {
+ await Promise.resolve()
+ }
+
+ assert.equal(gate.hasWaiter(), true)
+ const quit = createQuitTeardownCoordinator(finalQuit)
+ assert.equal(
+ quit.begin([
+ { run: () => lifecycle.shutdown(), waitForCompletion: lifecycle.hasPending() },
+ { run: () => sshExit.promise, waitForCompletion: true }
+ ]),
+ true
+ )
+ await assert.rejects(startup)
+ assert.equal(gate.hasWaiter(), false)
+ assert.equal(install.mock.calls.length, 0)
+ localExit.resolve()
+ await lifecycle.shutdown()
+ assert.equal(quit.begin([]), true)
+ assert.equal(finalQuit.mock.calls.length, 0)
+ sshExit.resolve()
+
+ for (let i = 0; i < 10; i++) {
+ await Promise.resolve()
+ }
+
+ assert.equal(finalQuit.mock.calls.length, 1)
+ assert.equal(quit.begin([]), false)
+})
+
+test('a child spawned before claim remains owned after the routing entry disappears', async () => {
+ const lifecycle = createLocalBackendLifecycle<ReturnType<typeof spawn>>({
+ stopChild: child => {
+ child.kill()
+ },
+ waitForExit: async child => {
+ if (child.exitCode === null && child.signalCode === null) {
+ await once(child, 'exit')
+ }
+ },
+ cancelSetup: () => {}
+ })
+
+ const child = lifecycle.spawn(() =>
+ spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' })
+ )
+
+ child.once('exit', () => lifecycle.release(child))
+
+ try {
+ await once(child, 'spawn')
+ // No connection-state attachment or persisted claim has happened yet.
+ await lifecycle.shutdown()
+ assert.ok(child.exitCode !== null || child.signalCode !== null)
+ assert.equal(lifecycle.hasPending(), false)
+ } finally {
+ if (child.exitCode === null && child.signalCode === null) {
+ child.kill('SIGKILL')
+ await once(child, 'exit')
+ }
+ }
+})
diff --git a/apps/desktop/electron/local-backend-lifecycle.ts b/apps/desktop/electron/local-backend-lifecycle.ts
new file mode 100644
index 00000000000..49f52d54760
--- /dev/null
+++ b/apps/desktop/electron/local-backend-lifecycle.ts
@@ -0,0 +1,105 @@
+import { createBackendShutdownCoordinator } from './backend-ownership'
+
+/** Observe every branch, but never leave quit parked on a lost exit/SSH callback. */
+export async function waitForTeardown(tasks: readonly Promise<unknown>[], timeoutMs: number): Promise<void> {
+ let timer: ReturnType<typeof setTimeout> | undefined
+
+ try {
+ await Promise.race([
+ Promise.allSettled(tasks),
+ new Promise<void>(resolve => {
+ timer = setTimeout(resolve, timeoutMs)
+ })
+ ])
+ } finally {
+ clearTimeout(timer)
+ }
+}
+
+interface LocalBackendLifecycleDeps<Child> {
+ stopChild: (child: Child) => void
+ waitForExit: (child: Child) => Promise<void>
+ cancelSetup: () => void
+ timeoutMs?: number
+}
+
+/**
+ * Physical ownership outlives routing entries: track starts before their first
+ * await and children before their asynchronous identity claim. The permanent
+ * shutdown signal and synchronous spawn fence make bounded waiting safe: a late
+ * resolver can finish, but can never create another owned backend.
+ */
+export function createLocalBackendLifecycle<Child>(deps: LocalBackendLifecycleDeps<Child>) {
+ const controller = new AbortController()
+ const starts = new Set<Promise<unknown>>()
+ const children = new Set<Child>()
+ const stops = new Map<Child, Promise<void>>()
+
+ function stop(child: Child | null | undefined): Promise<void> {
+ if (child == null) {
+ return Promise.resolve()
+ }
+
+ const existing = stops.get(child)
+
+ if (existing) {
+ return existing
+ }
+
+ const stopping = (async () => {
+ deps.stopChild(child)
+ await deps.waitForExit(child)
+ })()
+
+ stops.set(child, stopping)
+ void stopping.then(
+ () => stops.delete(child),
+ () => stops.delete(child)
+ )
+
+ return stopping
+ }
+
+ const shutdown = createBackendShutdownCoordinator(() => {
+ controller.abort(new Error('Hermes Desktop is quitting.'))
+ deps.cancelSetup()
+
+ return waitForTeardown([...starts, ...[...children].map(stop), ...stops.values()], deps.timeoutMs ?? 7_000)
+ })
+
+ return {
+ signal: controller.signal,
+ assertCanStart: () => controller.signal.throwIfAborted(),
+ hasPending: () => starts.size > 0 || children.size > 0 || stops.size > 0 || shutdown.isPending(),
+ start<T>(run: () => Promise<T>): Promise<T> {
+ if (controller.signal.aborted) {
+ return Promise.reject(controller.signal.reason)
+ }
+
+ // Defer invocation one microtask so the inventory precedes all work.
+ const promise = Promise.resolve().then(() => {
+ controller.signal.throwIfAborted()
+
+ return run()
+ })
+
+ starts.add(promise)
+ void promise.then(
+ () => starts.delete(promise),
+ () => starts.delete(promise)
+ )
+
+ return promise
+ },
+ spawn(create: () => Child): Child {
+ controller.signal.throwIfAborted()
+ const child = create()
+ children.add(child)
+
+ return child
+ },
+ release: (child: Child) => children.delete(child),
+ stop,
+ shutdown: shutdown.run
+ }
+}
diff --git a/apps/desktop/electron/pool-stop.test.ts b/apps/desktop/electron/pool-stop.test.ts
index 55d6c40c879..8010db64688 100644
--- a/apps/desktop/electron/pool-stop.test.ts
+++ b/apps/desktop/electron/pool-stop.test.ts
@@ -89,6 +89,14 @@ test('stop of an unknown key resolves without signalling anything', async () =>
assert.equal(stopper.inFlight('ghost'), undefined)
})
+test('a remote pooled descriptor without a local child does not require quit deferral', () => {
+ const { pool, stopper } = harness()
+
+ pool.set('remote', {})
+
+ assert.equal(stopper.hasPending(), false)
+})
+
test('stopAll stops every pooled backend and resolves after all exits', async () => {
const { addChild, exitResolvers, pool, stopper } = harness()
const a = addChild('a')
@@ -113,6 +121,31 @@ test('stopAll stops every pooled backend and resolves after all exits', async ()
assert.equal(settled, true)
})
+test('stopAll joins a stop whose pool entry was already evicted', async () => {
+ const { addChild, exitResolvers, pool, stopper } = harness()
+ const child = addChild('already-stopping')
+
+ const first = stopper.stop('already-stopping')
+
+ assert.equal(pool.size, 0)
+ assert.equal(stopper.hasPending(), true)
+
+ let settled = false
+
+ const all = stopper.stopAll().then(() => {
+ settled = true
+ })
+
+ await Promise.resolve()
+
+ assert.equal(settled, false)
+
+ exitResolvers.get(child)?.()
+ await Promise.all([first, all])
+ assert.equal(settled, true)
+ assert.equal(stopper.hasPending(), false)
+})
+
test('a respawn can await the in-flight stop before reusing the key', async () => {
const { addChild, exitResolvers, stopper } = harness()
const child = addChild('selena')
diff --git a/apps/desktop/electron/pool-stop.ts b/apps/desktop/electron/pool-stop.ts
index 767a65e1748..2ba33640af1 100644
--- a/apps/desktop/electron/pool-stop.ts
+++ b/apps/desktop/electron/pool-stop.ts
@@ -38,9 +38,11 @@ export interface PoolStopperDeps {
export interface PoolStopper {
/** The in-flight stop for a key, if any — await before respawning it. */
inFlight: (key: string) => Promise<void> | undefined
+ /** Whether the pool has a local child or an already-evicted stop in flight. */
+ hasPending: () => boolean
/** Stop one pooled backend; concurrent calls share the same promise. */
stop: (key: string) => Promise<void>
- /** Stop every pooled backend currently in the pool. */
+ /** Stop every pooled backend and join stops already in flight. */
stopAll: () => Promise<void>
}
@@ -78,9 +80,12 @@ export function createPoolStopper(deps: PoolStopperDeps): PoolStopper {
return {
inFlight: key => stops.get(key),
+ hasPending: () => stops.size > 0 || [...deps.pool.values()].some(entry => entry.process != null),
stop,
stopAll: async () => {
- await Promise.all([...deps.pool.keys()].map(stop))
+ const currentStops = [...deps.pool.keys()].map(stop)
+
+ await Promise.all(new Set([...stops.values(), ...currentStops]))
}
}
}
diff --git a/apps/desktop/electron/primary-backend-cancellation.test.ts b/apps/desktop/electron/primary-backend-cancellation.test.ts
new file mode 100644
index 00000000000..e50e4c9c57f
--- /dev/null
+++ b/apps/desktop/electron/primary-backend-cancellation.test.ts
@@ -0,0 +1,46 @@
+import assert from 'node:assert/strict'
+
+import { test } from 'vitest'
+
+import { createFirstRunSetupGate } from './first-run-setup-gate'
+import { runPrimaryBackendStartup } from './primary-backend-startup'
+
+test('quit cancels first-run startup without entering the installer', async () => {
+ const controller = new AbortController()
+ const gate = createFirstRunSetupGate({ stuckAfterMs: 0 })
+ let installed = false
+
+ const startup = runPrimaryBackendStartup({
+ signal: controller.signal,
+ resolveRemote: async () => null,
+ connectRemote: async () => ({}),
+ waitForLocalStart: async () => {},
+ prepareLocalBackend: () => ({ kind: 'bootstrap-needed' }),
+ waitForDecision: backend => gate.wait(backend),
+ ensureLocalRuntime: async () => {
+ installed = true
+
+ return {}
+ }
+ })
+
+ for (let i = 0; i < 20; i++) {
+ await Promise.resolve()
+ }
+
+ assert.equal(gate.hasWaiter(), true)
+ let settled = false
+ void startup.catch(() => {
+ settled = true
+ })
+ controller.abort()
+
+ for (let i = 0; i < 20; i++) {
+ await Promise.resolve()
+ }
+
+ assert.equal(settled, true, 'quit must not wait for a user choice')
+ gate.continueLocal()
+ await startup.catch(() => {})
+ assert.equal(installed, false, 'a late choice must not launch the installer')
+})
diff --git a/apps/desktop/electron/primary-backend-startup.ts b/apps/desktop/electron/primary-backend-startup.ts
index c105b7f3d6f..6c3a87352dd 100644
--- a/apps/desktop/electron/primary-backend-startup.ts
+++ b/apps/desktop/electron/primary-backend-startup.ts
@@ -1,6 +1,8 @@
+import { runBackendStartStep } from './backend-start-cancellation'
import type { FirstRunSetupDecision } from './first-run-setup-gate'
export interface PrimaryBackendStartupOptions<Backend, RuntimeBackend, Remote, Connection> {
+ signal?: AbortSignal
connectRemote: (remote: Remote) => Promise<Connection>
ensureLocalRuntime: (backend: Backend) => Promise<RuntimeBackend>
prepareLocalBackend: () => Backend | Promise<Backend>
@@ -80,34 +82,36 @@ export async function runPrimaryBackendStartup<Backend, RuntimeBackend, Remote,
prepareLocalBackend,
resolveRemote,
waitForDecision,
- waitForLocalStart
+ waitForLocalStart,
+ signal
}: PrimaryBackendStartupOptions<Backend, RuntimeBackend, Remote, Connection>): Promise<
PrimaryBackendStartupResult<RuntimeBackend, Connection>
> {
- const savedRemote = await resolveRemote()
+ const step = <T>(run: () => T | Promise<T>) => runBackendStartStep(signal, run)
+ const savedRemote = await step(resolveRemote)
if (savedRemote) {
- return { kind: 'remote', connection: await connectRemote(savedRemote) }
+ return { kind: 'remote', connection: await step(() => connectRemote(savedRemote)) }
}
- await waitForLocalStart()
+ await step(waitForLocalStart)
- const backend = await prepareLocalBackend()
- const decision = await waitForDecision(backend)
+ const backend = await step(prepareLocalBackend)
+ const decision = await step(() => waitForDecision(backend))
if (decision === 'remote-applied') {
- const appliedRemote = await resolveRemote()
+ const appliedRemote = await step(resolveRemote)
if (!appliedRemote) {
throw new Error('First-run remote setup completed without a saved remote backend.')
}
- return { kind: 'remote', connection: await connectRemote(appliedRemote) }
+ return { kind: 'remote', connection: await step(() => connectRemote(appliedRemote)) }
}
if (decision === 'reset') {
throw new FirstRunSetupResetError()
}
- return { kind: 'local', backend: await ensureLocalRuntime(backend) }
+ return { kind: 'local', backend: await step(() => ensureLocalRuntime(backend)) }
}
diff --git a/apps/desktop/electron/quit-teardown.test.ts b/apps/desktop/electron/quit-teardown.test.ts
new file mode 100644
index 00000000000..eee3072e3d7
--- /dev/null
+++ b/apps/desktop/electron/quit-teardown.test.ts
@@ -0,0 +1,127 @@
+import assert from 'node:assert/strict'
+
+import { test, vi } from 'vitest'
+
+import { backendQuitNeedsWait, createQuitTeardownCoordinator } from './quit-teardown'
+
+function deferred() {
+ let resolve!: () => void
+
+ const promise = new Promise<void>(done => {
+ resolve = done
+ })
+
+ return { promise, resolve }
+}
+
+test('remote-only cleanup does not cancel the original quit', () => {
+ const cleanup = vi.fn()
+ const requestFinalQuit = vi.fn()
+ const coordinator = createQuitTeardownCoordinator(requestFinalQuit)
+
+ const shouldPrevent = coordinator.begin([{ run: cleanup, waitForCompletion: false }])
+
+ assert.equal(shouldPrevent, false)
+ assert.equal(cleanup.mock.calls.length, 1)
+ assert.equal(requestFinalQuit.mock.calls.length, 0)
+})
+
+test('a settled remote descriptor is not backend work that requires a deferred quit', () => {
+ assert.equal(
+ backendQuitNeedsWait({
+ connectionPending: false,
+ poolPending: false,
+ processAttached: false,
+ shutdownPending: false
+ }),
+ false
+ )
+
+ for (const key of ['connectionPending', 'poolPending', 'processAttached', 'shutdownPending'] as const) {
+ assert.equal(
+ backendQuitNeedsWait({
+ connectionPending: false,
+ poolPending: false,
+ processAttached: false,
+ shutdownPending: false,
+ [key]: true
+ }),
+ true,
+ `${key} must defer quit`
+ )
+ }
+})
+
+test('one final quit waits for every required teardown branch', async () => {
+ const backend = deferred()
+ const ssh = deferred()
+ const requestFinalQuit = vi.fn()
+ const backendRun = vi.fn(() => backend.promise)
+ const sshRun = vi.fn(() => ssh.promise)
+ const coordinator = createQuitTeardownCoordinator(requestFinalQuit)
+
+ const tasks = [
+ { run: backendRun, waitForCompletion: true },
+ { run: sshRun, waitForCompletion: true }
+ ]
+
+ assert.equal(coordinator.begin(tasks), true)
+ assert.equal(coordinator.begin(tasks), true, 'a re-entrant quit stays deferred while teardown is pending')
+ assert.equal(backendRun.mock.calls.length, 1)
+ assert.equal(sshRun.mock.calls.length, 1)
+
+ backend.resolve()
+ await Promise.resolve()
+ assert.equal(requestFinalQuit.mock.calls.length, 0)
+
+ ssh.resolve()
+ await Promise.all([backend.promise, ssh.promise])
+ await Promise.resolve()
+ assert.equal(requestFinalQuit.mock.calls.length, 1)
+
+ assert.equal(coordinator.begin(tasks), false, 'the coordinator must not cancel its own final quit')
+ assert.equal(backendRun.mock.calls.length, 1)
+ assert.equal(sshRun.mock.calls.length, 1)
+})
+
+test('teardown failure still releases the final quit after all branches settle', async () => {
+ const requestFinalQuit = vi.fn()
+ const coordinator = createQuitTeardownCoordinator(requestFinalQuit)
+
+ assert.equal(
+ coordinator.begin([
+ {
+ run: () => {
+ throw new Error('cleanup failed')
+ },
+ waitForCompletion: true
+ }
+ ]),
+ true
+ )
+
+ await Promise.resolve()
+ await Promise.resolve()
+ assert.equal(requestFinalQuit.mock.calls.length, 1)
+})
+
+test('a synchronous reentrant quit cannot start a second teardown', async () => {
+ const finalQuit = vi.fn()
+ const coordinator = createQuitTeardownCoordinator(finalQuit)
+ const duplicate = vi.fn()
+ assert.equal(
+ coordinator.begin([
+ {
+ waitForCompletion: true,
+ run: () => {
+ assert.equal(coordinator.begin([{ run: duplicate, waitForCompletion: false }]), true)
+ }
+ }
+ ]),
+ true
+ )
+ await Promise.resolve()
+ await Promise.resolve()
+ assert.equal(duplicate.mock.calls.length, 0)
+ assert.equal(finalQuit.mock.calls.length, 1)
+})
diff --git a/apps/desktop/electron/quit-teardown.ts b/apps/desktop/electron/quit-teardown.ts
new file mode 100644
index 00000000000..eef68fb6646
--- /dev/null
+++ b/apps/desktop/electron/quit-teardown.ts
@@ -0,0 +1,75 @@
+export interface QuitTeardownTask {
+ /** Whether Electron must defer this quit until the task settles. */
+ waitForCompletion: boolean
+ /** Starts teardown. This is invoked synchronously from before-quit. */
+ run: () => Promise<unknown> | unknown
+}
+
+export interface QuitTeardownCoordinator {
+ /**
+ * Starts teardown once and reports whether the current quit must be
+ * prevented. Re-entrant quit requests are held until all required teardown
+ * settles; the coordinator then requests exactly one final quit.
+ */
+ begin: (tasks: readonly QuitTeardownTask[]) => boolean
+}
+
+export interface BackendQuitActivity {
+ connectionPending: boolean
+ poolPending: boolean
+ processAttached: boolean
+ shutdownPending: boolean
+}
+
+export function backendQuitNeedsWait(activity: BackendQuitActivity): boolean {
+ return activity.shutdownPending || activity.processAttached || activity.connectionPending || activity.poolPending
+}
+
+function runTask(task: QuitTeardownTask): Promise<unknown> {
+ try {
+ return Promise.resolve(task.run())
+ } catch (error) {
+ return Promise.reject(error)
+ }
+}
+
+/**
+ * Coordinates Electron's before-quit teardown without cancelling a quit that
+ * has no asynchronous work to wait for.
+ */
+export function createQuitTeardownCoordinator(requestFinalQuit: () => void): QuitTeardownCoordinator {
+ let started = false
+ let finished = false
+
+ return {
+ begin(tasks): boolean {
+ if (finished) {
+ return false
+ }
+
+ if (started) {
+ return true
+ }
+
+ started = true
+ const executions = tasks.map(task => ({ promise: runTask(task), waitForCompletion: task.waitForCompletion }))
+ const mustWait = executions.some(task => task.waitForCompletion)
+
+ if (!mustWait) {
+ // Observe asynchronous no-wait cleanup so a late rejection cannot
+ // become unhandled, but let Electron continue the original quit.
+ void Promise.allSettled(executions.map(task => task.promise))
+ finished = true
+
+ return false
+ }
+
+ void Promise.allSettled(executions.map(task => task.promise)).then(() => {
+ finished = true
+ requestFinalQuit()
+ })
+
+ return true
+ }
+ }
+}
diff --git a/apps/desktop/electron/ssh-teardown.test.ts b/apps/desktop/electron/ssh-teardown.test.ts
new file mode 100644
index 00000000000..b1f053ed17e
--- /dev/null
+++ b/apps/desktop/electron/ssh-teardown.test.ts
@@ -0,0 +1,55 @@
+import assert from 'node:assert/strict'
+
+import { test, vi } from 'vitest'
+
+import { createSshTeardownTracker } from './ssh-teardown'
+
+function deferred() {
+ let resolve!: () => void
+
+ const promise = new Promise<void>(done => {
+ resolve = done
+ })
+
+ return { promise, resolve }
+}
+
+test('quit joins teardown whose SSH routing entry was already removed', async () => {
+ const exit = deferred()
+ const tracker = createSshTeardownTracker()
+ const close = vi.fn(async () => {})
+ const stopped = tracker.track({ close }, () => exit.promise)
+ let done = false
+
+ const quit = tracker
+ .finish([], async () => {})
+ .then(() => {
+ done = true
+ })
+
+ await Promise.resolve()
+ assert.equal(done, false)
+ assert.equal(tracker.hasPending(), true)
+ exit.resolve()
+ await Promise.all([stopped, quit])
+ assert.equal(tracker.hasPending(), false)
+})
+
+test('a stuck SSH teardown and force cleanup cannot hang quit forever', async () => {
+ vi.useFakeTimers()
+
+ try {
+ const tracker = createSshTeardownTracker()
+ const close = vi.fn(() => new Promise<void>(() => {}))
+ void tracker.track({ close }, () => new Promise<void>(() => {}))
+ const force = vi.fn(() => new Promise<void>(() => {}))
+ const quit = tracker.finish([], force, 20, 10)
+ await vi.advanceTimersByTimeAsync(30)
+ await quit
+ assert.equal(close.mock.calls.length, 1)
+ assert.equal(force.mock.calls.length, 1)
+ assert.equal(vi.getTimerCount(), 0)
+ } finally {
+ vi.useRealTimers()
+ }
+})
diff --git a/apps/desktop/electron/ssh-teardown.ts b/apps/desktop/electron/ssh-teardown.ts
new file mode 100644
index 00000000000..dc0ca0c2297
--- /dev/null
+++ b/apps/desktop/electron/ssh-teardown.ts
@@ -0,0 +1,38 @@
+import { waitForTeardown } from './local-backend-lifecycle'
+
+/** Retain transports removed from routing until their remote kill has settled. */
+export function createSshTeardownTracker() {
+ const pending = new Map<Promise<void>, { close: () => Promise<unknown> }>()
+
+ return {
+ hasPending: () => pending.size > 0,
+ track(ssh: { close: () => Promise<unknown> }, teardown: () => Promise<void>): Promise<void> {
+ const promise = Promise.resolve().then(teardown)
+ pending.set(promise, ssh)
+ void promise.then(
+ () => pending.delete(promise),
+ () => pending.delete(promise)
+ )
+
+ return promise
+ },
+ async finish(
+ bootstraps: Promise<unknown>[],
+ forceCleanup: () => Promise<unknown>,
+ graceMs = 6_000,
+ forceMs = 1_000
+ ) {
+ await waitForTeardown([...pending.keys(), ...bootstraps], graceMs)
+ // Only abandon the transport after the existing remote-kill grace period.
+ // Closing SSH unblocks a wedged exec; both close and bootstrap force cleanup
+ // are bounded too, not an unbounded await after a nominal timeout.
+ await waitForTeardown(
+ [
+ Promise.resolve().then(forceCleanup),
+ ...[...new Set(pending.values())].map(ssh => Promise.resolve().then(() => ssh.close()))
+ ],
+ forceMs
+ )
+ }
+ }
+}
diff --git a/apps/desktop/electron/update-gate-cancellation.test.ts b/apps/desktop/electron/update-gate-cancellation.test.ts
new file mode 100644
index 00000000000..feb7a7f3179
--- /dev/null
+++ b/apps/desktop/electron/update-gate-cancellation.test.ts
@@ -0,0 +1,42 @@
+import assert from 'node:assert/strict'
+
+import { test } from 'vitest'
+
+import { waitForUpdateClearance } from './update-gate'
+
+test('quit interrupts an update-gated wait instead of waiting for the next poll', async () => {
+ const controller = new AbortController()
+ let slept = false
+
+ const waiting = waitForUpdateClearance(
+ { hasLiveMarker: () => true, isUpdateInFlight: () => false },
+ {
+ signal: controller.signal,
+ pollMs: 1000,
+ timeoutMs: 120000,
+ sleep: () => {
+ slept = true
+
+ return new Promise(() => {})
+ }
+ }
+ )
+
+ let outcome: unknown
+ void waiting.then(result => {
+ outcome = result
+ })
+
+ for (let i = 0; i < 10; i++) {
+ await Promise.resolve()
+ }
+
+ assert.equal(slept, true)
+ controller.abort()
+
+ for (let i = 0; i < 20; i++) {
+ await Promise.resolve()
+ }
+
+ assert.equal(outcome, 'cancelled')
+})
diff --git a/apps/desktop/electron/update-gate.ts b/apps/desktop/electron/update-gate.ts
index e7326af3782..441cb6b71b5 100644
--- a/apps/desktop/electron/update-gate.ts
+++ b/apps/desktop/electron/update-gate.ts
@@ -1,5 +1,7 @@
'use strict'
+import { runBackendStartStep } from './backend-start-cancellation'
+
/**
* update-gate.ts
*
@@ -47,9 +49,11 @@ export function updateGateReason(deps: UpdateGateDeps): UpdateGateReason {
return null
}
-export type UpdateClearanceOutcome = 'clear' | 'finished' | 'timeout'
+export type UpdateClearanceOutcome = 'clear' | 'finished' | 'timeout' | 'cancelled'
export interface WaitForUpdateClearanceOptions {
+ signal?: AbortSignal
+ isCancelled?: () => boolean
timeoutMs: number
pollMs: number
/** Invoked once per poll while parked (boot progress / logging). */
@@ -74,6 +78,12 @@ export async function waitForUpdateClearance(
const now = options.now || Date.now
const sleep = options.sleep || (ms => new Promise<void>(r => setTimeout(r, ms)))
+ const isCancelled = () => options.signal?.aborted || options.isCancelled?.()
+
+ if (isCancelled()) {
+ return 'cancelled'
+ }
+
let reason = updateGateReason(deps)
if (!reason) {
@@ -83,11 +93,42 @@ export async function waitForUpdateClearance(
const deadline = now() + options.timeoutMs
while (reason && now() < deadline) {
- if (options.onWaitTick) {
- await options.onWaitTick(reason)
+ if (isCancelled()) {
+ return 'cancelled'
+ }
+
+ let timer: ReturnType<typeof setTimeout> | undefined
+
+ try {
+ if (options.onWaitTick) {
+ await runBackendStartStep(options.signal, () => options.onWaitTick!(reason!))
+ }
+
+ if (isCancelled()) {
+ return 'cancelled'
+ }
+
+ await runBackendStartStep(options.signal, () =>
+ options.sleep
+ ? sleep(options.pollMs)
+ : new Promise<void>(resolve => {
+ timer = setTimeout(resolve, options.pollMs)
+ })
+ )
+ } catch (error) {
+ if (isCancelled()) {
+ return 'cancelled'
+ }
+
+ throw error
+ } finally {
+ clearTimeout(timer)
+ }
+
+ if (isCancelled()) {
+ return 'cancelled'
}
- await sleep(options.pollMs)
reason = updateGateReason(deps)
}