Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(byoa): put a deadline on the daemon's short HTTP calls (#40)

BillyKingf8d0b970f783
diff --git a/server/src/__tests__/agents-computer-http-timeout.test.ts b/server/src/__tests__/agents-computer-http-timeout.test.ts
new file mode 100644
index 0000000..9ed8924
--- /dev/null
+++ b/server/src/__tests__/agents-computer-http-timeout.test.ts
@@ -0,0 +1,82 @@
+/**
+ * The BYOA daemon's short request/response calls must have a deadline.
+ *
+ * The failure they guard against is not a server that REFUSES — that throws and
+ * is already handled — but one that accepts the connection and then never
+ * answers (half-open socket after a sleep/network switch, a hung proxy, a pod
+ * that stopped mid-request). A `fetch` with no signal never settles, and
+ * `try/catch` cannot catch a promise that doesn't settle. Since the first thing
+ * a turn awaits after its `turn START` log is a `runtimeBest('/status')` — before
+ * the engine spawn — one such request parks the turn forever: `finally { busy =
+ * false }` never runs, the agent stays permanently `busy`, later wakes collapse
+ * to `turn busy — coalescing`, and the heartbeat stops until the server marks the
+ * whole computer offline. Every agent on the machine goes down with it.
+ *
+ * These tests use a real socket that accepts and stays silent, so they exercise
+ * the actual not-settling case rather than a mock.
+ *
+ * Run: node --import tsx --test server/src/__tests__/agents-computer-http-timeout.test.ts
+ */
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { createServer, type Server } from 'node:http'
+
+/** A server that accepts requests and NEVER responds. */
+async function silentServer(): Promise<{ url: string; close: () => Promise<void> }> {
+ const server: Server = createServer(() => { /* deliberately never respond */ })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ const addr = server.address()
+ if (addr === null || typeof addr === 'string') throw new Error('no port')
+ return {
+ url: `http://127.0.0.1:${addr.port}`,
+ close: () => new Promise<void>((resolve) => { server.closeAllConnections?.(); server.close(() => resolve()) }),
+ }
+}
+
+test('a silent server aborts the fetch instead of hanging forever', async () => {
+ const { url, close } = await silentServer()
+ try {
+ const started = Date.now()
+ await assert.rejects(
+ fetch(url, { signal: AbortSignal.timeout(300) }),
+ (err: unknown) => (err as Error)?.name === 'TimeoutError' || (err as Error)?.name === 'AbortError',
+ 'a request to a non-responding server must reject, not park',
+ )
+ // The point is that it settles at all, promptly — not the exact duration.
+ assert.ok(Date.now() - started < 5_000, 'abort should fire on its own deadline')
+ } finally {
+ await close()
+ }
+})
+
+test('the abort surfaces as a throw, so a fire-and-forget wrapper can swallow it', async () => {
+ // This is the shape of runtimeBest/runtimeGet: the timeout turns a
+ // never-settling promise into a rejection, which their `catch` converts to
+ // null — so the turn continues to the engine spawn instead of parking.
+ const { url, close } = await silentServer()
+ try {
+ const best = async (): Promise<unknown> => {
+ try {
+ const res = await fetch(url, { signal: AbortSignal.timeout(300) })
+ return res.ok ? await res.json().catch(() => null) : null
+ } catch { return null }
+ }
+ assert.equal(await best(), null, 'a stalled call must degrade to null, not hang')
+ } finally {
+ await close()
+ }
+})
+
+test('a caller-supplied signal is respected over the default deadline', async () => {
+ // api() passes `init.signal ?? AbortSignal.timeout(...)`, so an explicit
+ // signal (e.g. a teardown controller) must still win.
+ const { url, close } = await silentServer()
+ try {
+ const ac = new AbortController()
+ const p = fetch(url, { signal: ac.signal })
+ ac.abort()
+ await assert.rejects(p, (err: unknown) => (err as Error)?.name === 'AbortError')
+ } finally {
+ await close()
+ }
+})
diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.ts
index 848292c..9b1d890 100644
--- a/server/src/agents/computer/daemon.ts
+++ b/server/src/agents/computer/daemon.ts
@@ -427,10 +427,27 @@ function parseArgs(argv: string[]): {
// ─── HTTP helpers ───────────────────────────────────────────────────────
+/** Wall-clock cap on every SHORT request/response call to the server (status,
+ * runs, token mint, heartbeat, agent sync).
+ *
+ * Without this, a request that never answers — a half-open socket surviving a
+ * laptop sleep/network switch, a hung proxy, a pod that accepted the connection
+ * and stopped — parks the turn forever: `catch` only sees throws, never a
+ * promise that simply doesn't settle. The turn's `finally { this.busy = false }`
+ * never runs, so the agent stays permanently `busy`, every later wake collapses
+ * to `turn busy — coalescing`, and the heartbeat interval stops going out until
+ * the server marks the whole computer offline. One stalled socket takes down
+ * every agent on the machine.
+ *
+ * Deliberately NOT applied to the wake-stream (an intentionally long-lived SSE
+ * connection, which has its own idle/backoff handling) or the npm version check. */
+const HTTP_TIMEOUT_MS = Math.max(1_000, Number(process.env.CUMORA_HTTP_TIMEOUT_MS ?? 20_000))
+
async function api<T>(serverUrl: string, path: string, init: RequestInit): Promise<T> {
const res = await fetch(`${serverUrl}${path}`, {
...init,
headers: { 'Content-Type': 'application/json', ...(init.headers ?? {}) },
+ signal: init.signal ?? AbortSignal.timeout(HTTP_TIMEOUT_MS),
})
if (!res.ok) {
const body = await res.text().catch(() => '')
@@ -440,7 +457,9 @@ async function api<T>(serverUrl: string, path: string, init: RequestInit): Promi
}
/** Fire-and-forget runtime call (status / runs). Never throws — observability
- * must never break the agent loop. */
+ * must never break the agent loop. The timeout is what makes that promise hold
+ * for a server that stops answering rather than refusing (see HTTP_TIMEOUT_MS):
+ * an abort throws, so it lands in the catch and the turn proceeds. */
async function runtimeBest(
serverUrl: string, path: string, token: string, body: unknown,
): Promise<unknown> {
@@ -449,6 +468,7 @@ async function runtimeBest(
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify(body),
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
})
return res.ok ? await res.json().catch(() => null) : null
} catch { return null }
@@ -461,6 +481,7 @@ async function runtimeGet<T>(
const res = await fetch(`${serverUrl}/runtime${path}`, {
method: 'GET',
headers: { Authorization: `Bearer ${token}` },
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
})
return res.ok ? await res.json().catch(() => null) as T | null : null
} catch { return null }
@@ -2345,6 +2366,9 @@ async function doRun(serverOverride?: string): Promise<void> {
await fetch(`${cfg.serverUrl}/api/computers/heartbeat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${cfg.deviceToken}` },
+ // A heartbeat that never answers must not outlive its own interval, or
+ // the beats queue up behind a dead socket and the computer reads offline.
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
// `supervised` tells the server HOW this daemon runs (service vs. a
// foreground command), so the app's upgrade banner can show the right
// update instructions for this machine.