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.

feat(core): quiet and self-paced clients — no broadcast, no pause ticket, still watching

review8fdc952a695d
diff --git a/src/core/platform-fake.ts b/src/core/platform-fake.ts
index b5b121432..ca97bff9d 100644
--- a/src/core/platform-fake.ts
+++ b/src/core/platform-fake.ts
@@ -47,6 +47,8 @@ export interface FakePlatform extends CorePlatform {
opened: string[]
/** Attached UI ids returned by clientIds() — tests push/splice this directly. */
clients: number[]
+ /** Quiet client ids returned by quietClientIds() (a live link's viewer) — same, push directly. */
+ quietClients: number[]
}
/**
@@ -90,6 +92,7 @@ export function fakePlatform(overrides: Partial<CorePlatform> = {}): FakePlatfor
sent: [],
opened: [],
clients: [],
+ quietClients: [],
handle(ch, fn) {
f.handlers[ch] = fn
},
@@ -109,6 +112,7 @@ export function fakePlatform(overrides: Partial<CorePlatform> = {}): FakePlatfor
f.sent.push({ to: 'broadcast', channel, args })
},
clientIds: () => f.clients,
+ quietClientIds: () => f.quietClients,
async openExternal(url) {
f.opened.push(url)
},
diff --git a/src/core/platform.ts b/src/core/platform.ts
index 8fe2823f6..924444d84 100644
--- a/src/core/platform.ts
+++ b/src/core/platform.ts
@@ -43,6 +43,10 @@ export interface CorePlatform {
* Electron: the main window, or none while it is closed). Lets a service address "everyone
* EXCEPT the sender", which broadcast() cannot express — see src/core/canvas-sync.ts. */
clientIds(): number[]
+ /** Clients that receive NO broadcast and are absent from `clientIds()` (a live link's viewer),
+ * but still count as watching a session they subscribe to. Only the pty reaper reads it
+ * (pty-reap.ts `liveClientIds`). Absent = there are none. */
+ quietClientIds?(): number[]
/**
* Is this attached UI the machine's OWNER — this app's own window (Electron), or a browser tab the
* Server Edition authenticated with its session cookie — as opposed to a relay peer (a teammate, a
diff --git a/src/core/pty-idle-reap.test.ts b/src/core/pty-idle-reap.test.ts
index f68380f27..4c0407099 100644
--- a/src/core/pty-idle-reap.test.ts
+++ b/src/core/pty-idle-reap.test.ts
@@ -178,6 +178,20 @@ describe('idle reap of unwatched client PTYs', () => {
expect(spawned[0].killed).toBe(false)
})
+ it('never reaps a session whose only subscriber is a QUIET client (a live link viewer)', async () => {
+ // A quiet client is absent from clientIds() by design (it receives no broadcast), so a sweep
+ // that asked clientIds() alone would release the pty under the viewer, and releaseClient sends
+ // that viewer no event at all: the link would go dead with nothing on either screen.
+ const WATCHER = 1_000_042
+ fake.quietClients.push(WATCHER)
+ await tmuxManager()
+ await create(WATCHER)
+
+ idle(REAP_IDLE_MS * 10)
+
+ expect(spawned[0].killed).toBe(false)
+ })
+
it('never reaps before the threshold', async () => {
await tmuxManager()
await create(ALICE)
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 8e8876451..c9f28ec79 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -69,7 +69,7 @@ import {
spawnFailureHint,
type PtyDevices
} from './pty-devices'
-import { REAP_SWEEP_MS, shouldReap } from './pty-reap'
+import { REAP_SWEEP_MS, liveClientIds, shouldReap } from './pty-reap'
import { ControlModeClient, type ControlSpawn } from './tmux-control-client'
import {
TMUX_SOCKET,
@@ -1131,14 +1131,15 @@ export class PtyManager {
* and its scrollback are untouched: this is the SAME detach the last subscriber's departure does,
* and the next `pty:create` re-attaches to it. Read pty-reap.ts before changing any of it.
*
- * "Attached" is decided against `platform().clientIds()`, not against the subscriber set: the
- * whole point is the subscriber whose window/tab/peer is GONE and which therefore can never send
+ * "Attached" is decided against the platform's live clients (`clientIds()` plus the quiet ones a
+ * live link's viewer attaches as — pty-reap.ts `liveClientIds`), not against the subscriber set:
+ * the whole point is the subscriber whose window/tab/peer is GONE and which therefore can never send
* the `pty:kill` that would release the pty. A client id is never reused (Electron webContents
* ids and the server's `nextUiId` both only go up), so a client that comes back comes back as a
* new id and creates its sessions afresh — there is no returning client to strand.
*/
private reapTick(): void {
- const live = new Set(platform().clientIds())
+ const live = liveClientIds(platform())
const now = Date.now()
for (const [sessionId, session] of [...this.sessions]) {
// A relay sink is a watcher (somebody's phone is mirroring this session); a parked terminal
@@ -1211,9 +1212,9 @@ export class PtyManager {
* outstanding (see `shadowCommand`). This method never rejects; failure is always null.
*
* WHAT A SHADOW IS NOT: not a subscriber, not a `Session`, not a renderer client id. Nothing in
- * this process that decides "is somebody watching" can see it — the reap sweep asks
- * `platform().clientIds()` and walks `this.sessions`, and the renderer's park and offscreen
- * dispose are per-node renderer state.
+ * this process that decides "is somebody watching" can see it — the reap sweep asks the
+ * platform's live clients (`liveClientIds`) and walks `this.sessions`, and the renderer's park
+ * and offscreen dispose are per-node renderer state.
*
* It IS a real tmux client, so anything that asks TMUX "is this session attached" does see it,
* and must subtract it. There is one such consumer: the session budget (session-budget.ts) culls
diff --git a/src/core/pty-reap.test.ts b/src/core/pty-reap.test.ts
index 936948a52..184182ea2 100644
--- a/src/core/pty-reap.test.ts
+++ b/src/core/pty-reap.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { REAP_IDLE_MS, shouldReap, type ReapCandidate } from './pty-reap'
+import { REAP_IDLE_MS, liveClientIds, shouldReap, type ReapCandidate } from './pty-reap'
/**
* The reap decision, in one place, so the three things it must never do can be pinned without a
@@ -48,3 +48,10 @@ describe('shouldReap', () => {
expect(shouldReap(candidate({ watched: true, unwatchedSince: 0 }), 365 * 86_400_000)).toBe(false)
})
})
+
+describe('liveClientIds', () => {
+ it('counts quiet clients as watchers', () => {
+ expect(liveClientIds({ clientIds: () => [1], quietClientIds: () => [9] })).toEqual(new Set([1, 9]))
+ expect(liveClientIds({ clientIds: () => [1] })).toEqual(new Set([1]))
+ })
+})
diff --git a/src/core/pty-reap.ts b/src/core/pty-reap.ts
index a17a55838..09e57783b 100644
--- a/src/core/pty-reap.ts
+++ b/src/core/pty-reap.ts
@@ -1,3 +1,5 @@
+import type { CorePlatform } from './platform'
+
/**
* IDLE REAP: give pty devices back to the OS without killing anybody's work.
*
@@ -57,6 +59,17 @@ export interface ReapCandidate {
unwatchedSince: number | null
}
+/**
+ * Every client that counts as watching: the ordinary ones and the QUIET ones (a live link's
+ * viewer). A quiet client is absent from `clientIds()` by design — it receives no broadcast — so
+ * without it here a session only a viewer holds would be released after the idle window, and
+ * `releaseClient` sends that viewer no event at all: the link goes dead with nothing on either
+ * screen saying so.
+ */
+export function liveClientIds(p: Pick<CorePlatform, 'clientIds' | 'quietClientIds'>): Set<number> {
+ return new Set([...p.clientIds(), ...(p.quietClientIds?.() ?? [])])
+}
+
/** Pure: may this session's client pty be released now? */
export function shouldReap(c: ReapCandidate, now: number, idleMs = REAP_IDLE_MS): boolean {
if (!c.tmuxBacked || c.watched || c.unwatchedSince === null) return false
diff --git a/src/core/ui-sink-registry.ts b/src/core/ui-sink-registry.ts
index 78caa6e8f..56da044e4 100644
--- a/src/core/ui-sink-registry.ts
+++ b/src/core/ui-sink-registry.ts
@@ -22,6 +22,19 @@ const PTY_CLOSED_PREFIX = 'pty:closed:'
/** A recycled session id is dead too (the node respawns under a NEW session id), so its
* backpressure bookkeeping must be pruned exactly like an exited/closed one. */
const PTY_RECYCLED_PREFIX = 'pty:recycled:'
+/** How the registry treats one client. Both default to the historical behaviour.
+ * - `quiet`: never enumerated for a broadcast (`broadcastIds`) — reachable by an addressed
+ * `sendTo` only. A live link's viewer is one: canvas ops, presence and agent status are not
+ * its business. `ids()` still lists it, and `quietIds()` names it, because the pty reaper must
+ * count it as watching (pty-reap.ts `liveClientIds`).
+ * - `selfPaced`: the sink paces itself. The registry takes no pause ticket for it (a stranger's
+ * slow socket must never freeze the owner's terminal) and never drops or resyncs its output
+ * (the watcher's stream filter must see every frame — src/core/watch-link/watcher-policy.ts). */
+export interface SinkOptions {
+ quiet?: boolean
+ selfPaced?: boolean
+}
+
/** Watermarks match the renderer terminal's own flow control. */
const WS_HIGH_WATER = 1_000_000
const WS_LOW_WATER = 256_000
@@ -90,6 +103,9 @@ type Desync = { attempts: number; nextAttemptAt: number }
*/
export class UiSinkRegistry {
private sinks = new Map<number, UiSink>()
+ /** Only the clients registered with an option set; empty for every client of today, so the
+ * hot paths (`broadcastIds`, `sendTo`) pay one `size` read or one map miss. */
+ private options = new Map<number, SinkOptions>()
private paused = new Set<string>()
private flowController?: (
uiId: number,
@@ -130,25 +146,44 @@ export class UiSinkRegistry {
private failures = new Map<number, number>()
private onSinkGone?: (id: number) => void
- register(id: number, sink: UiSink): void {
+ register(id: number, sink: UiSink, opts: SinkOptions = {}): void {
this.sinks.set(id, sink)
+ // A copy, so a caller mutating its options object later cannot change how this sink is served.
+ if (opts.quiet || opts.selfPaced)
+ this.options.set(id, { quiet: !!opts.quiet, selfPaced: !!opts.selfPaced })
+ else this.options.delete(id)
}
has(id: number): boolean {
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. */
+ /** How many sinks are registered (quiet ones included). The zero-peer fast path a shell's
+ * `broadcast` checks BEFORE calling `broadcastIds()`, 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). */
+ /** Every registered sink, quiet ones included, in registration order (Map preserves insertion
+ * order). A fan-out wants `broadcastIds()`. */
ids(): number[] {
return [...this.sinks.keys()]
}
+ /** The sinks a broadcast reaches: every one but the quiet ones, in registration order. */
+ broadcastIds(): number[] {
+ if (this.options.size === 0) return this.ids()
+ return this.ids().filter((id) => !this.options.get(id)?.quiet)
+ }
+
+ /** The quiet sinks, in registration order. Nothing is ever broadcast to them, but they are live
+ * clients: the pty reaper counts them as watching (pty-reap.ts `liveClientIds`). */
+ quietIds(): number[] {
+ if (this.options.size === 0) return []
+ return this.ids().filter((id) => this.options.get(id)?.quiet)
+ }
+
/** 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`. */
@@ -181,6 +216,7 @@ export class UiSinkRegistry {
unregister(id: number): void {
this.sinks.delete(id)
this.failures.delete(id)
+ this.options.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
@@ -194,6 +230,13 @@ export class UiSinkRegistry {
if (!sink) return
if (channel.startsWith(PTY_DATA_PREFIX)) {
const sessionId = channel.slice(PTY_DATA_PREFIX.length)
+ // A self-paced sink is handed every frame and nothing else: no drop, so no desync and no
+ // resync (the only way into either is `dropOrDesync`), and no pause ticket. It keeps its own
+ // parser in step with the pty and does its own drop-and-redraw (watcher-policy.ts).
+ if (this.options.get(uiId)?.selfPaced) {
+ this.deliver(uiId, () => sink.sendBinary(encodePtyData(sessionId, String(args[0] ?? ''))))
+ return
+ }
// Bounded memory: read the socket backlog BEFORE queueing more, so the ceiling can refuse.
if (this.dropOrDesync(uiId, sessionId, sink.bufferedAmount?.() ?? 0)) return
// A throwing sink must not unwind into the pty read loop, and a sink we could not write to
@@ -276,6 +319,7 @@ export class UiSinkRegistry {
// entry cannot disturb their loop — a later `sendTo` for an evicted id is simply a miss.
this.sinks.delete(uiId)
this.failures.delete(uiId)
+ this.options.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
}
diff --git a/src/core/ui-sink-registry.watcher.test.ts b/src/core/ui-sink-registry.watcher.test.ts
new file mode 100644
index 000000000..b2b75e9d4
--- /dev/null
+++ b/src/core/ui-sink-registry.watcher.test.ts
@@ -0,0 +1,130 @@
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { UiSinkRegistry, type UiSink } from './ui-sink-registry'
+import { IPC } from '../shared/ipc'
+
+const sink = (buffered = 0): UiSink & { bin: number; text: number } => {
+ const s = { bin: 0, text: 0, sendText: () => { s.text++ }, sendBinary: () => { s.bin++ }, bufferedAmount: () => buffered }
+ return s
+}
+
+describe('quiet and self-paced clients', () => {
+ it('a quiet client is in ids() and quietIds() but not broadcastIds()', () => {
+ const r = new UiSinkRegistry()
+ r.register(1, sink())
+ r.register(2, sink(), { quiet: true })
+ expect(r.ids()).toEqual([1, 2])
+ expect(r.broadcastIds()).toEqual([1])
+ expect(r.quietIds()).toEqual([2])
+ r.unregister(2)
+ expect(r.quietIds()).toEqual([])
+ })
+
+ it('a self-paced client is never paused, dropped or resynced by the registry', () => {
+ const r = new UiSinkRegistry()
+ const flow = vi.fn()
+ const resync = vi.fn(async () => 'SCREEN')
+ r.setFlowController(flow)
+ r.setResyncProvider(resync)
+ const s = sink(50_000_000)
+ r.register(7, s, { selfPaced: true })
+ for (let i = 0; i < 5; i++) r.sendTo(7, IPC.ptyData('s1'), 'x')
+ expect(s.bin).toBe(5)
+ expect(flow).not.toHaveBeenCalled()
+ expect(resync).not.toHaveBeenCalled()
+ })
+
+ it('an ordinary client past the high water still takes a pause ticket', () => {
+ const r = new UiSinkRegistry()
+ const flow = vi.fn()
+ r.setFlowController(flow)
+ r.register(8, sink(2_000_000))
+ r.sendTo(8, IPC.ptyData('s1'), 'x')
+ expect(flow).toHaveBeenCalledWith(8, 's1', false, 'socket')
+ })
+})
+
+/**
+ * The test above holds the socket at 50 MB, and at a backlog that never drains the registry would
+ * never resync ANY client — so it proves "never paused, never dropped" but says nothing about the
+ * resync. This walks the full drop-and-redraw cycle (high water → drop ceiling → drained → the
+ * drain sweep), which an ordinary client completes with a `pty:resync`; a self-paced client must
+ * come out of it with every frame delivered and no resync. The resync it would get is the
+ * registry's default capture, which is history on the SSH and session-host paths
+ * (src/core/watch-link/watcher-policy.ts refuses it as the second layer).
+ */
+describe('the full drop-and-redraw cycle', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ async function cycle(opts?: { selfPaced?: boolean }) {
+ vi.useFakeTimers()
+ const r = new UiSinkRegistry()
+ const flow = vi.fn()
+ const resync = vi.fn(async () => 'SCREEN')
+ r.setFlowController(flow)
+ r.setResyncProvider(resync)
+ let buffered = 2_000_000
+ const texts: string[] = []
+ let bins = 0
+ r.register(
+ 7,
+ { sendText: (j) => texts.push(j), sendBinary: () => { bins++ }, bufferedAmount: () => buffered },
+ opts
+ )
+ r.sendTo(7, IPC.ptyData('s1'), 'a') // past the high water
+ buffered = 50_000_000
+ r.sendTo(7, IPC.ptyData('s1'), 'b') // past the drop ceiling
+ r.sendTo(7, IPC.ptyData('s1'), 'c') // still backed up
+ buffered = 0
+ r.sendTo(7, IPC.ptyData('s1'), 'd') // drained
+ await vi.advanceTimersByTimeAsync(2_000) // several drain sweeps
+ const resyncs = texts.filter((j) => JSON.parse(j).channel === IPC.ptyResync('s1'))
+ r.unregister(7)
+ return { flow, resync, bins, resyncs }
+ }
+
+ it('an ordinary client is paused, dropped and resynced by it (the cycle reaches resync)', async () => {
+ const c = await cycle()
+ expect(c.flow).toHaveBeenCalledWith(7, 's1', false, 'socket')
+ expect(c.bins).toBe(1) // b, c and d were dropped
+ expect(c.resync).toHaveBeenCalledWith('s1')
+ expect(c.resyncs).toHaveLength(1)
+ })
+
+ it('a self-paced client comes out of it with every frame and no pause, drop or resync', async () => {
+ const c = await cycle({ selfPaced: true })
+ expect(c.flow).not.toHaveBeenCalled()
+ expect(c.bins).toBe(4)
+ expect(c.resync).not.toHaveBeenCalled()
+ expect(c.resyncs).toEqual([])
+ })
+
+ it('a client registered with no options keeps the historical behaviour', async () => {
+ const c = await cycle({})
+ expect(c.flow).toHaveBeenCalled()
+ expect(c.bins).toBe(1)
+ expect(c.resync).toHaveBeenCalled()
+ })
+})
+
+describe('sink options follow the sink', () => {
+ it('re-registering an id without options clears them', () => {
+ const r = new UiSinkRegistry()
+ r.register(3, sink(), { quiet: true })
+ r.register(3, sink())
+ expect(r.quietIds()).toEqual([])
+ expect(r.broadcastIds()).toEqual([3])
+ })
+
+ it('a quiet sink evicted for throwing is no longer listed anywhere', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const r = new UiSinkRegistry()
+ r.register(4, { sendText: () => { throw new Error('gone') }, sendBinary: () => {} }, { quiet: true })
+ r.sendTo(4, 'watch:meta', {})
+ r.sendTo(4, 'watch:meta', {})
+ expect(r.ids()).toEqual([])
+ expect(r.quietIds()).toEqual([])
+ warn.mockRestore()
+ })
+})
diff --git a/src/main/peer-registry.test.ts b/src/main/peer-registry.test.ts
index 6c1af3978..e1c279f9e 100644
--- a/src/main/peer-registry.test.ts
+++ b/src/main/peer-registry.test.ts
@@ -52,9 +52,10 @@ function fakePlatformWithPeers(wc: { sent: Array<{ id: number; channel: string;
},
broadcast: (ch, ...args) => {
for (const id of wcIds) wc.sent.push({ id, channel: ch, args })
- for (const id of peerRegistry().ids()) peerRegistry().sendTo(id, ch, ...args)
+ for (const id of peerRegistry().broadcastIds()) peerRegistry().sendTo(id, ch, ...args)
},
- clientIds: () => [...wcIds, ...peerRegistry().ids()],
+ clientIds: () => [...wcIds, ...peerRegistry().broadcastIds()],
+ quietClientIds: () => peerRegistry().quietIds(),
openExternal: async () => {}
}
initPlatform(p)
@@ -189,4 +190,11 @@ describe('peer sink registry', () => {
vi.advanceTimersByTime(5_000)
expect(flow).toEqual([[id, 'nt-a', false, 'socket']])
})
+
+ it('passes sink options through to the registry', () => {
+ registerPeerSink(4242, { sendText: () => {}, sendBinary: () => {} }, { quiet: true })
+ expect(peerRegistry().quietIds()).toContain(4242)
+ expect(peerRegistry().broadcastIds()).not.toContain(4242)
+ peerRegistry().unregister(4242)
+ })
})
diff --git a/src/main/peer-registry.ts b/src/main/peer-registry.ts
index f0b6b80b6..f53f9ed8e 100644
--- a/src/main/peer-registry.ts
+++ b/src/main/peer-registry.ts
@@ -15,7 +15,7 @@
//
// Cost to a solo desktop user: zero. With no peer registered the registry holds an empty Map, arms
// no timer, and every lookup is a miss — the webContents path is bit-identical to before.
-import { UiSinkRegistry, type UiSink } from '../core/ui-sink-registry'
+import { UiSinkRegistry, type SinkOptions, type UiSink } from '../core/ui-sink-registry'
import { presenceHub } from '../core/presence/hub'
import type { FlowOwner } from '../core/pty-manager'
@@ -38,9 +38,10 @@ export function peerRegistry(): UiSinkRegistry {
}
/** A relay peer connected. `id` must come from `allocateRelayClientId()`. The caller joins the
- * presence hub itself (as ws.ts does), so it can pick the peer `kind`. */
-export function registerPeerSink(id: number, sink: UiSink): void {
- registry.register(id, sink)
+ * presence hub itself (as ws.ts does), so it can pick the peer `kind`. `opts` (quiet, self-paced)
+ * is for a live link's viewer; every other peer passes none (see `SinkOptions`). */
+export function registerPeerSink(id: number, sink: UiSink, opts?: SinkOptions): void {
+ registry.register(id, sink, opts)
}
/**
diff --git a/src/main/platform-electron.test.ts b/src/main/platform-electron.test.ts
index b0c708507..992e7f6ca 100644
--- a/src/main/platform-electron.test.ts
+++ b/src/main/platform-electron.test.ts
@@ -237,6 +237,24 @@ describe('electronPlatform + relay peers', () => {
warn.mockRestore()
})
+ it('a QUIET peer gets no broadcast and is not a client, but is reachable and counts as watching', () => {
+ const p = electronPlatform()
+ h.clientIds = [1]
+ const loud = peerSink()
+ const quiet = peerSink()
+ registerPeerSink(PEER, loud.sink)
+ registerPeerSink(PEER + 1, quiet.sink, { quiet: true, selfPaced: true })
+
+ p.broadcast('presence:peer', { op: 'join' })
+ expect(loud.text).toHaveLength(1)
+ expect(quiet.text).toEqual([])
+ expect(p.clientIds()).toEqual([1, PEER])
+ expect(p.quietClientIds?.()).toEqual([PEER + 1])
+
+ p.sendTo(PEER + 1, 'watch:meta', {})
+ expect(JSON.parse(quiet.text[0]!).channel).toBe('watch:meta')
+ })
+
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 7fc935a9f..938655e0f 100644
--- a/src/main/platform-electron.ts
+++ b/src/main/platform-electron.ts
@@ -178,7 +178,9 @@ export function electronPlatform(): ElectronPlatform {
// fan out via broadcast, so a peer that only received sendTo would still see nothing.
const peers = peerRegistry()
if (peers.size === 0) return // solo desktop: no ids() array, no loop — allocation-free
- for (const id of peers.ids()) {
+ // A quiet peer (a live link's viewer) is never broadcast to: canvas ops, presence and agent
+ // status are not its business. It is reached by an addressed sendTo only.
+ for (const id of peers.broadcastIds()) {
// 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
@@ -194,7 +196,10 @@ export function electronPlatform(): ElectronPlatform {
}
}
},
- clientIds: () => [...mainWindowClientIds(), ...peerRegistry().ids()],
+ clientIds: () => [...mainWindowClientIds(), ...peerRegistry().broadcastIds()],
+ // Quiet peers are absent from clientIds() (the canvas reflector, like broadcast, must skip
+ // them) but still watch the sessions they subscribe to — the pty reaper reads this.
+ quietClientIds: () => peerRegistry().quietIds(),
// The app's own window is the owner; every relay peer (peerRegistry) is not.
isOwnerClient: (id) => !peerRegistry().has(id) && mainWindowClientIds().includes(id),
openExternal: (url) => shell.openExternal(url),
diff --git a/src/server/platform-server.test.ts b/src/server/platform-server.test.ts
index 139cc87e8..4347ecdf6 100644
--- a/src/server/platform-server.test.ts
+++ b/src/server/platform-server.test.ts
@@ -10,6 +10,8 @@ function fakeSink() {
return { sink, texts, bins }
}
+const makePlatform = () => new ServerPlatform({ userDataDir: '/tmp/x', appVersion: '1.0.0' })
+
describe('ServerPlatform', () => {
it('dispatches req to handle and handleWithSender (sender = uiId)', async () => {
const p = new ServerPlatform({ userDataDir: '/tmp/x', appVersion: '1.0.0' })
@@ -173,6 +175,27 @@ describe('ServerPlatform', () => {
expect(p.clientIds()).toEqual([2])
})
+ it('a quiet attach gets addressed sends only, and counts as a quiet client', () => {
+ const p = makePlatform()
+ const got: string[] = []
+ const loud = p.attach({ sendText: (j) => got.push('loud ' + j), sendBinary: () => {} }, { owner: true })
+ const quiet = p.attach({ sendText: (j) => got.push('quiet ' + j), sendBinary: () => {} }, { quiet: true, selfPaced: true })
+ p.broadcast('presence:sync', [])
+ expect(got.filter((g) => g.startsWith('quiet'))).toEqual([])
+ expect(p.clientIds()).toEqual([loud])
+ expect(p.quietClientIds()).toEqual([quiet])
+ p.sendTo(quiet, 'watch:meta', {})
+ expect(got.some((g) => g.startsWith('quiet'))).toBe(true)
+ })
+
+ it('a quiet attach is never the owner, and detach forgets it', () => {
+ const p = makePlatform()
+ const quiet = p.attach({ sendText: () => {}, sendBinary: () => {} }, { quiet: true })
+ expect(p.isOwnerClient(quiet)).toBe(false)
+ p.detach(quiet)
+ expect(p.quietClientIds()).toEqual([])
+ })
+
it('exposes userDataDir/appVersion/isPackaged; openExternal rejects', async () => {
const p = new ServerPlatform({ userDataDir: '/data', appVersion: '9.9.9' })
expect(p.userDataDir).toBe('/data')
diff --git a/src/server/platform-server.ts b/src/server/platform-server.ts
index f8396856c..45f44f36a 100644
--- a/src/server/platform-server.ts
+++ b/src/server/platform-server.ts
@@ -1,6 +1,6 @@
import type { CorePlatform } from '../core/platform'
import type { FlowOwner } from '../core/pty-manager'
-import { UiSinkRegistry, type UiSink } from '../core/ui-sink-registry'
+import { UiSinkRegistry, type SinkOptions, type UiSink } from '../core/ui-sink-registry'
import { E_NO_HANDLER, type RpcErr, type RpcOk, type RpcRequest } from '../shared/rpc'
// The sink interface + all of the per-(client, session) WS backpressure (pause/resume watermarks,
@@ -87,12 +87,19 @@ export class ServerPlatform implements CorePlatform {
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)
+ // A quiet connection (a live link's viewer) is never broadcast to: addressed sends only.
+ for (const uiId of this.registry.broadcastIds()) this.registry.sendTo(uiId, channel, ...args)
}
- /** Every attached connection, in attach order (detach removes). */
+ /** Every attached connection but the quiet ones, in attach order (detach removes). */
clientIds(): number[] {
- return this.registry.ids()
+ return this.registry.broadcastIds()
+ }
+
+ /** The quiet connections (a live link's viewer): no broadcast, not in `clientIds()`, but they
+ * still watch the sessions they subscribe to — the pty reaper reads this. */
+ quietClientIds(): number[] {
+ return this.registry.quietIds()
}
openExternal(_url: string): Promise<void> {
@@ -100,10 +107,11 @@ export class ServerPlatform implements CorePlatform {
}
/** `owner` only from ws.ts, whose upgrade gate authenticated the socket as THE server's user. A
- * relay-hosted peer (index.ts's hosted attach) is never an owner. */
- attach(sink: UiSink, opts: { owner?: boolean } = {}): number {
+ * relay-hosted peer (index.ts's hosted attach) is never an owner. `quiet` / `selfPaced` are for
+ * a live link's viewer (see `SinkOptions`); every other attach passes neither. */
+ attach(sink: UiSink, opts: { owner?: boolean } & SinkOptions = {}): number {
const id = this.nextUiId++
- this.registry.register(id, sink)
+ this.registry.register(id, sink, { quiet: opts.quiet, selfPaced: opts.selfPaced })
if (opts.owner === true) this.owners.add(id)
return id
}