Skip to content

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.

fix(pty): socket backpressure owes its own pause ticket (never cancels the renderer's)

enesdcec37461c97
diff --git a/src/core/pty-coattach.test.ts b/src/core/pty-coattach.test.ts
index a72262506..458a785b1 100644
--- a/src/core/pty-coattach.test.ts
+++ b/src/core/pty-coattach.test.ts
@@ -284,6 +284,87 @@ describe('terminal co-attach: one PTY, N subscribers', () => {
expect(spawned[0].paused).toBe(false)
})
+ // ── One client, TWO pause owners (Server Edition) ────────────────────────────────────────
+ // On the Server Edition a single uiId has two INDEPENDENT reasons to pause the same session:
+ // its browser's own xterm backlog (`pty:flow` cast → owner 'renderer') and the server's WS
+ // send-buffer backpressure (ServerPlatform → owner 'socket'). They drain at different times
+ // (the socket empties as fast as the browser reads bytes; xterm parses them far slower), so a
+ // ledger keyed by ClientId alone would let one hand back the other's pause — and the renderer's
+ // flow control is EDGE-latched, so a resume behind its back is permanent (invariant (b)).
+ it('a socket drain does NOT release the pause that client\'s RENDERER still owes', async () => {
+ const m = await manager()
+ const { sessionId } = await create(ALICE)
+
+ flow(ALICE, sessionId, false) // Alice's xterm is 1 MB behind the flood
+ m.setFlow(ALICE, sessionId, false, 'socket') // ...and her WS socket is backed up too
+ expect(spawned[0].paused).toBe(true)
+
+ m.setFlow(ALICE, sessionId, true, 'socket') // the socket drains into her browser
+ expect(spawned[0].paused).toBe(true) // her xterm is STILL drowning — must stay paused
+
+ flow(ALICE, sessionId, true) // her renderer finally drains
+ expect(spawned[0].paused).toBe(false)
+ })
+
+ it('a socket-owed pause IS released when only the socket owed it', async () => {
+ const m = await manager()
+ const { sessionId } = await create(ALICE)
+
+ m.setFlow(ALICE, sessionId, false, 'socket') // her renderer never paused (slow link, small xterm backlog)
+ expect(spawned[0].paused).toBe(true)
+
+ m.setFlow(ALICE, sessionId, true, 'socket')
+ expect(spawned[0].paused).toBe(false)
+ })
+
+ it('a renderer resume does NOT release the pause that client\'s SOCKET still owes', async () => {
+ const m = await manager()
+ const { sessionId } = await create(ALICE)
+
+ m.setFlow(ALICE, sessionId, false, 'socket')
+ flow(ALICE, sessionId, true) // a stray/late renderer resume — the socket is still jammed
+ expect(spawned[0].paused).toBe(true)
+ })
+
+ it('a client that disconnects owing BOTH kinds of pause returns both', async () => {
+ const m = await manager()
+ const { sessionId } = await create(ALICE)
+ await create(BOB) // Bob stays: the pty must keep streaming for him
+
+ flow(ALICE, sessionId, false)
+ m.setFlow(ALICE, sessionId, false, 'socket')
+ expect(spawned[0].paused).toBe(true)
+
+ m.dropClient(ALICE) // her tab vanished — neither pause can ever be returned by her
+ expect(spawned[0].paused).toBe(false) // invariant (a): nobody is frozen forever
+ expect(spawned[0].killed).toBe(false)
+ })
+
+ it('a client that KILLS a session while owing BOTH kinds of pause returns both', async () => {
+ const m = await manager()
+ const { sessionId } = await create(ALICE)
+ await create(BOB)
+
+ flow(ALICE, sessionId, false)
+ m.setFlow(ALICE, sessionId, false, 'socket')
+ kill(ALICE, sessionId) // Alice unmounts the node; she gets no more output for it
+ expect(spawned[0].paused).toBe(false)
+ expect(spawned[0].killed).toBe(false)
+ })
+
+ it('one client\'s socket drain leaves ANOTHER client\'s socket pause in place', async () => {
+ const m = await manager()
+ const { sessionId } = await create(ALICE)
+ await create(BOB)
+
+ m.setFlow(ALICE, sessionId, false, 'socket')
+ m.setFlow(BOB, sessionId, false, 'socket')
+ m.setFlow(ALICE, sessionId, true, 'socket')
+ expect(spawned[0].paused).toBe(true) // Bob's socket is still jammed
+ m.setFlow(BOB, sessionId, true, 'socket')
+ 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()
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 92472ecca..7b2626c1b 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -230,6 +230,32 @@ export async function findInLoginPath(bin: string): Promise<string | null> {
/** A UI client: an Electron webContents id or a ServerPlatform uiId. */
type ClientId = number
+/**
+ * WHO, within one client, owes us a resume (see `Session.pausedBy`).
+ *
+ * One client can be behind in TWO independent places, and only on the Server Edition does the
+ * second one exist:
+ * - `renderer` — its xterm write-backlog crossed the high-water mark and it cast `pty:flow`.
+ * This is the ONLY owner on the desktop, and it is EDGE-latched (TerminalNode: `if (!paused &&
+ * pending > HIGH_WATER)`) — once it has pumped its pause it will not re-pause.
+ * - `socket` — the server's own WS send buffer for that connection crossed WS_HIGH_WATER
+ * (`ServerPlatform.sendTo`), which is a different queue with a different drain time: the socket
+ * empties as fast as the browser READS bytes, while the renderer's backlog empties only as fast
+ * as xterm PARSES them.
+ * They must be separate ledger entries: keyed by ClientId alone they collapse into one, and the
+ * socket's drain (the sweep) would hand back the pause the renderer still owes — permanently,
+ * because the renderer cannot re-pause. That is invariant (b) on `pausedBy`.
+ */
+export type FlowOwner = 'renderer' | 'socket'
+/** All the owners one client can owe a pause under — the sweep on any leave path. */
+const FLOW_OWNERS: readonly FlowOwner[] = ['renderer', 'socket']
+
+/** The ledger key for one (client, owner) pause. `null` is the relay host's detached sink, which
+ * has no ClientId; it pauses on relay backpressure, i.e. as a `renderer`-side owner. */
+function flowTicket(clientId: ClientId | null, owner: FlowOwner): string {
+ return `${owner}#${clientId ?? 'relay'}`
+}
+
/** One client's reported fit, run through the same floor/clamp the pty itself gets, so a size we
* record for a client is comparable with the effective size we compute from all of them. */
function normalizeSize(cols: number, rows: number): PtySize {
@@ -288,22 +314,27 @@ interface Session {
/** Output arrived since the last scrollback snapshot — idle sessions skip the capture. */
outputSinceSnapshot: 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.
+ * The (client, owner) pairs that currently OWE us a resume — a ledger of FLOW TICKETS
+ * (`flowTicket`), not of clients. The pty is paused while this set is non-empty and resumes only
+ * when it becomes empty (`setFlow` / `releaseFlow`).
*
* 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.
+ * frozen, blank terminal forever). `kill` / `dropClient` / `join` return it — and `kill` /
+ * `dropClient` return EVERY owner's ticket for that client, not just the renderer's.
* (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).
+ *
+ * And the tickets are keyed by (client, OWNER), not by client, because a Server-Edition client
+ * has two independent pause owners with two different drain times (see `FlowOwner`): keyed by
+ * ClientId alone, the socket's drain would silently cancel the renderer's pause and break (b) —
+ * deterministically, for the whole rest of a flood.
*/
- pausedBy: Set<ClientId | null>
+ pausedBy: Set<string>
/** 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
@@ -739,9 +770,11 @@ export class PtyManager {
// 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)
+ // only THIS client's RENDERER pause: a pause owed by a DIFFERENT client that is still here and
+ // still drowning stays in place, and so does this client's own SOCKET pause — a fresh page says
+ // nothing about the state of the WS send buffer under it (invariant (b) on `pausedBy`), and the
+ // server returns that one itself when the socket drains.
+ this.releaseFlow(existing, clientId, 'renderer')
const base: PtyCreateResult = existing.accountFallback
? { sessionId: existingId, fresh: false, accountFallback: true }
: { sessionId: existingId, fresh: false }
@@ -1134,7 +1167,7 @@ export class PtyManager {
persistKey: persisted ? options.persistKey : undefined,
sshRemote: remote,
outputSinceSnapshot: true, // capture the initial screen on the first tick
- pausedBy: new Set<ClientId | null>(),
+ pausedBy: new Set<string>(),
accountFallback
}
if (persisted) this.ensureSnapshotTimer()
@@ -1293,18 +1326,29 @@ export class PtyManager {
* `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.
+ * `owner` says WHICH of the client's two queues is behind (see `FlowOwner`). It defaults to
+ * `renderer` — the only owner that exists on the desktop and over the relay — so the Server
+ * Edition's socket backpressure is the one caller that passes anything (`src/server/index.ts`).
+ * A socket drain then returns the SOCKET's ticket only, never the pause the browser's own xterm
+ * still owes.
+ *
+ * Single user: the set holds exactly his one renderer ticket while paused and is empty when he
+ * resumes, so the actuator sees exactly the pause/resume pair it always saw.
*/
- setFlow(clientId: ClientId | null, sessionId: string, resume: boolean): void {
+ setFlow(
+ clientId: ClientId | null,
+ sessionId: string,
+ resume: boolean,
+ owner: FlowOwner = 'renderer'
+ ): void {
const session = this.sessions.get(sessionId)
if (!session) return
if (resume) {
- this.releaseFlow(session, clientId)
+ this.releaseFlow(session, clientId, owner)
return
}
const wasPaused = session.pausedBy.size > 0
- session.pausedBy.add(clientId)
+ session.pausedBy.add(flowTicket(clientId, owner))
if (wasPaused) return // already paused by someone — pause() again would be a no-op
try {
session.proc.pause()
@@ -1314,15 +1358,26 @@ export class PtyManager {
}
/**
- * Return the pause `clientId` owed us — because it resumed, or because it LEFT (kill /
+ * Return a 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()`.
+ *
+ * `owner` scopes WHICH of that client's tickets is returned:
+ * - a drain returns exactly the one that drained (invariant (b)): the socket emptying says
+ * nothing about the browser's xterm backlog, and vice versa;
+ * - omitting it returns ALL of them, which is what a client's DEPARTURE means (invariant (a)):
+ * it receives nothing more on this session, so no owner of its can ever resume us again.
*/
- private releaseFlow(session: Session, clientId: ClientId | null): void {
- if (!session.pausedBy.delete(clientId)) return
+ private releaseFlow(session: Session, clientId: ClientId | null, owner?: FlowOwner): void {
+ const owners = owner ? [owner] : FLOW_OWNERS
+ let released = false
+ for (const o of owners) {
+ if (session.pausedBy.delete(flowTicket(clientId, o))) released = true
+ }
+ if (!released) return
if (session.pausedBy.size > 0) return
try {
session.proc.resume()
@@ -1331,6 +1386,11 @@ export class PtyManager {
}
}
+ /** Does this client owe a resume on this session under ANY owner? (dropClient's sweep gate.) */
+ private owesFlow(session: Session, clientId: ClientId | null): boolean {
+ return FLOW_OWNERS.some((o) => session.pausedBy.has(flowTicket(clientId, o)))
+ }
+
/**
* Input from ONE client into the (possibly shared) session.
*
@@ -1428,8 +1488,10 @@ export class PtyManager {
}
// 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`).
+ // for everyone who stayed. EVERY owner it owed goes back (no `owner` argument): it stops
+ // receiving this session's output entirely, so neither its renderer nor its socket can ever
+ // resume us again. 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.
@@ -1475,7 +1537,9 @@ export class PtyManager {
// the gate.
const hadSize = session.sizes.delete(clientId)
const hadShown = session.shown.delete(clientId)
- if (!hadSize && !hadShown && !session.pausedBy.has(clientId)) continue
+ if (!hadSize && !hadShown && !this.owesFlow(session, clientId)) continue
+ // Every owner's ticket, not just the renderer's: a vanished client's SOCKET pause is as
+ // unreturnable as its renderer's (invariant (a) — the pty would freeze for every co-viewer).
this.releaseFlow(session, clientId)
this.applySize(sessionId, session)
}
diff --git a/src/server/backpressure.test.ts b/src/server/backpressure.test.ts
index 3eddea291..17fd88959 100644
--- a/src/server/backpressure.test.ts
+++ b/src/server/backpressure.test.ts
@@ -34,6 +34,38 @@ describe('ws backpressure', () => {
])
})
+ it('books every pause/resume under the SOCKET owner, never the renderer\'s', () => {
+ // The whole point of the owner tag: this connection's browser casts its OWN pty:flow pauses
+ // under the same uiId, from a different queue (its xterm backlog) that drains at a different
+ // time. If the socket's pauses shared that ledger ticket, the drain below — and the sweep —
+ // would hand back a pause the renderer still owes, and the renderer is edge-latched: it would
+ // never re-pause. So EVERY call this class makes must carry 'socket'.
+ const p = new ServerPlatform({ userDataDir: '/tmp', appVersion: '0' })
+ const flow: Array<{ resume: boolean; owner: string }> = []
+ p.setFlowController((_uiId, _sid, resume, owner) => flow.push({ resume, owner }))
+ let buffered = 1_500_000
+ const ui = p.attach(sink(() => buffered))
+
+ p.sendTo(ui, 'pty:data:s1', 'chunk') // pause
+ buffered = 100_000
+ p.sendTo(ui, 'pty:data:s1', 'chunk') // drain → resume
+ expect(flow).toEqual([
+ { resume: false, owner: 'socket' },
+ { resume: true, owner: 'socket' }
+ ])
+
+ // ...and so must the one the drop-and-redraw ceiling hands back.
+ flow.length = 0
+ buffered = 1_500_000
+ p.sendTo(ui, 'pty:data:s1', 'chunk') // over high-water: pause again
+ buffered = 9_000_000
+ p.sendTo(ui, 'pty:data:s1', 'chunk') // over WS_DROP_WATER: desync → hand the pause back
+ expect(flow).toEqual([
+ { resume: false, owner: 'socket' },
+ { resume: true, owner: 'socket' }
+ ])
+ })
+
it('re-asserts pause on every high send so a renderer-side resume cannot latch it off', () => {
// The renderer's own xterm flow control drives the SAME ptyManager.setFlow actuator.
// If it resumes the pty underneath us while the socket buffer is still full, the
diff --git a/src/server/index.ts b/src/server/index.ts
index cfd89c69e..4b53c904f 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -82,11 +82,19 @@ export async function startServer(
// output, pause that tmux client so the OS pipe applies real backpressure (resumes below
// the low-water mark). See platform-server.ts sendTo.
//
- // 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))
+ // The pause is attributed to the UI whose socket is backed up (`uiId`) — so PtyManager's 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.
+ //
+ // It is booked under the 'socket' OWNER, not the same ticket as the pause that UI's own renderer
+ // casts over `pty:flow`. The two queues are different and drain at different times — the socket
+ // empties as fast as the browser reads bytes, the renderer's xterm backlog only as fast as it
+ // parses them — so sharing one ticket would let the socket's drain (sweepPaused) hand back the
+ // pause the renderer still owes. The renderer's flow control is edge-latched and would never
+ // re-pause: its backlog would then grow at network speed for the rest of the flood.
+ platform.setFlowController((uiId, sid, resume, owner) =>
+ ptyManager.setFlow(uiId, sid, resume, owner)
+ )
// 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.
diff --git a/src/server/platform-server.ts b/src/server/platform-server.ts
index e4517f07a..c92b33f6c 100644
--- a/src/server/platform-server.ts
+++ b/src/server/platform-server.ts
@@ -1,4 +1,5 @@
import type { CorePlatform } from '../core/platform'
+import type { FlowOwner } from '../core/pty-manager'
import { IPC } from '../shared/ipc'
import {
E_NO_HANDLER,
@@ -84,7 +85,17 @@ export class ServerPlatform implements CorePlatform {
// 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
+ private flowController?: (
+ uiId: number,
+ sessionId: string,
+ resume: boolean,
+ owner: FlowOwner
+ ) => void
+ /** Every pause this class books is owed by the SOCKET, never by the browser's xterm — a separate
+ * owner in PtyManager's ledger, because the two queues drain at different times and must not
+ * cancel each other (see `Session.pausedBy` / `FlowOwner`). Passed on every call so the tag is
+ * type-enforced at this seam and cannot be dropped by the wiring in index.ts. */
+ private static readonly OWNER: FlowOwner = 'socket'
/**
* The (client, session) pairs whose backlog we discarded; each gets a tmux redraw once its
@@ -109,7 +120,9 @@ export class ServerPlatform implements CorePlatform {
private sweepTimer?: ReturnType<typeof setInterval>
private resyncProvider?: (sessionId: string) => Promise<string>
- setFlowController(fn: (uiId: number, sessionId: string, resume: boolean) => void): void {
+ setFlowController(
+ fn: (uiId: number, sessionId: string, resume: boolean, owner: FlowOwner) => void
+ ): void {
this.flowController = fn
}
@@ -169,12 +182,13 @@ export class ServerPlatform implements CorePlatform {
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). 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.
+ // Re-assert the pause on EVERY high send (not just the rising edge), so this set can
+ // never disagree with the pty-side ledger about a pause we still owe. It is booked under
+ // the 'socket' owner there (see server/index.ts), i.e. a DIFFERENT ticket from the one
+ // this connection's browser casts over pty:flow for its own xterm backlog — the two
+ // queues drain at different times and must not cancel each other. 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)
// A flood that ENDS is the normal case, and the resume check below only runs when the
// NEXT chunk for this session is sent. If this is the last chunk, nothing else would ever
@@ -182,10 +196,10 @@ export class ServerPlatform implements CorePlatform {
// full pipe — and with co-attach that freezes the terminal for EVERY viewer. So the same
// drain sweep the desync path uses watches the socket for us (see sweepDesynced).
this.armSweep()
- this.flowController(uiId, sessionId, false)
+ this.flowController(uiId, sessionId, false, ServerPlatform.OWNER)
} else if (isPaused && buffered <= WS_LOW_WATER) {
this.paused.delete(key)
- this.flowController(uiId, sessionId, true)
+ this.flowController(uiId, sessionId, true, ServerPlatform.OWNER)
}
}
} else {
@@ -232,7 +246,7 @@ export class ServerPlatform implements CorePlatform {
// 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)
+ if (this.paused.delete(key)) this.flowController?.(uiId, sessionId, true, ServerPlatform.OWNER)
return true
}
@@ -351,7 +365,7 @@ export class ServerPlatform implements CorePlatform {
}
if ((sink.bufferedAmount?.() ?? 0) > WS_LOW_WATER) continue
this.paused.delete(key)
- this.flowController(uiId, key.slice(sep + 1), true)
+ this.flowController(uiId, key.slice(sep + 1), true, ServerPlatform.OWNER)
}
}