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
refactor: drop quiet and self-paced sinks and maxBridged — live links were their only users
review08d6d644d7b5
diff --git a/src/core/platform-fake.ts b/src/core/platform-fake.tsindex ca97bff9d..b5b121432 100644--- a/src/core/platform-fake.ts+++ b/src/core/platform-fake.ts@@ -47,8 +47,6 @@ 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[]}/**@@ -92,7 +90,6 @@ export function fakePlatform(overrides: Partial<CorePlatform> = {}): FakePlatforsent: [],opened: [],clients: [],- quietClients: [],handle(ch, fn) {f.handlers[ch] = fn},@@ -112,7 +109,6 @@ export function fakePlatform(overrides: Partial<CorePlatform> = {}): FakePlatforf.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.tsindex 924444d84..8fe2823f6 100644--- a/src/core/platform.ts+++ b/src/core/platform.ts@@ -43,10 +43,6 @@ 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, adiff --git a/src/core/pty-idle-reap.test.ts b/src/core/pty-idle-reap.test.tsindex c096f5b27..0d890c0c4 100644--- a/src/core/pty-idle-reap.test.ts+++ b/src/core/pty-idle-reap.test.ts@@ -180,20 +180,6 @@ 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.tsindex a8380a9be..55bbf7681 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -116,7 +116,7 @@ import {spawnFailureHint,type PtyDevices} from './pty-devices'-import { REAP_SWEEP_MS, liveClientIds, shouldReap } from './pty-reap'+import { REAP_SWEEP_MS, shouldReap } from './pty-reap'import { ControlModeClient, type ControlSpawn } from './tmux-control-client'import {TMUX_SOCKET,@@ -1491,15 +1491,14 @@ 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 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+ * "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* 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 = liveClientIds(platform())+ const live = new Set(platform().clientIds())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@@ -1574,9 +1573,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 the- * platform's live clients (`liveClientIds`) 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+ * `platform().clientIds()` 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) cullsdiff --git a/src/core/pty-reap.test.ts b/src/core/pty-reap.test.tsindex 184182ea2..936948a52 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, liveClientIds, shouldReap, type ReapCandidate } from './pty-reap'+import { REAP_IDLE_MS, 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,10 +48,3 @@ 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.tsindex 09e57783b..a17a55838 100644--- a/src/core/pty-reap.ts+++ b/src/core/pty-reap.ts@@ -1,5 +1,3 @@-import type { CorePlatform } from './platform'-/*** IDLE REAP: give pty devices back to the OS without killing anybody's work.*@@ -59,17 +57,6 @@ 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 falsediff --git a/src/core/relay/hosted-scheduler.test.ts b/src/core/relay/hosted-scheduler.test.tsindex 325d76ece..87b8fbfeb 100644--- a/src/core/relay/hosted-scheduler.test.ts+++ b/src/core/relay/hosted-scheduler.test.ts@@ -18,7 +18,6 @@ function harness(mints: Array<MintResult | (() => Promise<MintResult>)>, opts: {open?: (tok: string, ev: { onBridged(): void; onClose(): void }) => OpenedonStatus?: (s: SchedulerStatus) => voidfirstTimerId?: number- maxBridged?: number} = {}) {let t = 0const timers: Array<{ at: number; fn: () => void; id: number; ms: number }> = []@@ -41,10 +40,7 @@ function harness(mints: Array<MintResult | (() => Promise<MintResult>)>, opts: {},setTimeout: (fn, ms) => { const id = ++seq; timers.push({ at: t + ms, fn, id, ms }); delays.push(ms); return id },clearTimeout: (id) => { const i = timers.findIndex((x) => x.id === id); if (i >= 0) timers.splice(i, 1) },- onStatus: opts.onStatus,- // Passed only when the test names it, so every older test builds exactly the deps it always did- // (and an explicit `maxBridged: undefined` reaches the scheduler as such).- ...('maxBridged' in opts ? { maxBridged: opts.maxBridged } : {})+ onStatus: opts.onStatus}, () => t)const advance = async (ms: number) => {const target = t + ms@@ -602,171 +598,3 @@ describe('hosted scheduler', () => {expect(challenges).toBe(2)})})--// A live link's viewer cap: at maxBridged bridged sessions no idle listener is opened, so the broker-// turns further clients away ("no host waiting"); a session ending reopens one through the usual top().-describe('hosted scheduler maxBridged', () => {- it('opens no idle listener while maxBridged sessions are bridged, and reopens when one ends', async () => {- const opened: { ev: { onBridged(): void; onClose(): void }; closed: boolean }[] = []- const s = createHostedScheduler(- {- mint: async () => ({ ok: true, pairingToken: 't', hostId: 'h', ttlMs: 120_000 }),- open: (_t, ev) => {- const l = { ev, closed: false }- opened.push(l)- return { bridged: false, close: () => { l.closed = true } }- },- setTimeout: (fn, ms) => setTimeout(fn, ms),- clearTimeout: (h) => clearTimeout(h as ReturnType<typeof setTimeout>),- maxBridged: 2- },- () => Date.now()- )- s.start()- await vi.waitFor(() => expect(opened).toHaveLength(1))- opened[0].ev.onBridged()- await vi.waitFor(() => expect(opened).toHaveLength(2))- opened[1].ev.onBridged()- await new Promise((r) => setTimeout(r, 30))- expect(opened).toHaveLength(2)- opened[0].ev.onClose()- await vi.waitFor(() => expect(opened).toHaveLength(3))- s.stop()- })-- it('absent maxBridged (or an explicit undefined) keeps the old behaviour: every bridge gets a replacement', async () => {- for (const opts of [{}, { maxBridged: undefined }]) {- const h = harness(okMany(20), opts)- h.s.start(); await flush()- for (let i = 0; i < 12; i++) {- h.opened[h.opened.length - 1].ev.onBridged(); await flush()- }- expect(h.opened).toHaveLength(13)- expect(h.mintCalls()).toBe(13)- expect(h.s.status()).toMatchObject({ state: 'running', idle: 1, bridged: 12 })- }- })-- // Task 8 review: a cap that is not a whole number of peers is a wiring slip — 0 or a negative would- // be hosting that never listens, NaN a cap that never applies. Refused at construction, loudly.- it('refuses a maxBridged that is not an integer >= 1', () => {- for (const bad of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) {- expect(() => harness([], { maxBridged: bad }), String(bad)).toThrow(RangeError)- }- expect(() => harness([], { maxBridged: 1 })).not.toThrow()- expect(() => harness([], { maxBridged: undefined })).not.toThrow()- })-- it('maxBridged: 1 serves one peer at a time: no listener while it is connected, one again when it leaves', async () => {- const h = harness(okMany(10), { maxBridged: 1 })- h.s.start(); await flush()- expect(h.opened).toHaveLength(1)- h.opened[0].ev.onBridged(); await flush()- expect(h.opened).toHaveLength(1)- expect(h.s.status()).toMatchObject({ state: 'running', idle: 0, bridged: 1 })- await h.advance(HOUR)- expect(h.mintCalls()).toBe(1)- h.opened[0].ev.onClose(); await flush()- expect(h.opened).toHaveLength(2)- expect(h.s.status()).toMatchObject({ idle: 1, bridged: 0 })- h.opened[1].ev.onBridged(); await flush()- expect(h.opened).toHaveLength(2)- expect(h.mintCalls()).toBe(2)- })-- it('at the cap nothing is minted, no timer is armed, no status churns and nothing is written into the backoff', async () => {- const statuses: SchedulerStatus[] = []- const h = harness(okMany(10), { maxBridged: 2, onStatus: (st) => statuses.push(st) })- h.s.start(); await flush()- h.opened[0].ev.onBridged(); await flush()- h.opened[1].ev.onBridged(); await flush()- expect(h.opened).toHaveLength(2)- expect(h.s.status()).toMatchObject({ state: 'running', idle: 0, bridged: 2, lastError: null })- // Bridged listeners hold no refresh and the cap arms no retry: there is nothing to wake up and spin.- expect(h.timers).toHaveLength(0)- const delaysAtCap = h.delays.length- const emitsAtCap = statuses.length- await h.advance(HOUR)- expect(h.mintCalls()).toBe(2)- expect(h.delays).toHaveLength(delaysAtCap)- expect(statuses).toHaveLength(emitsAtCap)- expect(h.s.status()).toMatchObject({ state: 'running', idle: 0, bridged: 2, lastError: null })- // Leaving the cap is not a relay failure: the replacement is minted at once, and a relay that then- // drops it starts the backoff at its FIRST step — the time spent full advanced nothing.- h.opened[0].ev.onClose(); await flush()- expect(h.opened).toHaveLength(3)- expect(h.timers.map((x) => x.ms)).toEqual([90_000]) // only the new idle listener's refresh- h.opened[2].ev.onClose(); await flush()- expect(h.timers.map((x) => x.ms)).toEqual([1000])- })-- it('sessions ending together reopen ONE idle listener, not one per ended session', async () => {- const h = harness(okMany(10), { maxBridged: 3 })- h.s.start(); await flush()- for (let i = 0; i < 3; i++) {- h.opened[i].ev.onBridged(); await flush()- }- expect(h.opened).toHaveLength(3)- expect(h.s.status()).toMatchObject({ idle: 0, bridged: 3 })- // All three peers leave in the same tick (the relay dropping them together).- h.opened[0].ev.onClose(); h.opened[1].ev.onClose(); h.opened[2].ev.onClose()- await flush()- expect(h.mintCalls()).toBe(4)- expect(h.opened).toHaveLength(4)- expect(h.s.status()).toMatchObject({ idle: 1, bridged: 0 })- await h.advance(60_000) // and nothing more arrives later- expect(h.mintCalls()).toBe(4)- })-- it('sessions ending one after another from the cap still leave exactly one idle listener', async () => {- const h = harness(okMany(10), { maxBridged: 2 })- h.s.start(); await flush()- h.opened[0].ev.onBridged(); await flush()- h.opened[1].ev.onBridged(); await flush()- h.opened[0].ev.onClose(); await flush()- expect(h.opened).toHaveLength(3)- h.opened[1].ev.onClose(); await flush() // the idle replacement already exists- expect(h.opened).toHaveLength(3)- expect(h.mintCalls()).toBe(3)- expect(h.s.status()).toMatchObject({ idle: 1, bridged: 0 })- })-- it('a link that fills just as the mint budget runs out arms nothing; the budget owns the wait only once a session ends', async () => {- const h = harness(okMany(300), { maxBridged: 1 })- h.s.start(); await flush()- // A peer joins and leaves 199 times inside the hour: every leave is one mint, 200 in all.- for (let i = 0; i < 199; i++) {- const l = h.opened[h.opened.length - 1]- l.ev.onBridged(); await flush()- l.ev.onClose(); await flush()- }- expect(h.s.status()).toMatchObject({ mintsLastHour: 200, idle: 1, bridged: 0 })- h.opened[h.opened.length - 1].ev.onBridged(); await flush() // full, with the budget spent- expect(h.timers).toHaveLength(0)- expect(h.s.status()).toMatchObject({ idle: 0, bridged: 1, lastError: null })- h.opened[h.opened.length - 1].ev.onClose(); await flush() // below the cap: now the budget speaks- expect(h.s.status().lastError).toBe('mint budget')- expect(h.mintCalls()).toBe(200)- await h.advance(HOUR) // the window still holds the mints made at t=0- expect(h.mintCalls()).toBe(200)- await h.advance(1)- expect(h.mintCalls()).toBe(201)- expect(h.s.status()).toMatchObject({ state: 'running', idle: 1, bridged: 0 })- })-- it('a reopen from the cap answered 429 still waits the full 60 s, even when another session ends meanwhile', async () => {- const h = harness([ok(), ok(), { ok: false, kind: 'rate-limited', status: 429 }, ok(), ok()], { maxBridged: 2 })- h.s.start(); await flush()- h.opened[0].ev.onBridged(); await flush()- h.opened[1].ev.onBridged(); await flush()- h.opened[0].ev.onClose(); await flush() // the reopen mint is answered 429- expect(h.mintCalls()).toBe(3)- h.opened[1].ev.onClose(); await flush() // below the cap now, but the 429 wait owns the next mint- await h.advance(59_999)- expect(h.mintCalls()).toBe(3)- await h.advance(1)- expect(h.mintCalls()).toBe(4)- expect(h.opened).toHaveLength(3)- expect(h.s.status()).toMatchObject({ idle: 1, bridged: 0 })- })-})diff --git a/src/core/relay/hosted-scheduler.ts b/src/core/relay/hosted-scheduler.tsindex 4764c76c3..61b73ff98 100644--- a/src/core/relay/hosted-scheduler.ts+++ b/src/core/relay/hosted-scheduler.ts@@ -22,9 +22,6 @@// or a backend refusing every proof behind a flaky challenge would retry forever. Both refusals// are logged with their kind (warn, then error), so an operator can tell the two apart;// - while a backoff timer is armed it owns the next mint: nothing else may mint early;-// - a live link caps its bridged sessions (`maxBridged`): while full, no idle listener is kept (the-// broker turns further clients away), nothing is minted and no timer is armed; a session ending-// reopens ONE through the usual top().// Everything the injected deps can throw is caught: a scheduler that swallowed an exception would sit// in 'running' with no listener and no timer, i.e. hosting silently dead until a restart.import type { MintResult } from './host-token'@@ -71,11 +68,6 @@ export interface SchedulerDeps {setTimeout(fn: () => void, ms: number): unknownclearTimeout(h: unknown): voidonStatus?(s: SchedulerStatus): void- /** Open no idle listener while this many sessions are bridged (a live link's viewer cap). The- * broker closes a client that finds no idle host listener, so the cap needs no other code.- * Undefined = no cap; anything else must be an integer >= 1 (`createHostedScheduler` throws):- * 0 or a negative would be hosting that silently never listens, NaN a cap that never applies. */- maxBridged?: number}interface Entry {@@ -88,9 +80,6 @@ interface Entry {const clampDelay = (ms: number): number => Math.min(MAX_DELAY_MS, ms)export function createHostedScheduler(deps: SchedulerDeps, now: () => number) {- if (deps.maxBridged !== undefined && !(Number.isInteger(deps.maxBridged) && deps.maxBridged >= 1)) {- throw new RangeError(`maxBridged must be an integer >= 1 or undefined, not ${String(deps.maxBridged)}`)- }let state: SchedulerStatus['state'] = 'stopped'let lastError: string | null = nulllet opening = false@@ -179,18 +168,10 @@ export function createHostedScheduler(deps: SchedulerDeps, now: () => number) {for (const e of live) if (!e.bridged) n++return n}- const bridgedCount = (): number => {- let n = 0- for (const e of live) if (e.bridged) n++- return n- }// Keep one idle listener registered. Never two mints at once, and never ahead of an armed backoff.async function top(): Promise<void> {if (state !== 'running' || opening || retry !== null || idleCount() >= 1) return- // Full: mint nothing, arm nothing, leave the backoff and lastError as they are. Being full is- // neither proof nor failure of the relay leg, and a bridged session's onClose calls top() again.- if (deps.maxBridged !== undefined && bridgedCount() >= deps.maxBridged) returnif (status().mintsLastHour >= MINT_BUDGET_PER_HOUR) {// Out of budget: wait until the oldest mint in the window ages out (+1 ms, because the window// keeps a mint exactly an hour old). The retry slot makes every other path defer to this.diff --git a/src/core/ui-sink-registry.ts b/src/core/ui-sink-registry.tsindex 751d8677c..78caa6e8f 100644--- a/src/core/ui-sink-registry.ts+++ b/src/core/ui-sink-registry.ts@@ -22,24 +22,6 @@ 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).- * That hands the sink an OBLIGATION: the registry's 8 MB `WS_DROP_WATER` ceiling no longer bounds- * its backlog, so the sink MUST bound it itself, or a socket that never drains grows the host's- * memory until the process dies (relay-host's "OBLIGATION 2"). The watcher does it in two steps:- * it stops forwarding pty frames past `WATCHER_BUFFER_LIMIT` (512 KB, watcher-policy.ts) and the- * link host closes a viewer past `VIEWER_BACKLOG_CLOSE` (8 MB). A new self-paced sink owes the same. */-export interface SinkOptions {- quiet?: boolean- selfPaced?: boolean-}-/** Watermarks match the renderer terminal's own flow control. */const WS_HIGH_WATER = 1_000_000const WS_LOW_WATER = 256_000@@ -108,9 +90,6 @@ 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,@@ -151,49 +130,25 @@ export class UiSinkRegistry {private failures = new Map<number, number>()private onSinkGone?: (id: number) => void- register(id: number, sink: UiSink, opts: SinkOptions = {}): void {- // Over an id that is still live this REPLACES the sink, and the flow state belongs to the old one:- // it is released, not kept (a stale `paused` key under a self-paced re-register would never reach- // the resume check again, so the pty stayed paused for good). Unreachable today — every shell mints- // monotonic ids — which makes this the belt, not a path anyone takes.- if (this.sinks.has(id)) this.releaseFlowState(id)+ register(id: number, sink: UiSink): 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 (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. */+ /** 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, quiet ones included, in registration order (Map preserves insertion- * order). A fan-out wants `broadcastIds()`. */+ /** Every registered sink, in registration order (Map preserves insertion order). */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`. */@@ -220,28 +175,12 @@ export class UiSinkRegistry {return `${uiId} ${sessionId}`}- /** Release every flow entry of a client that STAYS registered (`register` over its live id): a- * pause it booked is handed back to PtyManager — the client is not leaving, so `dropClient` will not- * return it — and its desync, strikes and sweep interest are forgotten. */- private releaseFlowState(id: number): void {- const prefix = `${id} `- for (const key of [...this.paused]) {- if (!key.startsWith(prefix)) continue- this.paused.delete(key)- this.flowController?.(id, key.slice(prefix.length), true, UiSinkRegistry.OWNER)- }- for (const key of [...this.desynced.keys()]) if (key.startsWith(prefix)) this.desynced.delete(key)- this.failures.delete(id)- this.stopSweepIfIdle()- }-/** Drop the departing (or gone) client's sink and prune only ITS backpressure entries. 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). */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@@ -255,13 +194,6 @@ export class UiSinkRegistry {if (!sink) returnif (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@@ -340,12 +272,10 @@ export class UiSinkRegistry {// 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 an id SNAPSHOT (`broadcastIds()` / `ids()` return a- // fresh array), so removing this entry cannot disturb their loop — a later `sendTo` for an- // evicted id is simply a miss.+ // - 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)- 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.tsdeleted file mode 100644index b2fe7e444..000000000--- a/src/core/ui-sink-registry.watcher.test.ts+++ /dev/null@@ -1,160 +0,0 @@-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])- })-- // Task 6 review: registering over a LIVE id replaces the sink, and the old sink's flow state must- // not outlive it — a stale pause under a self-paced re-register would never be handed back.- it('re-registering a live id hands back the pause the old sink booked and forgets its desync', () => {- vi.useFakeTimers()- try {- const r = new UiSinkRegistry()- const flow = vi.fn()- r.setFlowController(flow)- r.setResyncProvider(async () => 'SCREEN')- r.register(9, sink(2_000_000))- r.sendTo(9, IPC.ptyData('s1'), 'x') // past the high water: a pause ticket- expect(flow).toHaveBeenLastCalledWith(9, 's1', false, 'socket')- flow.mockClear()- r.register(9, sink(0), { selfPaced: true })- expect(flow).toHaveBeenCalledWith(9, 's1', true, 'socket')- // And a desync of the old sink does not carry over either: a re-registered ordinary sink streams.- const big = sink(50_000_000)- r.register(10, sink(2_000_000))- r.sendTo(10, IPC.ptyData('s2'), 'a')- r.register(10, big)- r.sendTo(10, IPC.ptyData('s2'), 'b') // the old sink's backlog, not this one's- const fresh = sink(0)- r.register(10, fresh)- r.sendTo(10, IPC.ptyData('s2'), 'c')- expect(fresh.bin).toBe(1)- } finally {- vi.useRealTimers()- }- })-- 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.tsindex e1c279f9e..6c1af3978 100644--- a/src/main/peer-registry.test.ts+++ b/src/main/peer-registry.test.ts@@ -52,10 +52,9 @@ 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().broadcastIds()) peerRegistry().sendTo(id, ch, ...args)+ for (const id of peerRegistry().ids()) peerRegistry().sendTo(id, ch, ...args)},- clientIds: () => [...wcIds, ...peerRegistry().broadcastIds()],- quietClientIds: () => peerRegistry().quietIds(),+ clientIds: () => [...wcIds, ...peerRegistry().ids()],openExternal: async () => {}}initPlatform(p)@@ -190,11 +189,4 @@ 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.tsindex f53f9ed8e..f0b6b80b6 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 SinkOptions, type UiSink } from '../core/ui-sink-registry'+import { UiSinkRegistry, type UiSink } from '../core/ui-sink-registry'import { presenceHub } from '../core/presence/hub'import type { FlowOwner } from '../core/pty-manager'@@ -38,10 +38,9 @@ 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`. `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)+ * 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)}/**diff --git a/src/main/platform-electron.test.ts b/src/main/platform-electron.test.tsindex f22debb8b..66e8e725b 100644--- a/src/main/platform-electron.test.ts+++ b/src/main/platform-electron.test.ts@@ -237,24 +237,6 @@ 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('the main window hears a broadcast exactly once, however many peers are registered', () => {// The desktop host's agent events (agent:status, agent:subagent-activity, context:update) ride// broadcast so a joined team tab hears them; the host's own window must not hear them twice.@@ -270,17 +252,14 @@ describe('electronPlatform + relay peers', () => {}const a = peerSink()const b = peerSink()- const quiet = peerSink()registerPeerSink(PEER, a.sink)registerPeerSink(PEER + 1, dead)- registerPeerSink(PEER + 2, quiet.sink, { quiet: true, selfPaced: true })registerPeerSink(PEER + 3, b.sink)p.broadcast('agent:status', { nodeId: 'n1', kind: 'state', state: 'working' })expect(h.sent).toEqual([{ channel: 'agent:status', args: [{ nodeId: 'n1', kind: 'state', state: 'working' }] }])expect(a.text).toHaveLength(1)expect(b.text).toHaveLength(1)- expect(quiet.text).toEqual([])warn.mockRestore()})diff --git a/src/main/platform-electron.ts b/src/main/platform-electron.tsindex 28324d762..f2b552add 100644--- a/src/main/platform-electron.ts+++ b/src/main/platform-electron.ts@@ -178,9 +178,7 @@ 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- // 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()) {+ 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@@ -196,10 +194,7 @@ export function electronPlatform(): ElectronPlatform {}}},- 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(),+ clientIds: () => [...mainWindowClientIds(), ...peerRegistry().ids()],// 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.tsindex 4347ecdf6..139cc87e8 100644--- a/src/server/platform-server.test.ts+++ b/src/server/platform-server.test.ts@@ -10,8 +10,6 @@ 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' })@@ -175,27 +173,6 @@ 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.tsindex 45f44f36a..f8396856c 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 SinkOptions, type UiSink } from '../core/ui-sink-registry'+import { UiSinkRegistry, 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,19 +87,12 @@ export class ServerPlatform implements CorePlatform {broadcast(channel: string, ...args: any[]): void {if (this.registry.size === 0) return // no connection: no ids() array, no loop- // 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)+ for (const uiId of this.registry.ids()) this.registry.sendTo(uiId, channel, ...args)}- /** Every attached connection but the quiet ones, in attach order (detach removes). */+ /** Every attached connection, in attach order (detach removes). */clientIds(): number[] {- 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()+ return this.registry.ids()}openExternal(_url: string): Promise<void> {@@ -107,11 +100,10 @@ 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. `quiet` / `selfPaced` are for- * a live link's viewer (see `SinkOptions`); every other attach passes neither. */- attach(sink: UiSink, opts: { owner?: boolean } & SinkOptions = {}): number {+ * relay-hosted peer (index.ts's hosted attach) is never an owner. */+ attach(sink: UiSink, opts: { owner?: boolean } = {}): number {const id = this.nextUiId++- this.registry.register(id, sink, { quiet: opts.quiet, selfPaced: opts.selfPaced })+ this.registry.register(id, sink)if (opts.owner === true) this.owners.add(id)return id}