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
perf(daemon): trust a live wake-stream instead of draining /inbox every 20s (#291)
yetone9941bec8ec2c
diff --git a/server/src/__tests__/agents-computer-fallback-poll.test.ts b/server/src/__tests__/agents-computer-fallback-poll.test.tsnew file mode 100644index 0000000..28278c5--- /dev/null+++ b/server/src/__tests__/agents-computer-fallback-poll.test.ts@@ -0,0 +1,61 @@+/**+ * The BYOA daemon's 20s fallback inbox drain exists for ONE reason: a wake-stream+ * can be severed silently (the server writes onto a half-dead socket and counts+ * the wake delivered), so a live wake is lost until the daemon notices. But+ * draining on every tick, on every agent, whether or not the stream is fine, is+ * a loadInbox against Postgres per agent per 20s — with thousands of idle+ * agents that alone pegged the production database.+ *+ * fallbackPollDue is the gate: drain at the old cadence only while the stream+ * is NOT provably alive (never connected, disconnected, or silent past the+ * server's `: ping` keepalive), and otherwise only as a slow double-check.+ *+ * Run: node --import tsx --test server/src/__tests__/agents-computer-fallback-poll.test.ts+ */+import { test } from 'node:test'+import assert from 'node:assert/strict'+import { fallbackPollDue } from '../agents/computer/daemon.js'++const STALE = 75_000+const HEALTHY = 120_000+const base = { staleMs: STALE, healthyIntervalMs: HEALTHY }++test('fallbackPollDue: never-connected stream → every tick drains', () => {+ assert.equal(fallbackPollDue({ ...base, now: 1_000, streamLastSeenAt: null, lastInboxDrainAt: 1_000 }), true)+ assert.equal(fallbackPollDue({ ...base, now: 21_000, streamLastSeenAt: null, lastInboxDrainAt: 1_000 }), true)+})++test('fallbackPollDue: a stream that just proved alive → tick is a no-op', () => {+ const now = 1_000_000+ assert.equal(fallbackPollDue({ ...base, now, streamLastSeenAt: now - 5_000, lastInboxDrainAt: now - 20_000 }), false)+ // A ping within the stale window still counts as alive right up to the edge.+ assert.equal(fallbackPollDue({ ...base, now, streamLastSeenAt: now - (STALE - 1), lastInboxDrainAt: now - 20_000 }), false)+})++test('fallbackPollDue: silent for the stale window → drains again', () => {+ const now = 1_000_000+ assert.equal(fallbackPollDue({ ...base, now, streamLastSeenAt: now - STALE, lastInboxDrainAt: now - 20_000 }), true)+})++test('fallbackPollDue: healthy stream still gets the slow double-check', () => {+ const now = 1_000_000+ assert.equal(fallbackPollDue({ ...base, now, streamLastSeenAt: now - 1_000, lastInboxDrainAt: now - (HEALTHY - 1) }), false)+ assert.equal(fallbackPollDue({ ...base, now, streamLastSeenAt: now - 1_000, lastInboxDrainAt: now - HEALTHY }), true)+})++test('fallbackPollDue: a fresh runner (no drain yet) drains on its first healthy tick', () => {+ // lastInboxDrainAt starts at 0, so the first tick after connect is due even+ // though the stream is alive — the connect's own catch-up normally lands+ // first and moves the anchor; if it did not, this is the safety net.+ assert.equal(fallbackPollDue({ ...base, now: 200_000, streamLastSeenAt: 199_000, lastInboxDrainAt: 0 }), true)+})++test('fallbackPollDue: defaults are the production constants', () => {+ const now = 1_000_000+ // 74s of silence is still alive; 75s is not.+ assert.equal(fallbackPollDue({ now, streamLastSeenAt: now - 74_000, lastInboxDrainAt: now }), false)+ assert.equal(fallbackPollDue({ now, streamLastSeenAt: now - 75_000, lastInboxDrainAt: now }), true)+ // 119s since the last drain on a live stream is not due; 120s is.+ assert.equal(fallbackPollDue({ now, streamLastSeenAt: now, lastInboxDrainAt: now - 119_000 }), false)+ assert.equal(fallbackPollDue({ now, streamLastSeenAt: now, lastInboxDrainAt: now - 120_000 }), true)+})diff --git a/server/src/__tests__/agents-sse-parse.test.ts b/server/src/__tests__/agents-sse-parse.test.tsindex 072d956..dd9ac8a 100644--- a/server/src/__tests__/agents-sse-parse.test.ts+++ b/server/src/__tests__/agents-sse-parse.test.ts@@ -89,6 +89,19 @@ test('parseSseStream: `:` comment lines are skipped', async () => {assert.equal(out[0].event, 'wake')})+test('parseSseStream: onComment sees every `:` line, even a ping-only block', async () => {+ // The daemon keys its wake-stream liveness off the server's `: ping <ts>`+ // keepalive (wake-bus.ts writes one every 25s as its own block). The hook+ // must fire for that block even though nothing is yielded for it.+ const comments: string[] = []+ const out = await collect(parseSseStream(+ asUint8Stream([': ping 1\n\n', 'event: wake\n: mid-block note\ndata: x\n\n', ': ping 2\r\n\n']),+ { onComment: (line) => comments.push(line) },+ ))+ assert.deepEqual(comments, [': ping 1', ': mid-block note', ': ping 2'])+ assert.deepEqual(out, [{ event: 'wake', data: 'x' }])+})+test('parseSseStream: unknown fields are ignored, recognized fields are kept', async () => {// `retry:` and `: comment` are skipped; we keep event/data/id.const out = await collect(parseSseStream(asUint8Stream([diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.tsindex 327b8d1..881f400 100644--- a/server/src/agents/computer/daemon.ts+++ b/server/src/agents/computer/daemon.ts@@ -113,9 +113,27 @@ const RUN_HEARTBEAT_MS = 60_000// Fallback inbox drain. The wake-stream SSE can be silently severed by the// network edge (the server writes the wake onto a half-dead socket, counts it// delivered, and does nothing more), so a live wake can be lost until the daemon-// detects the drop and reconnects. This low-frequency self-drain bounds catch-up-// latency regardless of SSE health; an empty inbox makes the turn a cheap no-op.+// detects the drop and reconnects. This self-drain bounds catch-up latency+// regardless of SSE health; an empty inbox makes the turn a cheap no-op for the+// DAEMON — but not for the server: every drain is a loadInbox against Postgres,+// and at fleet scale (thousands of idle agents × one drain per 20s) that alone+// pegged Cloud SQL. So the tick stays at 20s, but a tick only drains when the+// stream is not provably alive (see fallbackPollDue): the server writes a+// `: ping` comment every 25s (wake-bus.ts), so a stream silent for three pings+// counts as dead and is polled at the old cadence AND torn down so streamLoop+// reconnects (a half-dead socket can otherwise sit "open" for many minutes);+// a stream that is demonstrably alive is trusted and only double-checked every+// INBOX_POLL_STREAM_HEALTHY_MS.const INBOX_POLL_MS = 20_000+const INBOX_POLL_STREAM_HEALTHY_MS = 120_000+const WAKE_STREAM_STALE_MS = 75_000+// Idle-tick `avail` reassert. Every idle drain used to POST /status {avail} —+// an UPDATE + Redis publish per agent per tick that changed nothing. The server+// now no-ops an avail→avail write, but the request itself (and its resolveDevice)+// still costs; so the daemon posts avail only when the last status it sent was+// something else, and re-asserts it this often as self-healing in case the+// server-side row drifted (a failed post, a restore from backup, ...).+const AVAIL_REASSERT_MS = 10 * 60_000// Pre-turn wake debounce. The FIRST wake from// an idle state arms this timer; wakes arriving within the window FOLD INTO it —// the turn snapshots ALL unread, so a burst of group messages becomes ONE big-@@ -649,6 +667,27 @@ async function runtimeGet<T>(} catch { return null }}+/** Should this 20s fallback tick actually drain the inbox?+ *+ * Yes when the wake-stream is not provably alive: never connected, or silent+ * (no event, no `: ping`) for WAKE_STREAM_STALE_MS. Otherwise the stream is+ * trusted to deliver wakes and the drain runs only as a slow double-check,+ * every INBOX_POLL_STREAM_HEALTHY_MS since the last drain. `streamLastSeenAt`+ * is null while disconnected. Exported for tests — pure. */+export function fallbackPollDue(input: {+ now: number+ streamLastSeenAt: number | null+ lastInboxDrainAt: number+ staleMs?: number+ healthyIntervalMs?: number+}): boolean {+ const staleMs = input.staleMs ?? WAKE_STREAM_STALE_MS+ const healthyIntervalMs = input.healthyIntervalMs ?? INBOX_POLL_STREAM_HEALTHY_MS+ const streamAlive = input.streamLastSeenAt !== null && input.now - input.streamLastSeenAt < staleMs+ if (!streamAlive) return true+ return input.now - input.lastInboxDrainAt >= healthyIntervalMs+}+/** Which conversation should show "<agent> is typing…" for this turn.** The wake's own conversation when it had one. Otherwise derive it from what is@@ -1745,6 +1784,17 @@ export class AgentRunner {private lastGroupSteeredMsgId: string | null = nullprivate lastGroupSteerAt = 0private pollTimer: ReturnType<typeof setInterval> | undefined+ /** Wake-stream liveness for fallbackPollDue: when the stream last showed+ * signs of life (connect, any event, any `: ping`); null while disconnected. */+ private streamLastSeenAt: number | null = null+ /** Aborts the current wake-stream fetch, so a stream that has gone silent can+ * be torn down and reconnected instead of waiting for TCP to notice. */+ private streamAbort: AbortController | null = null+ /** When snapshotUnread last hit /inbox — the anchor for the slow double-check. */+ private lastInboxDrainAt = 0+ /** The last status POST that succeeded, and when — see AVAIL_REASSERT_MS. */+ private lastPostedStatus: string | null = null+ private lastPostedStatusAt = 0private readonly adapter/** Privileged local broker: the engine sees only its IPC directory, while the* daemon keeps the short-lived runtime JWT in memory. */@@ -1993,10 +2043,36 @@ export class AgentRunner {await this.cliBroker.start()await this.loadSessionId()void this.streamLoop()- // SSE-independent safety net (see INBOX_POLL_MS): drain the inbox on a slow- // tick so a wake lost to a half-dead stream is still picked up within the- // interval. Skip while busy so it never piles on the live turn.- this.pollTimer = setInterval(() => { if (!this.busy && !this.stopped) this.scheduleWake('poll') }, INBOX_POLL_MS)+ // SSE-independent safety net (see INBOX_POLL_MS): tick every 20s, but only+ // drain when the wake-stream can't be trusted (or the slow double-check is+ // due), so a fleet of idle agents stops hammering /inbox in lockstep. Skip+ // while busy so it never piles on the live turn.+ this.pollTimer = setInterval(() => {+ if (this.busy || this.stopped) return+ const now = Date.now()+ // A connected stream that has missed three pings is half-dead: tear it+ // down so streamLoop reconnects (and its reconnect-catchup drains).+ if (this.streamLastSeenAt !== null && now - this.streamLastSeenAt >= WAKE_STREAM_STALE_MS && this.streamAbort) {+ console.warn(`[computer] ${this.agent.id} wake-stream silent for ${Math.round((now - this.streamLastSeenAt) / 1000)}s — reconnecting`)+ this.streamAbort.abort()+ }+ if (fallbackPollDue({ now, streamLastSeenAt: this.streamLastSeenAt, lastInboxDrainAt: this.lastInboxDrainAt })) {+ this.scheduleWake('poll')+ }+ }, INBOX_POLL_MS)+ }++ /** POST /status, skipping an idle `avail` the server already holds. Any other+ * status (thinking, resting…) always posts, and the avail right after it+ * posts too — only avail-after-avail is elided, and even that is re-asserted+ * every AVAIL_REASSERT_MS. A failed post is not remembered, so the next tick+ * retries it. */+ private async postStatus(token: string, status: 'avail' | 'thinking'): Promise<void> {+ const now = Date.now()+ if (status === 'avail' && this.lastPostedStatus === 'avail' && now - this.lastPostedStatusAt < AVAIL_REASSERT_MS) return+ const ok = await runtimeBest(this.cfg.serverUrl, '/status', token, { status })+ if (ok) { this.lastPostedStatus = status; this.lastPostedStatusAt = now }+ else this.lastPostedStatus = null}/** Phase 1 of shutdown: stop accepting NEW wakes/turns, but leave any in-flight@@ -2004,6 +2080,7 @@ export class AgentRunner {beginStop(): void {this.stopped = trueif (this.pollTimer) { clearInterval(this.pollTimer); this.pollTimer = undefined }+ this.streamAbort?.abort()if (this.wakeDebounceTimer) { clearTimeout(this.wakeDebounceTimer); this.wakeDebounceTimer = null }}@@ -2433,6 +2510,7 @@ export class AgentRunner {}private async snapshotUnread(token: string): Promise<{ seen: Map<string, string>; digest: string; hasReal: boolean; projectIds: string[] }> {+ this.lastInboxDrainAt = Date.now()const inbox = await runtimeGet<RuntimeInboxResponse>(this.cfg.serverUrl, '/inbox', token)const seen = new Map<string, string>()// Unread grouped BY CONVERSATION (first-seen order), each with the header@@ -2686,7 +2764,7 @@ export class AgentRunner {)if (!ag?.actionable || !ag.brief) returnconsole.log(`[computer] ${this.agent.id} agenda turn START — proactive board work${ag.focus ? `: ${ag.focus.slice(0, 80)}` : ''}`)- await runtimeBest(this.cfg.serverUrl, '/status', token, { status: 'thinking' })+ await this.postStatus(token, 'thinking')const run = (await runtimeBest(this.cfg.serverUrl, '/runs', token, {trigger: { source: 'byoa-agenda', engine: this.adapter.id },})) as { runId?: string } | null@@ -2731,7 +2809,7 @@ export class AgentRunner {// wraps because a slow flush must not block the chat path.this.currentRunId = nullvoid this.reporter.flush()- await runtimeBest(this.cfg.serverUrl, '/status', token, { status: 'avail' })+ await this.postStatus(token, 'avail')// Mirror chat path: release the concurrency slot regardless of outcome.bigBrainSem.release()}@@ -2945,7 +3023,7 @@ export class AgentRunner {// dropping that SSE payload here was why BYOA cards stayed in Todo.if (!wakeHasActionableInput(hasReal, activeBackgroundBrief)) {await this.ackSeen(token, seen)- await runtimeBest(this.cfg.serverUrl, '/status', token, { status: 'avail' })+ await this.postStatus(token, 'avail')// No per-tick log: this is the idle steady state (every poll × agent),// same reasoning as the 'inbox empty' skip below.// Chat is idle → maybe there's assigned BOARD work to proactively pick up@@ -2968,7 +3046,7 @@ export class AgentRunner {const backoff = Math.min(10 * 60_000, 30_000 * 2 ** (this.triageTroubleStreak - 1))this.triageBackoffUntil = Date.now() + backoffconsole.warn(`[computer] ${this.agent.id} triage RATE-LIMITED (#${this.triageTroubleStreak}, triage ${triageMs}ms) — backing off ${Math.round(backoff / 1000)}s, NOT waking the big brain, not acking`)- await runtimeBest(this.cfg.serverUrl, '/status', token, { status: 'avail' })+ await this.postStatus(token, 'avail')break}// FAIL-OPEN is a triage FAILURE, not a confirmed real task — so it must@@ -2981,7 +3059,7 @@ export class AgentRunner {const backoff = Math.min(10 * 60_000, 30_000 * 2 ** (this.triageTroubleStreak - 1))this.triageBackoffUntil = Date.now() + backoffconsole.warn(`[computer] ${this.agent.id} triage FAIL-OPEN (#${this.triageTroubleStreak}, triage ${triageMs}ms) — NOT waking the big brain, backing off ${Math.round(backoff / 1000)}s, not acking`)- await runtimeBest(this.cfg.serverUrl, '/status', token, { status: 'avail' })+ await this.postStatus(token, 'avail')break}// A clean, usable triage clears any prior backoff.@@ -2999,7 +3077,7 @@ export class AgentRunner {// unread sticks and the INBOX_POLL_MS drain re-triages it forever —// the loop that woke (or nearly woke) the big brain on every tick.await this.ackSeen(token, seen)- await runtimeBest(this.cfg.serverUrl, '/status', token, { status: 'avail' })+ await this.postStatus(token, 'avail')// Chat had nothing for us → maybe proactively pick up assigned board work.await this.maybeAgendaTurn(token)continue@@ -3018,7 +3096,7 @@ export class AgentRunner {? `manual brief ${activeBackgroundBrief.source ?? 'unknown'}`: `triage ${triageMs}ms`console.log(`[computer] ${this.agent.id} turn START (${reason}) — ${gateLabel}, spawning ${this.adapter.id}${convo ? ` for ${convo}` : ''}`)- await runtimeBest(this.cfg.serverUrl, '/status', token, { status: 'thinking' })+ await this.postStatus(token, 'thinking')// "<agent> is typing…" in the conversation that woke us, refreshed// while the engine works (BYOA runs can be long), cleared at the end.let typingTimer: ReturnType<typeof setInterval> | undefined@@ -3192,7 +3270,7 @@ export class AgentRunner {// from re-waking the big brain on the next drain. On engine FAILURE we// skip the ack so the unread survives for a retry / next wake.if (!engineError) await this.ackSeen(token, seen)- await runtimeBest(this.cfg.serverUrl, '/status', token, { status: 'avail' })+ await this.postStatus(token, 'avail')// A chat turn resets the "quiet" anchor: an agent that just acted in chat// isn't immediately pulled into an agenda turn (mirrors the cloud idle// scheduler only picking agents quiet for N minutes).@@ -3226,10 +3304,13 @@ export class AgentRunner {let backoff = 1000while (!this.stopped) {let connectedAt: number | null = null+ const abort = new AbortController()+ this.streamAbort = aborttry {const token = await this.ensureToken()const res = await fetch(`${this.cfg.serverUrl}/runtime/wake-stream`, {headers: { Authorization: `Bearer ${token}`, Accept: 'text/event-stream' },+ signal: abort.signal,})if (!res.ok || !res.body) {if (res.status === 401 || res.status === 403) this.invalidateToken(token)@@ -3237,8 +3318,13 @@ export class AgentRunner {}console.log(`[computer] ${this.agent.id} wake-stream connected (engine: ${this.adapter.id})`)connectedAt = Date.now()+ this.streamLastSeenAt = connectedAtthis.kickTurn('reconnect-catchup') // cold-start / reconnect catch-up- for await (const evt of parseSseStream(res.body as unknown as AsyncIterable<unknown>)) {+ // Every event AND every `: ping` comment is proof the stream is alive;+ // the fallback poll (fallbackPollDue) keys off this timestamp.+ const alive = (): void => { this.streamLastSeenAt = Date.now() }+ for await (const evt of parseSseStream(res.body as unknown as AsyncIterable<unknown>, { onComment: alive })) {+ alive()if (this.stopped) breakif (evt.event === 'wake' || evt.event === 'steer') {// 'wake': normal new-activity nudge. 'steer': a peer posted while we@@ -3277,6 +3363,8 @@ export class AgentRunner {const _cause = (err as { cause?: { code?: string; message?: string } } | null)?.causeconsole.warn(`[computer] ${this.agent.id} stream error: ${err instanceof Error ? err.message : err}${_cause ? ` cause=${_cause.code ?? _cause.message ?? JSON.stringify(_cause)}` : ''} · retry in ${backoff}ms`)}+ this.streamLastSeenAt = null+ if (this.streamAbort === abort) this.streamAbort = nullif (this.stopped) break// BOTH exits back off. Reset the ladder only after a connection that// actually stayed up — a 200 that closes immediately must not reset it, ordiff --git a/server/src/agents/runtime/sse-parse.ts b/server/src/agents/runtime/sse-parse.tsindex 5ea108d..4debf68 100644--- a/server/src/agents/runtime/sse-parse.ts+++ b/server/src/agents/runtime/sse-parse.ts@@ -15,10 +15,18 @@export interface SseEvent { event?: string; data?: string; id?: string }+export interface ParseSseOptions {+ /** Called for every `: comment` line. The server writes one as a keepalive+ * every 25s (wake-bus.ts), so a consumer that wants to know whether a+ * silent stream is alive or half-dead can hook it here; the comment itself+ * is never yielded as an event. */+ onComment?: (line: string) => void+}+/** Streaming SSE block parser. Each yielded event represents one* `event: ...\ndata: ...\n\n` block. `data:` lines accumulate* across continuation lines per the spec. */-export async function* parseSseStream(body: AsyncIterable<unknown>): AsyncGenerator<SseEvent> {+export async function* parseSseStream(body: AsyncIterable<unknown>, options: ParseSseOptions = {}): AsyncGenerator<SseEvent> {// TextDecoder with `stream: true` preserves partial UTF-8// sequences across chunk boundaries — critical when a multi-byte// codepoint splits across two read() calls.@@ -35,7 +43,10 @@ export async function* parseSseStream(body: AsyncIterable<unknown>): AsyncGeneraconst out: SseEvent = {}for (const rawLine of block.split('\n')) {const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine- if (line.startsWith(':')) continue // SSE comment / ping+ if (line.startsWith(':')) { // SSE comment / ping+ options.onComment?.(line)+ continue+ }const colon = line.indexOf(':')if (colon < 0) continueconst field = line.slice(0, colon)