Skip to content

The agent that grows with you

fix(desktop): gate the boot WS probe extension on child liveness, not output

brooklyn!b4bad6fca194
diff --git a/apps/desktop/electron/backend-claim.test.ts b/apps/desktop/electron/backend-claim.test.ts
index 03f7386e835..0b2555b86a2 100644
--- a/apps/desktop/electron/backend-claim.test.ts
+++ b/apps/desktop/electron/backend-claim.test.ts
@@ -4,7 +4,6 @@ import { EventEmitter } from 'node:events'
import { test } from 'vitest'
import {
- backendMakingProgress,
claimDecision,
createBackendOutputTail,
formatBackendExitLine,
@@ -133,52 +132,3 @@ test('exit line stays byte-identical to the legacy shape when the tail is empty
)
assert.equal(formatBackendExitLine('Hermes backend exited', 1, null, null), 'Hermes backend exited (1)')
})
-
-// --- output-tail activity tracking (#96177) -----------------------------------
-
-test('output tail tracks lastActivityAt from appends and attached streams', () => {
- const tail = createBackendOutputTail(64)
- assert.equal(tail.lastActivityAt(), 0, 'no output yet → 0')
-
- const child = { stderr: new EventEmitter(), stdout: new EventEmitter() }
- tail.attach(child)
- child.stdout.emit('data', Buffer.from('booting\n'))
-
- const stamped = tail.lastActivityAt()
- assert.ok(stamped > 0, 'attach-driven output records activity')
- assert.ok(Date.now() - stamped < 5_000, 'activity timestamp is recent')
-
- tail.append('more\n')
- assert.ok(tail.lastActivityAt() >= stamped, 'append refreshes the timestamp')
-})
-
-test('backendMakingProgress is true while the child is alive and emitting', () => {
- let clock = 1_000_000
- const tail = createBackendOutputTail(64, { now: () => clock })
- const child = { exitCode: null, killed: false }
-
- // No output yet: an alive process inside the (block-buffered) import
- // window still reads as progress.
- assert.equal(backendMakingProgress(child, tail, { now: () => clock }), true)
-
- tail.append('importing feishu\n')
- clock += 10_000
-
- // Recent output → progress.
- assert.equal(backendMakingProgress(child, tail, { now: () => clock }), true)
-
- clock += 31_000
-
- // Silence past the window → no progress.
- assert.equal(backendMakingProgress(child, tail, { now: () => clock }), false)
-})
-
-test('backendMakingProgress is false for a dead or killed child', () => {
- const tail = createBackendOutputTail(64)
- const now = () => 1_000_000
-
- assert.equal(backendMakingProgress({ exitCode: 1, killed: false }, tail, { now }), false)
- assert.equal(backendMakingProgress({ exitCode: null, killed: true }, tail, { now }), false)
- assert.equal(backendMakingProgress(null, tail, { now }), false)
- assert.equal(backendMakingProgress(undefined, tail, { now }), false)
-})
diff --git a/apps/desktop/electron/backend-claim.ts b/apps/desktop/electron/backend-claim.ts
index d6db8627aa0..fb53d21f7a9 100644
--- a/apps/desktop/electron/backend-claim.ts
+++ b/apps/desktop/electron/backend-claim.ts
@@ -188,12 +188,6 @@ export interface BackendOutputTail {
text(): string
/** Human-readable suffix for error messages, or '' when nothing buffered. */
describe(): string
- /**
- * Epoch ms of the last appended chunk, or 0 when nothing has been written
- * yet. Lets boot phases tell "backend still emitting output" from "backend
- * silent" (the WS probe's progress signal, #96177).
- */
- lastActivityAt(): number
}
export const DEFAULT_OUTPUT_TAIL_LIMIT = 8192
@@ -204,12 +198,8 @@ export const DEFAULT_OUTPUT_TAIL_LIMIT = 8192
* stderr (traceback, missing module, bad config) survives into the ownership
* error and the before-ready exit messages instead of a bare exit code.
*/
-export function createBackendOutputTail(
- limit: number = DEFAULT_OUTPUT_TAIL_LIMIT,
- { now = Date.now }: { now?: () => number } = {}
-): BackendOutputTail {
+export function createBackendOutputTail(limit: number = DEFAULT_OUTPUT_TAIL_LIMIT): BackendOutputTail {
let buffer = ''
- let lastActivityAt = 0
const append = (chunk: unknown) => {
buffer += String(chunk)
@@ -217,8 +207,6 @@ export function createBackendOutputTail(
if (buffer.length > limit) {
buffer = buffer.slice(buffer.length - limit)
}
-
- lastActivityAt = now()
}
return {
@@ -234,9 +222,6 @@ export function createBackendOutputTail(
const text = buffer.trim()
return text ? `\nRecent backend output:\n${text}` : ''
- },
- lastActivityAt() {
- return lastActivityAt
}
}
}
@@ -257,26 +242,3 @@ export function formatBackendExitLine(
): string {
return `${label} (${signal || code})${outputTail?.describe() ?? ''}`
}
-
-/**
- * Progress signal for boot phases that must tolerate a slow-but-alive
- * backend (the boot-time WS probe, #96177). True while the child process is
- * still running AND it has either produced no output yet (a cold-start
- * backend's stdout is block-buffered — an alive process inside the import
- * window is progress) or written output within the last `withinMs`. A
- * backend that died, or that has been silent longer than the window, reads
- * as "no progress".
- */
-export function backendMakingProgress(
- child: { exitCode: number | null; killed?: boolean } | null | undefined,
- outputTail: BackendOutputTail,
- { withinMs = 30_000, now = Date.now } = {}
-): boolean {
- if (!child || child.exitCode !== null || child.killed) {
- return false
- }
-
- const lastActivity = outputTail.lastActivityAt()
-
- return lastActivity === 0 || now() - lastActivity < withinMs
-}
diff --git a/apps/desktop/electron/gateway-ws-probe.test.ts b/apps/desktop/electron/gateway-ws-probe.test.ts
index dee7375b456..a92444d2a50 100644
--- a/apps/desktop/electron/gateway-ws-probe.test.ts
+++ b/apps/desktop/electron/gateway-ws-probe.test.ts
@@ -11,9 +11,15 @@
import assert from 'node:assert/strict'
-import { test } from 'vitest'
+import { afterEach, beforeEach, describe, test, vi } from 'vitest'
-import { probeGatewayWebSocket } from './gateway-ws-probe'
+import {
+ DEFAULT_CONNECT_TIMEOUT_MS,
+ DEFAULT_PROGRESS_CHECK_INTERVAL_MS,
+ probeGatewayWebSocket,
+ SPAWNED_BACKEND_MAX_CONNECT_WAIT_MS,
+ spawnedBackendProbeOptions
+} from './gateway-ws-probe'
// Minimal WebSocket double: records listeners synchronously (the probe attaches
// them in its executor) and exposes emit() so the test can replay events.
@@ -116,92 +122,221 @@ test('probe times out when the socket never opens', async () => {
assert.match(result.reason, /Timed out/)
})
-// --- progress-aware waiting (#96177) ------------------------------------------
-// A Windows cold start can hold the backend's GIL for 12-28s while gateway
-// platform modules import, leaving the WS upgrade unanswered past the fixed
-// 10s budget. With `keepWaitingWhile`, the probe must survive that window as
-// long as the backend reports progress — and still fail fast when it stops.
+// --- waiting on a spawned backend (#96177) ----------------------------------
+// A Windows cold start can stall the backend's event loop for 12-28s after
+// HTTP is up, leaving the upgrade unanswered past the fixed budget. Fake timers
+// drive every deadline so these cases never race the wall clock.
-test('probe waits past the base budget while keepWaitingWhile reports progress', async () => {
- const { FakeWs, instances } = makeFakeWs()
- let progressed = true
+async function advance(ms: number) {
+ await vi.advanceTimersByTimeAsync(ms)
+}
- const promise = probeGatewayWebSocket('ws://host/api/ws?token=t', {
- WebSocketImpl: FakeWs,
- connectTimeoutMs: 30,
- readyGraceMs: 10,
- progressCheckIntervalMs: 5,
- maxConnectWaitMs: 500,
- keepWaitingWhile: () => progressed
+// Observe settlement without awaiting, so a test can assert "still pending".
+function track<T>(promise: Promise<T>) {
+ const state: { result: T | undefined; settled: boolean } = { result: undefined, settled: false }
+ void promise.then(result => {
+ state.result = result
+ state.settled = true
+ })
+
+ return state
+}
+
+const WAITING = { connectTimeoutMs: 30, readyGraceMs: 10, progressCheckIntervalMs: 5, maxConnectWaitMs: 500 }
+
+describe('keepWaitingWhile', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
})
- // The upgrade lands AFTER the 30ms quiet budget — the exact cold-start
- // shape from #96177 (backend alive and importing, socket unanswered).
- setTimeout(() => {
+ test('keeps waiting past the base budget while the callback holds, then succeeds on open', async () => {
+ const { FakeWs, instances } = makeFakeWs()
+
+ const probe = track(
+ probeGatewayWebSocket('ws://host/api/ws?token=t', {
+ WebSocketImpl: FakeWs,
+ ...WAITING,
+ keepWaitingWhile: () => true
+ })
+ )
+
+ await advance(60)
+ assert.equal(probe.settled, false, 'still waiting well past the 30ms base budget')
+
instances[0].emit('open')
- }, 60)
+ await advance(10)
+ assert.deepEqual(probe.result, { ok: true })
+ })
- const result = await promise
- assert.equal(result.ok, true, 'progress-aware probe must outlive the fixed budget')
-})
+ test('fails at the next check once the callback turns false', async () => {
+ const { FakeWs } = makeFakeWs()
+ let alive = true
+
+ const probe = track(
+ probeGatewayWebSocket('ws://host/api/ws?token=t', {
+ WebSocketImpl: FakeWs,
+ ...WAITING,
+ keepWaitingWhile: () => alive
+ })
+ )
+
+ await advance(40)
+ assert.equal(probe.settled, false)
+
+ alive = false
+ await advance(5)
+ assert.equal(probe.result?.ok, false)
+ assert.match(probe.result?.reason, /backend stopped after the 30ms budget/)
+ })
-test('probe fails once progress stops after the base budget', async () => {
- const { FakeWs } = makeFakeWs()
- let progressed = true
+ test('never waits past maxConnectWaitMs even while the callback holds', async () => {
+ const { FakeWs } = makeFakeWs()
- const promise = probeGatewayWebSocket('ws://host/api/ws?token=t', {
- WebSocketImpl: FakeWs,
- connectTimeoutMs: 30,
- readyGraceMs: 10,
- progressCheckIntervalMs: 5,
- maxConnectWaitMs: 500,
- keepWaitingWhile: () => progressed
+ const probe = track(
+ probeGatewayWebSocket('ws://host/api/ws?token=t', {
+ WebSocketImpl: FakeWs,
+ ...WAITING,
+ maxConnectWaitMs: 60,
+ keepWaitingWhile: () => true
+ })
+ )
+
+ await advance(59)
+ assert.equal(probe.settled, false)
+
+ await advance(1)
+ assert.equal(probe.result?.ok, false)
+ assert.match(probe.result?.reason, /Timed out after 60ms .*still running at the 60ms cap/)
})
- setTimeout(() => {
- progressed = false
- }, 40)
+ test('a callback that holds with no explicit cap cannot extend past the base budget', async () => {
+ const { FakeWs } = makeFakeWs()
+
+ const probe = track(
+ probeGatewayWebSocket('ws://host/api/ws?token=t', {
+ WebSocketImpl: FakeWs,
+ connectTimeoutMs: 30,
+ readyGraceMs: 10,
+ keepWaitingWhile: () => true
+ })
+ )
+
+ await advance(30)
+ assert.equal(probe.result?.ok, false)
+ assert.match(probe.result?.reason, /still running at the 30ms cap/)
+ })
- const result = await promise
- assert.equal(result.ok, false)
- assert.match(result.reason, /Timed out/)
- assert.match(result.reason, /backend progress stopped after 30ms/, 'reason names the quiet budget')
+ test('a throwing callback fails closed at the base budget', async () => {
+ const { FakeWs } = makeFakeWs()
+
+ const probe = track(
+ probeGatewayWebSocket('ws://host/api/ws?token=t', {
+ WebSocketImpl: FakeWs,
+ ...WAITING,
+ keepWaitingWhile: () => {
+ throw new Error('boom')
+ }
+ })
+ )
+
+ await advance(30)
+ assert.deepEqual(probe.result, {
+ ok: false,
+ reason: 'Timed out after 30ms waiting for the WebSocket to open.'
+ })
+ })
+
+ test('without a callback the base budget is a single fixed deadline', async () => {
+ const { FakeWs } = makeFakeWs()
+
+ const probe = track(
+ probeGatewayWebSocket('ws://host/api/ws?token=t', {
+ WebSocketImpl: FakeWs,
+ connectTimeoutMs: 30,
+ readyGraceMs: 10
+ })
+ )
+
+ await advance(29)
+ assert.equal(probe.settled, false)
+
+ await advance(1)
+ assert.deepEqual(probe.result, {
+ ok: false,
+ reason: 'Timed out after 30ms waiting for the WebSocket to open.'
+ })
+ })
})
-test('probe respects the hard cap even while progress keeps reporting true', async () => {
- const { FakeWs } = makeFakeWs()
+describe('spawnedBackendProbeOptions', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ })
- const result = await probeGatewayWebSocket('ws://host/api/ws?token=t', {
- WebSocketImpl: FakeWs,
- connectTimeoutMs: 30,
- readyGraceMs: 10,
- progressCheckIntervalMs: 5,
- maxConnectWaitMs: 60,
- keepWaitingWhile: () => true
+ afterEach(() => {
+ vi.useRealTimers()
})
- assert.equal(result.ok, false)
- assert.match(result.reason, /Timed out/)
- assert.match(result.reason, /hard cap 60ms/, 'reason names the cap that ended the wait')
-})
+ test('outlasts a cold-start stall longer than the base budget while the child is alive', async () => {
+ const { FakeWs, instances } = makeFakeWs()
+ const stallMs = DEFAULT_CONNECT_TIMEOUT_MS * 3
-test('a throwing keepWaitingWhile fails closed at the base budget', async () => {
- const { FakeWs } = makeFakeWs()
+ const probe = track(
+ probeGatewayWebSocket('ws://127.0.0.1:1/api/ws?token=t', {
+ WebSocketImpl: FakeWs,
+ ...spawnedBackendProbeOptions(() => true)
+ })
+ )
- const result = await probeGatewayWebSocket('ws://host/api/ws?token=t', {
- WebSocketImpl: FakeWs,
- connectTimeoutMs: 20,
- readyGraceMs: 10,
- progressCheckIntervalMs: 5,
- maxConnectWaitMs: 500,
- keepWaitingWhile: () => {
- throw new Error('boom')
- }
+ await advance(stallMs)
+ assert.equal(probe.settled, false)
+
+ instances[0].emit('message')
+ await advance(0)
+ assert.deepEqual(probe.result, { ok: true })
})
- assert.equal(result.ok, false)
- assert.match(result.reason, /Timed out after \d+ms waiting for the WebSocket to open\./)
- assert.doesNotMatch(result.reason, /backend progress/, 'no extension when the check throws')
+ test('a child that exits mid-wait fails promptly instead of holding the boot to the cap', async () => {
+ const { FakeWs } = makeFakeWs()
+ let alive = true
+
+ const probe = track(
+ probeGatewayWebSocket('ws://127.0.0.1:1/api/ws?token=t', {
+ WebSocketImpl: FakeWs,
+ ...spawnedBackendProbeOptions(() => alive)
+ })
+ )
+
+ await advance(DEFAULT_CONNECT_TIMEOUT_MS * 2)
+ alive = false
+ await advance(DEFAULT_PROGRESS_CHECK_INTERVAL_MS)
+
+ assert.equal(probe.result?.ok, false)
+ assert.match(probe.result?.reason, /backend stopped/)
+ })
+
+ test('a live backend that never answers still fails, at the bounded cap', async () => {
+ const { FakeWs } = makeFakeWs()
+
+ const probe = track(
+ probeGatewayWebSocket('ws://127.0.0.1:1/api/ws?token=t', {
+ WebSocketImpl: FakeWs,
+ ...spawnedBackendProbeOptions(() => true)
+ })
+ )
+
+ await advance(SPAWNED_BACKEND_MAX_CONNECT_WAIT_MS - 1)
+ assert.equal(probe.settled, false)
+
+ await advance(1)
+ assert.equal(probe.result?.ok, false)
+ assert.match(probe.result?.reason, /cap/)
+ assert.ok(SPAWNED_BACKEND_MAX_CONNECT_WAIT_MS > DEFAULT_CONNECT_TIMEOUT_MS)
+ })
})
test('probe fails gracefully when the constructor throws', async () => {
diff --git a/apps/desktop/electron/gateway-ws-probe.ts b/apps/desktop/electron/gateway-ws-probe.ts
index 13ec15d051f..143fed15a79 100644
--- a/apps/desktop/electron/gateway-ws-probe.ts
+++ b/apps/desktop/electron/gateway-ws-probe.ts
@@ -24,12 +24,10 @@
* unit tests can drive the handshake without a real socket; in production the
* caller passes the Node/Electron global ``WebSocket``.
*
- * The boot-time probe for a LOCAL backend additionally supports progress-aware
- * waiting (#96177): a Windows cold start can hold the backend's GIL for
- * 12-28s while gateway platform modules byte-compile, leaving the upgrade
- * unanswered well past the fixed 10s budget. Passing ``keepWaitingWhile``
- * turns the one-shot connect timer into a deadline that only fires once the
- * backend stops reporting progress (and never past ``maxConnectWaitMs``).
+ * The boot-time probe of a backend child this app spawned also uses it, with
+ * ``keepWaitingWhile``: a Windows cold start can stall the backend's event
+ * loop for 12-28s after HTTP is up, well past the fixed 10s budget (#96177).
+ * See ``spawnedBackendProbeOptions``.
*/
const DEFAULT_CONNECT_TIMEOUT_MS = 10_000
@@ -38,8 +36,7 @@ const DEFAULT_CONNECT_TIMEOUT_MS = 10_000
// window: a frame (gateway.ready) or a still-open socket means success; an
// early close means the upgrade was accepted but the session was refused.
const DEFAULT_READY_GRACE_MS = 750
-// While a `keepWaitingWhile` progress callback is active, the connect
-// deadline is re-evaluated on this cadence instead of firing once.
+// Past the base budget, a `keepWaitingWhile` probe re-checks on this cadence.
const DEFAULT_PROGRESS_CHECK_INTERVAL_MS = 1_000
/**
@@ -55,26 +52,16 @@ function probeGatewayWebSocket<T>(
connectTimeoutMs?: number
readyGraceMs?: number
/**
- * Backend-progress-aware waiting (Windows cold start, #96177): once the
- * `connectTimeoutMs` budget passes, this callback is polled every
- * `progressCheckIntervalMs`. While it returns true, the probe keeps
- * waiting instead of failing on the fixed deadline — so a backend that
- * is still alive and emitting import progress (GIL held for 12-28s
- * while gateway platform modules byte-compile) is given room to finish,
- * while a silent/dead backend still fails fast. `maxConnectWaitMs` caps
- * the total wait even when progress keeps reporting true. When this
- * callback is omitted the probe behaves exactly as before: a single
- * fixed `connectTimeoutMs` deadline. A throwing callback is treated as
- * "no progress" (fail closed).
+ * Consulted once `connectTimeoutMs` passes, then every
+ * `progressCheckIntervalMs`: while it returns true the probe keeps
+ * waiting instead of failing, never past `maxConnectWaitMs`. Omitted, the
+ * probe is a single fixed `connectTimeoutMs` deadline. A throwing
+ * callback counts as false (fail closed).
*/
keepWaitingWhile?: () => boolean
/** Cadence at which the connect deadline is re-evaluated (default 1s). */
progressCheckIntervalMs?: number
- /**
- * Hard ceiling on the TOTAL wait when `keepWaitingWhile` is active.
- * Defaults to `connectTimeoutMs` — i.e. extension is opt-in; pass an
- * explicit cap to allow waiting past the base budget.
- */
+ /** Hard cap on the total wait; defaults to `connectTimeoutMs` (no extension). */
maxConnectWaitMs?: number
/** Extra upgrade-request headers (access-proxy credentials such as
* Cloudflare Access service tokens). Passed as the non-standard second
@@ -204,54 +191,55 @@ function probeGatewayWebSocket<T>(
addListener(socket, 'close', onClose)
if (connectTimeoutMs > 0) {
- // The connect budget is a *quiet* budget: on a healthy gateway the
- // upgrade completes in well under a second. When `keepWaitingWhile`
- // is provided (local cold-start boot, #96177), the deadline is
- // re-evaluated on a cadence instead of firing once — past the budget
- // the probe only fails when the progress callback stops reporting
- // forward motion, and never beyond `maxConnectWaitMs`.
- const startTime = Date.now()
- const connectDeadline = startTime + connectTimeoutMs
- const maxWaitDeadline = startTime + Math.max(connectTimeoutMs, maxConnectWaitMs)
- let extended = false
-
- const safeKeepWaiting = () => {
+ // A healthy gateway upgrades in well under a second, so the base budget
+ // stays short. With `keepWaitingWhile` (a locally spawned backend,
+ // #96177) the base deadline becomes a checkpoint: while the callback
+ // says the backend is still there, re-check on a cadence, never past
+ // `maxConnectWaitMs`. Without it this is the original one-shot timer.
+ const startedAt = Date.now()
+ const hardCapMs = Math.max(connectTimeoutMs, maxConnectWaitMs)
+
+ const shouldKeepWaiting = () => {
try {
return Boolean(keepWaitingWhile?.())
} catch {
- // A throwing progress check must never hold the probe open —
- // fail closed and report the plain timeout.
+ // A throwing check must never hold the probe open: fail closed.
return false
}
}
- const tick = () => {
+ const check = () => {
if (settled) {
return
}
- const now = Date.now()
- const progressSaysWait = safeKeepWaiting()
+ const elapsedMs = Date.now() - startedAt
- if (now >= maxWaitDeadline || (now >= connectDeadline && !progressSaysWait)) {
+ if (!shouldKeepWaiting()) {
finish({
ok: false,
- reason: extended
- ? `Timed out after ${now - startTime}ms waiting for the WebSocket to open (backend progress stopped after ${connectTimeoutMs}ms; hard cap ${maxConnectWaitMs}ms).`
- : `Timed out after ${connectTimeoutMs}ms waiting for the WebSocket to open.`
+ reason:
+ elapsedMs > connectTimeoutMs
+ ? `Timed out after ${elapsedMs}ms waiting for the WebSocket to open (backend stopped after the ${connectTimeoutMs}ms budget).`
+ : `Timed out after ${connectTimeoutMs}ms waiting for the WebSocket to open.`
})
return
}
- if (now >= connectDeadline) {
- extended = true
+ if (elapsedMs >= hardCapMs) {
+ finish({
+ ok: false,
+ reason: `Timed out after ${elapsedMs}ms waiting for the WebSocket to open (backend still running at the ${hardCapMs}ms cap).`
+ })
+
+ return
}
- connectTimer = setTimeout(tick, progressCheckIntervalMs)
+ connectTimer = setTimeout(check, Math.min(progressCheckIntervalMs, hardCapMs - elapsedMs))
}
- connectTimer = setTimeout(tick, Math.min(connectTimeoutMs, progressCheckIntervalMs))
+ connectTimer = setTimeout(check, connectTimeoutMs)
}
})
}
@@ -311,9 +299,33 @@ function closeReason(event, fallback) {
return fallback
}
+// Boot-time probe policy for a backend child THIS app spawned (#96177). On a
+// Windows cold start the backend answers HTTP, then holds the GIL for 12-28s
+// importing gateway platform modules; the event loop (and so the WS upgrade)
+// is stalled and the process prints nothing until it recovers — the
+// web_server loop heartbeat only logs "event loop stalled" afterwards. So the
+// honest signal is liveness: a live loopback child whose listener accepted
+// the TCP connect but has not answered the upgrade is busy, not refusing (a
+// refusal or auth rejection is an immediate error/close, not a timeout). A
+// dead child still fails at the base budget; a live-but-wedged one fails at
+// the cap, which reuses the port-announcement cold-start budget
+// (DEFAULT_PORT_ANNOUNCE_TIMEOUT_MS, backend-ready.ts). Remote gateways, the
+// "Test remote" button and host-backend attach keep the fixed budget.
+const SPAWNED_BACKEND_MAX_CONNECT_WAIT_MS = 90_000
+
+function spawnedBackendProbeOptions(isChildAlive: () => boolean) {
+ return {
+ connectTimeoutMs: DEFAULT_CONNECT_TIMEOUT_MS,
+ maxConnectWaitMs: SPAWNED_BACKEND_MAX_CONNECT_WAIT_MS,
+ keepWaitingWhile: isChildAlive
+ }
+}
+
export {
DEFAULT_CONNECT_TIMEOUT_MS,
DEFAULT_PROGRESS_CHECK_INTERVAL_MS,
DEFAULT_READY_GRACE_MS,
- probeGatewayWebSocket
+ probeGatewayWebSocket,
+ SPAWNED_BACKEND_MAX_CONNECT_WAIT_MS,
+ spawnedBackendProbeOptions
}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 3f328df1cb7..b6b23d8d4cb 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -50,7 +50,6 @@ import {
waitForBackendExit as waitForBackendExitImpl
} from './backend-child'
import {
- backendMakingProgress,
type BackendOutputTail,
claimDecision,
createBackendOutputTail,
@@ -226,7 +225,7 @@ import {
writeBufferToFile
} from './gateway-file-download'
import { startGatewaysAfterUpdateAbort, stopGatewayBeforeUpdate } from './gateway-stop-before-update'
-import { probeGatewayWebSocket } from './gateway-ws-probe'
+import { probeGatewayWebSocket, spawnedBackendProbeOptions } from './gateway-ws-probe'
import { registerGitIpc } from './git-ipc'
import {
describeGitHubCredentialSource,
@@ -2475,16 +2474,6 @@ const UPDATE_WAIT_POLL_MS = 1000
// updater's own progress window appears. (#50419)
const UPDATE_HANDOFF_DWELL_MS = 2500
-// Boot-time WS probe budget (#96177). The base connect budget stays short —
-// a healthy local backend upgrades in well under a second — but the probe
-// keeps waiting past it while the backend child is alive and still emitting
-// output (Windows cold start: the GIL is held 12-28s while gateway platform
-// modules byte-compile, leaving the WS upgrade unanswered). The hard cap
-// mirrors the port-announcement cold-start budget (90s, backend-ready.ts) so
-// a genuinely hung backend still fails the boot instead of hanging forever.
-const WS_PROBE_CONNECT_TIMEOUT_MS = 10_000
-const WS_PROBE_MAX_WAIT_MS = 90_000
-
// Gate deps shared by the primary-window boot path and the pool-backend
// spawn path. Consulting the on-disk marker, the in-process updateInFlight
// flag, AND the successful detached hand-off state is load-bearing (#73822):
@@ -12813,8 +12802,10 @@ async function runPoolBackendStart(
assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })
ready = true
+ const childAlive = () => child.exitCode === null && !child.killed
+
const authToken = await adoptServedDashboardToken(baseUrl, token, {
- childAlive: () => child.exitCode === null && !child.killed,
+ childAlive,
label: `Hermes backend for profile "${profile}"`,
rememberLog
})
@@ -12827,17 +12818,12 @@ async function runPoolBackendStart(
// HTTP /api/status can pass while WS auth fails (separate transport, separate guards).
const wsUrl = `ws://127.0.0.1:${port}/api/ws?token=${encodeURIComponent(authToken)}`
+ // Our own child: a cold start can stall its loop past the base budget (#96177).
const wsProbe = await probeGatewayWebSocket(wsUrl, {
WebSocketImpl: globalThis.WebSocket,
- // #96177: a cold-start backend can hold the GIL for 12-28s importing
- // gateway platform modules with the socket open but the event loop
- // stalled, leaving the upgrade unanswered past a fixed 10s budget. Keep
- // waiting while the child is alive and still emitting output; the hard
- // cap mirrors the port-announcement cold-start budget.
- connectTimeoutMs: WS_PROBE_CONNECT_TIMEOUT_MS,
- maxConnectWaitMs: WS_PROBE_MAX_WAIT_MS,
- keepWaitingWhile: () => backendMakingProgress(child, outputTail)
+ ...spawnedBackendProbeOptions(childAlive)
})
+
assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })
if (!wsProbe.ok) {
@@ -13667,8 +13653,10 @@ async function runHermesStart({ supervisorRecovery = false }: { supervisorRecove
primaryExitRecovery.reset()
backendStartFailure = null
+ const childAlive = () => hermesProcess.exitCode === null && !hermesProcess.killed
+
const authToken = await adoptServedDashboardToken(baseUrl, token, {
- childAlive: () => hermesProcess.exitCode === null && !hermesProcess.killed,
+ childAlive,
rememberLog
})
@@ -13677,16 +13665,12 @@ async function runHermesStart({ supervisorRecovery = false }: { supervisorRecove
// Verify the WebSocket session token before declaring backend ready.
const wsUrl = `ws://127.0.0.1:${port}/api/ws?token=${encodeURIComponent(authToken)}`
+ // Same policy as the pool path: our own child may still be cold-starting (#96177).
const wsProbe = await probeGatewayWebSocket(wsUrl, {
WebSocketImpl: globalThis.WebSocket,
- // #96177: same progress-aware budget as the pool-backend path — a
- // Windows cold start can stall the backend event loop for 12-28s
- // (GIL held during gateway platform imports), so wait while the
- // child is alive and emitting output instead of failing at 10s.
- connectTimeoutMs: WS_PROBE_CONNECT_TIMEOUT_MS,
- maxConnectWaitMs: WS_PROBE_MAX_WAIT_MS,
- keepWaitingWhile: () => backendMakingProgress(hermesProcess, primaryOutputTail)
+ ...spawnedBackendProbeOptions(childAlive)
})
+
backendConnectionState.assertCurrentAttempt(connectionAttempt)
if (!wsProbe.ok) {