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(pty): flow control is owed PER CLIENT — a drowning viewer can no longer be resumed behind its back
enes813c3c80f7c3
diff --git a/src/core/pty-coattach.test.ts b/src/core/pty-coattach.test.tsindex 2c0c379c6..643b32dc4 100644--- a/src/core/pty-coattach.test.ts+++ b/src/core/pty-coattach.test.ts@@ -49,6 +49,7 @@ vi.mock('node-pty', () => ({const ALICE = 1const BOB = 2+const CAROL = 3describe('terminal co-attach: one PTY, N subscribers', () => {let fake: FakePlatform@@ -79,6 +80,10 @@ describe('terminal co-attach: one PTY, N subscribers', () => {// pty:kill is sender-aware (it unsubscribes ONE client), so it lands in senderListeners.const kill = (clientId: number, sessionId: string) =>fake.senderListeners[IPC.ptyKill](clientId, sessionId)+ // pty:flow is sender-aware too: a pause is OWED by the client whose xterm backlog overflowed,+ // so it can only be returned by that client (or by its departure).+ const flow = (clientId: number, sessionId: string, resume: boolean) =>+ fake.senderListeners[IPC.ptyFlow](clientId, sessionId, resume)it('a second client on the same persistKey subscribes instead of spawning', async () => {await manager()@@ -192,33 +197,84 @@ describe('terminal co-attach: one PTY, N subscribers', () => {expect(spawned[0].killed).toBe(true)})- // ── Finding 1: a joiner must never inherit a PAUSED pty ────────────────────────────────- // Flow control is per-client in the renderer (xterm backlog > 1 MB → setFlow(false)) and its- // `paused` flag only clears when more data arrives. So a pty left paused by a client that- // vanished can never be resumed by a new one: it would show a blank, frozen terminal forever.- it('a client joining a PAUSED session resumes the pty (an empty backlog cannot resume it)', async () => {+ // ── Flow control is OWED PER CLIENT (`pausedBy`) ─────────────────────────────────────────+ // Two invariants, and a single `paused` boolean per session can only ever satisfy one of them:+ // (a) a pause owed by a client that LEFT is always returned → nobody is frozen forever;+ // (b) a pause owed by a client that is STILL HERE is never silently cancelled → its renderer's+ // write queue cannot grow without bound (its flow control is EDGE-latched: once it has+ // pumped `setFlow(false)` it will not re-pause, so a resume behind its back is permanent).+ it('a solo client pauses and resumes its own pty (single-user path unchanged)', async () => {await manager()const { sessionId } = await create(ALICE)- fake.listeners[IPC.ptyFlow](sessionId, false) // Alice's xterm backlog crossed the high water mark++ flow(ALICE, sessionId, false)+ expect(spawned[0].paused).toBe(true)+ flow(ALICE, sessionId, true)+ expect(spawned[0].paused).toBe(false)+ })++ it('a client joining a session PAUSED by a client that left resumes the pty', async () => {+ await manager()+ const { sessionId } = await create(ALICE)+ flow(ALICE, sessionId, false) // Alice's xterm backlog crossed the high water markexpect(spawned[0].paused).toBe(true)- // Alice's browser tab is gone (or reloaded): a new client co-attaches to the same node.- const bob = await create(BOB)- expect(bob.sessionId).toBe(sessionId)- expect(spawned[0].paused).toBe(false) // a joiner has an empty backlog by definition+ // Alice's tab is gone; her renderer reloads (same client id) and re-creates the node. Her new+ // page has an empty backlog, so it will never send the resume her old page owed us.+ const again = await create(ALICE)+ expect(again.sessionId).toBe(sessionId)+ expect(spawned[0].paused).toBe(false)})it('a departing client cannot leave the pty paused for the subscribers that stay', async () => {await manager()const { sessionId } = await create(ALICE)await create(BOB)- fake.listeners[IPC.ptyFlow](sessionId, false)+ flow(ALICE, sessionId, false)expect(spawned[0].paused).toBe(true)kill(ALICE, sessionId) // the client that paused it leavesexpect(spawned[0].paused).toBe(false) // Bob's terminal keeps streaming})+ it('a DIFFERENT client joining does NOT cancel a pause the drowning client still owes', async () => {+ await manager()+ const { sessionId } = await create(ALICE)+ flow(ALICE, sessionId, false) // Alice is 1 MB behind a `yes`-grade flood+ expect(spawned[0].paused).toBe(true)++ await create(BOB) // Bob opens the same node — Alice is still drowning+ expect(spawned[0].paused).toBe(true) // resuming here would grow Alice's queue without bound++ flow(ALICE, sessionId, true) // Alice drains → the last owed resume lands+ expect(spawned[0].paused).toBe(false)+ })++ it('a DIFFERENT client leaving does NOT cancel a pause the drowning client still owes', async () => {+ await manager()+ const { sessionId } = await create(ALICE)+ await create(BOB)+ flow(ALICE, sessionId, false)++ kill(BOB, sessionId) // Bob closes his tab; Alice is still behind+ expect(spawned[0].paused).toBe(true)+ expect(spawned[0].killed).toBe(false)+ })++ it('the pty resumes only when the LAST owed resume lands', async () => {+ await manager()+ const { sessionId } = await create(ALICE)+ await create(BOB)+ flow(ALICE, sessionId, false)+ flow(BOB, sessionId, false)+ expect(spawned[0].paused).toBe(true)++ flow(ALICE, sessionId, true)+ expect(spawned[0].paused).toBe(true) // Bob is still behind+ flow(BOB, sessionId, true)+ expect(spawned[0].paused).toBe(false)+ })+// ── Finding 2: a client that vanishes (WS close / destroyed webContents) is dropped ──────it('dropClient unsubscribes the client from EVERY session and releases the empty ones', async () => {const m = await manager()@@ -247,13 +303,23 @@ describe('terminal co-attach: one PTY, N subscribers', () => {const m = await manager()const { sessionId } = await create(ALICE)await create(BOB)- fake.listeners[IPC.ptyFlow](sessionId, false)+ flow(ALICE, sessionId, false)m.dropClient(ALICE)expect(spawned[0].paused).toBe(false)expect(spawned[0].killed).toBe(false)})+ it('dropClient leaves a pause another (still present) client owes in place', async () => {+ const m = await manager()+ const { sessionId } = await create(ALICE)+ await create(BOB)+ flow(ALICE, sessionId, false)++ m.dropClient(BOB) // Bob's tab vanished; Alice is still drowning+ expect(spawned[0].paused).toBe(true)+ })+it('dropClient leaves a relay-served (detached) pty alone', async () => {const m = await manager()const id = m.attachDetached('node-1', { onData: () => {}, onExit: () => {} })@@ -295,6 +361,23 @@ describe('terminal co-attach: one PTY, N subscribers', () => {expect(b.status).toBe('fulfilled')expect(spawned).toHaveLength(1) // Bob's create spawned after the failure cleared the entry})++ // TWO racers behind ONE failed spawn: the first survivor re-spawns, and the second must see+ // THAT spawn in `inflight` (the entry it awaited is long gone) instead of spawning again — a+ // second `tmux -A -D` would detach the first survivor's client, which is the very race the+ // in-flight guard exists to prevent.+ it('two creates racing a failed spawn resolve to ONE session, not two', async () => {+ await manager()+ failNextSpawn = true+ const [a, b, c] = await Promise.allSettled([create(ALICE), create(BOB), create(CAROL)])+ expect(a.status).toBe('rejected')+ expect(b.status).toBe('fulfilled')+ expect(c.status).toBe('fulfilled')+ expect(spawned).toHaveLength(1)+ const bId = b.status === 'fulfilled' ? b.value.sessionId : 'b'+ const cId = c.status === 'fulfilled' ? c.value.sessionId : 'c'+ expect(cId).toBe(bId)+ })})describe('size negotiation: smallest subscriber wins', () => {diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 68d5150a2..fd3906873 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -272,12 +272,23 @@ interface Session {sshRemote?: NonNullable<PtyCreateOptions['sshRemote']>/** Output arrived since the last scrollback snapshot — idle sessions skip the capture. */outputSinceSnapshot: boolean- /** True while the pty is paused by flow control (`setFlow(id,false)`). Tracked because the- * resume can otherwise be LOST: the renderer's flow control is per-client and only resumes- * when more data arrives, so a pty paused by a client that then vanished (tab closed) would- * stay paused forever — a co-attaching client would inherit a frozen, blank terminal it can- * never unfreeze. Every subscriber change re-checks it (join / leave / dropClient). */- paused: boolean+ /**+ * The clients that currently OWE us a resume: each has cast `pty:flow(sessionId,false)` because+ * ITS OWN xterm write-backlog crossed the high-water mark. The pty is paused while this set is+ * non-empty and resumes only when it becomes empty (`setFlow` / `releaseFlow`). `null` keys the+ * relay host's detached sink, which pauses on relay backpressure and has no ClientId.+ *+ * It has to be a SET, not a boolean, because both of these must hold at once:+ * (a) a pause owed by a client that LEFT is always returned (its renderer is gone and will+ * never send the matching resume — the co-attaching or remaining clients would stare at a+ * frozen, blank terminal forever). `kill` / `dropClient` / `join` return it.+ * (b) a pause owed by a client that is STILL HERE is never silently cancelled. That client's+ * flow control is EDGE-latched (`if (!paused && pending > HIGH_WATER)` in TerminalNode) —+ * once it has pumped the pause it will NOT re-pause, so resuming the pty behind its back is+ * permanent and its write queue then grows without bound for the rest of the flood.+ * A single boolean can only ever satisfy one of the two (it cannot tell the cases apart).+ */+ pausedBy: Set<ClientId | null>/** True when this node had an `accountId` but its config dir was gone at spawn, so we fell back* to the system account. `create()` surfaces it to the renderer (warning chip). */accountFallback?: boolean@@ -409,8 +420,14 @@ export class PtyManager {(senderId: number, sessionId: string, cols: number | null, rows: number | null) =>this.resize(senderId, sessionId, cols, rows))- platform().on(IPC.ptyFlow, (sessionId: string, resume: boolean) =>- this.setFlow(sessionId, resume)+ // Sender-aware: a pause belongs to the client whose xterm backlog overflowed, and only that+ // client (or its departure) can return it — see `Session.pausedBy`. Registered ONLY here:+ // `on` and `onWithSender` compose on the same channel, so a leftover plain listener would+ // run the flow change twice (and, with an unattributed sessionId, wrongly).+ platform().onWithSender(+ IPC.ptyFlow,+ (senderId: number, sessionId: string, resume: boolean) =>+ this.setFlow(senderId, sessionId, resume))// Sender-aware: with co-attach a kill detaches just THAT client, and the pty (and the tmux// session behind it) survives while any other subscriber is still watching.@@ -446,6 +463,12 @@ export class PtyManager {await inflight.catch(() => undefined) // the other spawn failed → fall through and try ourselvesconst late = this.join(clientId, options, key)if (late) return late+ // The spawn we awaited REJECTED, so there is no session to join. With two clients queued+ // behind that one failure, the first of them re-spawns — and the second must see THAT spawn+ // (published below, synchronously) rather than fall through and spawn a second tmux client,+ // whose `-D` would detach the first. Recurse: the in-flight guard is the barrier, so waiting+ // on a *new* in-flight entry is exactly the same wait as the one we just did.+ if (this.inflight.get(key)) return this.create(clientId, options)}const spawn = this.spawnNew(clientId, options)this.inflight.set(key, spawn)@@ -479,12 +502,12 @@ export class PtyManager {existing.sizes.set(clientId, size)existing.shown.set(clientId, size)this.applySize(existingId, existing)- // A joiner's backlog is empty by definition, so it will never issue the resume that a- // previous (now gone) client's flow control owed us — and no data would ever arrive to- // trigger one either. Resume here, or the new client stares at a frozen terminal forever.- // (Per-client backpressure is Task 5's job; this only guarantees a join never lands on a- // paused pty.)- this.resumeIfPaused(existing)+ // A (re)joining client's backlog is empty by definition, so its fresh page will never issue a+ // resume its PREVIOUS page owed us — a renderer reload keeps the same ClientId, so without this+ // the reloaded terminal would stay frozen forever with no data arriving to unstick it. Return+ // only THIS client's owed pause: a pause owed by a DIFFERENT client that is still here and+ // still drowning stays in place (invariant (b) on `pausedBy`).+ this.releaseFlow(existing, clientId)// KNOWN GAP — plain-shell (tmux disabled / unavailable) co-attach: `fresh:false` makes the// renderer skip the cold-restore scrollback replay, and with no tmux there is no client to// redraw the screen either, so this joiner sees a blank-but-live terminal until the next@@ -877,7 +900,7 @@ export class PtyManager {persistKey: persisted ? options.persistKey : undefined,sshRemote: remote,outputSinceSnapshot: true, // capture the initial screen on the first tick- paused: false,+ pausedBy: new Set<ClientId | null>(),accountFallback}if (persisted) this.ensureSnapshotTimer()@@ -971,32 +994,54 @@ export class PtyManager {}/**- * Flow control: the renderer pauses us when xterm's write backlog grows past a high- * watermark and resumes once it drains, so a flood can't grow the renderer buffer- * without bound. node-pty pause()/resume() stops/starts reading the pty fd; the OS- * pipe applies backpressure to the producing process.+ * Flow control: a client pauses us when ITS xterm write backlog grows past a high watermark and+ * resumes once it drains, so a flood can't grow that renderer's buffer without bound. node-pty+ * pause()/resume() stops/starts reading the pty fd; the OS pipe applies backpressure to the+ * producing process.+ *+ * Co-attach makes this per-client: there is ONE pty behind N subscribers, so it must be paused+ * while ANY subscriber is behind (the slowest viewer sets the pace — the alternative, dropping+ * output for the laggard, needs a per-client backlog and a redraw, which is Task 5) and resumed+ * only when the LAST owed resume lands. `pausedBy` is that ledger.+ *+ * `clientId` is null for the relay host's detached pty, whose sink pauses on relay backpressure+ * and returns the resume on drain — one more owner in the same ledger, no special casing.+ *+ * Single user: the set holds exactly his ClientId while paused and is empty when he resumes, so+ * the actuator sees exactly the pause/resume pair it always saw.*/- setFlow(sessionId: string, resume: boolean): void {+ setFlow(clientId: ClientId | null, sessionId: string, resume: boolean): void {const session = this.sessions.get(sessionId)if (!session) return- session.paused = !resume+ if (resume) {+ this.releaseFlow(session, clientId)+ return+ }+ const wasPaused = session.pausedBy.size > 0+ session.pausedBy.add(clientId)+ if (wasPaused) return // already paused by someone — pause() again would be a no-optry {- if (resume) session.proc.resume()- else session.proc.pause()+ session.proc.pause()} catch {- // pause/resume can throw if the proc already exited; ignore.+ // pause can throw if the proc already exited; ignore.}}- /** Resume a pty that flow control left paused. Called on every subscriber change, because a- * pause is owed a resume by the client that issued it — and that client may be gone. */- private resumeIfPaused(session: Session): void {- if (!session.paused) return- session.paused = false+ /**+ * Return the pause `clientId` owed us — because it resumed, or because it LEFT (kill /+ * dropClient) or reloaded (join). The pty resumes only when the ledger empties: a pause still+ * owed by a client that is here and behind must survive every other client's comings and goings,+ * or that client's renderer queue grows without bound (its flow control is edge-latched and will+ * never re-pause). No-op when this client owed nothing — the single-user resume path is then+ * exactly the old `paused=false; proc.resume()`.+ */+ private releaseFlow(session: Session, clientId: ClientId | null): void {+ if (!session.pausedBy.delete(clientId)) return+ if (session.pausedBy.size > 0) returntry {session.proc.resume()} catch {- // proc already exited; ignore.+ // resume can throw if the proc already exited; ignore.}}@@ -1064,14 +1109,14 @@ export class PtyManager {session.sizes.delete(clientId)session.shown.delete(clientId)}+ // The departing client (or sink) may have been one of the ones that paused us, and it will+ // never send the matching resume now — leaving that pause in place would freeze the terminal+ // for everyone who stayed. A pause owed by a client that is STILL here is untouched: the pty+ // stays paused until IT drains (its renderer cannot re-pause — see `Session.pausedBy`).+ this.releaseFlow(session, clientId)if (session.subscribers.size > 0 || session.onData) {// Somebody is still watching: the departing client's size no longer constrains the pty.this.applySize(sessionId, session)- // The departing client may have been the one that paused us (its xterm backlog was over- // the watermark) — and it will never send the matching resume now. Leaving the pause in- // place would freeze the terminal for everyone who stayed. Whoever is still behind will- // re-pause on their next high-water send.- this.resumeIfPaused(session)return}if (session.flushTimer) clearTimeout(session.flushTimer)@@ -1288,6 +1333,10 @@ export class PtyManager {}this.sessions.clear()this.byPersistKey.clear()+ // Clear the in-flight index with the other two, or a create still spawning at quit would leave+ // a promise (and the session it resolves to) reachable from a manager that has released+ // everything else — a later create would then co-attach to a session we already let go.+ this.inflight.clear()return Promise.all(finals).then(() => undefined)}diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.tsindex 9092cb2cf..046a4bf3a 100644--- a/src/main/remote/host-service.ts+++ b/src/main/remote/host-service.ts@@ -68,7 +68,9 @@ export interface HostPtyManager {cols: number | null,rows: number | null): void- setFlow(sessionId: string, resume: boolean): void+ /** `clientId` is null for a relay-served (detached) pty: the pause is owed by the host's sink,+ * which returns it on drain — see PtyManager.setFlow / Session.pausedBy. */+ setFlow(clientId: number | null, sessionId: string, resume: boolean): void/** `clientId` is null for a relay-served (detached) pty: the sinks ARE its only subscriber. */kill(clientId: number | null, sessionId: string): void}@@ -170,10 +172,10 @@ export function createHostHandlers(if (!ok && !stream.paused) {// Relay buffer is full — pause the PTY so the OS pipe backpressures the producer.stream.paused = true- pty.setFlow(stream.sessionId, false)+ pty.setFlow(null, stream.sessionId, false)} else if (ok && stream.paused) {stream.paused = false- pty.setFlow(stream.sessionId, true)+ pty.setFlow(null, stream.sessionId, true)}},onExit: (exitCode) => {diff --git a/src/server/backpressure.test.ts b/src/server/backpressure.test.tsindex 519f83399..3f3210fd8 100644--- a/src/server/backpressure.test.ts+++ b/src/server/backpressure.test.ts@@ -9,7 +9,7 @@ describe('ws backpressure', () => {it('pauses the session when buffered crosses the high-water mark and resumes below low', () => {const p = new ServerPlatform({ userDataDir: '/tmp', appVersion: '0' })const flow: Array<{ sid: string; resume: boolean }> = []- p.setFlowController((sid, resume) => flow.push({ sid, resume }))+ p.setFlowController((_uiId, sid, resume) => flow.push({ sid, resume }))let buffered = 0const ui = p.attach(sink(() => buffered))@@ -40,7 +40,7 @@ describe('ws backpressure', () => {// server must be able to re-pause — an edge-latched guard would silently latch OFF.const p = new ServerPlatform({ userDataDir: '/tmp', appVersion: '0' })const flow: Array<{ sid: string; resume: boolean }> = []- p.setFlowController((sid, resume) => flow.push({ sid, resume }))+ p.setFlowController((_uiId, sid, resume) => flow.push({ sid, resume }))const ui = p.attach(sink(() => 1_500_000)) // stays above high-waterp.sendTo(ui, 'pty:data:s1', 'chunk') // pause (rising edge)@@ -57,6 +57,54 @@ describe('ws backpressure', () => {])})+ // The pause must be ATTRIBUTED to the backed-up connection: PtyManager keeps a per-client ledger+ // (Session.pausedBy) and pauses the shared pty while ANY viewer owes a resume. Sending the pause+ // without a uiId would make it unattributable — and a pause the drowning browser still owes could+ // then be cancelled by another browser's join/leave (unbounded backlog on the drowning one).+ it('attributes the pause/resume to the ui whose socket is backed up', () => {+ 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 }))+ let aBuffered = 0+ const a = p.attach(sink(() => aBuffered))+ const b = p.attach(sink(() => 0)) // B keeps up++ aBuffered = 1_500_000+ p.sendTo(a, 'pty:data:s1', 'chunk')+ expect(flow).toEqual([{ uiId: a, sid: 's1', resume: false }])++ // B is keeping up, but B never paused: its send must NOT hand back the resume A owes. (With a+ // sessionId-keyed flag it would — and with the pty then paused for nobody, no data would ever+ // arrive for A to re-assert it. Attribution is what makes the pause survivable.)+ p.sendTo(b, 'pty:data:s1', 'chunk')+ expect(flow).toHaveLength(1)++ aBuffered = 0+ p.sendTo(a, 'pty:data:s1', 'chunk') // A drained → A returns its own pause+ expect(flow.at(-1)).toEqual({ uiId: a, sid: 's1', resume: true })+ })++ it('a disconnecting connection does not drop another one\'s pause flag', () => {+ 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 }))+ let aBuffered = 1_500_000+ const a = p.attach(sink(() => aBuffered))+ const b = p.attach(sink(() => 0))++ p.sendTo(a, 'pty:data:s1', 'chunk') // A is behind → paused+ p.detach(b) // B closes its tab+ expect(flow).toEqual([{ uiId: a, sid: 's1', resume: false }])++ // A's flag survived B's departure, so A's drain still fires exactly one resume.+ aBuffered = 0+ p.sendTo(a, 'pty:data:s1', 'chunk')+ expect(flow).toEqual([+ { uiId: a, sid: 's1', resume: false },+ { uiId: a, sid: 's1', resume: true }+ ])+ })+it('does no flow control when no controller is set (and non-pty channels are unaffected)', () => {const p = new ServerPlatform({ userDataDir: '/tmp', appVersion: '0' })const ui = p.attach(sink(() => 5_000_000))diff --git a/src/server/index.ts b/src/server/index.tsindex b473732f0..897e2bc1c 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -81,7 +81,12 @@ export async function startServer(// WS backpressure: when a connection's socket send buffer fills while streaming pty// output, pause that tmux client so the OS pipe applies real backpressure (resumes below// the low-water mark). See platform-server.ts sendTo.- platform.setFlowController((sid, resume) => ptyManager.setFlow(sid, resume))+ //+ // The pause is attributed to the UI whose socket is backed up (`uiId`), exactly like the pause+ // that UI's own renderer casts over `pty:flow` — so PtyManager's per-client ledger (Session+ // .pausedBy) returns it when that UI drains OR when it disconnects, and one backed-up browser+ // can no longer be un-paused by another browser's join/leave.+ platform.setFlowController((uiId, sid, resume) => ptyManager.setFlow(uiId, sid, resume))// 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.diff --git a/src/server/platform-server.test.ts b/src/server/platform-server.test.tsindex 44937ecb0..96cc3caf8 100644--- a/src/server/platform-server.test.ts+++ b/src/server/platform-server.test.ts@@ -121,19 +121,19 @@ describe('ServerPlatform', () => {expect(b.texts).toHaveLength(1)})- it('detach clears the backpressure paused map', () => {+ it("detach clears the departing connection's backpressure entries", () => {const p = new ServerPlatform({ userDataDir: '/tmp', appVersion: '0' })p.setFlowController(() => {})const ui = p.attach({ sendText: () => {}, sendBinary: () => {}, bufferedAmount: () => 2_000_000 })- p.sendTo(ui, 'pty:data:s1', 'x') // buffered > high → session s1 marked paused+ p.sendTo(ui, 'pty:data:s1', 'x') // buffered > high → (ui, s1) marked pausedp.detach(ui)- // After detach the paused entry is gone: a fresh attach + low-buffer send does not emit a- // spurious resume.+ // The entry is gone with the connection: a fresh attach + low-buffer send does not emit a+ // spurious resume for a pause the NEW connection never issued.const flow: Array<{ sid: string; resume: boolean }> = []- p.setFlowController((sid, resume) => flow.push({ sid, resume }))+ p.setFlowController((_uiId, sid, resume) => flow.push({ sid, resume }))const ui2 = p.attach({ sendText: () => {}, sendBinary: () => {}, bufferedAmount: () => 0 })p.sendTo(ui2, 'pty:data:s1', 'x')- expect(flow).toEqual([]) // not paused (map was cleared) → no resume fired+ expect(flow).toEqual([]) // ui2 owes nothing → no resume fired})it('exposes userDataDir/appVersion/isPackaged; openExternal rejects', async () => {diff --git a/src/server/platform-server.ts b/src/server/platform-server.tsindex 93c22eb0e..d89adfadf 100644--- a/src/server/platform-server.ts+++ b/src/server/platform-server.ts@@ -37,22 +37,32 @@ export class ServerPlatform implements CorePlatform {private sinks = new Map<number, UiSink>()private nextUiId = 1- // WS backpressure: per-session paused flag + the controller that pauses/resumes the pty.+ // WS backpressure: which (ui, session) streams this server has paused, + the controller that+ // pauses/resumes the pty.//- // Keyed by sessionId ALONE, which co-attach (one pty, N subscribers) has made too coarse: a- // session's pty:data now fans out to every subscribed ui, so this flag cannot express "behind- // for browser A, flowing for browser B", and `flowController` pauses the ONE pty behind the- // session for EVERYONE. Net effect today: one slow/backed-up browser pauses the shared pty for- // all viewers (bounded — the pause is re-asserted per high send and resumes below LOW_WATER,- // and PtyManager resumes on any subscriber change so nobody can be left frozen). Task 5 rekeys- // this to (uiId, sessionId) and decides the pty-side policy (pause when ANY viewer is behind).- private paused = new Map<string, boolean>()- private flowController?: (sessionId: string, resume: boolean) => void-- setFlowController(fn: (sessionId: string, resume: boolean) => void): void {+ // Both sides are per-CLIENT, and they have to be. Co-attach means one pty fans out to N+ // subscribers, so a pause has to say WHO is behind: PtyManager keeps a per-client ledger+ // (Session.pausedBy), pauses the shared pty while ANY viewer owes a resume, and resumes it only+ // when the last owed resume lands — or when the client that owed it disconnects (dropClient).+ // A `paused` flag keyed by sessionId alone cannot express "behind for browser A, flowing for+ // 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.+ private paused = new Set<string>()+ private flowController?: (uiId: number, sessionId: string, resume: boolean) => void++ setFlowController(fn: (uiId: number, sessionId: string, resume: boolean) => void): void {this.flowController = 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}`+ }+constructor(opts: { userDataDir: string; appVersion: string }) {this.userDataDir = opts.userDataDirthis.appVersion = opts.appVersion@@ -91,19 +101,20 @@ export class ServerPlatform implements CorePlatform {sink.sendBinary(encodePtyData(sessionId, String(args[0] ?? '')))if (this.flowController) {const buffered = sink.bufferedAmount?.() ?? 0- const isPaused = this.paused.get(sessionId) ?? false+ const key = ServerPlatform.flowKey(uiId, sessionId)+ const isPaused = this.paused.has(key)if (buffered > WS_HIGH_WATER) {- // Re-assert the pause on EVERY high send (not just the rising edge). The- // renderer's own xterm flow control drives the same setFlow actuator and may- // have resumed the pty underneath us; an edge-latched `!isPaused` guard would- // then never re-pause until the buffer drained to LOW. proc.pause() is- // idempotent, and this branch only runs when data actually arrived (the pty was- // running), so it self-limits — no spamming.- this.paused.set(sessionId, true)- this.flowController(sessionId, false)+ // Re-assert the pause on EVERY high send (not just the rising edge). This connection's+ // browser runs the SAME flow control on its xterm backlog and casts pty:flow under the+ // same uiId, so it may have handed back the pause underneath us; an edge-latched+ // `!isPaused` guard would then never re-pause until the buffer drained to LOW.+ // proc.pause() is idempotent, and this branch only runs when data actually arrived (the+ // pty was running), so it self-limits — no spamming.+ this.paused.add(key)+ this.flowController(uiId, sessionId, false)} else if (isPaused && buffered <= WS_LOW_WATER) {- this.paused.set(sessionId, false)- this.flowController(sessionId, true)+ this.paused.delete(key)+ this.flowController(uiId, sessionId, true)}}} else {@@ -127,23 +138,13 @@ export class ServerPlatform implements CorePlatform {detach(uiId: number): void {this.sinks.delete(uiId)- // KNOWN WRONG, and knowingly left so — do not read this as a design.- //- // This clears the backpressure flags of EVERY connection, not just the departing one. It was- // written when the Server Edition was single-UI ("every paused session belonged to the- // departing connection"), which team presence has made false: two browsers are now a normal- // configuration, and browser B disconnecting drops browser A's pause flags. The consequence is- // bounded — a session A had paused is treated as unpaused, so the next high-water send- // re-pauses it (sendTo re-asserts the pause on EVERY high send, not just the rising edge) —- // but until then A can take one burst it should not have.- //- // The real fix is not a smaller patch here: `paused` is keyed by sessionId ALONE, so it cannot- // represent "paused for A, flowing for B" at all, and neither can `flowController`, which- // pauses the ONE tmux client behind that session. Stage 2 rekeys the map to (clientId,- // sessionId) and decides the pty-side policy (pause when ANY viewer is behind); a half-fix here- // — e.g. only clearing this uiId's entries — would silently leak a stale pause into the next- // attach, which is worse than the over-clear.- this.paused.clear()+ // Drop only the DEPARTING connection's backpressure entries. (This used to clear the map for+ // every connection — harmless when the Server Edition was single-UI, wrong the moment two+ // browsers share a session, since it dropped the other one's flags.) Nothing leaks: uiIds are+ // monotonic, so a reconnect is a new key, and the pty-side pause this connection owed is+ // 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)}async dispatch(uiId: number, req: RpcRequest): Promise<RpcOk | RpcErr> {diff --git a/test/remote/host-handlers.test.ts b/test/remote/host-handlers.test.tsindex 98004d66d..256b29217 100644--- a/test/remote/host-handlers.test.ts+++ b/test/remote/host-handlers.test.ts@@ -36,7 +36,9 @@ function fakePty() {write: (sessionId, data) => calls.push({ method: 'write', args: [sessionId, data] }),resize: (clientId, sessionId, cols, rows) =>calls.push({ method: 'resize', args: [clientId, sessionId, cols, rows] }),- setFlow: (sessionId, resume) => calls.push({ method: 'setFlow', args: [sessionId, resume] }),+ // A relay-served (detached) pty has no ClientId: its pause is owed by the host's sink (null).+ setFlow: (clientId, sessionId, resume) =>+ calls.push({ method: 'setFlow', args: [clientId, sessionId, resume] }),// Relay-served ptys are killed with clientId null (they have no UI subscribers).kill: (clientId, sessionId) => calls.push({ method: 'kill', args: [clientId, sessionId] })}@@ -196,12 +198,12 @@ describe('createHostHandlers', () => {await openViaAttach(h)pty.sinks().onData('a') // send fails → pause- expect(pty.calls).toContainEqual({ method: 'setFlow', args: ['pty-1', false] })+ expect(pty.calls).toContainEqual({ method: 'setFlow', args: [null, 'pty-1', false] })// Flip the socket to succeed, then deliver more output → resume.sock.socket.sendFrame = vi.fn(() => true)pty.sinks().onData('b')- expect(pty.calls).toContainEqual({ method: 'setFlow', args: ['pty-1', true] })+ expect(pty.calls).toContainEqual({ method: 'setFlow', args: [null, 'pty-1', true] })})it('rejects unknown RPC methods', () => {