The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
refactor: improve WebSocket and Redis bus architecture, add voice budgeting, and introduce unit tests
0xken15499885bc632b
diff --git a/backend/Dockerfile.k8s b/backend/Dockerfile.k8sindex 62d31cb0d..f91ae886a 100644--- a/backend/Dockerfile.k8s+++ b/backend/Dockerfile.k8s@@ -60,6 +60,12 @@ COPY --from=builder /app/dist ./distENV NODE_ENV=production# Role selector. Override to `job` on the worker Deployment (replicas: 1).ENV APP=api+# Each pod is one node process (no pm2 cluster here), so cap V8's old space explicitly: without it V8+# sizes the heap from the NODE's RAM, not the pod's cgroup limit, and a leak becomes an OOM-kill of the+# whole pod instead of a bounded GC. Set the pod's memory limit to ~1.5x this. Override per Deployment+# (the api role streams to many sockets and wants more headroom than the job role). Merge, don't clobber,+# any NODE_OPTIONS a manifest already sets.+ENV NODE_OPTIONS=--max-old-space-size=1024USER backend@@ -68,6 +74,7 @@ USER backendEXPOSE 8085 8087# `exec` replaces the shell, so node ends up as PID 1 and receives SIGTERM directly; both entry-# points shut down on it (server.ts closes the listeners; worker.ts stops the billing loop and hard--# exits after 5s, so give the worker terminationGracePeriodSeconds >= 10).+# points shut down on it (server.ts closes the listeners, then DRAINS open websockets with a 1012+# close + ~4s grace before quitting Redis, so give the api terminationGracePeriodSeconds >= 10 too;+# worker.ts stops the billing loop and hard-exits after 5s, so the job also needs >= 10).CMD ["sh", "-c", "case \"$APP\" in api) exec node dist/server.js ;; job) exec node dist/worker.js ;; *) echo \"FATAL: unknown APP='$APP' (expected 'api' or 'job')\" >&2; exit 1 ;; esac"]diff --git a/backend/README.md b/backend/README.mdindex 93cf1472c..600cf3862 100644--- a/backend/README.md+++ b/backend/README.md@@ -76,6 +76,26 @@ make release-backend ARGS=--dry-run # preview, tags/pushes nothing(equivalent to `bash backend/scripts/release-be.sh`, see that script for details).+### Memory sizing and Redis limits++The `backend` app runs as a pm2 cluster: every worker has its own V8 heap. `ecosystem.config.cjs`+pins the heap with `--max-old-space-size` (`BACKEND_HEAP_MB`, default 1024) and recycles a worker at+`BACKEND_MAX_MEMORY` (default `1536M`), so size the container roughly as+`instances × BACKEND_MAX_MEMORY × 1.25`. `Dockerfile.k8s` runs one plain `node` per container — pass+`NODE_OPTIONS=--max-old-space-size=…` there and set the pod limit ~1.5× that.++Per-process ceilings that bound WebSocket memory (all in `src/lib`): `wsServer.ts` `WS_LIMITS`+(inbound frame size per endpoint), `wsSend.ts` `SEND_HIGH_WATER` / `SEND_KILL_WATER` (outbound+backpressure: droppable frames skipped, slow consumers closed 1013), `orderedInbox.ts`+`DEFAULT_MAX_INFLIGHT` (queued frames per socket), `VOICE_INFLIGHT_MAX_BYTES` (PCM held for STT across+all device sockets) and `APP_PROXY_MAX_RELAY_FRAME_BYTES` (largest app-proxy frame relayed cross-instance).++App-proxy bodies can cross instances through Redis pub/sub in multi-MiB messages. Redis' default+`client-output-buffer-limit pubsub 32mb 8mb 60` disconnects a subscriber that falls behind, so on the+Redis side set it to at least `64mb 16mb 60` and alert on `client_recent_max_output_buffer`. The+app-proxy channels ride their own subscriber connection (`appSub` in `bus.ts`), so a disconnect there+cannot take the chat / presence subscriptions down with it.+## PersistencePrisma over the **same MongoDB** as the agent-manager (no migration files — `prisma db push` atdiff --git a/backend/ecosystem.config.cjs b/backend/ecosystem.config.cjsindex 8345ce1a7..1d5ca6fca 100644--- a/backend/ecosystem.config.cjs+++ b/backend/ecosystem.config.cjs@@ -15,6 +15,14 @@ module.exports = {script: 'dist/server.js',exec_mode: 'cluster',instances: 'max',+ // Shutdown drains websockets (1012) before exit — give it room: 4s close grace + Redis quit.+ kill_timeout: 10000,+ // Each cluster worker has its own V8 heap, so the container's memory limit must cover+ // instances × heap (plus ~50% for buffers / native). Without an explicit ceiling V8 sizes the old+ // space from the HOST's RAM, and a leak on one worker surfaces as the OOM-killer taking the whole pod+ // instead of pm2 recycling one process. BACKEND_HEAP_MB / BACKEND_MAX_MEMORY tune both together.+ node_args: `--max-old-space-size=${process.env.BACKEND_HEAP_MB || 1024}`,+ max_memory_restart: process.env.BACKEND_MAX_MEMORY || '1536M',env: { NODE_ENV: 'production' },},],diff --git a/backend/ecosystem.config.cjs.docker b/backend/ecosystem.config.cjs.dockerindex c3525aef2..823dbfe21 100644--- a/backend/ecosystem.config.cjs.docker+++ b/backend/ecosystem.config.cjs.docker@@ -30,6 +30,14 @@ module.exports = {script: 'dist/server.js',exec_mode: 'cluster',instances,+ // Shutdown drains websockets (1012) before exit — give it room: 4s close grace + Redis quit.+ kill_timeout: 10000,+ // Each cluster worker has its own V8 heap, so the container's memory limit must cover+ // instances × heap (plus ~50% for buffers / native). Without an explicit ceiling V8 sizes the old+ // space from the HOST's RAM, and a leak on one worker surfaces as the OOM-killer taking the whole pod+ // instead of pm2 recycling one process. BACKEND_HEAP_MB / BACKEND_MAX_MEMORY tune both together.+ node_args: `--max-old-space-size=${process.env.BACKEND_HEAP_MB || 1024}`,+ max_memory_restart: process.env.BACKEND_MAX_MEMORY || '1536M',env: { NODE_ENV: 'production' },},],diff --git a/backend/src/config/env.ts b/backend/src/config/env.tsindex 37d6c2bb7..1af23680e 100644--- a/backend/src/config/env.ts+++ b/backend/src/config/env.ts@@ -195,6 +195,17 @@ const envSchema = z.object({APP_PROXY_MAX_WS_FRAME_BYTES: z.string().default('8388608').transform(Number), // 8 MiBAPP_PROXY_MAX_STREAMS_PER_SUBDOMAIN: z.string().default('128').transform(Number),APP_PROXY_IDLE_TIMEOUT_MS: z.string().default('300000').transform(Number), // 5 min+ // Largest single app-proxy frame relayed CROSS-INSTANCE through Redis pub/sub (co-located streams+ // never touch Redis). Above it the stream is aborted rather than published: Redis disconnects a+ // pub/sub subscriber that exceeds client-output-buffer-limit, so an oversized message is a threat to+ // every stream on that connection, not just its own. Default sits just above the largest legitimate+ // frame (APP_PROXY_MAX_WS_FRAME_BYTES base64'd into JSON).+ APP_PROXY_MAX_RELAY_FRAME_BYTES: z.string().default('16777216').transform(Number), // 16 MiB++ // Voice PCM held in this process across ALL device sockets (each utterance can reach stt.MAX_PCM =+ // 20 MiB). A budget rather than a per-socket cap so N devices rambling at once degrade to a+ // VOICE_BUFFER_FULL error instead of an OOM. Size against the worker heap (ecosystem.config.cjs).+ VOICE_INFLIGHT_MAX_BYTES: z.string().default('536870912').transform(Number), // 512 MiB})diff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.tsindex 1574268f7..44d23eab2 100644--- a/backend/src/lib/adapterWs.ts+++ b/backend/src/lib/adapterWs.ts@@ -14,7 +14,8 @@*/import type { IncomingMessage } from 'http'import type { Duplex } from 'stream'-import { WebSocketServer, WebSocket, type RawData } from 'ws'+import { WebSocket, type RawData } from 'ws'+import { createWss, WS_LIMITS } from './wsServer.js'import { prisma } from './prisma.js'import {publishUp, claimMachineOwner, releaseMachineOwner, publishDeviceE2eePair,@@ -22,6 +23,7 @@ import {setMachineAppState, clearMachineAppState,} from './bus.js'import { trackSocketLiveness } from './hub.js'+import { guardedSend, guardedSendJson } from './wsSend.js'import { attachNodeRole, PRESENCE_TTL_SEC } from './nodeRole.js'import { recordCreatedAgent, recordDeletedAgent } from './agentTracker.js'import type { Frame } from './tunnel.js'@@ -49,13 +51,7 @@ import {terminalP2pPolicy,} from './p2pSignaling.js'-const wss = new WebSocketServer({- noServer: true,- handleProtocols: (protocols) => {- const first = [...protocols][0]- return first ?? false- },-})+const wss = createWss(WS_LIMITS.adapter, { echoFirstProtocol: true })// machineId → the current adapter socket. One writer per machineId: down:{machineId} must have exactly// one consumer, so a reconnecting adapter supersedes its predecessor (same as attachNode does).@@ -172,8 +168,9 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c// stale local socket on a same-computer reconnect landing on this worker.owners.get(machineId)?.close(4000, 'superseded')owners.set(machineId, ws)+ const send = (obj: unknown): boolean => guardedSendJson(ws, obj, 'must', { machineId, kind: 'adapter' })logger.info('adapter connected', { machineId, computer: label })- try { ws.send(JSON.stringify({ t: 'connected', machineId })) } catch { /* ignore */ }+ send({ t: 'connected', machineId })// Last desktop-app state THIS socket asserted. Socket-scoped on purpose: a new adapter connection// starts with no claim and must re-assert, so a fresh value can never renew a stale one.@@ -217,9 +214,7 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c}// Tell the adapter its machine's display name (it mirrors it locally for `harness status`); null when// unnamed so a stale mirror clears. Renames while connected arrive the same way (machine_meta).- try {- ws.send(JSON.stringify({ t: 'down', connId: '', frame: { type: 'machine_meta', payload: { name: currentName?.trim() || seededName } } }))- } catch { /* ignore */ }+ send({ t: 'down', connId: '', frame: { type: 'machine_meta', payload: { name: currentName?.trim() || seededName } } })// The node role — down subscription, presence, `__clients` resync, node_status — is shared with// every other backer of a machine and lives in nodeRole.ts. Only the delivery and teardown are@@ -230,7 +225,7 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, cofflineReason: 'remote computer offline',deliver: (msg) => {if (ws.readyState !== WebSocket.OPEN) return- try { ws.send(JSON.stringify({ t: 'down', connId: msg.connId, frame: msg.frame })) } catch { /* ignore */ }+ send({ t: 'down', connId: msg.connId, frame: msg.frame })// `machine_revoked` used to be pushed and nothing more, leaving the socket open and the machine// still serving if the client ignored it — an old CLI, a dropped frame. Close it ourselves right// after the send so revocation does not depend on the client cooperating. Same shape as@@ -252,8 +247,8 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c},})const terminalDownUnsub = await subscribeTerminalDown(machineId, (packet) => {- if (ws.readyState !== WebSocket.OPEN) return- try { ws.send(packet) } catch { /* ignore */ }+ // Terminal input toward the adapter is 'must': dropping keystrokes is not recoverable client-side.+ guardedSend(ws, packet, 'must', { machineId, kind: 'adapter' })})// Liveness. The previous implementation pinged every 25 s and terminated on a single missed PONG —diff --git a/backend/src/lib/appTunnel.ts b/backend/src/lib/appTunnel.tsindex a6160d788..234c2a1cb 100644--- a/backend/src/lib/appTunnel.ts+++ b/backend/src/lib/appTunnel.ts@@ -15,7 +15,8 @@import type { IncomingMessage, ServerResponse } from 'http'import type { Duplex } from 'stream'import { randomUUID } from 'crypto'-import { WebSocketServer, WebSocket } from 'ws'+import { WebSocket } from 'ws'+import { createWss } from './wsServer.js'import { subscribeAppUp, publishAppDown } from './bus.js'import * as registry from './registry.js'import { env } from '../config/env.js'@@ -34,7 +35,8 @@ const RESPONSE_TIMEOUT_MS = 30_000type UpFrame = AppResEnvelope | AppBodyEnvelope | AppWsMsgEnvelope | AppWsCloseEnvelope | AppAbortEnvelope-const wss = new WebSocketServer({ noServer: true })+// Public app sockets: never accept more than the per-frame relay cap (and never less than 64 KiB).+const wss = createWss(Math.max(64 * 1024, env.APP_PROXY_MAX_WS_FRAME_BYTES))// streamId → local up-handler, for streams whose manager socket is on THIS instance (LOCAL mode). The// manager-ws message loop calls deliverAppUpLocal before falling back to publishAppUp.diff --git a/backend/src/lib/bus.test.ts b/backend/src/lib/bus.test.tsnew file mode 100644index 000000000..6dca8d7a0--- /dev/null+++ b/backend/src/lib/bus.test.ts@@ -0,0 +1,126 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++// One fake ioredis per `new Redis(...)`; the bus creates four (pub, sub, terminalSub, appSub).+const state = vi.hoisted(() => {+ const instances: unknown[] = []+ // Which HEXPIRE calls should error, consumed in order (true = error → fallback expire for that key).+ let hexpireErrors: boolean[] = []+ return {+ instances,+ setHexpireErrors: (e: boolean[]) => { hexpireErrors = [...e] },+ nextHexpireError: (): Error | null => (hexpireErrors.shift() ? new Error('ERR unknown command HEXPIRE') : null),+ }+})++vi.mock('ioredis', () => {+ class FakePipeline {+ calls: Array<{ cmd: string; args: unknown[] }> = []+ results: Array<[Error | null, unknown]> = []+ hdel(...args: unknown[]) { this.calls.push({ cmd: 'hdel', args }); this.results.push([null, 1]); return this }+ hset(...args: unknown[]) { this.calls.push({ cmd: 'hset', args }); this.results.push([null, 1]); return this }+ expire(...args: unknown[]) { this.calls.push({ cmd: 'expire', args }); this.results.push([null, 1]); return this }+ hgetall(...args: unknown[]) { this.calls.push({ cmd: 'hgetall', args }); this.results.push([null, {}]); return this }+ get(...args: unknown[]) { this.calls.push({ cmd: 'get', args }); this.results.push([null, null]); return this }+ call(cmd: string, ...args: unknown[]) {+ this.calls.push({ cmd, args })+ // Simulate Redis < 7.4: HEXPIRE errors. state.hexpireErrors decides per-call.+ this.results.push([state.nextHexpireError(), null])+ return this+ }+ exec = vi.fn(async () => this.results)+ }+ class FakeRedis {+ publish = vi.fn(async () => 1)+ subscribe = vi.fn(async () => 1)+ unsubscribe = vi.fn(async () => 1)+ quit = vi.fn(async () => 'OK')+ on = vi.fn()+ pipelines: FakePipeline[] = []+ pipeline() { const p = new FakePipeline(); this.pipelines.push(p); return p }+ opts: unknown+ constructor(_url: string, opts: unknown) { this.opts = opts; state.instances.push(this) }+ }+ return { Redis: FakeRedis }+})+vi.mock('../config/env.js', () => ({ env: { REDIS_URL: 'redis://test' } }))+vi.mock('../utils/logger.js', () => ({ logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn() } }))++const bus = await import('./bus.js')+type MockFn = ReturnType<typeof vi.fn>+const pub = state.instances[0] as unknown as {+ publish: MockFn; subscribe: MockFn; opts: unknown+ pipelines: Array<{ calls: Array<{ cmd: string; args: unknown[] }> }>+}++describe('bus redis options', () => {+ it('fails publishes fast instead of queuing them while Redis is down, and keeps subscribers retrying', () => {+ const pubOpts = pub.opts as { enableOfflineQueue?: boolean; maxRetriesPerRequest?: number | null }+ expect(pubOpts.enableOfflineQueue).toBe(false)+ expect(pubOpts.maxRetriesPerRequest).toBe(1)+ for (const sub of state.instances.slice(1) as Array<{ opts: { maxRetriesPerRequest?: number | null } }>) {+ expect(sub.opts.maxRetriesPerRequest).toBeNull()+ }+ expect(state.instances).toHaveLength(4)+ })+})++describe('publishUp', () => {+ beforeEach(() => { pub.publish.mockClear() })++ it('mirrors node_status onto the status channel as the bare frame', async () => {+ const frame = { type: 'node_status', payload: { online: true } }+ await bus.publishUp('m1', { webEligible: true, commanderEligible: true, frame })+ const channels = pub.publish.mock.calls.map((c: unknown[]) => c[0])+ expect(channels).toContain('up:m1')+ expect(channels).toContain('status:m1')+ const statusCall = pub.publish.mock.calls.find((c: unknown[]) => c[0] === 'status:m1')!+ expect(JSON.parse(statusCall[1] as string)).toEqual(frame)+ })++ it('does not mirror ordinary frames', async () => {+ await bus.publishUp('m1', { webEligible: true, commanderEligible: false, frame: { type: 'text_delta', payload: { content: 'x' } } })+ expect(pub.publish.mock.calls.map((c: unknown[]) => c[0])).toEqual(['up:m1'])+ })++ it('returns 0 and does not throw when Redis rejects', async () => {+ pub.publish.mockRejectedValueOnce(new Error('ECONNREFUSED'))+ await expect(bus.publishDown('m1', { connId: 'c', frame: { type: 'message' } })).resolves.toBe(0)+ })+})++describe('subscribeAppUp', () => {+ it('rides its own subscriber connection, not the main one', async () => {+ const [, mainSub, , appSub] = state.instances as Array<{ subscribe: MockFn }>+ await bus.subscribeAppUp('s1', () => undefined)+ expect(appSub.subscribe).toHaveBeenCalledWith('appup:s1')+ expect(mainSub.subscribe).not.toHaveBeenCalledWith('appup:s1')+ })+})+++describe('setAgentClientCountsBatch HEXPIRE fallback', () => {+ const pipelinesOf = () => (pub as unknown as { pipelines: Array<{ calls: Array<{ cmd: string; args: unknown[] }> }> }).pipelines++ it('only re-expires the keys whose own HEXPIRE errored', async () => {+ // Two rows with counts (each → hset + HEXPIRE); make only the SECOND HEXPIRE fail.+ const before = pipelinesOf().length+ state.setHexpireErrors([false, true])+ await bus.setAgentClientCountsBatch('inst-1', [+ { machineId: 'm1', ui: 1, commander: 0, commanderActive: 0 },+ { machineId: 'm2', ui: 0, commander: 2, commanderActive: 1 },+ ])+ const created = pipelinesOf().slice(before)+ const expireCalls = created.flatMap((p) => p.calls).filter((c) => c.cmd === 'expire')+ expect(expireCalls).toHaveLength(1)+ expect(expireCalls[0].args[0]).toContain('m2')+ })++ it('issues no fallback when every HEXPIRE succeeds', async () => {+ const before = pipelinesOf().length+ state.setHexpireErrors([false])+ await bus.setAgentClientCountsBatch('inst-1', [{ machineId: 'm3', ui: 1, commander: 0, commanderActive: 0 }])+ const created = pipelinesOf().slice(before)+ const expireCalls = created.flatMap((p) => p.calls).filter((c) => c.cmd === 'expire')+ expect(expireCalls).toHaveLength(0)+ })+})diff --git a/backend/src/lib/bus.ts b/backend/src/lib/bus.tsindex 2255d9061..ee1eb9995 100644--- a/backend/src/lib/bus.ts+++ b/backend/src/lib/bus.ts@@ -18,53 +18,95 @@import { Redis } from 'ioredis'import { env } from '../config/env.js'import { logger } from '../utils/logger.js'-import type { UpBusMsg, DownBusMsg } from './tunnel.js'--const redisOpts = { maxRetriesPerRequest: null as null, lazyConnect: false }--export const pub = new Redis(env.REDIS_URL, redisOpts)-const sub = new Redis(env.REDIS_URL, redisOpts)-const terminalSub = new Redis(env.REDIS_URL, redisOpts)+import type { Frame, UpBusMsg, DownBusMsg } from './tunnel.js'++// A connection in subscriber mode must never fail its (re)SUBSCRIBE commands, so the sub side keeps+// ioredis' "retry forever" setting.+const subOpts = { maxRetriesPerRequest: null as null, lazyConnect: false }+// The pub/KV side is the opposite: a command that cannot reach Redis must FAIL FAST, not wait. With the+// default offline queue, every `publish` issued during a Redis outage (every up-frame from every manager+// socket, every terminal packet) was stringified and parked in this process' heap until reconnect, and+// every `await pub.set(...)` in an attach path hung — pinning its closure — for the whole outage.+const pubOpts = {+ maxRetriesPerRequest: 1,+ enableOfflineQueue: false,+ commandTimeout: 5_000,+ lazyConnect: false,+}++export const pub = new Redis(env.REDIS_URL, pubOpts)+const sub = new Redis(env.REDIS_URL, subOpts)+const terminalSub = new Redis(env.REDIS_URL, subOpts)+// App-proxy replies (`appup:{streamId}`) can be multi-MiB base64 bodies. Redis cuts a subscriber that+// exceeds `client-output-buffer-limit pubsub`; on the shared connection that took every chat / presence+// subscription of this instance down with it (ioredis re-subscribes, but everything in between is lost).+// Isolated here, a heavy app stream can only hurt app streams.+const appSub = new Redis(env.REDIS_URL, subOpts)++/** Every fan-out publish is best-effort: Redis unreachable → dropped with a warning, 0 subscribers.+ * Callers already read 0 as "nobody holds this machine right now", which is exactly the truth. */+async function safePublish(channel: string, payload: string | Buffer): Promise<number> {+ try {+ return await pub.publish(channel, payload)+ } catch (err) {+ logger.warn('[bus] publish dropped', { channel, error: err instanceof Error ? err.message : String(err) })+ return 0+ }+}pub.on('error', (err: Error) => logger.error('[bus] pub redis error', err))sub.on('error', (err: Error) => logger.error('[bus] sub redis error', err))terminalSub.on('error', (err: Error) => logger.error('[bus] terminal sub redis error', err))+appSub.on('error', (err: Error) => logger.error('[bus] app sub redis error', err))export async function closeBus(): Promise<void> {- await Promise.allSettled([pub.quit(), sub.quit(), terminalSub.quit()])+ await Promise.allSettled([pub.quit(), sub.quit(), terminalSub.quit(), appSub.quit()])}type Cb = (msg: unknown) => void-const channelSubs = new Map<string, Set<Cb>>()-const channelSubscribePromises = new Map<string, Promise<void>>()-sub.on('message', (channel: string, payload: string) => {- const set = channelSubs.get(channel)- if (!set || set.size === 0) return- let msg: unknown- try {- msg = JSON.parse(payload)- } catch (err) {- logger.error('[bus] bad JSON on channel', err, { channel })- return- }- for (const cb of set) {+/** One refcounted JSON subscriber registry per subscribe-mode connection. */+interface JsonSubscriber {+ conn: Redis+ channelSubs: Map<string, Set<Cb>>+ channelSubscribePromises: Map<string, Promise<void>>+}++function createJsonSubscriber(conn: Redis, label: string): JsonSubscriber {+ const registry: JsonSubscriber = { conn, channelSubs: new Map(), channelSubscribePromises: new Map() }+ conn.on('message', (channel: string, payload: string) => {+ const set = registry.channelSubs.get(channel)+ if (!set || set.size === 0) return+ let msg: unknowntry {- cb(msg)+ msg = JSON.parse(payload)} catch (err) {- logger.error('[bus] subscriber callback threw', err, { channel })+ logger.error(`[bus] bad JSON on channel (${label})`, err, { channel })+ return}- }-})+ for (const cb of set) {+ try {+ cb(msg)+ } catch (err) {+ logger.error(`[bus] subscriber callback threw (${label})`, err, { channel })+ }+ }+ })+ return registry+}++const mainSubscriber = createJsonSubscriber(sub, 'main')+const appSubscriber = createJsonSubscriber(appSub, 'app')/** Refcounted subscribe: SUBSCRIBEs on the first callback for a channel, UNSUBSCRIBEs on the last. */-async function addSub(channel: string, cb: Cb): Promise<() => void> {+async function addSubOn(reg: JsonSubscriber, channel: string, cb: Cb): Promise<() => void> {+ const { conn, channelSubs, channelSubscribePromises } = reglet set = channelSubs.get(channel)let subscribePromise = channelSubscribePromises.get(channel)if (!set) {set = new Set()channelSubs.set(channel, set)- subscribePromise = sub.subscribe(channel)+ subscribePromise = conn.subscribe(channel).then(() => undefined).catch((err) => {logger.error('[bus] subscribe failed', err, { channel })@@ -95,12 +137,19 @@ async function addSub(channel: string, cb: Cb): Promise<() => void> {s.delete(cb)if (s.size === 0) {channelSubs.delete(channel)- sub.unsubscribe(channel).catch(() => { /* ignore */ })+ conn.unsubscribe(channel).catch(() => { /* ignore */ })}}}+const addSub = (channel: string, cb: Cb): Promise<() => void> => addSubOn(mainSubscriber, channel, cb)+const upChannel = (machineId: string): string => `up:${machineId}`+// Transition-only mirror of `up:`. The machine-list watchers (webWs.watchAgents / deviceWs.watchMachines)+// used to subscribe `up:{machineId}` for EVERY machine the user owns just to pick out node_status —+// which meant parsing and dispatching the full turn/delta stream of machines nobody was looking at.+const statusChannel = (machineId: string): string => `status:${machineId}`+const STATUS_TYPES = new Set(['node_status', 'machine_app_status'])const downChannel = (machineId: string): string => `down:${machineId}`const mgrChannel = (managerId: string): string => `mgr:${managerId}`const appDownChannel = (machineId: string): string => `appdown:${machineId}`@@ -145,10 +194,10 @@ export function subscribeTerminalDown(machineId: string, callback: BinaryCb): Prreturn addBinarySub(terminalDownChannel(machineId), callback)}export function publishTerminalUp(machineId: string, payload: Uint8Array): Promise<number> {- return pub.publish(terminalUpChannel(machineId), Buffer.from(payload))+ return safePublish(terminalUpChannel(machineId), Buffer.from(payload))}export function publishTerminalDown(machineId: string, payload: Uint8Array): Promise<number> {- return pub.publish(terminalDownChannel(machineId), Buffer.from(payload))+ return safePublish(terminalDownChannel(machineId), Buffer.from(payload))}// ── up / down data channels ──────────────────────────────────────────────────────────────────────@@ -162,11 +211,18 @@ export function subscribeDown(machineId: string, cb: (msg: DownBusMsg) => void):}export function publishUp(machineId: string, msg: UpBusMsg): Promise<number> {- return pub.publish(upChannel(machineId), JSON.stringify(msg))+ const type = (msg.frame as { type?: unknown } | undefined)?.type+ if (typeof type === 'string' && STATUS_TYPES.has(type)) void safePublish(statusChannel(machineId), JSON.stringify(msg.frame))+ return safePublish(upChannel(machineId), JSON.stringify(msg))+}++/** node_status / machine_app_status frames only (the bare frame, not the UpBusMsg envelope). */+export function subscribeStatus(machineId: string, cb: (frame: Frame) => void): Promise<() => void> {+ return addSub(statusChannel(machineId), cb as Cb)}export function publishDown(machineId: string, msg: DownBusMsg): Promise<number> {- return pub.publish(downChannel(machineId), JSON.stringify(msg))+ return safePublish(downChannel(machineId), JSON.stringify(msg))}// ── app-proxy tunnel channels ────────────────────────────────────────────────────────────────────@@ -180,15 +236,15 @@ export function subscribeAppDown(machineId: string, cb: (msg: unknown) => void):return addSub(appDownChannel(machineId), cb)}export function publishAppDown(machineId: string, msg: unknown): Promise<number> {- return pub.publish(appDownChannel(machineId), JSON.stringify(msg))+ return safePublish(appDownChannel(machineId), JSON.stringify(msg))}/** app→client frames (app_res, app_res_body, app_ws_msg/close, app_abort) → the origin instance. */export function subscribeAppUp(streamId: string, cb: (msg: unknown) => void): Promise<() => void> {- return addSub(appUpChannel(streamId), cb)+ return addSubOn(appSubscriber, appUpChannel(streamId), cb)}export function publishAppUp(streamId: string, msg: unknown): Promise<number> {- return pub.publish(appUpChannel(streamId), JSON.stringify(msg))+ return safePublish(appUpChannel(streamId), JSON.stringify(msg))}// ── manager command channel (Phase 3) ──────────────────────────────────────────────────────────@@ -198,7 +254,7 @@ export function subscribeMgr(managerId: string, cb: (msg: unknown) => void): Pro}export function publishMgr(managerId: string, msg: unknown): Promise<number> {- return pub.publish(mgrChannel(managerId), JSON.stringify(msg))+ return safePublish(mgrChannel(managerId), JSON.stringify(msg))}// Per-request reply channel for the provisioning RPC (backend → mgr:{managerId} → manager → reply).@@ -209,7 +265,7 @@ export function subscribeReply(requestId: string, cb: (msg: unknown) => void): P}export function publishReply(requestId: string, msg: unknown): Promise<number> {- return pub.publish(replyChannel(requestId), JSON.stringify(msg))+ return safePublish(replyChannel(requestId), JSON.stringify(msg))}// ── agent→manager presence (which manager currently owns an agent's node) ─────────────────────────@@ -232,6 +288,20 @@ export async function getAgentPresence(machineId: string): Promise<string | null}}+/** One MGET for a whole machine list (the watchers seed N machines at once). Missing/failed → null. */+export async function getAgentPresenceMany(machineIds: string[]): Promise<Map<string, string | null>> {+ const out = new Map<string, string | null>()+ if (machineIds.length === 0) return out+ try {+ const vals = await pub.mget(...machineIds.map(presenceKey))+ machineIds.forEach((id, i) => out.set(id, vals[i] ?? null))+ } catch (err) {+ logger.error('[bus] getAgentPresenceMany failed', err, { count: machineIds.length })+ for (const id of machineIds) out.set(id, null)+ }+ return out+}+// A device's last-selected machine, so the backend can restore the active machine after a reconnect. A// multi_machine device renders agents by attaching to every machine WITHOUT sending machine_select, so on a// fresh connection `activeMachineId` would otherwise stay null and voice/RPCs fail with "no machine selected".@@ -405,6 +475,27 @@ export async function getMachineAppState(}}+function parseAppState(raw: string | null): { engine: string; state: string } | null {+ if (!raw) return null+ const sep = raw.indexOf(':')+ if (sep <= 0 || sep === raw.length - 1) return null+ return { engine: raw.slice(0, sep), state: raw.slice(sep + 1) }+}++/** MGET variant of getMachineAppState for the list seeds. */+export async function getMachineAppStateMany(machineIds: string[]): Promise<Map<string, { engine: string; state: string } | null>> {+ const out = new Map<string, { engine: string; state: string } | null>()+ if (machineIds.length === 0) return out+ try {+ const vals = await pub.mget(...machineIds.map(appStateKey))+ machineIds.forEach((id, i) => out.set(id, parseAppState(vals[i] ?? null)))+ } catch (err) {+ logger.error('[bus] getMachineAppStateMany failed', err, { count: machineIds.length })+ for (const id of machineIds) out.set(id, null)+ }+ return out+}+export async function clearMachineAppState(machineId: string): Promise<void> {try {await pub.del(appStateKey(machineId))@@ -460,7 +551,7 @@ export interface DeviceStatusMsg { deviceId: string; online: boolean; lastSeenAt/** Per-USER transition channel (one sub per watching web socket); messages are PER-DEVICE. */export function publishDeviceStatus(userId: string, msg: DeviceStatusMsg): Promise<number> {- return pub.publish(deviceStatusChannel(userId), JSON.stringify(msg))+ return safePublish(deviceStatusChannel(userId), JSON.stringify(msg))}export function subscribeDeviceStatus(userId: string, cb: (msg: DeviceStatusMsg) => void): Promise<() => void> {@@ -476,7 +567,7 @@ export interface DeviceMachineListChangedMsg {}export function publishDeviceMachineListChanged(userId: string, msg: DeviceMachineListChangedMsg): Promise<number> {- return pub.publish(deviceMachineListChannel(userId), JSON.stringify(msg))+ return safePublish(deviceMachineListChannel(userId), JSON.stringify(msg))}export function subscribeDeviceMachineListChanged(userId: string, cb: (msg: DeviceMachineListChangedMsg) => void): Promise<() => void> {@@ -495,7 +586,7 @@ export interface DeviceE2eePairMsg {}export function publishDeviceE2eePair(userId: string, msg: DeviceE2eePairMsg): Promise<number> {- return pub.publish(deviceE2eePairChannel(userId), JSON.stringify(msg))+ return safePublish(deviceE2eePairChannel(userId), JSON.stringify(msg))}export function subscribeDeviceE2eePair(userId: string, cb: (msg: DeviceE2eePairMsg) => void): Promise<() => void> {@@ -511,7 +602,7 @@ const deviceControlChannel = (deviceId: string): string => `devctl:${deviceId}`export interface DeviceControlMsg { action: 'revoked' | 'superseded'; by?: string }export function publishDeviceControl(deviceId: string, msg: DeviceControlMsg): Promise<number> {- return pub.publish(deviceControlChannel(deviceId), JSON.stringify(msg))+ return safePublish(deviceControlChannel(deviceId), JSON.stringify(msg))}export function subscribeDeviceControl(deviceId: string, cb: (msg: DeviceControlMsg) => void): Promise<() => void> {@@ -575,26 +666,90 @@ export async function setAgentClientCount(machineId: string, instanceId: string,}}+/** Heartbeat variant: every local agent's counts in ONE pipeline instead of 2 round trips per agent.+ * Same field format and per-field TTL as setAgentClientCount; HEXPIRE failures fall back to a key TTL. */+export async function setAgentClientCountsBatch(+ instanceId: string,+ rows: Array<{ machineId: string; ui: number; commander: number; commanderActive: number }>,+): Promise<void> {+ if (rows.length === 0) return+ const p = pub.pipeline()+ // Remember which pipeline result index each HEXPIRE lands at, so the fallback only re-expires the keys+ // whose HEXPIRE actually failed (rather than every key on any single failure).+ const hexpireByKey: Array<{ key: string; index: number }> = []+ let cmdIndex = 0+ for (const r of rows) {+ const key = clientsKey(r.machineId)+ if (r.ui === 0 && r.commander === 0) { p.hdel(key, instanceId); cmdIndex += 1; continue }+ p.hset(key, instanceId, `${r.ui},${r.commander},${r.commanderActive}`)+ p.call('HEXPIRE', key, String(CLIENT_COUNT_TTL_SEC), 'FIELDS', '1', instanceId)+ hexpireByKey.push({ key, index: cmdIndex + 1 }) // hset is cmdIndex, HEXPIRE is the next command+ cmdIndex += 2+ }+ let results: Array<[Error | null, unknown]> | null+ try {+ results = await p.exec()+ } catch (err) {+ logger.error('[bus] setAgentClientCountsBatch failed', err, { count: rows.length })+ return+ }+ // A HEXPIRE error (Redis < 7.4) → coarser whole-key TTL, exactly like the single-row path. Only the+ // keys whose own HEXPIRE errored need it; a null result set (shouldn't happen post-exec) falls back for all.+ const failedKeys = results+ ? hexpireByKey.filter(({ index }) => results![index]?.[0]).map(({ key }) => key)+ : hexpireByKey.map(({ key }) => key)+ if (failedKeys.length > 0) {+ const fb = pub.pipeline()+ for (const key of failedKeys) fb.expire(key, CLIENT_COUNT_TTL_SEC)+ try { await fb.exec() } catch { /* best-effort */ }+ }+}++function sumClientFields(h: Record<string, string>): { ui: number; commander: number; commanderActive: number } {+ let ui = 0+ let commander = 0+ let commanderActive = 0+ for (const v of Object.values(h)) {+ const [u, c, a] = String(v).split(',')+ ui += parseInt(u, 10) || 0+ commander += parseInt(c, 10) || 0+ commanderActive += parseInt(a, 10) || 0+ }+ return { ui, commander, commanderActive }+}+/** Sum of every live instance's counts for an agent (expired fields already dropped Redis-side). */export async function getAgentClientTotals(machineId: string): Promise<{ ui: number; commander: number; commanderActive: number }> {try {- const h = await pub.hgetall(clientsKey(machineId))- let ui = 0- let commander = 0- let commanderActive = 0- for (const v of Object.values(h)) {- const [u, c, a] = String(v).split(',')- ui += parseInt(u, 10) || 0- commander += parseInt(c, 10) || 0- commanderActive += parseInt(a, 10) || 0- }- return { ui, commander, commanderActive }+ return sumClientFields(await pub.hgetall(clientsKey(machineId)))} catch (err) {logger.error('[bus] getAgentClientTotals failed', err, { machineId })return { ui: 0, commander: 0, commanderActive: 0 }}}+/** Totals + commander join generation in one round trip (the `__clients` recompute reads both). */+export async function getAgentClientState(machineId: string): Promise<{+ totals: { ui: number; commander: number; commanderActive: number }+ commanderJoinGeneration: number | undefined+}> {+ try {+ const res = await pub.pipeline().hgetall(clientsKey(machineId)).get(commanderJoinGenerationKey(machineId)).exec()+ const [hErr, h] = res?.[0] ?? [null, {}]+ const [gErr, g] = res?.[1] ?? [null, null]+ if (hErr) throw hErr+ if (gErr) throw gErr+ const generation = g == null ? undefined : Number(g)+ return {+ totals: sumClientFields((h ?? {}) as Record<string, string>),+ commanderJoinGeneration: generation != null && Number.isSafeInteger(generation) && generation >= 0 ? generation : undefined,+ }+ } catch (err) {+ logger.error('[bus] getAgentClientState failed', err, { machineId })+ return { totals: { ui: 0, commander: 0, commanderActive: 0 }, commanderJoinGeneration: undefined }+ }+}+/** Monotonic machine-wide generation. Unlike the aggregate count, this changes for EVERY commander attach,* including a leave/rejoin that is coalesced to the same total before the node sees a count snapshot. */export async function bumpCommanderJoinGeneration(machineId: string): Promise<number | undefined> {diff --git a/backend/src/lib/deviceWs.ts b/backend/src/lib/deviceWs.tsindex a820d24a5..fbebac0b5 100644--- a/backend/src/lib/deviceWs.ts+++ b/backend/src/lib/deviceWs.ts@@ -1,12 +1,14 @@import type { IncomingMessage } from 'http'import type { Duplex } from 'stream'-import { WebSocketServer, WebSocket, type RawData } from 'ws'+import { WebSocket, type RawData } from 'ws'+import { createWss, WS_LIMITS } from './wsServer.js'import { randomUUID } from 'crypto'import { attachHubClient, trackSocketLiveness, DEVICE_IDLE_DEADLINE_MS, type HubClient } from './hub.js'import {getAgentPresence,- getMachineAppState,- subscribeUp,+ getAgentPresenceMany,+ getMachineAppStateMany,+ subscribeStatus,setDevicePresence,clearDevicePresence,publishDeviceStatus,@@ -23,6 +25,7 @@ import * as registry from './registry.js'import { nodeRequest } from './nodeRpc.js'import type { Frame } from './tunnel.js'import { transcribe, MAX_PCM, normalizeLang } from './stt.js'+import { reserveVoice, releaseVoice } from './voiceBudget.js'import { prisma } from './prisma.js'import { deviceService } from '../services/index.js'import { touchDeviceOnlineDay } from './dailyTracking.js'@@ -30,6 +33,9 @@ import { utcDayKey } from '../types/analytics.js'import { agentLimit, recordCreatedAgent } from './agentTracker.js'import { env } from '../config/env.js'import { logger } from '../utils/logger.js'+import { fireAndForget } from '../utils/async.js'+import { guardedSend, guardedSendJson } from './wsSend.js'+import { createOrderedInbox } from './orderedInbox.js'import { ensureMachineReady, getMachineLifecycleStatus, type MachineLifecycleStatus } from './machineLifecycle.js'import { normalizeComputerId } from './deviceAuth.js'import { authenticateAccessToken, SsoAuthError } from './ssoAuth.js'@@ -65,13 +71,7 @@ import {// that single machine (the old firmware never sends machine_select), so a rolling deploy doesn't brick it.// Echo the offered subprotocol (the device token) so the ESP client accepts the handshake.-const wss = new WebSocketServer({- noServer: true,- handleProtocols: (protocols) => {- const first = [...protocols][0]- return first ?? false- },-})+const wss = createWss(WS_LIMITS.device, { echoFirstProtocol: true })// Presence refresh must beat the key TTL (45s in bus.setDevicePresence) with margin.const DEVICE_PRESENCE_REFRESH_MS = 15_000@@ -93,9 +93,7 @@ function clampSr(sr: unknown): number {}function safeSend(ws: WebSocket, obj: unknown): void {- if (ws.readyState === WebSocket.OPEN) {- try { ws.send(JSON.stringify(obj)) } catch { /* ignore */ }- }+ guardedSendJson(ws, obj, 'must', { kind: 'device' })}type DeviceSend = (obj: unknown) => void@@ -502,7 +500,7 @@ function relay(device: WebSocket, opts: RelayOpts): void {controlUnsub?.()controlUnsub = unsubvoid publishDeviceControl(id, { action: 'superseded', by: connToken }) // force any older half-open socket to park now- })+ }).catch((err) => logger.warn('device control subscribe failed', { userId, deviceId: id, error: errMsg(err) }))}if (deviceId) startPresence(deviceId)@@ -534,10 +532,23 @@ function relay(device: WebSocket, opts: RelayOpts): void {const ROUTE_AUTO_THRESHOLD = 0.75const ROUTE_PENDING_TTL_MS = 60_000const pendingRoutes = new Map<string, { text: string; goal: boolean; loop: boolean; ts: number }>()+ // Pruned on a timer too, not only on the next route_confirm: a device that walks away after a routed+ // utterance would otherwise keep its transcript here until it next confirms something.+ const pendingRoutesPrune = setInterval(() => {+ const now = Date.now()+ for (const [k, v] of pendingRoutes) if (now - v.ts > ROUTE_PENDING_TTL_MS) pendingRoutes.delete(k)+ }, ROUTE_PENDING_TTL_MS)+ pendingRoutesPrune.unref()let voiceSr = 16000let voiceLang: string = 'en' // STT language for this utterance (device Settings; see VOICE_LANGS)let chunks: Buffer[] = []let voiceSize = 0+ // Bytes this connection currently holds against the process-wide voice budget (voiceBudget.ts). Kept+ // separately from voiceSize because finishVoice keeps its concat'd copy alive through STT after the+ // chunk array is cleared. Released at every point the PCM is let go.+ let voiceBudgeted = 0+ let voiceOverBudget = false+ const releaseVoiceBudget = (): void => { releaseVoice(voiceBudgeted); voiceBudgeted = 0; voiceOverBudget = false }let voiceIdleTimer: NodeJS.Timeout | null = nulllet voiceMaxTimer: NodeJS.Timeout | null = nulllet deviceFirmwareVersion: string | null = null@@ -556,9 +567,7 @@ function relay(device: WebSocket, opts: RelayOpts): void {const payload = JSON.stringify(obj)const ac = activeClient()if (ac && activeMachineId && registry.queueCommanderFrame(activeMachineId, ac.connId, obj, payload)) return- if (device.readyState === WebSocket.OPEN) {- try { device.send(payload) } catch { /* ignore */ }- }+ guardedSend(device, payload, 'must', { userId, kind: 'device' })}const sendDeviceNow = (obj: unknown): void => safeSend(device, obj)const clearVoiceQueue = (): void => {@@ -571,8 +580,7 @@ function relay(device: WebSocket, opts: RelayOpts): void {const queued = registry.flushCommanderVoiceQueue(activeMachineId, ac.connId)if (!queued.length) returnfor (const q of queued) {- if (device.readyState !== WebSocket.OPEN) break- try { device.send(q.payload) } catch { /* ignore */ }+ if (!guardedSend(device, q.payload, 'must', { userId, kind: 'device' })) break}logger.info('commander voice queue flushed', { userId, machineId: activeMachineId, connId: ac.connId, frames: queued.length, reason })}@@ -585,6 +593,7 @@ function relay(device: WebSocket, opts: RelayOpts): void {voiceActive = falsechunks = []voiceSize = 0+ releaseVoiceBudget()voiceMode = 'turn'voiceRequestId = nullvoiceAgentId = null@@ -654,9 +663,10 @@ function relay(device: WebSocket, opts: RelayOpts): void {for (const id of [...machineMeta.keys()]) if (!wanted.has(id)) { machineMeta.delete(id); machineApp.delete(id) }for (const [id] of wanted) {if (statusSubs.has(id)) continue- // Bus subscriptions are refcounted — co-existing with the commander's up:{id} sub is fine.- const unsub = await subscribeUp(id, (msg) => {- const fr = msg.frame as { type?: string; payload?: { online?: boolean; status?: MachineLifecycleStatus; reason?: string; engine?: string; state?: string } }+ // `status:{id}` carries only node_status / machine_app_status — not the machine's turn stream,+ // which subscribing `up:` here used to pull in for every machine on the picker.+ const unsub = await subscribeStatus(id, (frame) => {+ const fr = frame as { type?: string; payload?: { online?: boolean; status?: MachineLifecycleStatus; reason?: string; engine?: string; state?: string } }// Desktop-app presence: one single-row status frame, the same partial path node_status uses.// Deliberately NOT publishDeviceMachineListChanged — that re-queries Mongo per device and// pushes machines_changed to every browser tab, so quitting Cursor would cost a DB round trip.@@ -698,16 +708,18 @@ function relay(device: WebSocket, opts: RelayOpts): void {}}// Seed the full current picture (presence keys = source of truth) so the list is right immediately.+ // Presence and app state come back in one MGET each, instead of 2 GETs per machine.+ const ids = [...wanted.keys()]+ const [presence, appStates] = await Promise.all([getAgentPresenceMany(ids), getMachineAppStateMany(ids)])const statuses = await Promise.all(- [...wanted.values()].map(async (f) => {- const online = !!(await getAgentPresence(f.machineId))- const status = online ? 'running' : await getMachineLifecycleStatus(f.machineId)+ ids.map(async (machineId) => {+ const online = !!presence.get(machineId)+ const status = online ? 'running' : await getMachineLifecycleStatus(machineId)// Seed the app state from Redis too, so a device that connects while the Mac has been up for- // an hour sees "Cursor open" immediately instead of waiting for the next transition. Issued- // inside the existing Promise.all, so it adds no wall-clock latency.- const app = online ? await getMachineAppState(f.machineId) : null- if (app) machineApp.set(f.machineId, app); else machineApp.delete(f.machineId)- return machineRow(f.machineId, online, { status: status === 'unknown' ? 'offline' as const : status })+ // an hour sees "Cursor open" immediately instead of waiting for the next transition.+ const app = online ? appStates.get(machineId) ?? null : null+ if (app) machineApp.set(machineId, app); else machineApp.delete(machineId)+ return machineRow(machineId, online, { status: status === 'unknown' ? 'offline' as const : status })}),)if (gen === watchGen && !closed) sendMachines(statuses, true)@@ -738,19 +750,31 @@ function relay(device: WebSocket, opts: RelayOpts): void {}}+ // Several list pokes in a row (a bulk rename fans `machines_changed` to every device of the user)+ // collapse into one re-derivation ≤250ms later. `machines_watch` from the device stays synchronous+ // (it is awaited on the ordered inbox and the firmware expects the full list as its reply).+ const WATCH_DEBOUNCE_MS = 250+ let watchMachinesTimer: NodeJS.Timeout | null = null+ const scheduleWatchMachines = (): void => {+ if (watchMachinesTimer) clearTimeout(watchMachinesTimer)+ watchMachinesTimer = setTimeout(() => {+ watchMachinesTimer = null+ if (closed) return+ void watchMachines().catch((err) => logger.warn('device watchMachines failed', { userId, error: errMsg(err) }))+ }, WATCH_DEBOUNCE_MS)+ }+// ── Machine selection (ported from webWs.bindAgent; + remote guard + deviceId re-tag) ───────────────let selectGen = 0const seedNodeStatus = (machineId: string): void => {- void getAgentPresence(machineId).then((mgr) => {- if (device.readyState === WebSocket.OPEN && activeMachineId === machineId) {- const online = !!mgr- void getMachineLifecycleStatus(machineId).then((status) => {- if (device.readyState === WebSocket.OPEN && activeMachineId === machineId) {- sendDevice({ type: 'node_status', payload: { online, status: online ? 'running' : status === 'unknown' ? 'offline' : status } })- }- })- }- })+ fireAndForget((async () => {+ const mgr = await getAgentPresence(machineId)+ if (device.readyState !== WebSocket.OPEN || activeMachineId !== machineId) return+ const online = !!mgr+ const status = await getMachineLifecycleStatus(machineId)+ if (device.readyState !== WebSocket.OPEN || activeMachineId !== machineId) return+ sendDevice({ type: 'node_status', payload: { online, status: online ? 'running' : status === 'unknown' ? 'offline' : status } })+ })(), 'device seed node_status', { userId, machineId })}const bindMachine = async (machineIdRaw: unknown): Promise<void> => {if (typeof machineIdRaw !== 'string' || !machineIdRaw) return@@ -829,6 +853,8 @@ function relay(device: WebSocket, opts: RelayOpts): void {if (closed) returnclosed = truereleaseLiveness()+ clearInterval(pendingRoutesPrune)+ pendingRoutes.clear()if (presenceTimer) { clearInterval(presenceTimer); presenceTimer = null }if (controlUnsub) { controlUnsub(); controlUnsub = null }if (machineListUnsub) { machineListUnsub(); machineListUnsub = null }@@ -837,14 +863,15 @@ function relay(device: WebSocket, opts: RelayOpts): void {// Conditional clear: only publish offline if the key is really gone (a superseding reconnect// keeps its own key → we stay silent). lastSeenAt = the moment the device actually went away.const seenAt = new Date()- void clearDevicePresence(id, connToken).then((gone) => {- if (gone) void publishDeviceStatus(userId, { deviceId: id, online: false, lastSeenAt: seenAt.toISOString() })- })+ fireAndForget(clearDevicePresence(id, connToken).then((gone) => {+ if (gone) return publishDeviceStatus(userId, { deviceId: id, online: false, lastSeenAt: seenAt.toISOString() })+ }), 'device offline publish', { userId, deviceId: id })void prisma.deviceBinding.update({ where: { deviceId: id }, data: { lastSeenAt: seenAt } }).catch(() => { /* best effort */ })touchDevicePresence(id, false)}for (const [, unsub] of statusSubs) unsub()statusSubs.clear()+ if (watchMachinesTimer) { clearTimeout(watchMachinesTimer); watchMachinesTimer = null }// Resumable upload: if a streamed recording is still in flight (no voice_end seen) and the firmware sent// an uploadId, PARK it in Redis (grace ~60s) instead of discarding, so the device's reconnect can resume// it — possibly on a different backend instance. Otherwise discard as before.@@ -856,6 +883,7 @@ function relay(device: WebSocket, opts: RelayOpts): void {}const pcm = Buffer.concat(chunks)clearVoiceTimers(); voiceActive = false+ chunks = []; voiceSize = 0; releaseVoiceBudget()void parkVoiceUpload(deviceId, meta, pcm)logger.info('commander voice parked (WS drop mid-stream)', { userId, deviceId, uploadId: voiceUploadId, bytes: pcm.length })} else {@@ -895,7 +923,7 @@ function relay(device: WebSocket, opts: RelayOpts): void {// normalizeLang gates on the SAME list Deepgram enforces; firmware older than the picker sends no// `lang` at all and lands on the default.voiceLang = normalizeLang(msg.lang)- chunks = []; voiceSize = 0+ chunks = []; voiceSize = 0; releaseVoiceBudget()// A fresh utterance invalidates any parked partial from a previous (abandoned) recording on this device.if (deviceId) void evictVoiceUpload(deviceId)const ac = activeClient()@@ -960,6 +988,15 @@ function relay(device: WebSocket, opts: RelayOpts): void {return}const m = parked.meta+ // The rehydrated partial counts against the budget like live chunks would have.+ if (!reserveVoice(parked.pcm.length)) {+ sendDeviceNow({ type: 'voice_resume_reject', uploadId })+ sendDeviceNow({ type: 'error', message: 'VOICE_BUFFER_FULL' })+ logger.warn('commander voice_resume refused — voice budget exhausted', { userId, deviceId, uploadId, bytes: parked.pcm.length })+ return+ }+ releaseVoiceBudget()+ voiceBudgeted = parked.pcm.lengthvoiceActive = truevoiceMode = m.mode; voiceRoute = m.route; voiceGoal = m.goal; voiceLoop = m.loop === true; voiceAutonomy = m.autonomyvoiceAgentId = m.agentId; voiceSessionId = m.sessionId; voiceRequestId = m.requestId@@ -1149,16 +1186,41 @@ function relay(device: WebSocket, opts: RelayOpts): void {// Device → backend. Binary is voice PCM (buffered for STT); JSON is routed by type. Voice + hello are// synchronous; machine-select / RPC / chat go through a strict in-order chain (bindMachine awaits a DB// lookup, and a machine_select followed immediately by agents_list must not be routed by the PREVIOUS- // selection — the same leak webWs guards against).- let frameChain: Promise<void> = Promise.resolve()+ // selection — the same leak webWs guards against). Bounded (see orderedInbox.ts): past the ceiling a+ // frame is refused and answered right away instead of parking in the heap behind a machine wake.+ let lastOverflowLogAt = 0+ const inbox = createOrderedInbox<CommanderMsg>(+ handleFrame,+ (err, msg) => logger.warn('commander frame failed', { userId, type: msg.type, error: errMsg(err) }),+ (msg, inflight) => {+ const requestId = payloadOf(msg).requestId+ if (typeof requestId === 'string' && typeof msg.type === 'string') {+ sendDeviceNow({ type: `${msg.type}_result`, payload: { requestId, error: 'INBOUND_OVERFLOW' } })+ } else {+ sendDeviceNow({ type: 'error', message: 'INBOUND_OVERFLOW' })+ }+ const now = Date.now()+ if (now - lastOverflowLogAt > 10_000) {+ lastOverflowLogAt = now+ logger.warn('commander inbound overflow — refusing frames', { userId, machineId: activeMachineId, inflight, type: msg.type })+ }+ },+ )device.on('message', (raw: RawData, isBinary: boolean) => {if (isBinary) {if (voiceActive) {const buf = raw as Buffer- if (voiceSize + buf.length <= MAX_PCM) {+ if (voiceSize + buf.length <= MAX_PCM && reserveVoice(buf.length)) {+ voiceBudgeted += buf.lengthchunks.push(buf)voiceSize += buf.lengtharmVoiceIdleTimer()+ } else if (!voiceOverBudget && voiceSize + buf.length <= MAX_PCM) {+ // Process-wide budget, not this upload's cap: tell the device once so it can stop recording+ // instead of trickling chunks that are silently dropped; the utterance stays open for voice_end.+ voiceOverBudget = true+ sendDeviceNow({ type: 'error', message: 'VOICE_BUFFER_FULL' })+ logger.warn('commander voice chunk dropped — voice budget exhausted', { userId, machineId: activeMachineId, bytes: voiceSize })}}return // audio is NOT forwarded upstream; non-voice binary is dropped@@ -1169,9 +1231,7 @@ function relay(device: WebSocket, opts: RelayOpts): void {if (msg.type === 'voice_end') { void finishVoice(); return }if (msg.type === 'voice_resume') { void handleVoiceResume(msg); return }if (msg.type === 'device_hello') { handleHello(msg); return }- frameChain = frameChain- .then(() => handleFrame(msg))- .catch((err) => logger.warn('commander frame failed', { userId, type: msg.type, error: errMsg(err) }))+ inbox.enqueue(msg)})device.on('close', closeBoth)device.on('error', closeBoth)@@ -1180,11 +1240,11 @@ function relay(device: WebSocket, opts: RelayOpts): void {// the device then drives selection with machine_select (or its saved-machine auto-select on connect).void subscribeDeviceMachineListChanged(userId, (msg) => {logger.info('device machine list changed — refreshing picker', { userId, reason: msg.reason })- void watchMachines().catch((err) => logger.warn('device watchMachines failed', { userId, error: errMsg(err) }))+ scheduleWatchMachines()}).then((unsub) => {if (closed) { unsub(); return }machineListUnsub = unsub- })+ }).catch((err) => logger.warn('device machine-list subscribe failed', { userId, error: errMsg(err) }))void watchMachines().catch((err) => logger.warn('device watchMachines failed', { userId, error: errMsg(err) }))async function finishVoice(): Promise<void> {@@ -1192,6 +1252,9 @@ function relay(device: WebSocket, opts: RelayOpts): void {clearVoiceTimers()voiceActive = falseconst pcm = Buffer.concat(chunks); chunks = []; voiceSize = 0+ // `pcm` lives until this function returns (STT upload); hand the budget back only then.+ const budgetHeld = voiceBudgeted+ voiceBudgeted = 0; voiceOverBudget = falseif (deviceId && voiceUploadId) void evictVoiceUpload(deviceId) // finalizing → the parked copy is obsoleteconst uploadId = voiceUploadId ?? randomUUID()const quotaCheck = voiceQuotaCheck@@ -1326,6 +1389,8 @@ function relay(device: WebSocket, opts: RelayOpts): void {} else {sendDeviceNow({ type: 'error', message: errMsg(err) })}+ } finally {+ releaseVoice(budgetHeld)}}diff --git a/backend/src/lib/hub.test.ts b/backend/src/lib/hub.test.tsnew file mode 100644index 000000000..f4d5ed3a2--- /dev/null+++ b/backend/src/lib/hub.test.ts@@ -0,0 +1,97 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import type { WebSocket } from 'ws'++const bus = vi.hoisted(() => ({+ setAgentClientCount: vi.fn(async () => undefined),+ setAgentClientCountsBatch: vi.fn(async () => undefined),+ getAgentClientState: vi.fn(async () => ({ totals: { ui: 0, commander: 0, commanderActive: 0 }, commanderJoinGeneration: undefined })),+ bumpCommanderJoinGeneration: vi.fn(async () => 1),+ publishDown: vi.fn(async () => 1),+ publishUp: vi.fn(async () => 1),+ publishTerminalDown: vi.fn(async () => 1),+ subscribeUp: vi.fn(async () => () => undefined),+ subscribeTerminalUp: vi.fn(async () => () => undefined),+}))+vi.mock('./bus.js', () => bus)+vi.mock('./providerLink.js', () => ({ routeDown: async (_m: string, _d: unknown, fallback: () => Promise<number>) => fallback() }))+vi.mock('../utils/logger.js', () => ({ logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn() } }))++const { attachHubClient, deliverUpLocal, sendClientsControl } = await import('./hub.js')+const { SEND_HIGH_WATER, SEND_KILL_WATER } = await import('./wsSend.js')++function socket(out: unknown[], bufferedAmount = 0): WebSocket {+ return {+ readyState: 1,+ bufferedAmount,+ send: (data: unknown) => { out.push(data) },+ close: vi.fn(),+ terminate: vi.fn(),+ on: () => undefined,+ } as unknown as WebSocket+}++const flush = (): Promise<void> => new Promise((r) => setImmediate(() => setImmediate(r)))++describe('hub fan-out backpressure', () => {+ const attached: Array<ReturnType<typeof attachHubClient>> = []+ beforeEach(async () => {+ while (attached.length) attached.pop()!.detach()+ await flush()+ bus.setAgentClientCount.mockClear()+ bus.bumpCommanderJoinGeneration.mockClear()+ })++ it('delivers terminal_output losslessly even when the outbound buffer is backed up (must, not droppable)', () => {+ const machineId = `hub-bp-${Date.now()}`+ const sent: string[] = []+ // High-water but below kill-water: nothing may be silently dropped (a dropped terminal frame is an+ // undetectable gap that stalls the pane), so both frames must still be sent.+ const client = attachHubClient(socket(sent, SEND_HIGH_WATER + 1), machineId, 'web')+ attached.push(client)++ deliverUpLocal(machineId, { webEligible: true, commanderEligible: false, frame: { type: 'terminal_output', payload: {} } })+ deliverUpLocal(machineId, { webEligible: true, commanderEligible: false, frame: { type: 'text_delta', payload: { content: 'x' } } })+ expect(sent).toHaveLength(2)+ expect(sent[0]).toContain('terminal_output')+ expect(sent[1]).toContain('text_delta')+ })++ it('closes a web client whose buffer is past the kill line instead of buffering unbounded', () => {+ const machineId = `hub-kill-${Date.now()}`+ const sent: string[] = []+ const ws = socket(sent, SEND_KILL_WATER + 1) as unknown as { close: ReturnType<typeof vi.fn>; readyState: number }+ const client = attachHubClient(ws as never, machineId, 'web')+ attached.push(client)+ deliverUpLocal(machineId, { webEligible: true, commanderEligible: false, frame: { type: 'terminal_output', payload: {} } })+ expect(sent).toHaveLength(0)+ expect(ws.close).toHaveBeenCalledWith(1013, 'slow consumer')+ })+})++describe('sendClientsControl coalescing', () => {+ beforeEach(async () => {+ await flush() // let any attach/detach flush from the previous describe land first+ bus.setAgentClientCount.mockClear()+ bus.bumpCommanderJoinGeneration.mockClear()+ })++ it('collapses a burst of calls for one machine into a single count write, OR-ing commanderJoined', async () => {+ const machineId = `hub-coalesce-${Date.now()}`+ sendClientsControl(machineId, false)+ sendClientsControl(machineId, true)+ sendClientsControl(machineId, false)+ expect(bus.setAgentClientCount).not.toHaveBeenCalled()+ await flush()+ expect(bus.setAgentClientCount).toHaveBeenCalledTimes(1)+ expect(bus.bumpCommanderJoinGeneration).toHaveBeenCalledTimes(1)+ })++ it('keeps distinct machines separate', async () => {+ const a = `hub-a-${Date.now()}`+ const b = `hub-b-${Date.now()}`+ sendClientsControl(a)+ sendClientsControl(b)+ await flush()+ expect(bus.setAgentClientCount).toHaveBeenCalledTimes(2)+ })+})diff --git a/backend/src/lib/hub.ts b/backend/src/lib/hub.tsindex 3eaae0fd8..57cfb1675 100644--- a/backend/src/lib/hub.ts+++ b/backend/src/lib/hub.ts@@ -10,12 +10,12 @@ import { WebSocket } from 'ws'import { randomUUID } from 'crypto'import {bumpCommanderJoinGeneration,- getAgentClientTotals,- getCommanderJoinGeneration,+ getAgentClientState,publishDown,publishTerminalDown,publishUp,setAgentClientCount,+ setAgentClientCountsBatch,subscribeUp,subscribeTerminalUp,} from './bus.js'@@ -26,6 +26,7 @@ import type { Frame, UpBusMsg } from './tunnel.js'import { routeDown } from './providerLink.js'import { logger } from '../utils/logger.js'import { decodeTerminalHop, encodeTerminalHop, TerminalHopDirection } from './terminalBinary.js'+import { guardedSend, guardedSendJson } from './wsSend.js'// Reserved inner-frame type: backend→node client-presence signal (drives the node's event buffering// and replay-on-connect + commander recap warm). Never surfaced to a real client.@@ -44,8 +45,12 @@ export function deliverTerminalUpLocal(machineId: string, packet: Uint8Array): vconst decoded = decodeTerminalHop(packet)if (!decoded || decoded.direction !== TerminalHopDirection.up) returnconst client = registry.clientsFor(machineId).find((candidate) => candidate.kind === 'web' && candidate.connId === decoded.connId)- if (!client || client.socket.readyState !== WebSocket.OPEN) return- try { client.socket.send(decoded.clientFrame) } catch { /* ignore */ }+ if (!client) return+ // Lossless: terminal frames are opaque E2EE bytes with no per-frame ack, so a silently dropped output+ // frame leaves a gap the client cannot detect or request a keyframe for — it just stalls+ // (TERMINAL_RENDER_STALLED). Backpressure is bounded instead by the kill-water close in guardedSend:+ // a genuinely stuck reader is disconnected and does a full resync on reconnect.+ guardedSend(client.socket, decoded.clientFrame, 'must', { machineId, connId: decoded.connId, kind: 'web' })}/** Deliver an up-frame to every local client of the agent (device/exclude filters applied). Called both@@ -58,36 +63,36 @@ export function deliverUpLocal(machineId: string, msg: UpBusMsg): void {// The payload itself is untouched (stays E2EE-encrypted for remote machines). Web sockets re-attach per// agent (one machine at a time) so they never need it — keep their wire byte-identical. Computed lazily.let commanderPayload: string | null = null- for (const c of registry.clientsFor(machineId)) {- if (msg.excludeConnId && c.connId === msg.excludeConnId) continue+ registry.forEachClient(machineId, (c) => {+ if (msg.excludeConnId && c.connId === msg.excludeConnId) return// Device-targeted push (e.g. device_revoked): only the commander socket whose reported deviceId// matches. A socket that hasn't reported one (legacy fw / pre-hello) never matches — harmless.- if (msg.targetDeviceId && c.deviceId !== msg.targetDeviceId) continue+ if (msg.targetDeviceId && c.deviceId !== msg.targetDeviceId) return// Connection-targeted push (E2EE pairing/welcome + per-client encrypted RPC replies): only the// one web socket that owns this connId. Absent ⇒ normal fan-out.- if (msg.targetConnId && c.connId !== msg.targetConnId) continue- if (msg.targetKind && c.kind !== msg.targetKind) continue+ if (msg.targetConnId && c.connId !== msg.targetConnId) return+ if (msg.targetKind && c.kind !== msg.targetKind) return// A `targetConnId`-addressed frame is E2EE traffic for exactly ONE connection (pairing/welcome/rekey,// per-client encrypted RPC replies) — for a WEB browser OR a hardware device. It bypasses the// kind/eligibility/`_result` filters below: those trim the broadcast fan-out, but a connId-targeted// frame is not a broadcast. Without this, `e2e_status_result` etc. never reach a paired device// (commanders are filtered by `!commanderEligible` and by the `_result` suppression).if (!msg.targetConnId) {- if (c.kind === 'web' && msg.webEligible === false) continue // device-only frame (forwardToCommander)- if (c.kind === 'commander' && !msg.commanderEligible) continue // preserve COMMANDER_FORWARD filter+ if (c.kind === 'web' && msg.webEligible === false) return // device-only frame (forwardToCommander)+ if (c.kind === 'commander' && !msg.commanderEligible) return // preserve COMMANDER_FORWARD filter// RPC replies (`<x>_result`) are answered to the device directly by deviceWs (trimmed); the// raw node reply must never reach a device — it's only for the backend nodeRequest awaiter / web.- if (c.kind === 'commander' && typeof frameType === 'string' && frameType.endsWith('_result')) continue+ if (c.kind === 'commander' && typeof frameType === 'string' && frameType.endsWith('_result')) return}// Commander gets the machineId-tagged frame; web gets the untagged one.const out = c.kind === 'commander'? (commanderPayload ??= JSON.stringify({ ...(msg.frame as Record<string, unknown>), machineId: machineId })): payload- if (c.kind === 'commander' && registry.queueCommanderFrame(machineId, c.connId, msg.frame, out)) continue- if (c.socket.readyState === WebSocket.OPEN) {- try { c.socket.send(out) } catch { /* ignore */ }- }- }+ if (c.kind === 'commander' && registry.queueCommanderFrame(machineId, c.connId, msg.frame, out)) return+ // 'must': every fan-out frame is either order-sensitive (chat deltas) or opaque (terminal). None can+ // be silently dropped without corrupting the client; a stuck reader is bounded by the kill-water close.+ guardedSend(c.socket, out, 'must', { machineId, connId: c.connId, kind: c.kind })+ })}/**@@ -113,11 +118,29 @@ export function pushDeviceRevoked(machineId: string, deviceId: string): void {* over that socket. If we're not B_m, poke B_m (via down:{machineId}, whose sole subscriber IS B_m).* Call after the local registry mutation (attach/detach) so clientCounts reflects the new state.*/-export async function sendClientsControl(machineId: string, commanderJoined = false): Promise<void> {+export function sendClientsControl(machineId: string, commanderJoined = false): void {+ // Coalesced per machine within one turn of the event loop. A multi-attach device connecting with N+ // machines, or a web tab switching agents (detach+attach back-to-back), fired this N× in a row — each+ // one an HSET+HEXPIRE, sometimes an INCR, then HGETALL+GET or a PUBLISH. One flush reads the registry+ // AFTER every synchronous mutation, so it publishes the same final state with a fraction of the traffic.+ const prev = pendingClientsControl.get(machineId)+ if (prev !== undefined) { pendingClientsControl.set(machineId, prev || commanderJoined); return }+ pendingClientsControl.set(machineId, commanderJoined)+ setImmediate(() => {+ const joined = pendingClientsControl.get(machineId) ?? false+ pendingClientsControl.delete(machineId)+ void sendClientsControlNow(machineId, joined).catch((err) => logger.warn('sendClientsControl failed', { machineId, error: err instanceof Error ? err.message : String(err) }))+ })+}+const pendingClientsControl = new Map<string, boolean>()++async function sendClientsControlNow(machineId: string, commanderJoined: boolean): Promise<void> {const { ui, commander, commanderActive } = registry.clientCounts(machineId) // capture sync (post-mutation), before awaitawait setAgentClientCount(machineId, INSTANCE_ID, ui, commander, commanderActive)// Count snapshots can coalesce (1→0→1 may be observed as 1→1). Persist a separate join generation so- // every real commander attach still forces the node/adapter to replay its live state.+ // every real commander attach still forces the node/adapter to replay its live state. Several attaches+ // within one event-loop tick coalesce to a SINGLE bump here (the flag is OR-ed in sendClientsControl);+ // that is safe because the replay it triggers is idempotent — one bump still forces one replay.if (commanderJoined) await bumpCommanderJoinGeneration(machineId)if (registry.controlSocketFor(machineId)) { await recomputeAndSendClients(machineId); return }void publishDown(machineId, { connId: '', frame: { type: CLIENTS_DIRTY } })@@ -126,17 +149,14 @@ export async function sendClientsControl(machineId: string, commanderJoined = fa/** B_m-only: read the cross-instance total and emit `__clients` down the local manager control socket* (single in-order writer → the node's last frame is always the true global state). */export async function recomputeAndSendClients(machineId: string): Promise<void> {- const [{ ui, commander, commanderActive }, commanderJoinGeneration] = await Promise.all([- getAgentClientTotals(machineId),- getCommanderJoinGeneration(machineId),- ])+ const { totals: { ui, commander, commanderActive }, commanderJoinGeneration } = await getAgentClientState(machineId)const frame = {type: CLIENTS_FRAME,payload: { ui, commander, commanderActive, ...(commanderJoinGeneration != null ? { commanderJoinGeneration } : {}) },}const local = registry.controlSocketFor(machineId)if (local && local.readyState === WebSocket.OPEN) {- try { local.send(JSON.stringify({ t: 'down', machineId: machineId, connId: '', frame })) } catch { /* ignore */ }+ guardedSendJson(local, { t: 'down', machineId: machineId, connId: '', frame }, 'must', { machineId, kind: 'control' })return}// B_m's control socket briefly gone (mid-failover) → best-effort via Redis (sole subscriber is B_m).@@ -263,23 +283,30 @@ setInterval(() => {// Client-count upkeep. Cadence is bound to the Redis field TTL, NOT to how fast a dead peer is noticed.export const CLIENT_HEARTBEAT_MS = 25_000-setInterval(() => {+// The resyncs below are spread across this window instead of fired as one burst.+const CLIENT_RESYNC_SPREAD_MS = 20_000+function clientHeartbeatTick(): void {// Refresh this instance's client-count fields (25s < 45s TTL) so an idle client isn't garbage-collected- // out of the global total. A crashed instance simply stops refreshing → its fields expire.- for (const machineId of registry.localAgentIds()) {- const { ui, commander, commanderActive } = registry.clientCounts(machineId)- void setAgentClientCount(machineId, INSTANCE_ID, ui, commander, commanderActive)- }+ // out of the global total. A crashed instance simply stops refreshing → its fields expire. One pipeline+ // for every local agent, not 2 round trips each.+ const rows = registry.localAgentIds().map((machineId) => ({ machineId, ...registry.clientCounts(machineId) }))+ void setAgentClientCountsBatch(INSTANCE_ID, rows)// B_m periodic resync: re-emit the summed `__clients` for every agent whose control socket lives// here. Field EXPIRY (a client-holding instance crashed — its fields age out of the hash after 45s)// has no attach/detach event to poke a recompute, so without this the node keeps the ghost count// forever (brain recap stays warm for a device that's gone). Receivers apply the absolute value// idempotently, so re-sending an unchanged count is a no-op — and doubles as self-heal for any- // `__clients` frame lost to a pub/sub drop. Converges ≤ TTL(45s) + sweep(25s).- for (const machineId of registry.controlAgentIds()) {- void recomputeAndSendClients(machineId)- }-}, CLIENT_HEARTBEAT_MS).unref?.()+ // `__clients` frame lost to a pub/sub drop. Converges ≤ TTL(45s) + sweep(25s) + spread(20s).+ const ids = registry.controlAgentIds()+ ids.forEach((machineId, i) => {+ setTimeout(() => { void recomputeAndSendClients(machineId) }, Math.floor((i / ids.length) * CLIENT_RESYNC_SPREAD_MS)).unref?.()+ })+}+// Random start offset so instances booted together (a rolling deploy) don't all hit Redis in phase.+setTimeout(() => {+ clientHeartbeatTick()+ setInterval(clientHeartbeatTick, CLIENT_HEARTBEAT_MS).unref?.()+}, Math.floor(Math.random() * 5_000)).unref?.()/** Register a client socket into the hub. The caller still owns the socket's 'message' handler. */export function attachHubClient(socket: WebSocket, machineId: string, kind: ClientKind): HubClient {@@ -316,14 +343,14 @@ export function attachHubClient(socket: WebSocket, machineId: string, kind: Clie}).catch(() => { /* logged in bus */ })}- void sendClientsControl(machineId, kind === 'commander')+ sendClientsControl(machineId, kind === 'commander')const sendDown = (frame: Frame): void => {// Fast-path: if THIS instance holds the agent's control manager socket (co-located), send the// down frame straight to it — no Redis. Local delivery is guaranteed reachable (socket open).const local = registry.controlSocketFor(machineId)if (local && local.readyState === WebSocket.OPEN) {- try { local.send(JSON.stringify({ t: 'down', machineId: machineId, connId, frame })) } catch { /* ignore */ }+ guardedSendJson(local, { t: 'down', machineId: machineId, connId, frame }, 'must', { machineId, kind: 'control' })return}// publishDown returns the Redis subscriber count. 0 = no backend holds this agent's manager@@ -333,9 +360,7 @@ export function attachHubClient(socket: WebSocket, machineId: string, kind: Clievoid routeDown(machineId, { connId, frame }, () => publishDown(machineId, { connId, frame })).then((n) => {// HANDLED_IN_PROCESS = a provider machine, which has no socket to count. Only a real zero// means "nobody holds this machine right now".- if (n === 0 && socket.readyState === WebSocket.OPEN) {- try { socket.send(JSON.stringify({ type: 'node_status', payload: { online: false, reason: 'unreachable' } })) } catch { /* ignore */ }- }+ if (n === 0) guardedSendJson(socket, { type: 'node_status', payload: { online: false, reason: 'unreachable' } }, 'must', { machineId, connId })}).catch(() => { /* ignore */ })}@@ -346,13 +371,11 @@ export function attachHubClient(socket: WebSocket, machineId: string, kind: Clieconst packet = encodeTerminalHop(TerminalHopDirection.down, connId, clientFrame)if (!packet) returnvoid publishTerminalDown(machineId, packet).then((subscribers) => {- if (subscribers === 0 && socket.readyState === WebSocket.OPEN) {- try { socket.send(JSON.stringify({ type: 'terminal_transport_error', payload: { code: 'TERMINAL_UNREACHABLE' } })) } catch { /* ignore */ }- }+ if (subscribers === 0) guardedSendJson(socket, { type: 'terminal_transport_error', payload: { code: 'TERMINAL_UNREACHABLE' } }, 'must', { machineId, connId })}).catch(() => { /* ignore */ })},setActive: (active: boolean) => {- if (registry.setClientActive(machineId, connId, active)) void sendClientsControl(machineId)+ if (registry.setClientActive(machineId, connId, active)) sendClientsControl(machineId)},detach: () => {// The Harness owns per-connection E2EE state and terminal controller@@ -377,5 +400,5 @@ function detachConn(machineId: string, connId: string): void {const terminalUnsub = terminalUpSubs.get(machineId)if (terminalUnsub) { terminalUnsub(); terminalUpSubs.delete(machineId) }}- void sendClientsControl(machineId)+ sendClientsControl(machineId)}diff --git a/backend/src/lib/managerWs.test.ts b/backend/src/lib/managerWs.test.tsindex 3b1ec4f6b..14c58b133 100644--- a/backend/src/lib/managerWs.test.ts+++ b/backend/src/lib/managerWs.test.ts@@ -6,6 +6,7 @@ const state = vi.hoisted(() => ({setAgentPresence: vi.fn(async () => undefined),clearAgentPresence: vi.fn(async () => undefined),publishUp: vi.fn(async () => 1),+ publishAppUp: vi.fn(async () => 1),recomputeAndSendClients: vi.fn(async () => undefined),agentsByManager: new Map<string, Set<string>>(),controlSockets: new Map<string, unknown>(),@@ -20,11 +21,11 @@ vi.mock('./bus.js', () => ({subscribeMgr: vi.fn(async () => vi.fn()),publishReply: vi.fn(async () => 1),subscribeAppDown: vi.fn(async () => vi.fn()),- publishAppUp: vi.fn(async () => 1),+ publishAppUp: state.publishAppUp,setAppInstance: vi.fn(async () => undefined),clearAppInstance: vi.fn(async () => undefined),}))-vi.mock('../config/env.js', () => ({ env: { MESH_ENABLED: false } }))+vi.mock('../config/env.js', () => ({ env: { MESH_ENABLED: false, APP_PROXY_MAX_RELAY_FRAME_BYTES: 1024 } }))vi.mock('./instance.js', () => ({ INSTANCE_ID: 'backend-test' }))vi.mock('./registry.js', () => ({PROCESS_ID: 'backend-test',@@ -110,4 +111,20 @@ describe('manager node readiness', () => {ws.emit('close')})++ it('aborts instead of relaying an app frame too large for cross-instance pub/sub', () => {+ const ws = new FakeManagerSocket()+ attachManager(ws as never, 'manager-2', 'app')++ const small = { t: 'app_res_body', streamId: 'stream-small', chunk: 'AAAA' }+ ws.emit('message', Buffer.from(JSON.stringify(small)))+ expect(state.publishAppUp).toHaveBeenCalledWith('stream-small', small)++ const big = { t: 'app_res_body', streamId: 'stream-big', chunk: 'A'.repeat(4096) }+ ws.emit('message', Buffer.from(JSON.stringify(big)))+ expect(state.publishAppUp).not.toHaveBeenCalledWith('stream-big', big)+ expect(state.publishAppUp).toHaveBeenCalledWith('stream-big', { t: 'app_abort', streamId: 'stream-big', reason: 'frame_too_large' })++ ws.emit('close')+ })})diff --git a/backend/src/lib/managerWs.ts b/backend/src/lib/managerWs.tsindex 0a07e65ba..2ca3e80e9 100644--- a/backend/src/lib/managerWs.ts+++ b/backend/src/lib/managerWs.ts@@ -12,7 +12,8 @@import type { IncomingMessage } from 'http'import type { Duplex } from 'stream'import { randomUUID } from 'crypto'-import { WebSocketServer, WebSocket, type RawData } from 'ws'+import { WebSocket, type RawData } from 'ws'+import { createWss, WS_LIMITS } from './wsServer.js'import { prisma } from './prisma.js'import {publishUp,@@ -34,11 +35,13 @@ import { deliverUpLocal, recomputeAndSendClients, CLIENTS_DIRTY } from './hub.jsimport { recordCreatedAgent, recordDeletedAgent } from './agentTracker.js'import type { ManagerFrame, DownBusMsg } from './tunnel.js'import { logger } from '../utils/logger.js'+import { fireAndForget } from '../utils/async.js'+import { guardedSendJson } from './wsSend.js'import { getMachineLifecycleState } from './machineLifecycle.js'const PRESENCE_TTL_SEC = 30-const wss = new WebSocketServer({ noServer: true })+const wss = createWss(WS_LIMITS.manager)/** Fastify/http upgrade hook for `/api/manager-ws`. Auth = manager apiKey (`x-api-key`) + `managerId`. */export function handleManagerUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void {@@ -62,6 +65,8 @@ export function attachManager(ws: WebSocket, managerId: string, poolKind: 'contr// for presence + provisioning placement.const connKey = `${managerId}#${randomUUID()}`registry.addManager(connKey, ws)+ // A manager that stops reading must not be allowed to pin unbounded down-frames in our heap either.+ const send = (obj: unknown): boolean => guardedSendJson(ws, obj, 'must', { managerId, connKey, pool: poolKind })logger.info('manager connected', { managerId, connKey, pool: poolKind })// machineId → unsubscribe for its down:{machineId} subscription (this instance is B_m for that agent).@@ -95,7 +100,7 @@ export function attachManager(ws: WebSocket, managerId: string, poolKind: 'contrconst cmd = msg as { requestId?: string; cmd?: 'create' | 'start' | 'stop' | 'destroy' | 'app_create' | 'app_delete'; payload?: Record<string, unknown> }if (!cmd?.requestId || !cmd.cmd) returnif (ws.readyState === WebSocket.OPEN) {- try { ws.send(JSON.stringify({ t: 'provision', requestId: cmd.requestId, cmd: cmd.cmd, payload: cmd.payload ?? {} })) } catch { /* ignore */ }+ send({ t: 'provision', requestId: cmd.requestId, cmd: cmd.cmd, payload: cmd.payload ?? {} })}}).then((u) => { unsubMgr = u }).catch((err) => logger.error('manager-ws subscribeMgr failed', err, { managerId }))}@@ -139,7 +144,7 @@ export function attachManager(ws: WebSocket, managerId: string, poolKind: 'contrif ((msg.frame as { type?: string })?.type === CLIENTS_DIRTY) { void recomputeAndSendClients(machineId); return }// Forward a client message down this manager socket → manager → node.if (ws.readyState === WebSocket.OPEN) {- try { ws.send(JSON.stringify({ t: 'down', machineId: machineId, connId: msg.connId, frame: msg.frame })) } catch { /* ignore */ }+ send({ t: 'down', machineId: machineId, connId: msg.connId, frame: msg.frame })}}).then((unsub) => {downSubPending.delete(machineId)@@ -166,7 +171,7 @@ export function attachManager(ws: WebSocket, managerId: string, poolKind: 'contrif (unsub) { unsub(); downSubs.delete(machineId) }void clearAgentPresence(machineId)// Intentional manual/idle stop is a first-class lifecycle state; unexpected detach remains `offline`.- void getMachineLifecycleState(machineId).then(({ status: rawStatus, stopReason }) => {+ fireAndForget(getMachineLifecycleState(machineId).then(({ status: rawStatus, stopReason }) => {const stopped = rawStatus === 'stopping' || rawStatus === 'stopped'return publishUp(machineId, {webEligible: true,@@ -178,7 +183,7 @@ export function attachManager(ws: WebSocket, managerId: string, poolKind: 'contr: { online: false, status: 'offline', reason: 'node offline' },},})- })+ }), 'manager-ws unregister node_status', { managerId, machineId })logger.info('node unregistered', { managerId, machineId })}@@ -194,7 +199,7 @@ export function attachManager(ws: WebSocket, managerId: string, poolKind: 'contrappDownSubPending.add(machineId)void subscribeAppDown(machineId, (frame) => {if (ws.readyState === WebSocket.OPEN) {- try { ws.send(JSON.stringify(frame)) } catch { /* ignore */ }+ send(frame)}}).then((unsub) => {appDownSubPending.delete(machineId)@@ -218,55 +223,56 @@ export function attachManager(ws: WebSocket, managerId: string, poolKind: 'contrws.on('message', (raw: RawData) => {lastSeen = Date.now()- let env: ManagerFrame- try { env = JSON.parse(raw.toString()) as ManagerFrame } catch { return }- switch (env.t) {+ const rawBytes = Buffer.isBuffer(raw) ? raw.length : Array.isArray(raw) ? raw.reduce((n, b) => n + b.length, 0) : raw.byteLength+ let frame: ManagerFrame+ try { frame = JSON.parse(raw.toString()) as ManagerFrame } catch { return }+ switch (frame.t) {case 'up': {// Tap project lifecycle to maintain machine_agents (plan cap) — replaces the old /proxy// response tap; works for BOTH web and device WS create/delete.- const f = env.frame as { type?: string; payload?: { agent?: { id?: unknown; name?: unknown }; agentId?: unknown; machineId?: unknown } }+ const f = frame.frame as { type?: string; payload?: { agent?: { id?: unknown; name?: unknown }; agentId?: unknown; machineId?: unknown } }if (f?.type === 'agent_synced') {- void recordCreatedAgent(env.machineId, f.payload?.agent).catch(() => { /* best effort */ })+ void recordCreatedAgent(frame.machineId, f.payload?.agent).catch(() => { /* best effort */ })} else if (f?.type === 'agent_deleted' && typeof f.payload?.agentId === 'string') {// See adapterWs.ts: producers send `agentId`, so reading `machineId` recorded nothing.- void recordDeletedAgent(env.machineId, f.payload.agentId).catch(() => { /* best effort */ })+ void recordDeletedAgent(frame.machineId, f.payload.agentId).catch(() => { /* best effort */ })}const upMsg = {- excludeConnId: env.excludeConnId,- webEligible: env.webEligible,- commanderEligible: env.commanderEligible,- frame: env.frame,+ excludeConnId: frame.excludeConnId,+ webEligible: frame.webEligible,+ commanderEligible: frame.commanderEligible,+ frame: frame.frame,originPid: registry.PROCESS_ID,}// Fast-path: hand straight to THIS instance's local clients (no Redis round-trip); the tagged// publish still fans out to clients on other instances, which won't double-deliver here.- deliverUpLocal(env.machineId, upMsg)- void publishUp(env.machineId, upMsg)+ deliverUpLocal(frame.machineId, upMsg)+ void publishUp(frame.machineId, upMsg)break}case 'register':- register(env.machineId)+ register(frame.machineId)breakcase 'unregister':- unregister(env.machineId)+ unregister(frame.machineId)breakcase 'app_register':- appRegister(env.machineId)+ appRegister(frame.machineId)breakcase 'app_unregister':- appUnregister(env.machineId)+ appUnregister(frame.machineId)breakcase 'hello':// capacity advertised for placement; presence refreshed opportunistically. Only the pool's// CONTROL socket subscribes provisioning (so a provision command isn't forwarded N times).- if (env.control) subscribeProvisioning()+ if (frame.control) subscribeProvisioning()refreshPresence()breakcase 'ping':refreshPresence()breakcase 'provision_result':- void publishReply(env.requestId, { ok: env.ok, data: env.data, error: env.error })+ void publishReply(frame.requestId, { ok: frame.ok, data: frame.data, error: frame.error })breakcase 'app_res':case 'app_body':@@ -276,7 +282,16 @@ export function attachManager(ws: WebSocket, managerId: string, poolKind: 'contrcase 'app_abort':// App-proxy tunnel app→client frame. Fast-path: if the origin client stream is on THIS instance// (co-located), hand it straight to the local handler — no Redis. Else republish by streamId.- if (!deliverAppUpLocal(env.streamId, env)) void publishAppUp(env.streamId, env)+ if (deliverAppUpLocal(frame.streamId, frame)) break+ // Cross-instance goes through Redis pub/sub, where one oversized message can get the subscriber+ // disconnected (client-output-buffer-limit). Abort this stream instead of risking every stream+ // on that connection; the public side answers 502 / closes 1011 for it.+ if (rawBytes > env.APP_PROXY_MAX_RELAY_FRAME_BYTES) {+ logger.warn('app-tunnel frame too large for cross-instance relay — aborting stream', { managerId, streamId: frame.streamId, bytes: rawBytes })+ void publishAppUp(frame.streamId, { t: 'app_abort', streamId: frame.streamId, reason: 'frame_too_large' })+ break+ }+ void publishAppUp(frame.streamId, frame)breakdefault:breakdiff --git a/backend/src/lib/orderedInbox.test.ts b/backend/src/lib/orderedInbox.test.tsnew file mode 100644index 000000000..e13be25d4--- /dev/null+++ b/backend/src/lib/orderedInbox.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it, vi } from 'vitest'+import { createOrderedInbox } from './orderedInbox.js'++const tick = (): Promise<void> => new Promise((r) => setImmediate(r))++describe('createOrderedInbox', () => {+ it('processes frames strictly in order even when a handler is slow', async () => {+ const seen: number[] = []+ let releaseFirst!: () => void+ const inbox = createOrderedInbox<number>(+ async (n) => {+ if (n === 1) await new Promise<void>((r) => { releaseFirst = r })+ seen.push(n)+ },+ () => { throw new Error('unexpected') },+ () => { throw new Error('unexpected overflow') },+ )+ inbox.enqueue(1); inbox.enqueue(2); inbox.enqueue(3)+ await tick()+ expect(seen).toEqual([])+ expect(inbox.inflight()).toBe(3)+ releaseFirst()+ await tick(); await tick(); await tick()+ expect(seen).toEqual([1, 2, 3])+ expect(inbox.inflight()).toBe(0)+ })++ it('refuses frames past maxInflight, reports them, and keeps the chain intact', async () => {+ const overflow = vi.fn()+ let release!: () => void+ const handled: number[] = []+ const inbox = createOrderedInbox<number>(+ async (n) => { if (n === 1) await new Promise<void>((r) => { release = r }); handled.push(n) },+ () => undefined,+ overflow,+ { maxInflight: 2 },+ )+ expect(inbox.enqueue(1)).toBe(true)+ expect(inbox.enqueue(2)).toBe(true)+ expect(inbox.enqueue(3)).toBe(false)+ expect(overflow).toHaveBeenCalledWith(3, 2)+ expect(inbox.inflight()).toBe(2)+ await tick() // the first handler has started and parked on `release`+ release()+ await tick(); await tick(); await tick()+ expect(handled).toEqual([1, 2])+ // capacity is back once the chain drained+ expect(inbox.enqueue(4)).toBe(true)+ await tick(); await tick()+ expect(handled).toEqual([1, 2, 4])+ })++ it('routes a throwing handler to onError and continues with the next frame', async () => {+ const onError = vi.fn()+ const handled: number[] = []+ const inbox = createOrderedInbox<number>(+ async (n) => { if (n === 1) throw new Error('boom'); handled.push(n) },+ onError,+ () => undefined,+ )+ inbox.enqueue(1); inbox.enqueue(2)+ await tick(); await tick(); await tick()+ expect(onError).toHaveBeenCalledTimes(1)+ expect((onError.mock.calls[0][0] as Error).message).toBe('boom')+ expect(handled).toEqual([2])+ expect(inbox.inflight()).toBe(0)+ })+})diff --git a/backend/src/lib/orderedInbox.ts b/backend/src/lib/orderedInbox.tsnew file mode 100644index 000000000..eff3fc27d--- /dev/null+++ b/backend/src/lib/orderedInbox.ts@@ -0,0 +1,52 @@+/**+ * Strict in-order processing of inbound frames, with a ceiling.+ *+ * The web and device endpoints must handle frames one at a time in arrival order (a `machine_select`+ * followed by an RPC must not be routed by the previous selection). That was a promise chain — but a+ * chain has no ceiling, and one link can legitimately wait a long time (`ensureMachineReady` blocks up+ * to ~190s while a stopped machine provisions). Everything a client sent meanwhile sat in the heap, with+ * nothing to stop it: a client can push thousands of RPCs per minute inside the rate guards.+ *+ * Deliberately NOT `ws.pause()`: pausing the socket also stops reading ping/pong control frames, so the+ * liveness sweep would kill a healthy client (and the ESP32 firmware expects its own pings answered).+ * Instead, past `maxInflight` a frame is refused via `onOverflow` — the caller answers it immediately+ * (fast-fail the RPC / error frame) so the client is not left waiting on something that will never run.+ */+export interface OrderedInboxOptions {+ maxInflight?: number+}++export const DEFAULT_MAX_INFLIGHT = 256++export interface OrderedInbox<T> {+ /** Queue a frame. Returns false when it was refused (overflow) — `onOverflow` has already been called. */+ enqueue: (frame: T) => boolean+ /** Frames queued or running right now. */+ inflight: () => number+}++export function createOrderedInbox<T>(+ handle: (frame: T) => Promise<void>,+ onError: (err: unknown, frame: T) => void,+ onOverflow: (frame: T, inflight: number) => void,+ opts: OrderedInboxOptions = {},+): OrderedInbox<T> {+ const maxInflight = opts.maxInflight ?? DEFAULT_MAX_INFLIGHT+ let chain: Promise<void> = Promise.resolve()+ let inflight = 0+ return {+ enqueue: (frame: T): boolean => {+ if (inflight >= maxInflight) {+ onOverflow(frame, inflight)+ return false+ }+ inflight+++ chain = chain+ .then(() => handle(frame))+ .catch((err) => onError(err, frame))+ .finally(() => { inflight-- })+ return true+ },+ inflight: () => inflight,+ }+}diff --git a/backend/src/lib/providerLink.ts b/backend/src/lib/providerLink.tsindex 0d02a9496..83e42eec2 100644--- a/backend/src/lib/providerLink.ts+++ b/backend/src/lib/providerLink.ts@@ -348,14 +348,17 @@ export async function dispatch(machineId: string, msg: DownBusMsg): Promise<void* can be cached for the process lifetime without a staleness problem — the only way it changes is a* new machine, which is a new key.*/-const modeCache = new Map<string, string>()+// Same 5-minute lifetime as the profile cache: a machine's authMode changes rarely, but the map must not+// grow one entry per machine ever seen and keep it for the life of the process.+const modeCache = new Map<string, { mode: string; at: number }>()+const MODE_TTL_MS = PROFILE_TTL_MSasync function authModeOf(machineId: string): Promise<string> {const cached = modeCache.get(machineId)- if (cached) return cached+ if (cached && Date.now() - cached.at < MODE_TTL_MS) return cached.modeconst row = await prisma.machine.findUnique({ where: { machineId }, select: { authMode: true } })const mode = row?.authMode ?? 'self'- modeCache.set(machineId, mode)+ modeCache.set(machineId, { mode, at: Date.now() })return mode}diff --git a/backend/src/lib/registry.ts b/backend/src/lib/registry.tsindex ac802d824..7c5bbd4b6 100644--- a/backend/src/lib/registry.ts+++ b/backend/src/lib/registry.ts@@ -88,6 +88,14 @@ export function clientsFor(machineId: string): ClientConn[] {return m ? [...m.values()] : []}+/** Allocation-free walk for the per-frame fan-out (`clientsFor` copies the array on every frame).+ * Map iteration tolerates removal mid-walk, so a send that triggers a detach is safe here. */+export function forEachClient(machineId: string, fn: (c: ClientConn) => void): void {+ const m = clientsByAgent.get(machineId)+ if (!m) return+ for (const c of m.values()) fn(c)+}+/** Every local client (web + commander) across all agents — for the hub keep-alive sweep. */export function allClients(): ClientConn[] {const out: ClientConn[] = []diff --git a/backend/src/lib/terminalRouting.test.ts b/backend/src/lib/terminalRouting.test.tsindex 7daefecb2..df76dc855 100644--- a/backend/src/lib/terminalRouting.test.ts+++ b/backend/src/lib/terminalRouting.test.ts@@ -13,9 +13,9 @@ vi.mock('./bus.js', () => ({publishDown: bus.publishDown,publishTerminalDown: async () => 1,setAgentClientCount: async () => undefined,- getAgentClientTotals: async () => ({ ui: 0, commander: 0, commanderActive: 0 }),+ setAgentClientCountsBatch: async () => undefined,+ getAgentClientState: async () => ({ totals: { ui: 0, commander: 0, commanderActive: 0 }, commanderJoinGeneration: 1 }),bumpCommanderJoinGeneration: async () => 1,- getCommanderJoinGeneration: async () => 1,}))const { attachHubClient, deliverTerminalUpLocal, deliverUpLocal } = await import('./hub.js')diff --git a/backend/src/lib/voiceBudget.test.ts b/backend/src/lib/voiceBudget.test.tsnew file mode 100644index 000000000..a7e9bce7b--- /dev/null+++ b/backend/src/lib/voiceBudget.test.ts@@ -0,0 +1,33 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++vi.mock('../config/env.js', () => ({ env: { VOICE_INFLIGHT_MAX_BYTES: 100 } }))++const { reserveVoice, releaseVoice, voiceInflightBytes } = await import('./voiceBudget.js')++describe('voiceBudget', () => {+ beforeEach(() => { releaseVoice(voiceInflightBytes()) })++ it('reserves up to the cap and refuses beyond it without taking anything', () => {+ expect(reserveVoice(60)).toBe(true)+ expect(reserveVoice(40)).toBe(true)+ expect(voiceInflightBytes()).toBe(100)+ expect(reserveVoice(1)).toBe(false)+ expect(voiceInflightBytes()).toBe(100)+ })++ it('release frees capacity and never goes negative', () => {+ reserveVoice(50)+ releaseVoice(30)+ expect(voiceInflightBytes()).toBe(20)+ releaseVoice(1_000)+ expect(voiceInflightBytes()).toBe(0)+ expect(reserveVoice(100)).toBe(true)+ })++ it('ignores non-positive amounts', () => {+ expect(reserveVoice(0)).toBe(true)+ expect(reserveVoice(-5)).toBe(true)+ releaseVoice(-5)+ expect(voiceInflightBytes()).toBe(0)+ })+})diff --git a/backend/src/lib/voiceBudget.ts b/backend/src/lib/voiceBudget.tsnew file mode 100644index 000000000..79adf15c2--- /dev/null+++ b/backend/src/lib/voiceBudget.ts@@ -0,0 +1,27 @@+/**+ * Process-wide budget for voice PCM buffered ahead of STT. Every device socket may hold up to+ * `MAX_PCM` (20 MiB) for one utterance, and `finishVoice` briefly holds a second copy (`Buffer.concat`);+ * with nothing above the per-socket cap, "many devices recording at once" was a straight path to the+ * OOM-killer taking a whole cluster worker — and every socket on it — instead of one upload failing.+ */+import { env } from '../config/env.js'++let inflightBytes = 0++/** Take `bytes` from the budget. Returns false (and takes nothing) when it would exceed the cap. */+export function reserveVoice(bytes: number): boolean {+ if (bytes <= 0) return true+ if (inflightBytes + bytes > env.VOICE_INFLIGHT_MAX_BYTES) return false+ inflightBytes += bytes+ return true+}++/** Give `bytes` back. Clamped at zero so a double release can never grant more than the cap. */+export function releaseVoice(bytes: number): void {+ if (bytes <= 0) return+ inflightBytes = Math.max(0, inflightBytes - bytes)+}++export function voiceInflightBytes(): number {+ return inflightBytes+}diff --git a/backend/src/lib/webWs.ts b/backend/src/lib/webWs.tsindex 140bff2e5..08be0f388 100644--- a/backend/src/lib/webWs.ts+++ b/backend/src/lib/webWs.ts@@ -18,16 +18,20 @@*/import type { IncomingMessage } from 'http'import type { Duplex } from 'stream'-import { WebSocketServer, WebSocket, type RawData } from 'ws'+import { WebSocket, type RawData } from 'ws'+import { createWss, WS_LIMITS } from './wsServer.js'import { extractKey } from '../utils/crypto.js'import { machineIdFromKey } from '../utils/crypto.js'import { prisma, machineAlive } from './prisma.js'-import { getAgentPresence, subscribeUp, getDevicePresence, subscribeDeviceStatus, subscribeDeviceMachineListChanged, subscribeDeviceE2eePair } from './bus.js'+import { getAgentPresence, getAgentPresenceMany, subscribeStatus, getDevicePresence, subscribeDeviceStatus, subscribeDeviceMachineListChanged, subscribeDeviceE2eePair } from './bus.js'import { attachHubClient, trackSocketLiveness, type HubClient } from './hub.js'import { authenticateAccessToken, SsoAuthError, type AuthUser } from './ssoAuth.js'-import type { Frame, UpBusMsg } from './tunnel.js'+import type { Frame } from './tunnel.js'import { machineOnline } from './providerLink.js'import { logger } from '../utils/logger.js'+import { fireAndForget } from '../utils/async.js'+import { guardedSendJson } from './wsSend.js'+import { createOrderedInbox } from './orderedInbox.js'import { ensureMachineReady, getMachineLifecycleStatus, type MachineLifecycleStatus } from './machineLifecycle.js'import type { Machine } from '@prisma/client'import { machineBillingAllowsDataPlane } from './billingState.js'@@ -52,17 +56,13 @@ import {import { touchUserOnlineDay, recordRemoteUsage } from './dailyTracking.js'import { utcDayKey } from '../types/analytics.js'-const wss = new WebSocketServer({- noServer: true,- handleProtocols: (protocols) => {- const first = [...protocols][0]- return first ?? false- },-})+const wss = createWss(WS_LIMITS.web, { echoFirstProtocol: true })// Device-status re-seed: covers the silent-offline case (worker crash → presence TTL 45s ages out// with no transition published) — the watcher re-reads presence keys on this cadence.const DEVICE_RESEED_MS = 30_000+// Trailing debounce for list re-derivations poked by machines_watch (see scheduleWatchAgents).+const WATCH_DEBOUNCE_MS = 250/** HTTP upgrade hook for `/api/web-ws`. Subprotocol = SSO access token or legacy agent apiKey. */export function handleWebUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void {@@ -118,8 +118,9 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {const terminalRate = new TerminalRateGuard()const p2pSignalRate = new P2pSignalRateGuard()+ const send = (obj: unknown): boolean => guardedSendJson(ws, obj, 'must', { userId: user.sub })logger.info('web user connected', { userId: user.sub })- try { ws.send(JSON.stringify({ type: 'connected', payload: { userId: user.sub } })) } catch { /* ignore */ }+ send({ type: 'connected', payload: { userId: user.sub } })// Daily presence: mark today online now, and re-check on the existing 30s re-seed tick / on// disconnect so a connection spanning UTC midnight gets counted for the new day too. The guard@@ -149,7 +150,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {const statusSubs = new Map<string, () => void>()const sendStatuses = (statuses: Array<{ machineId: string; online: boolean; status?: MachineLifecycleStatus; reason?: string }>): void => {if (ws.readyState !== WebSocket.OPEN || statuses.length === 0) return- try { ws.send(JSON.stringify({ type: 'machines_status', payload: { statuses } })) } catch { /* ignore */ }+ send({ type: 'machines_status', payload: { statuses } })}const watchAgents = async (): Promise<void> => {const gen = ++watchGen@@ -164,9 +165,11 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {}for (const id of wanted) {if (statusSubs.has(id)) continue- // Bus subscriptions are refcounted — co-existing with the hub's up:{machineId} sub is fine.- const unsub = await subscribeUp(id, (msg: UpBusMsg) => {- const f = msg.frame as { type?: string; payload?: { online?: boolean; status?: MachineLifecycleStatus; reason?: string } }+ // `status:{machineId}` carries only node_status / machine_app_status transitions — not the+ // machine's whole turn stream, which is what subscribing `up:` here used to pull in for every+ // machine the user owns, whether or not anyone was looking at it.+ const unsub = await subscribeStatus(id, (frame) => {+ const f = frame as { type?: string; payload?: { online?: boolean; status?: MachineLifecycleStatus; reason?: string } }if (f?.type === 'node_status') {sendStatuses([{ machineId: id, online: f.payload?.online === true, ...(f.payload?.status ? { status: f.payload.status } : {}), ...(f.payload?.reason ? { reason: f.payload.reason } : {}) }])}@@ -175,17 +178,32 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {statusSubs.set(id, unsub)}// Seed the full current picture (presence keys = source of truth) so the list is right immediately.+ // One MGET for every presence key, not one GET per machine.+ const ids = [...wanted]+ const presence = await getAgentPresenceMany(ids)const statuses = await Promise.all(- [...wanted].map(async (id) => {+ ids.map(async (id) => {// Same assertion as the per-agent seeds: a provider machine has no presence key and is always// online, so reading presence alone would list it as offline on the machine cards too.- const online = await machineOnline(id, !!(await getAgentPresence(id)))+ const online = await machineOnline(id, !!presence.get(id))const lifecycle = online ? 'running' : await getMachineLifecycleStatus(id)return { machineId: id, online, status: lifecycle === 'unknown' ? 'offline' as const : lifecycle }}),)if (gen === watchGen && !closed) sendStatuses(statuses)}+ // A machine create/rename/delete pokes every open tab of the user at once (`machines_changed` ++ // the client's `machines_watch` reply); several in a row (a bulk rename) must not re-derive the+ // list each time. Trailing debounce: the last poke wins, ≤250ms later.+ let watchAgentsTimer: NodeJS.Timeout | null = null+ const scheduleWatchAgents = (): void => {+ if (watchAgentsTimer) clearTimeout(watchAgentsTimer)+ watchAgentsTimer = setTimeout(() => {+ watchAgentsTimer = null+ if (closed) return+ void watchAgents().catch((err) => logger.warn('web-ws watchAgents failed', { userId: user.sub, error: String(err) }))+ }, WATCH_DEBOUNCE_MS)+ }void watchAgents().catch((err) => logger.warn('web-ws watchAgents failed', { userId: user.sub, error: String(err) }))// ── Live device-status feed (mirror of watchAgents; per-DEVICE statuses over one per-user sub) ──@@ -195,7 +213,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {// publishes offline, the presence key just ages out (TTL 45s) — the poll notices within ~30s.const sendDeviceStatuses = (statuses: Array<{ deviceId: string; online: boolean; lastSeenAt?: string | null }>): void => {if (ws.readyState !== WebSocket.OPEN || statuses.length === 0) return- try { ws.send(JSON.stringify({ type: 'devices_status', payload: { statuses } })) } catch { /* ignore */ }+ send({ type: 'devices_status', payload: { statuses } })}let deviceStatusUnsub: (() => void) | null = nulllet deviceSeedTimer: NodeJS.Timeout | null = null@@ -237,7 +255,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {try { ws.close(4403, `env:${msg.autonomousEnv}`) } catch { /* ignore */ }return}- try { ws.send(JSON.stringify({ type: 'machines_changed', payload: { reason: msg.reason } })) } catch { /* ignore */ }+ send({ type: 'machines_changed', payload: { reason: msg.reason } })})if (closed) { machineListUnsub(); machineListUnsub = null }})().catch((err) => logger.warn('web-ws machine-list watch failed', { userId: user.sub, error: String(err) }))@@ -251,30 +269,26 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {if (ws.readyState !== WebSocket.OPEN) returnconst { kind, ...payload } = msgconst type = kind === 'cleared' ? 'device_e2ee_pair_cleared' : 'device_e2ee_pair_pending'- try { ws.send(JSON.stringify({ type, payload })) } catch { /* ignore */ }+ send({ type, payload })})if (closed) { deviceE2eePairUnsub(); deviceE2eePairUnsub = null }})().catch((err) => logger.warn('web-ws device-e2ee-pair watch failed', { userId: user.sub, error: String(err) }))// ── Agent selection ──────────────────────────────────────────────────────────────────────────const ack = (machineId: string): void => {- try {- ws.send(JSON.stringify({- type: 'connected',- payload: { machineId: machineId, p2p: terminalP2pPolicy(user.sub, machineId) },- }))- } catch { /* ignore */ }- // Authoritative node-liveness for the newly-scoped agent (same seed the legacy mode sends).- void getAgentPresence(machineId).then(async (mgr) => {- if (ws.readyState === WebSocket.OPEN && currentAgentId === machineId) {- const online = await machineOnline(machineId, !!mgr)- void getMachineLifecycleStatus(machineId).then((lifecycle) => {- if (ws.readyState === WebSocket.OPEN && currentAgentId === machineId) {- try { ws.send(JSON.stringify({ type: 'node_status', payload: { online, status: online ? 'running' : lifecycle === 'unknown' ? 'offline' : lifecycle } })) } catch { /* ignore */ }- }- })- }+ send({+ type: 'connected',+ payload: { machineId: machineId, p2p: terminalP2pPolicy(user.sub, machineId) },})+ // Authoritative node-liveness for the newly-scoped agent (same seed the legacy mode sends).+ fireAndForget((async () => {+ const mgr = await getAgentPresence(machineId)+ if (ws.readyState !== WebSocket.OPEN || currentAgentId !== machineId) return+ const online = await machineOnline(machineId, !!mgr)+ const lifecycle = await getMachineLifecycleStatus(machineId)+ if (ws.readyState !== WebSocket.OPEN || currentAgentId !== machineId) return+ send({ type: 'node_status', payload: { online, status: online ? 'running' : lifecycle === 'unknown' ? 'offline' : lifecycle } })+ })(), 'web-ws seed node_status', { userId: user.sub, machineId })}const bindAgent = async (machineIdRaw: unknown): Promise<void> => {if (typeof machineIdRaw !== 'string' || !machineIdRaw) return@@ -284,20 +298,20 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {if (closed || gen !== selectGen) return // superseded by a newer selectif (!binding || binding.deletedAt || binding.userId !== user.sub) {logger.warn('machine_select rejected', { userId: user.sub, machineId })- try { ws.send(JSON.stringify({ type: 'machine_select_error', payload: { machineId: machineId, error: 'NOT_YOUR_MACHINE' } })) } catch { /* ignore */ }+ send({ type: 'machine_select_error', payload: { machineId: machineId, error: 'NOT_YOUR_MACHINE' } })return}if (storedAutonomousEnvironment(binding.autonomousEnv) !== user.autonomousEnv) {logger.warn('machine_select environment rejected', { userId: user.sub, machineId, autonomousEnv: user.autonomousEnv })- try { ws.send(JSON.stringify({ type: 'machine_select_error', payload: { machineId: machineId, error: 'MACHINE_ENV_MISMATCH' } })) } catch { /* ignore */ }+ send({ type: 'machine_select_error', payload: { machineId: machineId, error: 'MACHINE_ENV_MISMATCH' } })return}if (binding.billingStatus === 'pending') {- try { ws.send(JSON.stringify({ type: 'machine_select_error', payload: { machineId: machineId, error: 'MACHINE_PAYMENT_PENDING' } })) } catch { /* ignore */ }+ send({ type: 'machine_select_error', payload: { machineId: machineId, error: 'MACHINE_PAYMENT_PENDING' } })return}if (binding.billingStatus === 'suspended') {- try { ws.send(JSON.stringify({ type: 'machine_select_error', payload: { machineId: machineId, error: 'MACHINE_SUBSCRIPTION_REQUIRED' } })) } catch { /* ignore */ }+ send({ type: 'machine_select_error', payload: { machineId: machineId, error: 'MACHINE_SUBSCRIPTION_REQUIRED' } })return}try {@@ -305,7 +319,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {} catch (err) {if (!closed && gen === selectGen) {const code = err instanceof Error && 'code' in err ? String((err as { code?: unknown }).code) : 'MACHINE_START_FAILED'- try { ws.send(JSON.stringify({ type: 'machine_select_error', payload: { machineId: machineId, error: code } })) } catch { /* ignore */ }+ send({ type: 'machine_select_error', payload: { machineId: machineId, error: code } })}return}@@ -321,6 +335,19 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {ack(machineId)}+ // Presence, remembered briefly. Every non-terminal frame used to cost one Redis GET on the hot path;+ // the key itself has a 30s TTL, so a 2s memory of "it was there" is well inside its own staleness.+ // Only a POSITIVE answer is cached — an absent key must keep triggering the wake path.+ const PRESENCE_MEMORY_MS = 2_000+ let presenceSeen: { machineId: string; at: number } | null = null+ const presentRecently = async (machineId: string): Promise<boolean> => {+ const now = Date.now()+ if (presenceSeen && presenceSeen.machineId === machineId && now - presenceSeen.at < PRESENCE_MEMORY_MS) return true+ const present = !!(await getAgentPresence(machineId))+ presenceSeen = present ? { machineId, at: now } : null+ return present+ }+const handleFrame = async (frame: Frame): Promise<void> => {const type = frame.type as string | undefined// Double-underscore frames are backend-to-Harness control messages. A web@@ -329,13 +356,13 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {const isTerminal = typeof type === 'string' && TERMINAL_DOWN_TYPES.has(type)const terminalNamespace = typeof type === 'string' && type.startsWith('terminal_')if (terminalNamespace && !isTerminal) {- try { ws.send(JSON.stringify({ type: 'terminal_transport_error', payload: { code: 'TERMINAL_TYPE_REJECTED' } })) } catch { /* ignore */ }+ send({ type: 'terminal_transport_error', payload: { code: 'TERMINAL_TYPE_REJECTED' } })return}if (isTerminal) {const bytes = terminalFrameBytes(frame)if (bytes > TERMINAL_ENVELOPE_MAX_BYTES || !isEncryptedTerminalFrame(frame) || !terminalRate.allow(type!, bytes)) {- try { ws.send(JSON.stringify({ type: 'terminal_transport_error', payload: { code: 'TERMINAL_FRAME_REJECTED' } })) } catch { /* ignore */ }+ send({ type: 'terminal_transport_error', payload: { code: 'TERMINAL_FRAME_REJECTED' } })return}}@@ -358,7 +385,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {return}if (p2pNamespace && !isP2pSignal) {- try { ws.send(JSON.stringify({ type: 'p2p_transport_error', payload: { code: 'P2P_TYPE_REJECTED' } })) } catch { /* ignore */ }+ send({ type: 'p2p_transport_error', payload: { code: 'P2P_TYPE_REJECTED' } })return}if (isP2pSignal) {@@ -368,7 +395,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {: falseif (!policyEnabled || bytes > P2P_SIGNAL_MAX_BYTES|| !isEncryptedP2pFrame(frame) || !p2pSignalRate.allow(bytes)) {- try { ws.send(JSON.stringify({ type: 'p2p_transport_error', payload: { code: 'P2P_SIGNAL_REJECTED' } })) } catch { /* ignore */ }+ send({ type: 'p2p_transport_error', payload: { code: 'P2P_SIGNAL_REJECTED' } })return}// Remote-usage signal: a p2p_offer actually starts a new p2p session (vs. the ICE/abort@@ -392,7 +419,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {return}if (type === 'machines_watch') {- void watchAgents().catch(() => { /* logged above */ })+ scheduleWatchAgents()return}if (type === 'devices_watch') {@@ -403,12 +430,12 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {// A selected machine can idle-stop while the tab remains open. Turn-producing messages always// refresh the wake lease; other frames wake only when presence says the node is down.try {- if ((isTerminal && terminalFrameNeedsWake(type!)) || (!isTerminal && (type === 'message' || !(await getAgentPresence(currentBinding.machineId))))) {+ if ((isTerminal && terminalFrameNeedsWake(type!)) || (!isTerminal && (type === 'message' || !(await presentRecently(currentBinding.machineId))))) {await ensureMachineReady(currentBinding)}} catch (err) {const message = err instanceof Error ? err.message : 'Machine could not be started'- try { ws.send(JSON.stringify({ type: 'error', payload: { message } })) } catch { /* ignore */ }+ send({ type: 'error', payload: { message } })return}client.sendDown(frame)@@ -418,7 +445,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {// 20s timeout; drop fire-and-forget frames.const requestId = (frame.payload as { requestId?: unknown } | undefined)?.requestIdif (typeof requestId === 'string' && typeof type === 'string') {- try { ws.send(JSON.stringify({ type: `${type}_result`, payload: { requestId, error: 'NO_MACHINE_SELECTED' } })) } catch { /* ignore */ }+ send({ type: `${type}_result`, payload: { requestId, error: 'NO_MACHINE_SELECTED' } })}}@@ -427,7 +454,26 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {// by the PREVIOUS selection's client — an agent-switch could leak the old agent's projects/replies// into the new view, or lose the RPC entirely. The chain makes every frame wait for the frames// (incl. selects) before it, restoring the single-socket ordering guarantee end-to-end.- let frameChain: Promise<void> = Promise.resolve()+ // Bounded (see orderedInbox.ts): past the ceiling a frame is refused and answered right away.+ let lastOverflowLogAt = 0+ const inbox = createOrderedInbox<Frame>(+ handleFrame,+ (err, frame) => logger.warn('web-ws frame failed', { userId: user.sub, type: frame.type, error: String(err) }),+ (frame, inflight) => {+ const type = frame.type as string | undefined+ const requestId = (frame.payload as { requestId?: unknown } | undefined)?.requestId+ if (typeof requestId === 'string' && typeof type === 'string') {+ send({ type: `${type}_result`, payload: { requestId, error: 'INBOUND_OVERFLOW' } })+ } else {+ send({ type: 'error', payload: { code: 'INBOUND_OVERFLOW', message: 'too many frames in flight' } })+ }+ const now = Date.now()+ if (now - lastOverflowLogAt > 10_000) {+ lastOverflowLogAt = now+ logger.warn('web-ws inbound overflow — refusing frames', { userId: user.sub, machineId: currentAgentId ?? undefined, inflight, type })+ }+ },+ )ws.on('message', (raw: RawData, isBinary: boolean) => {if (isBinary) {const parsed = parseTerminalClientFrame(new Uint8Array(raw as Buffer))@@ -439,7 +485,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {const rateKey = parsed?.kind === TerminalBinaryKind.input ? 'terminal_input' : 'terminal_paste'if (!client || !currentBinding || !parsed || !TERMINAL_BINARY_CLIENT_UP_KINDS.has(parsed.kind)|| !terminalRate.allow(rateKey, parsed.bytes.length)) {- try { ws.send(JSON.stringify({ type: 'terminal_transport_error', payload: { code: 'TERMINAL_BINARY_REJECTED' } })) } catch { /* ignore */ }+ send({ type: 'terminal_transport_error', payload: { code: 'TERMINAL_BINARY_REJECTED' } })return}client.sendTerminalDown(parsed.bytes)@@ -447,9 +493,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {}let frame: Frametry { frame = JSON.parse(raw.toString()) as Frame } catch { return }- frameChain = frameChain- .then(() => handleFrame(frame))- .catch((err) => logger.warn('web-ws frame failed', { userId: user.sub, type: frame.type, error: String(err) }))+ inbox.enqueue(frame)})const cleanup = (): void => {@@ -461,6 +505,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {currentBinding = nullfor (const [, unsub] of statusSubs) unsub()statusSubs.clear()+ if (watchAgentsTimer) { clearTimeout(watchAgentsTimer); watchAgentsTimer = null }if (deviceSeedTimer) { clearInterval(deviceSeedTimer); deviceSeedTimer = null }if (deviceStatusUnsub) { deviceStatusUnsub(); deviceStatusUnsub = null }if (machineListUnsub) { machineListUnsub(); machineListUnsub = null }@@ -476,19 +521,21 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {function attachWebClient(ws: WebSocket, machineId: string): void {const client = attachHubClient(ws, machineId, 'web')const terminalRate = new TerminalRateGuard()+ const send = (obj: unknown): boolean => guardedSendJson(ws, obj, 'must', { machineId, connId: client.connId })logger.info('web client connected (legacy)', { machineId, connId: client.connId })- ws.send(JSON.stringify({ type: 'connected', payload: { machineId: machineId } }))+ send({ type: 'connected', payload: { machineId: machineId } })// Authoritative node-liveness signal on connect (presence key = source of truth, set on register +// refreshed by the manager ping). Explicit BOTH ways so a client that connects while the node is// already up gets `online:true` immediately, not just inferred from the absence of an offline event.- void getAgentPresence(machineId).then(async (mgr) => {+ fireAndForget((async () => {+ const mgr = await getAgentPresence(machineId)const online = await machineOnline(machineId, !!mgr)if (ws.readyState === WebSocket.OPEN) {- try { ws.send(JSON.stringify({ type: 'node_status', payload: { online } })) } catch { /* ignore */ }+ send({ type: 'node_status', payload: { online } })}- })+ })(), 'web-ws seed node_status (legacy)', { machineId })ws.on('message', (raw: RawData, isBinary: boolean) => {if (isBinary) {@@ -512,7 +559,10 @@ function attachWebClient(ws: WebSocket, machineId: string): void {client.sendDown(frame)})+ let closed = falseconst cleanup = (): void => {+ if (closed) return // 'error' is followed by 'close': detach (and its __client_disconnected) only once+ closed = trueclient.detach()logger.info('web client disconnected (legacy)', { machineId, connId: client.connId })}diff --git a/backend/src/lib/wsSend.test.ts b/backend/src/lib/wsSend.test.tsnew file mode 100644index 000000000..6c98ad623--- /dev/null+++ b/backend/src/lib/wsSend.test.ts@@ -0,0 +1,73 @@+import { describe, expect, it, vi } from 'vitest'+import type { WebSocket } from 'ws'++vi.mock('../utils/logger.js', () => ({ logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn() } }))++const { guardedSend, guardedSendJson, SEND_HIGH_WATER, SEND_KILL_WATER } = await import('./wsSend.js')++function fakeSocket(bufferedAmount: number, readyState = 1) {+ const ws = {+ readyState,+ bufferedAmount,+ send: vi.fn(),+ close: vi.fn(),+ terminate: vi.fn(),+ }+ return ws as unknown as WebSocket & typeof ws+}++describe('guardedSend', () => {+ it('sends when the outbound buffer is small', () => {+ const ws = fakeSocket(0)+ expect(guardedSend(ws, 'x', 'droppable')).toBe(true)+ expect(ws.send).toHaveBeenCalledWith('x')+ })++ it('refuses a closed socket without touching it', () => {+ const ws = fakeSocket(0, 3)+ expect(guardedSend(ws, 'x', 'must')).toBe(false)+ expect(ws.send).not.toHaveBeenCalled()+ })++ it('drops droppable frames above the high-water mark but still sends must frames', () => {+ const ws = fakeSocket(SEND_HIGH_WATER + 1)+ expect(guardedSend(ws, 'out', 'droppable')).toBe(false)+ expect(ws.send).not.toHaveBeenCalled()+ expect(guardedSend(ws, 'delta', 'must')).toBe(true)+ expect(ws.send).toHaveBeenCalledWith('delta')+ })++ it('closes a slow consumer above the kill-water mark and terminates after the grace', () => {+ vi.useFakeTimers()+ try {+ const ws = fakeSocket(SEND_KILL_WATER + 1)+ expect(guardedSend(ws, 'x', 'must')).toBe(false)+ expect(ws.send).not.toHaveBeenCalled()+ expect(ws.close).toHaveBeenCalledWith(1013, 'slow consumer')+ expect(ws.terminate).not.toHaveBeenCalled()+ vi.advanceTimersByTime(2_000)+ expect(ws.terminate).toHaveBeenCalled()+ } finally {+ vi.useRealTimers()+ }+ })++ it('does not terminate a socket that finished closing on its own', () => {+ vi.useFakeTimers()+ try {+ const ws = fakeSocket(SEND_KILL_WATER + 1)+ guardedSend(ws, 'x', 'must')+ ws.readyState = 3 // CLOSED before the grace elapses+ vi.advanceTimersByTime(2_000)+ expect(ws.terminate).not.toHaveBeenCalled()+ } finally {+ vi.useRealTimers()+ }+ })++ it('guardedSendJson serializes and defaults to must', () => {+ const ws = fakeSocket(SEND_HIGH_WATER + 1)+ expect(guardedSendJson(ws, { type: 'node_status' })).toBe(true)+ expect(ws.send).toHaveBeenCalledWith('{"type":"node_status"}')+ })+})diff --git a/backend/src/lib/wsSend.ts b/backend/src/lib/wsSend.tsnew file mode 100644index 000000000..edfbc777d--- /dev/null+++ b/backend/src/lib/wsSend.ts@@ -0,0 +1,58 @@+/**+ * Outbound send with backpressure. `ws.send()` never blocks and never drops: whatever the peer does not+ * read piles up in this process' heap (`bufferedAmount`). A browser tab throttled in the background, or+ * a peer behind a small TCP window, while an agent streams turn deltas / terminal output, therefore grew+ * memory linearly with stream rate — and the liveness sweep could not catch it, because that measures+ * INBOUND silence and a slow reader still answers pings.+ *+ * Two thresholds, one policy per frame:+ * - over SEND_HIGH_WATER a `droppable` frame is skipped. A frame is only droppable when losing it is+ * invisible to the client — a full-snapshot frame that a later one supersedes. It is NOT for+ * order-sensitive streams (chat deltas) or opaque byte streams (terminal output has no per-frame ack,+ * so a dropped frame is an undetectable gap that stalls the pane); those ride until the kill line.+ * - over SEND_KILL_WATER the peer is declared a slow consumer and closed (1013 = try again later, the+ * client's reconnect backoff handles it). `terminate()` follows shortly, since a peer that is not+ * reading is unlikely to complete the close handshake either. This close is what bounds memory for+ * `must` frames.+ */+import { WebSocket } from 'ws'+import { logger } from '../utils/logger.js'++export const SEND_HIGH_WATER = 2 * 1024 * 1024+export const SEND_KILL_WATER = 8 * 1024 * 1024+const SLOW_CONSUMER_TERMINATE_MS = 2_000++export type SendPolicy = 'must' | 'droppable'++let droppedFrames = 0+let slowConsumerCloses = 0++/** Counters for diagnostics / a future metrics endpoint. */+export function sendStats(): { droppedFrames: number; slowConsumerCloses: number } {+ return { droppedFrames, slowConsumerCloses }+}++/** Returns true when the frame was handed to `ws`; false when skipped, dropped, or the socket was closed. */+export function guardedSend(ws: WebSocket, data: string | Uint8Array, policy: SendPolicy, info?: Record<string, unknown>): boolean {+ if (ws.readyState !== WebSocket.OPEN) return false+ const buffered = ws.bufferedAmount+ if (buffered > SEND_KILL_WATER) {+ slowConsumerCloses+++ logger.warn('ws slow consumer — closing', { ...info, buffered })+ try { ws.close(1013, 'slow consumer') } catch { /* ignore */ }+ setTimeout(() => {+ if (ws.readyState !== WebSocket.CLOSED) { try { ws.terminate() } catch { /* ignore */ } }+ }, SLOW_CONSUMER_TERMINATE_MS).unref?.()+ return false+ }+ if (policy === 'droppable' && buffered > SEND_HIGH_WATER) {+ droppedFrames+++ return false+ }+ try { ws.send(data); return true } catch { return false }+}++/** JSON convenience over guardedSend. */+export function guardedSendJson(ws: WebSocket, obj: unknown, policy: SendPolicy = 'must', info?: Record<string, unknown>): boolean {+ return guardedSend(ws, JSON.stringify(obj), policy, info)+}diff --git a/backend/src/lib/wsServer.test.ts b/backend/src/lib/wsServer.test.tsnew file mode 100644index 000000000..dba4ae11f--- /dev/null+++ b/backend/src/lib/wsServer.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it, vi } from 'vitest'++// A minimal fake WebSocketServer so createWss's `wss.on('connection', …)` wiring is observable+// without a real network handshake.+const hoisted = vi.hoisted(() => ({ servers: [] as Array<{ handlers: Record<string, Function[]>; clients: Set<unknown> }> }))+vi.mock('ws', () => {+ class FakeWss {+ handlers: Record<string, Function[]> = {}+ clients = new Set<unknown>()+ constructor(_opts: unknown) { hoisted.servers.push(this) }+ on(event: string, cb: Function) { (this.handlers[event] ??= []).push(cb); return this }+ emit(event: string, ...args: unknown[]) { for (const cb of this.handlers[event] ?? []) cb(...args) }+ }+ return { WebSocketServer: FakeWss }+})++const { createWss, RELEASE_UPGRADE_SLOT } = await import('./wsServer.js')++describe('createWss upgrade-slot release', () => {+ it('calls the raw socket’s release hook on a successful connection', () => {+ const wss = createWss(1024) as unknown as { emit: (e: string, ...a: unknown[]) => void }+ const release = vi.fn()+ const rawSocket: Record<PropertyKey, unknown> = { [RELEASE_UPGRADE_SLOT]: release }+ // ws emits 'connection' with the WebSocket; createWss reaches its ._socket.+ wss.emit('connection', { _socket: rawSocket })+ expect(release).toHaveBeenCalledTimes(1)+ })++ it('is a no-op for a socket that carries no release hook (e.g. the app-proxy)', () => {+ const wss = createWss(1024) as unknown as { emit: (e: string, ...a: unknown[]) => void }+ expect(() => wss.emit('connection', { _socket: {} })).not.toThrow()+ expect(() => wss.emit('connection', {})).not.toThrow()+ })+})diff --git a/backend/src/lib/wsServer.ts b/backend/src/lib/wsServer.tsnew file mode 100644index 000000000..fec8939bc--- /dev/null+++ b/backend/src/lib/wsServer.ts@@ -0,0 +1,83 @@+/**+ * One place to construct every `WebSocketServer` in the backend, so the edge limits live together:+ *+ * - `maxPayload`: `ws` defaults to 100 MiB per message. Everything here parses the message with+ * `JSON.parse(raw.toString())` on the event loop, so an authenticated client could stall a whole+ * cluster worker (and allocate ~3× the frame in heap) with one oversized frame. Each endpoint gets+ * the ceiling its real traffic needs (see WS_LIMITS); `ws` closes 1009 before we ever see the bytes.+ * - `perMessageDeflate: false`: no zlib context per socket and no inflate amplification.+ *+ * Every server is registered so shutdown can drain them (`drainAllSockets`) — `noServer` sockets are+ * invisible to `http.Server#close`, which is why the old shutdown just let `process.exit` cut them.+ */+import { WebSocketServer } from 'ws'+import type { Socket } from 'net'++// A raw upgrade socket carries its pre-auth-slot release fn under this symbol (set in server.ts). createWss+// calls it on a successful upgrade so a completed handshake frees its slot immediately, rather than being+// held for the connection's lifetime or a fixed timeout.+export const RELEASE_UPGRADE_SLOT = Symbol('releaseUpgradeSlot')+export type SlotSocket = Socket & { [RELEASE_UPGRADE_SLOT]?: () => void }++export const WS_LIMITS = {+ /** Terminal envelopes are capped at 512 KiB (terminalRelay); chat/RPC frames are far smaller. */+ web: 1024 * 1024,+ /** PCM chunks are ~640 B (20 ms @ 16 kHz); device JSON RPCs are tiny. */+ device: 256 * 1024,+ /** App-proxy frames ride these sockets: 8 MiB of body → ~11.2 MiB once base64'd into JSON. */+ manager: 16 * 1024 * 1024,+ adapter: 16 * 1024 * 1024,+} as const++const servers = new Set<WebSocketServer>()++export interface CreateWssOptions {+ /** Echo the first offered subprotocol (the credential) so browsers / the ESP client accept the handshake. */+ echoFirstProtocol?: boolean+}++export function createWss(maxPayload: number, opts: CreateWssOptions = {}): WebSocketServer {+ const wss = new WebSocketServer({+ noServer: true,+ maxPayload,+ perMessageDeflate: false,+ ...(opts.echoFirstProtocol+ ? { handleProtocols: (protocols: Set<string>) => [...protocols][0] ?? false }+ : {}),+ })+ // A successful upgrade means the pre-auth phase is over (the 101 was sent) → free its slot now. Sockets+ // not created through server.ts's upgrade cap (e.g. the app-proxy) simply carry no release fn.+ wss.on('connection', (ws) => {+ const raw = (ws as unknown as { _socket?: SlotSocket })._socket+ raw?.[RELEASE_UPGRADE_SLOT]?.()+ })+ servers.add(wss)+ return wss+}++/** Number of open sockets across every server — for shutdown logging / diagnostics. */+export function openSocketCount(): number {+ let n = 0+ for (const wss of servers) n += wss.clients.size+ return n+}++/**+ * Politely close every socket (1012 = "service restart": clients reconnect with backoff instead of+ * treating it as an error), give the close handshake `graceMs`, then terminate whatever is left so a+ * half-open peer cannot hold the process past PM2's kill_timeout. Per-socket 'close' handlers run as+ * usual, which is what clears presence / owner keys before exit.+ */+export async function drainAllSockets(graceMs = 4_000): Promise<void> {+ for (const wss of servers) {+ for (const client of wss.clients) {+ try { client.close(1012, 'server restart') } catch { /* ignore */ }+ }+ }+ await new Promise((resolve) => setTimeout(resolve, graceMs))+ for (const wss of servers) {+ for (const client of wss.clients) {+ try { client.terminate() } catch { /* ignore */ }+ }+ }+}diff --git a/backend/src/server.ts b/backend/src/server.tsindex b9b3cea08..50c611d25 100644--- a/backend/src/server.ts+++ b/backend/src/server.ts@@ -18,6 +18,24 @@ import { handleManagerUpgrade } from './lib/managerWs.js'import { handleAdapterUpgrade } from './lib/adapterWs.js'import { logger } from './utils/logger.js'import { startTurnCredentialRefresh } from './lib/turnCredentials.js'+import { closeBus } from './lib/bus.js'+import { drainAllSockets, openSocketCount, RELEASE_UPGRADE_SLOT, type SlotSocket } from './lib/wsServer.js'++// Node ≥ 15 turns an unhandled rejection into a process exit. On a cluster worker that holds thousands of+// sockets, one DB/Redis hiccup inside a fire-and-forget promise would then drop every one of them and+// leave their presence keys as ghosts until TTL. Log it instead; `fireAndForget` (utils/async.ts) is the+// per-call-site fix, this is the net under it.+process.on('unhandledRejection', (reason) => {+ logger.error('unhandledRejection', reason instanceof Error ? reason : new Error(String(reason)))+})++// Handshakes in flight: each one holds a raw socket AND an outbound SSO profile call (5s timeout) before+// we know whether it is legitimate. Without a ceiling, a flood of junk tokens is a cheap way to pin file+// descriptors and outbound HTTP on this worker. Over the cap → 503 + Retry-After; a healthy client's+// reconnect backoff handles that fine.+const MAX_PENDING_UPGRADES = 500+const UPGRADE_HANDSHAKE_TIMEOUT_MS = 10_000+let pendingUpgrades = 0// One http.Server fronts everything. Inverted transport: there is NO data-plane HTTP reverse-proxy// anymore (web + device data ride the hub WS). HTTP is entirely the Fastify control API@@ -37,6 +55,26 @@ const app = Fastify({// data. Nothing in this codebase called setNoDelay() before, so every socket here defaulted to// Nagle-enabled.if (socket instanceof net.Socket) socket.setNoDelay(true)+ if (pendingUpgrades >= MAX_PENDING_UPGRADES) {+ try { socket.write('HTTP/1.1 503 Service Unavailable\r\nRetry-After: 2\r\nConnection: close\r\nContent-Length: 0\r\n\r\n') } catch { /* ignore */ }+ socket.destroy()+ return+ }+ pendingUpgrades+++ // The slot covers only the PRE-auth handshake (the expensive, unauthenticated phase: an open socket+ // plus one outbound SSO call). It is released the instant that phase settles — on a successful+ // upgrade (createWss fires RELEASE_UPGRADE_SLOT from the wss 'connection' event) or on the socket+ // dying (auth-fail destroy / ws.close) — NOT held for the connection's life or a fixed window, so a+ // burst of completed reconnects never starves new handshakes. The timer is only a backstop for a+ // handshake that neither completes nor closes (a hung peer mid-negotiation).+ let released = false+ const release = (): void => { if (!released) { released = true; pendingUpgrades-- } }+ ;(socket as SlotSocket)[RELEASE_UPGRADE_SLOT] = release+ socket.once('close', release)+ setTimeout(release, UPGRADE_HANDSHAKE_TIMEOUT_MS).unref()+ // A handshake that never completes (auth call hung, peer went silent) must not hold the socket.+ // `ws` resets the timeout to 0 once it completes the upgrade, so this only ever fires pre-upgrade.+ if (socket instanceof net.Socket) socket.setTimeout(UPGRADE_HANDSHAKE_TIMEOUT_MS, () => socket.destroy())const path = (req.url ?? '').split('?')[0]// Inverted-transport hub endpoints (terminated here, not proxied):// /api/web-ws — web clients (replaces the old proxied /proxy/api/ws)@@ -117,13 +155,29 @@ async function start(): Promise<void> {// Internal mesh listener (Phase 2, MESH_ENABLED) — peers forward here when this instance owns the socket.const meshServer = startMeshProxy()- const shutdown = async (signal: string) => {- logger.info(`Received ${signal}, shutting down...`)+ let shuttingDown = false+ const shutdown = async (signal: string, exitCode = 0) => {+ if (shuttingDown) return+ shuttingDown = true+ logger.info(`Received ${signal}, shutting down...`, { openSockets: openSocketCount() })try {appProxyServer.close()meshServer?.close()- await app.close()- process.exit(0)+ // Start Fastify's close (it tells the http server to stop accepting new connections) but DON'T await+ // it yet: http.Server#close only resolves once every connection has ended, and an upgraded WebSocket+ // is a connection that never ends on its own — so awaiting here would hang until clients happened to+ // disconnect, and the drain below would never run.+ const fastifyClosed = app.close().catch((err) => logger.error('fastify close error', err))+ // Now end the WebSockets (invisible to http.Server#close), which is what lets fastifyClosed settle.+ await drainAllSockets()+ // Sockets terminated at the end of the drain fire their 'close' handler on the next tick, and those+ // handlers clear presence/owner keys as fire-and-forget Redis writes. Let them land before closeBus+ // quits the connection, else a half-open socket's key survives on TTL alone.+ await new Promise((resolve) => setTimeout(resolve, 250))+ // Bounded wait for Fastify to finish (onClose hooks, Prisma disconnect); never block shutdown on it.+ await Promise.race([fastifyClosed, new Promise((resolve) => setTimeout(resolve, 5_000))])+ await closeBus()+ process.exit(exitCode)} catch (err) {logger.error('Error during shutdown', err)process.exit(1)@@ -131,6 +185,12 @@ async function start(): Promise<void> {}process.on('SIGINT', () => void shutdown('SIGINT'))process.on('SIGTERM', () => void shutdown('SIGTERM'))+ // Truly unrecoverable: drain politely so clients reconnect elsewhere, then let PM2/k8s restart us.+ process.on('uncaughtException', (err) => {+ logger.error('uncaughtException — draining', err)+ void shutdown('uncaughtException', 1)+ setTimeout(() => process.exit(1), 8_000).unref()+ })await app.listen({ port: env.PORT, host: '0.0.0.0' })logger.info(`backend listening on ${env.PORT}`)diff --git a/backend/src/utils/async.ts b/backend/src/utils/async.tsnew file mode 100644index 000000000..a5c3854ca--- /dev/null+++ b/backend/src/utils/async.ts@@ -0,0 +1,12 @@+import { logger } from './logger.js'++/**+ * Fire-and-forget with a guaranteed catch. Node ≥ 15 turns an unhandled rejection into a process+ * crash, so a `void promise.then(async …)` whose callback awaits the DB or Redis is a latent+ * "one hiccup kills the cluster worker (and every socket on it)". Route every such call through here.+ */+export function fireAndForget(p: Promise<unknown>, what: string, ctx?: Record<string, unknown>): void {+ p.catch((err: unknown) => {+ logger.warn(`${what} failed`, { ...ctx, error: err instanceof Error ? err.message : String(err) })+ })+}