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): cap a slow client's ws backlog — drop and redraw from tmux instead of buffering forever
enes2ea6eb3974d0
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex fd3906873..cd9406470 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -1185,6 +1185,23 @@ export class PtyManager {}}+ /**+ * The CURRENT screen of a live session, by sessionId — the redraw sent to a client that fell so+ * far behind that its socket backlog was discarded (see ServerPlatform's WS_DROP_WATER). Reuses+ * the existing `tmux capture-pane -e` paths (`captureSnapshot`, which the relay host already+ * paints a joining mirror with; `captureSession` for an ssh-project node, whose tmux lives on the+ * remote host) rather than adding a second capture. '' when the session or tmux is unavailable —+ * the client then just clears and resumes streaming.+ */+ async captureForResync(sessionId: string): Promise<string> {+ const session = this.sessions.get(sessionId)+ if (!session) return ''+ const key = session.persistKey ?? session.indexKey+ if (!key) return ''+ if (session.sshRemote) return this.captureSession(key)+ return this.captureSnapshot(key)+ }+/*** Snapshot a node's recent scrollback (with colors, `-e`) to disk for cold-restart replay.* Best-effort: a missing session / unavailable tmux just leaves the prior snapshot in place.diff --git a/src/server/backpressure.test.ts b/src/server/backpressure.test.tsindex 3f3210fd8..a5b23bce7 100644--- a/src/server/backpressure.test.ts+++ b/src/server/backpressure.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect } from 'vitest'+import { describe, it, expect, vi } from 'vitest'import { ServerPlatform, type UiSink } from './platform-server'function sink(buffered: () => number): UiSink {@@ -112,3 +112,129 @@ describe('ws backpressure', () => {expect(() => p.sendTo(ui, 'some:event', 1)).not.toThrow()})})++describe('ws drop-and-redraw ceiling (bounded memory)', () => {+ /** A sink whose buffer GROWS with every byte it is handed — a client that is not draining. */+ type Growing = { buffered: number; sends: number; resyncs: string[]; sink: UiSink }+ function growingSink(start = 0): Growing {+ const s: Growing = {+ buffered: start,+ sends: 0,+ resyncs: [] as string[],+ sink: {+ sendText: (json: string) => {+ const m = JSON.parse(json)+ if (typeof m.channel === 'string' && m.channel.startsWith('pty:resync:'))+ s.resyncs.push(String(m.args[0]))+ },+ sendBinary: (b: Uint8Array) => {+ s.sends+++ s.buffered += b.byteLength+ },+ bufferedAmount: () => s.buffered+ } as UiSink+ }+ return s+ }++ it('a client over WS_DROP_WATER stops receiving that session, the other client is untouched, and the pty is NOT paused', () => {+ const p = new ServerPlatform({ userDataDir: '/tmp', appVersion: '0' })+ const flow: Array<{ sid: string; resume: boolean }> = []+ p.setFlowController((_uiId, sid, resume) => flow.push({ sid, resume }))+ p.setResyncProvider(async () => 'SCREEN')+ const slow = growingSink(8_000_001) // already past the ceiling+ const fast = growingSink(0)+ const slowId = p.attach(slow.sink)+ const fastId = p.attach(fast.sink)++ for (let i = 0; i < 3; i++) {+ p.sendTo(slowId, 'pty:data:s1', 'chunk')+ p.sendTo(fastId, 'pty:data:s1', 'chunk')+ }+ expect(slow.sends).toBe(0) // dropped — nothing more is queued for it+ expect(slow.buffered).toBe(8_000_001) // …so its buffer stops growing (bounded)+ expect(fast.sends).toBe(3) // the fast client keeps streaming, uninterrupted+ expect(flow).toEqual([]) // and the shared pty is never paused for it+ })++ it('a client that crosses the ceiling while it OWED a pause hands that pause back', async () => {+ // The whole point of dropping: a desynced client must not hold the shared pty hostage. It+ // stopped receiving output, so it can never drain and return the pause itself — the drop is+ // where the resume is owed back, or the other viewers' terminal would freeze forever.+ const p = new ServerPlatform({ userDataDir: '/tmp', appVersion: '0' })+ const flow: Array<{ uiId: number; sid: string; resume: boolean }> = []+ p.setFlowController((uiId, sid, resume) => flow.push({ uiId, sid, resume }))+ p.setResyncProvider(async () => 'SCREEN')+ let buffered = 2_000_000 // above HIGH, below DROP+ const ui = p.attach({+ sendText: () => {},+ sendBinary: () => {},+ bufferedAmount: () => buffered+ })++ p.sendTo(ui, 'pty:data:s1', 'chunk') // over high-water → this client owes a resume+ expect(flow).toEqual([{ uiId: ui, sid: 's1', resume: false }])++ buffered = 9_000_000 // it never drained: past the ceiling+ p.sendTo(ui, 'pty:data:s1', 'chunk') // → desynced, and the pause is returned+ expect(flow).toEqual([+ { uiId: ui, sid: 's1', resume: false },+ { uiId: ui, sid: 's1', resume: true }+ ])+ })++ it('resyncs ONCE via the tmux capture path when the client drains, then resumes streaming', 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') // over the ceiling → desync + drop+ expect(slow.sends).toBe(0)++ slow.buffered = 1000 // the socket drained below WS_LOW_WATER+ p.sendTo(id, 'pty:data:s1', 'b') // still dropped: the redraw is in flight+ p.sendTo(id, 'pty:data:s1', 'c')+ await vi.waitFor(() => expect(slow.resyncs).toEqual(['CURRENT SCREEN']))+ expect(capture).toHaveBeenCalledTimes(1) // ONE capture — not a replay of the backlog+ expect(capture).toHaveBeenCalledWith('s1')++ slow.buffered = 1000+ p.sendTo(id, 'pty:data:s1', 'd') // resynced → normal streaming resumes+ expect(slow.sends).toBe(1)+ })++ it('desyncing one (client, session) does not desync that client s other sessions', () => {+ const p = new ServerPlatform({ userDataDir: '/tmp', appVersion: '0' })+ p.setFlowController(() => {})+ p.setResyncProvider(async () => '')+ const s = growingSink(8_000_001)+ const id = p.attach(s.sink)++ p.sendTo(id, 'pty:data:s1', 'x') // s1 crosses the ceiling → dropped+ expect(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+ expect(s.sends).toBe(1)+ })++ 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(() => {})+ 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', 'x') // desynced+ p.detach(id) // tab closed while behind+ slow.buffered = 0+ p.sendTo(id, 'pty:data:s1', 'y') // gone: no send, no capture+ await Promise.resolve()+ expect(slow.sends).toBe(0)+ expect(slow.resyncs).toEqual([])+ expect(capture).not.toHaveBeenCalled()+ })+})diff --git a/src/server/index.ts b/src/server/index.tsindex 897e2bc1c..cfd89c69e 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -88,6 +88,10 @@ export async function startServer(// can no longer be un-paused by another browser's join/leave.platform.setFlowController((uiId, sid, resume) => ptyManager.setFlow(uiId, sid, resume))+ // Bounded memory: a client whose socket backlog we discarded (WS_DROP_WATER) is REDRAWN from+ // tmux — the current screen — rather than replayed. See platform-server.ts dropOrDesync.+ platform.setResyncProvider((sid) => ptyManager.captureForResync(sid))+// Desktop's src/main/index.ts registers a few pty handlers outside PtyManager. Of those,// ptyCapture delegates purely to core (ptyManager.captureSession), so it belongs here.// The others (ptyGenerateName / ptyGenerateGroupName → commit-message.ts; ptyReadSessionNamediff --git a/src/server/platform-server.ts b/src/server/platform-server.tsindex d89adfadf..0fca203cf 100644--- a/src/server/platform-server.ts+++ b/src/server/platform-server.ts@@ -1,4 +1,5 @@import type { CorePlatform } from '../core/platform'+import { IPC } from '../shared/ipc'import {E_NO_HANDLER,encodePtyData,@@ -19,6 +20,16 @@ const PTY_DATA_PREFIX = 'pty:data:'/** Watermarks match the renderer terminal's own flow control. */const WS_HIGH_WATER = 1_000_000const WS_LOW_WATER = 256_000+/**+ * Hard ceiling per (client, session). Because backpressure is per-client (a slow client must not+ * pause the pty for everyone), a client that never drains would otherwise grow its send buffer+ * without bound until the server OOMs. Past this we DROP that session's output for that client and+ * redraw it from tmux once it recovers: for a terminal the CURRENT SCREEN is what matters, not the+ * 8 MB of scrollback a bad link missed — replaying that backlog would be slower to deliver, stale+ * on arrival, and keep the buffer full. tmux is the authoritative source of the current screen.+ * Do not "fix" this back into a replay.+ */+const WS_DROP_WATER = 8_000_000type Handler = { fn: (...args: any[]) => unknown; withSender: boolean }type Listener = { fn: (...args: any[]) => void; withSender: boolean }@@ -48,16 +59,32 @@ export class ServerPlatform implements CorePlatform {// browser B": B's low-water send would hand back the resume A owes, and with the pty paused no// further data would arrive for A to re-assert it — the terminal would hang for both of them.//- // Still Task 5's: a viewer that STAYS behind currently sets the pace for everyone (the slowest- // socket throttles the shared pty). The fix is a per-client drop-and-redraw above a second,- // higher watermark (WS_DROP_WATER) rather than pausing the producer indefinitely.+ // A viewer that STAYS behind does not set the pace for everyone: above WS_DROP_WATER we stop+ // sending to it and redraw it from tmux when it recovers (see `dropOrDesync`), so the pause it+ // owes is bounded in time and the producer is never throttled indefinitely by one bad link.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>()+ /** Redraws currently in flight (a capture is async) — one per (client, session), never N. */+ private resyncing = new Set<string>()+ private resyncProvider?: (sessionId: string) => Promise<string>+setFlowController(fn: (uiId: number, sessionId: string, resume: boolean) => void): void {this.flowController = fn}+ /** 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. */+ setResyncProvider(fn: (sessionId: string) => Promise<string>): void {+ this.resyncProvider = fn+ }+/** Key of one client's view of one session — the unit backpressure is tracked in. */private static flowKey(uiId: number, sessionId: string): string {return `${uiId} ${sessionId}`@@ -98,6 +125,8 @@ export class ServerPlatform implements CorePlatform {if (!sink) returnif (channel.startsWith(PTY_DATA_PREFIX)) {const sessionId = channel.slice(PTY_DATA_PREFIX.length)+ // Bounded memory: read the socket backlog BEFORE queueing more, so the ceiling can refuse.+ if (this.dropOrDesync(uiId, sessionId, sink.bufferedAmount?.() ?? 0)) returnsink.sendBinary(encodePtyData(sessionId, String(args[0] ?? '')))if (this.flowController) {const buffered = sink.bufferedAmount?.() ?? 0@@ -122,6 +151,45 @@ export class ServerPlatform implements CorePlatform {}}+ /**+ * 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+ * redraw hasn't landed yet), or because it just crossed WS_DROP_WATER.+ */+ 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)+ return true+ }+ if (buffered <= WS_DROP_WATER) return false+ this.desynced.add(key)+ // 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+ // would freeze forever. Hand the pause back here; the clients still being served decide alone.+ if (this.paused.delete(key)) this.flowController?.(uiId, sessionId, true)+ return true+ }++ /** Redraw one desynced client from tmux, then let it stream again. One capture, never a replay. */+ private async resync(uiId: number, sessionId: string): Promise<void> {+ const key = ServerPlatform.flowKey(uiId, sessionId)+ if (this.resyncing.has(key)) return+ this.resyncing.add(key)+ try {+ const screen = this.resyncProvider ? await this.resyncProvider(sessionId) : ''+ if (!this.sinks.has(uiId)) return // client left while the capture was in flight+ 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)+ }+ }+broadcast(channel: string, ...args: any[]): void {for (const uiId of this.sinks.keys()) this.sendTo(uiId, channel, ...args)}@@ -145,6 +213,9 @@ export class ServerPlatform implements CorePlatform {// returned by PtyManager.dropClient (wired to the same close hook in server/index.ts).const prefix = `${uiId} `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)}async dispatch(uiId: number, req: RpcRequest): Promise<RpcOk | RpcErr> {diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 94e46b57b..dd0208e8b 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -82,6 +82,10 @@ export const IPC = {/** The node was permanently destroyed by another client (payload: { by: ClientId }). The* remaining subscribers show a "closed by <name>" state instead of respawning the session. */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. */+ ptyResync: (sessionId: string) => `pty:resync:${sessionId}`,workspaceLoad: 'workspace:load',workspaceSave: 'workspace:save',workspaceProbeFolder: 'workspace:probe-folder',