Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(server): resync a desynced client on DRAIN, never with an empty capture
enesa32b076b004e
diff --git a/docs/team-presence.md b/docs/team-presence.mdindex 41c2be009..a698c9793 100644--- a/docs/team-presence.md+++ b/docs/team-presence.md@@ -153,13 +153,29 @@ Changes:high-water, so the slowest link no longer sets the pace for the team.That alone would let a slow client's send buffer grow without bound, so it is capped:- at `WS_DROP_WATER` (8 MB buffered for one client on one session) we **drop that client's+ at `WS_DROP_WATER` (8 MB buffered on one client's socket) we **drop that client'squeued output** rather than pause the others, and when its buffer drains we **resynchroniseit by redrawing the current screen from tmux** (reusing the existing `capture-pane` path)with a "reconnected — earlier output skipped" separator. For a terminal the current screenis what matters, not the 8 MB of scrollback a bad link missed; tmux is the authoritative- source of that screen. Drop-and-redraw is per `(client, session)`: a desynced phone affects- neither the other clients of that session nor its own other sessions.+ source of that screen.++ Three properties of that ceiling, stated honestly:+ - **The bound is per SOCKET, not per session.** `bufferedAmount` is `ws.bufferedAmount` — one+ number for the whole connection, which is where the bytes actually sit. So a client that+ floods past the ceiling on one session desyncs on *every* session it is watching (each on its+ next chunk). Other **viewers** of those sessions are untouched — they have their own sockets.+ - **Recovery is per `(client, session)`:** the desync state is keyed that way, so each session+ gets its own capture and its own redraw.+ - **The drain is the trigger, not the next chunk.** The common case is a flood that *ends*+ (`npm run build` finishes; the socket drains; no further output ever arrives). A redraw hung+ off the next chunk would never fire, leaving the user on a screen truncated mid-flood. A+ 250 ms sweep — armed on desync, cleared when the desynced set empties, so the healthy path+ pays nothing — watches the socket and redraws once it is back under the low-water mark.+ - **An empty capture is never sent.** `captureForResync` returns `''` on any tmux/ssh failure,+ and the renderer's resync handler resets the terminal; sending `''` would blank a live+ terminal. An empty/failed capture keeps the client desynced and is retried with backoff+ (250 ms → 10 s cap). `pty:resync` payloads are therefore guaranteed non-empty.### Typing attribution — and why it is server-sidediff --git a/src/server/backpressure.test.ts b/src/server/backpressure.test.tsindex a5b23bce7..1b012b734 100644--- a/src/server/backpressure.test.ts+++ b/src/server/backpressure.test.ts@@ -206,20 +206,121 @@ describe('ws drop-and-redraw ceiling (bounded memory)', () => {expect(slow.sends).toBe(1)})- it('desyncing one (client, session) does not desync that client s other sessions', () => {+ // The ceiling is a SOCKET-wide bound, because `bufferedAmount` is `ws.bufferedAmount` — there is+ // no per-session send queue to measure. So when one session floods the socket past the ceiling,+ // EVERY session on that socket desyncs on its next chunk. That is the honest semantics (and the+ // memory bound we actually want: the socket is what holds the bytes). What IS per (client,+ // session) is the desync STATE and the redraw: each session is captured and repainted on its own.+ it('the ceiling is socket-wide: a second session on the drowning socket also desyncs — but each session gets its OWN redraw', async () => {const p = new ServerPlatform({ userDataDir: '/tmp', appVersion: '0' })p.setFlowController(() => {})- p.setResyncProvider(async () => '')+ const capture = vi.fn(async (sid: string) => `SCREEN ${sid}`)+ p.setResyncProvider(capture)const s = growingSink(8_000_001)const id = p.attach(s.sink)p.sendTo(id, 'pty:data:s1', 'x') // s1 crosses the ceiling → dropped+ p.sendTo(id, 'pty:data:s2', 'y') // s2 shares the SAME socket buffer → also droppedexpect(s.sends).toBe(0)- s.buffered = 0 // the buffer is a socket-wide number; s2 is nowhere near the ceiling- p.sendTo(id, 'pty:data:s2', 'y') // a DIFFERENT session on the same client still streams++ s.buffered = 1000 // the socket drained: both sessions recover, each with its own capture+ await vi.waitFor(+ () => expect([...s.resyncs].sort()).toEqual(['SCREEN s1', 'SCREEN s2']),+ { timeout: 3000 }+ )+ expect(capture.mock.calls.map((c) => c[0]).sort()).toEqual(['s1', 's2'])++ p.sendTo(id, 'pty:data:s2', 'z') // resynced → normal streaming resumes for bothexpect(s.sends).toBe(1)})+ // FINDING 1: the flood ENDS. The build finishes, the socket drains, and NO further pty output+ // ever arrives — so a redraw triggered by "the next chunk of that session" never happens and the+ // user stares at a truncated screen forever. The drain itself must be the trigger.+ it('resyncs a desynced client when its buffer DRAINS, even though no further output arrives', async () => {+ const p = new ServerPlatform({ userDataDir: '/tmp', appVersion: '0' })+ p.setFlowController(() => {})+ const capture = vi.fn(async () => 'CURRENT SCREEN')+ p.setResyncProvider(capture)+ const slow = growingSink(8_000_001)+ const id = p.attach(slow.sink)++ p.sendTo(id, 'pty:data:s1', 'a') // the flood crosses the ceiling → desync + drop+ expect(slow.sends).toBe(0)++ // Still above the low-water mark: the redraw must NOT fire yet (it would land behind an 8 MB+ // backlog and be stale on arrival).+ slow.buffered = 2_000_000+ await new Promise((r) => setTimeout(r, 400))+ expect(capture).not.toHaveBeenCalled()++ // The flood is over and the socket drained. Nothing else is ever sent on this session.+ slow.buffered = 1000+ await vi.waitFor(() => expect(slow.resyncs).toEqual(['CURRENT SCREEN']), { timeout: 3000 })+ expect(capture).toHaveBeenCalledTimes(1) // exactly one capture, not one per sweep tick+ })++ // FINDING 2: captureForResync returns '' on ANY tmux/ssh failure (ControlMaster blip, session+ // mid-respawn). The renderer's resync contract is reset() + separator + write(payload), so an+ // empty payload would WIPE a live terminal. An empty capture must never be sent.+ it('never sends a resync for an empty/failed capture — it retries instead of clearing the screen', async () => {+ const p = new ServerPlatform({ userDataDir: '/tmp', appVersion: '0' })+ p.setFlowController(() => {})+ const capture = vi.fn(async () => '') // tmux/ssh hiccup: every capture comes back empty+ p.setResyncProvider(capture)+ const slow = growingSink(8_000_001)+ const id = p.attach(slow.sink)++ p.sendTo(id, 'pty:data:s1', 'a') // desynced+ slow.buffered = 0 // drained → resync attempts start++ await vi.waitFor(() => expect(capture.mock.calls.length).toBeGreaterThanOrEqual(2), { timeout: 3000 })+ expect(slow.resyncs).toEqual([]) // NOTHING sent: an empty resync would blank a live terminal+ p.sendTo(id, 'pty:data:s1', 'b')+ expect(slow.sends).toBe(0) // still desynced (output still dropped) → the retry keeps its chance++ // The blip passes: the next capture succeeds and the client is finally repainted + streaming.+ capture.mockResolvedValue('BACK')+ await vi.waitFor(() => expect(slow.resyncs).toEqual(['BACK']), { timeout: 3000 })+ slow.buffered = 0+ p.sendTo(id, 'pty:data:s1', 'c')+ expect(slow.sends).toBe(1)+ })++ it('a throwing resync provider is contained: no unhandled rejection, the client stays desynced and recovers', async () => {+ const p = new ServerPlatform({ userDataDir: '/tmp', appVersion: '0' })+ p.setFlowController(() => {})+ const capture = vi.fn(async () => {+ throw new Error('tmux exploded')+ })+ p.setResyncProvider(capture as unknown as (sid: string) => Promise<string>)+ const slow = growingSink(8_000_001)+ const id = p.attach(slow.sink)++ p.sendTo(id, 'pty:data:s1', 'a')+ slow.buffered = 0+ await vi.waitFor(() => expect(capture.mock.calls.length).toBeGreaterThanOrEqual(1), { timeout: 3000 })+ expect(slow.resyncs).toEqual([])+ expect(slow.sends).toBe(0) // still desynced, not crashed+ })++ it('a dead session leaves no desync/pause state behind (pruned on pty:exit)', async () => {+ const p = new ServerPlatform({ userDataDir: '/tmp', appVersion: '0' })+ const flow: Array<{ sid: string; resume: boolean }> = []+ p.setFlowController((_uiId, sid, resume) => flow.push({ sid, resume }))+ const capture = vi.fn(async () => 'SCREEN')+ p.setResyncProvider(capture)+ const slow = growingSink(8_000_001)+ const id = p.attach(slow.sink)++ p.sendTo(id, 'pty:data:s1', 'a') // desynced+ p.sendTo(id, 'pty:exit:s1', 0) // the session died while the client was behind+ slow.buffered = 0+ await new Promise((r) => setTimeout(r, 500))+ expect(capture).not.toHaveBeenCalled() // nothing to capture — and no sweep is left running+ expect(slow.resyncs).toEqual([])+ })+it('a client that leaves while desynced is not redrawn, and leaves no state behind', async () => {const p = new ServerPlatform({ userDataDir: '/tmp', appVersion: '0' })p.setFlowController(() => {})diff --git a/src/server/platform-server.ts b/src/server/platform-server.tsindex 0fca203cf..ee7d22908 100644--- a/src/server/platform-server.ts+++ b/src/server/platform-server.ts@@ -17,6 +17,9 @@ export interface UiSink {}const PTY_DATA_PREFIX = 'pty:data:'+/** Session-death channels — the point where a (client, session)'s backpressure state is pruned. */+const PTY_EXIT_PREFIX = 'pty:exit:'+const PTY_CLOSED_PREFIX = 'pty:closed:'/** Watermarks match the renderer terminal's own flow control. */const WS_HIGH_WATER = 1_000_000const WS_LOW_WATER = 256_000@@ -30,6 +33,21 @@ const WS_LOW_WATER = 256_000* Do not "fix" this back into a replay.*/const WS_DROP_WATER = 8_000_000+/**+ * How often the desynced set is swept for clients whose socket has drained. A flood that ENDS is+ * the normal case (`npm run build` finishes, the socket drains, no further pty output ever+ * arrives) — driving the redraw off the NEXT chunk of that session would leave such a client on a+ * screen truncated mid-flood forever. The sweep is the drain trigger, and it only runs while+ * something is actually desynced (armed on desync, cleared when the set empties), so the healthy+ * path — the only path a solo user is ever on — pays nothing.+ */+const RESYNC_SWEEP_MS = 250+/** A capture that comes back empty is retried on this schedule (250 ms, 500, 1 s … capped), so a+ * session that can never be captured cannot turn the sweep into a subprocess treadmill. */+const RESYNC_BACKOFF_MAX_MS = 10_000++/** One (client, session) whose backlog we discarded, and when its redraw may next be attempted. */+type Desync = { attempts: number; nextAttemptAt: number }type Handler = { fn: (...args: any[]) => unknown; withSender: boolean }type Listener = { fn: (...args: any[]) => void; withSender: boolean }@@ -65,12 +83,27 @@ export class ServerPlatform implements CorePlatform {private paused = new Set<string>()private flowController?: (uiId: number, sessionId: string, resume: boolean) => void- /** The (client, session) pairs whose backlog we discarded; each gets a tmux redraw once it- * drains back under WS_LOW_WATER. Keyed like `paused` — desync is per (client, session), so a- * drowning phone affects neither the other viewers of that session nor its own other sessions. */- private desynced = new Set<string>()+ /**+ * The (client, session) pairs whose backlog we discarded; each gets a tmux redraw once its+ * socket drains back under WS_LOW_WATER.+ *+ * The BOUND is socket-wide, not per session: `UiSink.bufferedAmount` is `ws.bufferedAmount` —+ * one number for the whole connection, because that is where the bytes actually sit (there is no+ * per-session send queue to measure, and the socket is what would OOM us). So a client that+ * floods the socket past WS_DROP_WATER on ONE session desyncs on EVERY session it is watching,+ * as soon as each gets its next chunk. That is deliberate: at 8 MB queued, that connection is+ * hopeless for all of its terminals, and dropping only the loudest session would leave the+ * others queueing behind the same jammed socket.+ *+ * What IS per (client, session) is the desync STATE and the recovery: each session is captured+ * and repainted on its own, and other VIEWERS of those sessions are untouched (they have their+ * own sockets). Keyed like `paused`.+ */+ private desynced = new Map<string, Desync>()/** Redraws currently in flight (a capture is async) — one per (client, session), never N. */private resyncing = new Set<string>()+ /** Armed only while `desynced` is non-empty (see RESYNC_SWEEP_MS). */+ private sweepTimer?: ReturnType<typeof setInterval>private resyncProvider?: (sessionId: string) => Promise<string>setFlowController(fn: (uiId: number, sessionId: string, resume: boolean) => void): void {@@ -78,9 +111,9 @@ export class ServerPlatform implements CorePlatform {}/** How a desynced client is brought back: the session's CURRENT screen, captured from tmux- * (PtyManager.captureForResync). Unset (tests / no tmux) degrades to an EMPTY redraw — the- * client still clears and resumes streaming; it just isn't repainted. It must never be left- * desynced forever, which is what a bail-out here would do. */+ * (PtyManager.captureForResync). Unset (tests / no tmux) means nothing can ever repaint this+ * client, so a desync is simply cleared and streaming resumes un-repainted — it must never be+ * left desynced forever, which is what a silent bail-out would do. */setResyncProvider(fn: (sessionId: string) => Promise<string>): void {this.resyncProvider = fn}@@ -147,10 +180,26 @@ export class ServerPlatform implements CorePlatform {}}} else {+ // A session that DIED takes its backpressure state with it: nothing will ever be captured or+ // resumed for it again, and a stale desync key would keep the sweep (and its tmux captures)+ // alive for a session that no longer exists. Both channels are per-subscriber, so this prunes+ // exactly the (this client, that session) entries. Costs the healthy path nothing — pty:data+ // never reaches this branch.+ const deadPrefix = [PTY_EXIT_PREFIX, PTY_CLOSED_PREFIX].find((p) => channel.startsWith(p))+ if (deadPrefix) this.forgetFlowState(ServerPlatform.flowKey(uiId, channel.slice(deadPrefix.length)))sink.sendText(JSON.stringify({ t: 'ev', channel, args }))}}+ /** Drop every trace of one (client, session) from the backpressure bookkeeping. The pty-side+ * pause is not handed back here: these are dead-session / departing-client paths, where+ * PtyManager's own ledger (kill / dropClient) releases it. */+ private forgetFlowState(key: string): void {+ this.paused.delete(key)+ this.desynced.delete(key)+ this.stopSweepIfIdle()+ }+/*** The bounded-memory gate for one (client, session). Returns true when this chunk must be* DISCARDED — either because the client is already desynced (its backlog was dropped and the@@ -159,12 +208,15 @@ export class ServerPlatform implements CorePlatform {private dropOrDesync(uiId: number, sessionId: string, buffered: number): boolean {const key = ServerPlatform.flowKey(uiId, sessionId)if (this.desynced.has(key)) {- // Drained enough to be worth talking to again → redraw it onto the CURRENT screen.- if (buffered <= WS_LOW_WATER) void this.resync(uiId, sessionId)+ // Output is still flowing, so take the chance to recover early — the sweep would get there+ // within RESYNC_SWEEP_MS anyway, but a chunk we can see right now is free.+ this.maybeResync(uiId, sessionId, buffered)return true}if (buffered <= WS_DROP_WATER) return false- this.desynced.add(key)+ // nextAttemptAt 0: the very first drain (from the sweep or the next chunk) redraws immediately.+ this.desynced.set(key, { attempts: 0, nextAttemptAt: 0 })+ this.armSweep()// We stopped streaming to this client, so it must not hold the shared pty hostage: a pause it// owes could never be returned (it receives nothing, so it can never drain and re-report), and// PtyManager keeps the pty paused while ANY client owes a resume — the other viewers' terminal@@ -173,21 +225,101 @@ export class ServerPlatform implements CorePlatform {return true}- /** Redraw one desynced client from tmux, then let it stream again. One capture, never a replay. */+ /** Redraw a desynced client IF it has drained and its (backoff-gated) turn has come. */+ private maybeResync(uiId: number, sessionId: string, buffered: number): void {+ const key = ServerPlatform.flowKey(uiId, sessionId)+ const state = this.desynced.get(key)+ if (!state || this.resyncing.has(key)) return+ // Never redraw into a socket that is still backed up: the repaint would queue behind the+ // backlog and be stale by the time it arrived. And never faster than the backoff allows.+ if (buffered > WS_LOW_WATER || Date.now() < state.nextAttemptAt) return+ // A provider that throws would otherwise be an unhandled rejection → process exit under Node's+ // default. `resync` already contains its own failures; this is the last line of defence.+ void this.resync(uiId, sessionId).catch((err) => {+ console.warn(+ '[nodeterm-server] resync failed',+ err instanceof Error ? err.message : String(err)+ )+ })+ }++ /**+ * Redraw one desynced client from tmux, then let it stream again. One capture, never a replay.+ *+ * CONTRACT WITH THE RENDERER: a `pty:resync:<sid>` event is only ever sent with a NON-EMPTY+ * payload, so the renderer may reset the terminal and repaint from it unconditionally. Captures+ * fail empty (`captureForResync` returns '' on any tmux/ssh error — a ControlMaster blip, tmux+ * not yet resolved, a session mid-respawn), and sending that would blank a perfectly live+ * terminal and leave only the separator. So an empty capture sends NOTHING: the client stays+ * desynced (output still dropped, screen intact, if stale) and the sweep retries with backoff.+ */private async resync(uiId: number, sessionId: string): Promise<void> {const key = ServerPlatform.flowKey(uiId, sessionId)if (this.resyncing.has(key)) returnthis.resyncing.add(key)try {- const screen = this.resyncProvider ? await this.resyncProvider(sessionId) : ''+ if (!this.desynced.has(key)) return+ if (!this.resyncProvider) {+ // No capture path at all (tests / no tmux): retrying is pointless and staying desynced+ // would strand the client forever. Resume streaming un-repainted.+ this.desynced.delete(key)+ return+ }+ let screen = ''+ try {+ screen = await this.resyncProvider(sessionId)+ } catch {+ screen = '' // treated exactly like an empty capture: retry, never clear the screen+ }if (!this.sinks.has(uiId)) return // client left while the capture was in flight+ const state = this.desynced.get(key)+ if (!state) return // pruned (session died) while the capture was in flight+ if (!screen) {+ state.attempts+++ state.nextAttemptAt =+ Date.now() + Math.min(RESYNC_SWEEP_MS * 2 ** (state.attempts - 1), RESYNC_BACKOFF_MAX_MS)+ return+ }this.desynced.delete(key)// Not a pty:data frame, so it is not subject to the gate above (and the flag is cleared// anyway): a plain event the terminal turns into a clear + redraw.this.sendTo(uiId, IPC.ptyResync(sessionId), screen)} finally {this.resyncing.delete(key)+ this.stopSweepIfIdle()+ }+ }++ /** The drain trigger. A flood that ends leaves no further pty output to hang a redraw off, so a+ * low-frequency sweep watches the socket instead. It exists ONLY while something is desynced. */+ private armSweep(): void {+ if (this.sweepTimer || this.desynced.size === 0) return+ this.sweepTimer = setInterval(() => this.sweepDesynced(), RESYNC_SWEEP_MS)+ // Must never hold the process (or a vitest run) open.+ this.sweepTimer.unref?.()+ }++ private stopSweepIfIdle(): void {+ if (this.sweepTimer && this.desynced.size === 0) {+ clearInterval(this.sweepTimer)+ this.sweepTimer = undefined+ }+ }++ private sweepDesynced(): void {+ for (const key of [...this.desynced.keys()]) {+ const sep = key.indexOf(' ')+ const uiId = Number(key.slice(0, sep))+ const sink = this.sinks.get(uiId)+ if (!sink) {+ this.desynced.delete(key) // client gone (belt and braces: detach already prunes)+ continue+ }+ // `maybeResync` is a no-op above the low-water mark and while a capture is in flight, so a+ // client that never drains costs one bufferedAmount read per tick — it cannot spin.+ this.maybeResync(uiId, key.slice(sep + 1), sink.bufferedAmount?.() ?? 0)}+ this.stopSweepIfIdle()}broadcast(channel: string, ...args: any[]): void {@@ -215,7 +347,8 @@ export class ServerPlatform implements CorePlatform {for (const key of this.paused) if (key.startsWith(prefix)) this.paused.delete(key)// Same for the drop-and-redraw state: a departing client leaves none behind (and an in-flight// capture for it lands on a missing sink, so it is discarded — see `resync`).- for (const key of this.desynced) if (key.startsWith(prefix)) this.desynced.delete(key)+ for (const key of this.desynced.keys()) if (key.startsWith(prefix)) this.desynced.delete(key)+ this.stopSweepIfIdle() // the last desynced client left → no timer survives it}async dispatch(uiId: number, req: RpcRequest): Promise<RpcOk | RpcErr> {diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex dd0208e8b..891ebeae6 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -84,7 +84,10 @@ export const IPC = {ptyClosed: (sessionId: string) => `pty:closed:${sessionId}`,/** Redraw for a client that fell too far behind: the session's CURRENT screen, captured from* tmux. Sent instead of the discarded backlog (payload: the capture text). The terminal clears- * and repaints from it — see ServerPlatform's WS_DROP_WATER. */+ * and repaints from it — see ServerPlatform's WS_DROP_WATER.+ * CONTRACT: the payload is guaranteed NON-EMPTY (a failed capture is retried, never sent — an+ * empty redraw would wipe a live terminal). The renderer must still IGNORE an empty payload+ * rather than reset on it. */ptyResync: (sessionId: string) => `pty:resync:${sessionId}`,workspaceLoad: 'workspace:load',workspaceSave: 'workspace:save',