Skip to content

The agent that grows with you

fix(desktop): make boot WS probe wait on backend progress instead of a fixed 10s cap

Finn7634fc04e5a4b06
diff --git a/apps/desktop/electron/backend-claim.test.ts b/apps/desktop/electron/backend-claim.test.ts
index 0b2555b86a2..03f7386e835 100644
--- a/apps/desktop/electron/backend-claim.test.ts
+++ b/apps/desktop/electron/backend-claim.test.ts
@@ -4,6 +4,7 @@ import { EventEmitter } from 'node:events'
import { test } from 'vitest'
import {
+ backendMakingProgress,
claimDecision,
createBackendOutputTail,
formatBackendExitLine,
@@ -132,3 +133,52 @@ 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 fb53d21f7a9..d6db8627aa0 100644
--- a/apps/desktop/electron/backend-claim.ts
+++ b/apps/desktop/electron/backend-claim.ts
@@ -188,6 +188,12 @@ 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
@@ -198,8 +204,12 @@ 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): BackendOutputTail {
+export function createBackendOutputTail(
+ limit: number = DEFAULT_OUTPUT_TAIL_LIMIT,
+ { now = Date.now }: { now?: () => number } = {}
+): BackendOutputTail {
let buffer = ''
+ let lastActivityAt = 0
const append = (chunk: unknown) => {
buffer += String(chunk)
@@ -207,6 +217,8 @@ export function createBackendOutputTail(limit: number = DEFAULT_OUTPUT_TAIL_LIMI
if (buffer.length > limit) {
buffer = buffer.slice(buffer.length - limit)
}
+
+ lastActivityAt = now()
}
return {
@@ -222,6 +234,9 @@ export function createBackendOutputTail(limit: number = DEFAULT_OUTPUT_TAIL_LIMI
const text = buffer.trim()
return text ? `\nRecent backend output:\n${text}` : ''
+ },
+ lastActivityAt() {
+ return lastActivityAt
}
}
}
@@ -242,3 +257,26 @@ 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 c4bb52fe0a4..dee7375b456 100644
--- a/apps/desktop/electron/gateway-ws-probe.test.ts
+++ b/apps/desktop/electron/gateway-ws-probe.test.ts
@@ -116,6 +116,94 @@ 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.
+
+test('probe waits past the base budget while keepWaitingWhile reports progress', async () => {
+ const { FakeWs, instances } = makeFakeWs()
+ let progressed = true
+
+ const promise = probeGatewayWebSocket('ws://host/api/ws?token=t', {
+ WebSocketImpl: FakeWs,
+ connectTimeoutMs: 30,
+ readyGraceMs: 10,
+ progressCheckIntervalMs: 5,
+ maxConnectWaitMs: 500,
+ keepWaitingWhile: () => progressed
+ })
+
+ // The upgrade lands AFTER the 30ms quiet budget — the exact cold-start
+ // shape from #96177 (backend alive and importing, socket unanswered).
+ setTimeout(() => {
+ instances[0].emit('open')
+ }, 60)
+
+ const result = await promise
+ assert.equal(result.ok, true, 'progress-aware probe must outlive the fixed budget')
+})
+
+test('probe fails once progress stops after the base budget', async () => {
+ const { FakeWs } = makeFakeWs()
+ let progressed = true
+
+ const promise = probeGatewayWebSocket('ws://host/api/ws?token=t', {
+ WebSocketImpl: FakeWs,
+ connectTimeoutMs: 30,
+ readyGraceMs: 10,
+ progressCheckIntervalMs: 5,
+ maxConnectWaitMs: 500,
+ keepWaitingWhile: () => progressed
+ })
+
+ setTimeout(() => {
+ progressed = false
+ }, 40)
+
+ 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('probe respects the hard cap even while progress keeps reporting true', async () => {
+ const { FakeWs } = makeFakeWs()
+
+ const result = await probeGatewayWebSocket('ws://host/api/ws?token=t', {
+ WebSocketImpl: FakeWs,
+ connectTimeoutMs: 30,
+ readyGraceMs: 10,
+ progressCheckIntervalMs: 5,
+ maxConnectWaitMs: 60,
+ keepWaitingWhile: () => true
+ })
+
+ 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('a throwing keepWaitingWhile fails closed at the base budget', async () => {
+ const { FakeWs } = makeFakeWs()
+
+ 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')
+ }
+ })
+
+ 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('probe fails gracefully when the constructor throws', async () => {
class ThrowingWs {
constructor() {
diff --git a/apps/desktop/electron/gateway-ws-probe.ts b/apps/desktop/electron/gateway-ws-probe.ts
index d761f1170c1..13ec15d051f 100644
--- a/apps/desktop/electron/gateway-ws-probe.ts
+++ b/apps/desktop/electron/gateway-ws-probe.ts
@@ -23,6 +23,13 @@
* a post-upgrade auth rejection). The ``WebSocketImpl`` is injectable so the
* 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``).
*/
const DEFAULT_CONNECT_TIMEOUT_MS = 10_000
@@ -31,6 +38,9 @@ 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.
+const DEFAULT_PROGRESS_CHECK_INTERVAL_MS = 1_000
/**
* Attempt a live WebSocket connection and classify the outcome.
@@ -44,6 +54,28 @@ function probeGatewayWebSocket<T>(
WebSocketImpl?: any
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).
+ */
+ 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.
+ */
+ maxConnectWaitMs?: number
/** Extra upgrade-request headers (access-proxy credentials such as
* Cloudflare Access service tokens). Passed as the non-standard second
* constructor argument `{ headers }` that Node's (undici) WebSocket —
@@ -58,6 +90,9 @@ function probeGatewayWebSocket<T>(
const WebSocketImpl = options.WebSocketImpl
const connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS
const readyGraceMs = options.readyGraceMs ?? DEFAULT_READY_GRACE_MS
+ const progressCheckIntervalMs = options.progressCheckIntervalMs ?? DEFAULT_PROGRESS_CHECK_INTERVAL_MS
+ const keepWaitingWhile = options.keepWaitingWhile
+ const maxConnectWaitMs = options.maxConnectWaitMs ?? connectTimeoutMs
const headers = options.headers && Object.keys(options.headers).length > 0 ? options.headers : null
if (typeof WebSocketImpl !== 'function') {
@@ -169,12 +204,54 @@ function probeGatewayWebSocket<T>(
addListener(socket, 'close', onClose)
if (connectTimeoutMs > 0) {
- connectTimer = setTimeout(() => {
- finish({
- ok: false,
- reason: `Timed out after ${connectTimeoutMs}ms waiting for the WebSocket to open.`
- })
- }, connectTimeoutMs)
+ // 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 = () => {
+ try {
+ return Boolean(keepWaitingWhile?.())
+ } catch {
+ // A throwing progress check must never hold the probe open —
+ // fail closed and report the plain timeout.
+ return false
+ }
+ }
+
+ const tick = () => {
+ if (settled) {
+ return
+ }
+
+ const now = Date.now()
+ const progressSaysWait = safeKeepWaiting()
+
+ if (now >= maxWaitDeadline || (now >= connectDeadline && !progressSaysWait)) {
+ 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.`
+ })
+
+ return
+ }
+
+ if (now >= connectDeadline) {
+ extended = true
+ }
+
+ connectTimer = setTimeout(tick, progressCheckIntervalMs)
+ }
+
+ connectTimer = setTimeout(tick, Math.min(connectTimeoutMs, progressCheckIntervalMs))
}
})
}
@@ -234,4 +311,9 @@ function closeReason(event, fallback) {
return fallback
}
-export { DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_READY_GRACE_MS, probeGatewayWebSocket }
+export {
+ DEFAULT_CONNECT_TIMEOUT_MS,
+ DEFAULT_PROGRESS_CHECK_INTERVAL_MS,
+ DEFAULT_READY_GRACE_MS,
+ probeGatewayWebSocket
+}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 6779b7ac93b..3f328df1cb7 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -50,6 +50,7 @@ import {
waitForBackendExit as waitForBackendExitImpl
} from './backend-child'
import {
+ backendMakingProgress,
type BackendOutputTail,
claimDecision,
createBackendOutputTail,
@@ -2474,6 +2475,16 @@ 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):
@@ -12815,7 +12826,18 @@ async function runPoolBackendStart(
// Verify the WebSocket session token before declaring backend ready.
// 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)}`
- const wsProbe = await probeGatewayWebSocket(wsUrl, { WebSocketImpl: globalThis.WebSocket })
+
+ 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)
+ })
assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })
if (!wsProbe.ok) {
@@ -13654,7 +13676,17 @@ 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)}`
- const wsProbe = await probeGatewayWebSocket(wsUrl, { WebSocketImpl: globalThis.WebSocket })
+
+ 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)
+ })
backendConnectionState.assertCurrentAttempt(connectionAttempt)
if (!wsProbe.ok) {