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(peer): isolate each sink send so one dead relay peer can't break the fan-out

enes193c3995a5ec
diff --git a/src/core/ui-sink-registry.test.ts b/src/core/ui-sink-registry.test.ts
index c3a537558..823ae3813 100644
--- a/src/core/ui-sink-registry.test.ts
+++ b/src/core/ui-sink-registry.test.ts
@@ -72,3 +72,107 @@ describe('UiSinkRegistry', () => {
expect(() => r.sendTo(9, 'pty:data:s1', 'y')).not.toThrow() // gone → silent no-op
})
})
+
+/**
+ * A sink that THROWS is a dead connection, and one dead connection must never take the fan-out
+ * (or the emitter behind it — presenceHub.emit / the canvas reflector) down with it: with the sends
+ * unisolated, peer B's half-closed relay socket would stop peer C from ever seeing the presence
+ * diff, and blow up the HOST's own emit.
+ */
+describe('UiSinkRegistry — a throwing sink is contained', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ it('a sink whose sendText throws neither unwinds nor starves the other sinks', () => {
+ const r = new UiSinkRegistry()
+ const good = sink()
+ r.register(1, { sendText: () => { throw new Error('EPIPE') }, sendBinary: () => {} })
+ r.register(2, good.ui)
+ // The fan-out every broadcast does (ServerPlatform.broadcast / electronPlatform.broadcast).
+ expect(() => {
+ for (const id of r.ids()) r.sendTo(id, 'presence:peer', { op: 'join' })
+ }).not.toThrow()
+ expect(JSON.parse(good.texts[0]!)).toEqual({
+ t: 'ev',
+ channel: 'presence:peer',
+ args: [{ op: 'join' }]
+ })
+ expect(warn).toHaveBeenCalled() // never silent
+ })
+
+ it('a sink whose sendBinary throws neither unwinds nor starves the other sinks', () => {
+ const r = new UiSinkRegistry()
+ const good = sink()
+ r.register(1, { sendText: () => {}, sendBinary: () => { throw new Error('EPIPE') } })
+ r.register(2, good.ui)
+ expect(() => {
+ for (const id of r.ids()) r.sendTo(id, 'pty:data:s1', 'hello')
+ }).not.toThrow()
+ expect(decodePtyData(good.bins[0]!)).toEqual({ sessionId: 's1', data: 'hello' })
+ })
+
+ it('a sink that keeps throwing is treated as GONE: evicted, handler run, iteration safe', () => {
+ const r = new UiSinkRegistry()
+ const goneIds: number[] = []
+ r.setSinkGoneHandler((id) => goneIds.push(id))
+ const good = sink()
+ r.register(1, { sendText: () => { throw new Error('EPIPE') }, sendBinary: () => {} })
+ r.register(2, good.ui)
+ // Two fan-outs over the SAME ids() snapshot: the eviction happens mid-iteration (the dead sink
+ // is dropped from the Map while the loop is still walking it), and the healthy sink behind it
+ // must still be served on both passes.
+ for (let i = 0; i < 2; i++) for (const id of r.ids()) r.sendTo(id, 'presence:peer', { i })
+ expect(goneIds).toEqual([1]) // exactly once, the dead one
+ expect(r.has(1)).toBe(false)
+ expect(r.has(2)).toBe(true)
+ expect(good.texts).toHaveLength(2)
+ // Gone means gone: no further send is even attempted at it (and it cannot be evicted twice).
+ r.sendTo(1, 'presence:peer', { i: 9 })
+ expect(goneIds).toEqual([1])
+ })
+
+ it('a TRANSIENT throw never evicts a healthy sink', () => {
+ const r = new UiSinkRegistry()
+ const goneIds: number[] = []
+ r.setSinkGoneHandler((id) => goneIds.push(id))
+ let blip = true
+ const texts: string[] = []
+ r.register(1, {
+ sendText: (j) => {
+ if (blip) {
+ blip = false
+ throw new Error('transient')
+ }
+ texts.push(j)
+ },
+ sendBinary: () => {}
+ })
+ r.sendTo(1, 'presence:peer', { n: 1 }) // throws once…
+ r.sendTo(1, 'presence:peer', { n: 2 }) // …and the sink recovers: the strike is reset
+ r.sendTo(1, 'presence:peer', { n: 3 })
+ r.sendTo(1, 'presence:peer', { n: 4 })
+ expect(goneIds).toEqual([])
+ expect(r.has(1)).toBe(true)
+ expect(texts).toHaveLength(3)
+ })
+
+ it('with no gone-handler wired, a dead sink still evicts itself (no state left behind)', () => {
+ vi.useFakeTimers()
+ try {
+ const r = new UiSinkRegistry()
+ r.setFlowController(() => {})
+ r.register(9, {
+ sendText: () => { throw new Error('EPIPE') },
+ sendBinary: () => {},
+ bufferedAmount: () => 1_500_000
+ })
+ r.sendTo(9, 'pty:data:s1', 'x') // jammed socket → pause booked, drain sweep armed
+ expect(vi.getTimerCount()).toBeGreaterThan(0)
+ r.sendTo(9, 'presence:peer', {})
+ r.sendTo(9, 'presence:peer', {}) // second consecutive throw → gone
+ expect(r.has(9)).toBe(false)
+ expect(vi.getTimerCount()).toBe(0) // …and no sweep timer outlives it
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+})
diff --git a/src/core/ui-sink-registry.ts b/src/core/ui-sink-registry.ts
index 8cb15921a..fd40ced43 100644
--- a/src/core/ui-sink-registry.ts
+++ b/src/core/ui-sink-registry.ts
@@ -47,6 +47,23 @@ 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
+/**
+ * How many CONSECUTIVE throwing sends make a sink DEAD (any successful send resets the count).
+ *
+ * A sink is a socket write. `ws.send` does not throw synchronously on a dead socket — which is why
+ * an unisolated send was survivable in the Server Edition — but a relay connection's sink CAN
+ * (writing to a half-closed stream throws ERR_STREAM_WRITE_AFTER_END / EPIPE), and that is a strong
+ * signal the connection is gone. Gone is exactly what the shell's teardown (presence leave,
+ * PtyManager.dropClient, unregister) is for, so we run it rather than shouting into a dead socket
+ * forever.
+ *
+ * Why not on the FIRST throw: a transient failure from a sink that is otherwise healthy would then
+ * kick a live teammate out of the session (dropping their pty subscriptions and their facepile
+ * entry). Two consecutive throws, across two separate sends, cannot be a blip. The real close hook
+ * (`unregisterPeerSink` / ws 'close') still evicts a dead peer on its own; this is the safety net
+ * for the case where it never fires.
+ */
+const SINK_FAILURE_LIMIT = 2
/** One (client, session) whose backlog we discarded, and when its redraw may next be attempted. */
type Desync = { attempts: number; nextAttemptAt: number }
@@ -108,6 +125,10 @@ export class UiSinkRegistry {
/** Armed only while `desynced` is non-empty (see RESYNC_SWEEP_MS). */
private sweepTimer?: ReturnType<typeof setInterval>
private resyncProvider?: (sessionId: string) => Promise<string>
+ /** Consecutive throwing sends per sink (see SINK_FAILURE_LIMIT). Only ever touched on the failure
+ * path — a healthy fan-out reads `size` and nothing else. */
+ private failures = new Map<number, number>()
+ private onSinkGone?: (id: number) => void
register(id: number, sink: UiSink): void {
this.sinks.set(id, sink)
@@ -117,11 +138,24 @@ export class UiSinkRegistry {
return this.sinks.has(id)
}
+ /** How many sinks are registered. The zero-peer fast path a shell's `broadcast` checks BEFORE
+ * calling `ids()`, so a solo desktop user allocates no array per broadcast. */
+ get size(): number {
+ return this.sinks.size
+ }
+
/** Every registered sink, in registration order (Map preserves insertion order). */
ids(): number[] {
return [...this.sinks.keys()]
}
+ /** The shell's full teardown for a sink that has proven dead (== what its socket-close handler
+ * runs: presence leave + PtyManager.dropClient + unregister). Unset means the registry only
+ * evicts its own state — see `noteSinkFailure`. */
+ setSinkGoneHandler(fn: (id: number) => void): void {
+ this.onSinkGone = fn
+ }
+
setFlowController(
fn: (uiId: number, sessionId: string, resume: boolean, owner: FlowOwner) => void
): void {
@@ -146,6 +180,7 @@ export class UiSinkRegistry {
* connection owed is returned by PtyManager.dropClient (wired to the same close hook). */
unregister(id: number): void {
this.sinks.delete(id)
+ this.failures.delete(id)
const prefix = `${id} `
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
@@ -161,7 +196,10 @@ export class UiSinkRegistry {
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)) return
- sink.sendBinary(encodePtyData(sessionId, String(args[0] ?? '')))
+ // A throwing sink must not unwind into the pty read loop, and a sink we could not write to
+ // tells us nothing about its socket backlog — so the flow-control block below is skipped.
+ if (!this.deliver(uiId, () => sink.sendBinary(encodePtyData(sessionId, String(args[0] ?? '')))))
+ return
if (this.flowController) {
const buffered = sink.bufferedAmount?.() ?? 0
const key = UiSinkRegistry.flowKey(uiId, sessionId)
@@ -198,10 +236,50 @@ export class UiSinkRegistry {
)
if (deadPrefix)
this.forgetFlowState(UiSinkRegistry.flowKey(uiId, channel.slice(deadPrefix.length)))
- sink.sendText(JSON.stringify({ t: 'ev', channel, args }))
+ this.deliver(uiId, () => sink.sendText(JSON.stringify({ t: 'ev', channel, args })))
}
}
+ /**
+ * The ONLY place a sink is written to. One bad sink must affect nothing but itself: a throw here
+ * would otherwise unwind out of the caller's fan-out loop (`broadcast`) — so the peers AFTER it
+ * never get the message — and on out of the EMITTER behind it (presenceHub.emit, the canvas-sync
+ * reflector), i.e. one peer's dead socket would freeze the HOST's own facepile and stop its canvas
+ * reflecting. Returns whether the write landed.
+ */
+ private deliver(uiId: number, write: () => void): boolean {
+ try {
+ write()
+ } catch (err) {
+ this.noteSinkFailure(uiId, err)
+ return false
+ }
+ // Healthy path: one Map.size read (the map is empty unless something has actually thrown).
+ if (this.failures.size) this.failures.delete(uiId)
+ return true
+ }
+
+ /** Book a strike against a sink that threw; past SINK_FAILURE_LIMIT consecutive ones it is dead. */
+ private noteSinkFailure(uiId: number, err: unknown): void {
+ const strikes = (this.failures.get(uiId) ?? 0) + 1
+ this.failures.set(uiId, strikes)
+ // Shell-neutral prefix: this runs in the Server Edition AND in the desktop shell (relay peers).
+ console.warn(
+ `[ui-sink] send to client ${uiId} threw (${strikes}/${SINK_FAILURE_LIMIT})`,
+ err instanceof Error ? err.message : String(err)
+ )
+ if (strikes < SINK_FAILURE_LIMIT) return
+ // Dead. Drop the sink FIRST, for two reasons:
+ // - re-entrancy: the teardown below broadcasts (a presence `leave` diff fans out to every
+ // client), which would come straight back through sendTo into this same dying sink;
+ // - iteration safety: callers fan out over the `ids()` SNAPSHOT (an array), so removing this
+ // entry cannot disturb their loop — a later `sendTo` for an evicted id is simply a miss.
+ this.sinks.delete(uiId)
+ this.failures.delete(uiId)
+ if (this.onSinkGone) this.onSinkGone(uiId) // full teardown (leave + dropClient + unregister)
+ else this.unregister(uiId) // nothing wired: at least leave none of OUR state behind
+ }
+
/** 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. */
diff --git a/src/main/peer-registry.test.ts b/src/main/peer-registry.test.ts
index 7a7fe08ce..2f6e6f7e1 100644
--- a/src/main/peer-registry.test.ts
+++ b/src/main/peer-registry.test.ts
@@ -127,6 +127,43 @@ describe('peer sink registry', () => {
expect(peerRegistry().has(id)).toBe(false) // sink + flow/desync bookkeeping cleared
})
+ it('a peer whose sink keeps throwing is torn down like a closed socket, and only IT is', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ vi.useFakeTimers()
+ const platform = fakePlatformWithPeers({ sent: [] })
+ const deadId = allocateRelayClientId()
+ const liveId = allocateRelayClientId()
+ const live = fakeSink()
+ registerPeerSink(deadId, {
+ sendText: () => {
+ throw new Error('EPIPE: relay socket half-closed')
+ },
+ sendBinary: () => {},
+ bufferedAmount: () => 0
+ })
+ registerPeerSink(liveId, live.sink)
+
+ // The hub's own emit fans out to every client: the dead sink throws on each of them, and must
+ // never unwind into presenceHub (that is the HOST's facepile freezing over a third peer's dead
+ // socket). Its strikes run out here and it is evicted mid-fan-out; the live peer keeps working.
+ expect(() => {
+ presenceHub.join(deadId, 'phone')
+ presenceHub.join(liveId, 'phone')
+ platform.broadcast(IPC.canvasMut, { seq: 1 })
+ platform.broadcast(IPC.canvasMut, { seq: 2 })
+ }).not.toThrow()
+
+ // The full unregisterPeerSink teardown ran for the dead peer, and only for it:
+ expect(presenceHub.peers().some((p) => p.clientId === deadId)).toBe(false) // no ghost peer
+ expect(gone).toEqual([deadId]) // PtyManager.dropClient — no leaked pty subscription
+ expect(peerRegistry().has(deadId)).toBe(false)
+ expect(vi.getTimerCount()).toBe(0) // no leaked sweep timer
+ expect(peerRegistry().has(liveId)).toBe(true)
+ expect(live.text.filter((m) => m.channel === IPC.canvasMut)).toHaveLength(2)
+ expect(warn).toHaveBeenCalled()
+ warn.mockRestore()
+ })
+
it('teardown leaves no pause owed and no live sweep timer behind', () => {
vi.useFakeTimers()
const platform = fakePlatformWithPeers({ sent: [] })
diff --git a/src/main/peer-registry.ts b/src/main/peer-registry.ts
index 497ff5e45..f0b6b80b6 100644
--- a/src/main/peer-registry.ts
+++ b/src/main/peer-registry.ts
@@ -26,6 +26,13 @@ export type { UiSink }
const registry = new UiSinkRegistry()
let onPeerGone: ((id: number) => void) | null = null
+/** A peer sink that keeps THROWING is a dead connection (a half-closed relay socket), and the
+ * registry hands it back here rather than shouting into it forever: a dead peer needs precisely
+ * the teardown a closed socket gets. Registered at module scope so it holds even if `wirePeerRegistry`
+ * never ran — the teardown then still leaves the hub and the sink set clean (only `onPeerGone`
+ * warns). */
+registry.setSinkGoneHandler((id) => unregisterPeerSink(id))
+
export function peerRegistry(): UiSinkRegistry {
return registry
}
@@ -51,7 +58,16 @@ export function registerPeerSink(id: number, sink: UiSink): void {
*/
export function unregisterPeerSink(id: number): void {
presenceHub.leave(id)
- onPeerGone?.(id)
+ if (onPeerGone) onPeerGone(id)
+ // Never silent: an optional call would turn "the boot wiring regressed" into a no-op, and the
+ // damage (step 2 above: the pty layer never hears this subscriber left) is invisible until a
+ // shared terminal is frozen for every other viewer, with nothing pointing back at the cause.
+ else
+ console.warn(
+ `[peer-registry] peer ${id} left, but wirePeerRegistry() was never called: PtyManager.dropClient` +
+ ' did NOT run, so its pty subscriptions (and any pause it owed) leak — a shared terminal can' +
+ ' stay frozen for every other viewer. This is a boot-wiring bug in src/main/index.ts.'
+ )
registry.unregister(id)
}
diff --git a/src/main/platform-electron.test.ts b/src/main/platform-electron.test.ts
index 2bbc5cb01..74e21206f 100644
--- a/src/main/platform-electron.test.ts
+++ b/src/main/platform-electron.test.ts
@@ -161,6 +161,35 @@ describe('electronPlatform + relay peers', () => {
})
})
+ it('one peer whose sink throws does not starve the other peers, the window, or the emitter', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const p = electronPlatform()
+ h.clientIds = [1]
+ const dead: UiSink = {
+ sendText: () => {
+ throw new Error('EPIPE: relay socket half-closed')
+ },
+ sendBinary: () => {},
+ bufferedAmount: () => 0
+ }
+ const alive = peerSink()
+ registerPeerSink(PEER, dead)
+ registerPeerSink(PEER + 1, alive.sink)
+
+ // The exact 4c failure: a presence diff / canvas mutation fans out while peer B's socket is
+ // dead. It must not unwind out of broadcast (that would blow up presenceHub.emit / the canvas
+ // reflector on the HOST) and peer C must still be served.
+ expect(() => p.broadcast('presence:peer', { op: 'join' })).not.toThrow()
+ expect(h.sent).toContainEqual({ channel: 'presence:peer', args: [{ op: 'join' }] })
+ expect(JSON.parse(alive.text[0]!)).toEqual({
+ t: 'ev',
+ channel: 'presence:peer',
+ args: [{ op: 'join' }]
+ })
+ expect(warn).toHaveBeenCalled()
+ warn.mockRestore()
+ })
+
it('is BIT-IDENTICAL to the webContents-only path with no peer registered (merge gate)', () => {
const p = electronPlatform()
h.clientIds = [5]
diff --git a/src/main/platform-electron.ts b/src/main/platform-electron.ts
index 693f07fda..bc6eea4f4 100644
--- a/src/main/platform-electron.ts
+++ b/src/main/platform-electron.ts
@@ -47,7 +47,22 @@ export function electronPlatform(): CorePlatform {
// …plus every relay peer. Not optional: presence diffs (presence:peer) and canvas mutations
// fan out via broadcast, so a peer that only received sendTo would still see nothing.
const peers = peerRegistry()
- for (const id of peers.ids()) peers.sendTo(id, ch, ...args)
+ if (peers.size === 0) return // solo desktop: no ids() array, no loop — allocation-free
+ for (const id of peers.ids()) {
+ // One peer must never break the fan-out. UiSinkRegistry.sendTo already contains a throwing
+ // SINK (and evicts a dead one), so this only catches the rest of the path — the flow
+ // controller it may call into. Either way the invariant is the same: an exception here
+ // would skip every peer after this one AND unwind into the emitter (presenceHub.emit, the
+ // canvas reflector), freezing the HOST's own presence/canvas over someone else's socket.
+ try {
+ peers.sendTo(id, ch, ...args)
+ } catch (err) {
+ console.warn(
+ `[peer] broadcast of ${ch} to peer ${id} failed`,
+ err instanceof Error ? err.message : String(err)
+ )
+ }
+ }
},
clientIds: () => [...mainWindowClientIds(), ...peerRegistry().ids()],
openExternal: (url) => shell.openExternal(url),
diff --git a/src/server/platform-server.ts b/src/server/platform-server.ts
index 714d28e09..92043a7b8 100644
--- a/src/server/platform-server.ts
+++ b/src/server/platform-server.ts
@@ -71,11 +71,19 @@ export class ServerPlatform implements CorePlatform {
this.registry.setResyncProvider(fn)
}
+ /** What to run for a connection whose sink has proven DEAD (it threw on consecutive sends): the
+ * same teardown its 'close' runs — presence leave + PtyManager.dropClient + detach. Wired in
+ * ws.ts, which owns that teardown. */
+ setSinkGoneHandler(fn: (uiId: number) => void): void {
+ this.registry.setSinkGoneHandler(fn)
+ }
+
sendTo(uiId: number, channel: string, ...args: any[]): void {
this.registry.sendTo(uiId, channel, ...args)
}
broadcast(channel: string, ...args: any[]): void {
+ if (this.registry.size === 0) return // no connection: no ids() array, no loop
for (const uiId of this.registry.ids()) this.registry.sendTo(uiId, channel, ...args)
}
diff --git a/src/server/ws.ts b/src/server/ws.ts
index 825a593eb..e7612792b 100644
--- a/src/server/ws.ts
+++ b/src/server/ws.ts
@@ -94,6 +94,24 @@ export function attachWsServer(server: http.Server, opts: WsServerOpts): void {
const { platform, auth, onClientGone, heartbeatMs = WS_HEARTBEAT_MS } = opts
const wss = new WebSocketServer({ noServer: true, maxPayload: WS_MAX_PAYLOAD })
+ // The one teardown for a connection that is GONE — whether by a clean 'close', or because its sink
+ // proved dead (the registry evicted it after consecutive throwing sends and called this back).
+ // Order matches 'close': leave the hub, hand the pty layer its subscriber back, detach the sink.
+ // Idempotent, so a sink-gone eviction that races the real 'close' is harmless.
+ const teardown = (uiId: number): void => {
+ presenceHub.leave(uiId)
+ // This client is a pty subscriber, and nothing else would ever tell PtyManager it is gone (a
+ // closed tab sends no `pty:kill`). Leaving it subscribed leaks the pty client, skips the
+ // detach-time scrollback snapshot, and can strand a session it had paused — a client joining
+ // that node later would inherit a frozen pty.
+ onClientGone?.(uiId)
+ platform.detach(uiId)
+ }
+ // `ws.send` does not throw synchronously on a dead socket, so this rarely fires server-side — but
+ // if a sink ever does throw consecutively, treat it exactly like a close rather than shouting into
+ // a dead socket forever (the registry already dropped the sink before calling back).
+ platform.setSinkGoneHandler(teardown)
+
// Liveness heartbeat. Node enables no TCP keepalive on an upgraded socket, so a browser that
// simply VANISHES (laptop asleep, wifi dropped, NAT idle-reap) leaves a half-open socket: no FIN
// ever arrives, 'close' never fires, and the peer would sit in the presence hub — a ghost cursor
@@ -180,14 +198,6 @@ export function attachWsServer(server: http.Server, opts: WsServerOpts): void {
console.warn('[nodeterm-server] ws socket error', (e && e.code) || e)
})
- ws.on('close', () => {
- presenceHub.leave(uiId)
- // Before detaching the sink: this client is a pty subscriber, and nothing else would ever
- // tell PtyManager it is gone (a closed tab sends no `pty:kill`). Leaving it subscribed
- // leaks the pty client, skips the detach-time scrollback snapshot, and can strand a
- // session it had paused — a client joining that node later would inherit a frozen pty.
- onClientGone?.(uiId)
- platform.detach(uiId)
- })
+ ws.on('close', () => teardown(uiId))
})
}