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(core): a watcher join does no wrong-machine read and no throwaway capture; seams refuse misuse

review6fffe78734b8
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 2383b7b06..09c30c72e 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -2411,6 +2411,10 @@ export class PtyManager {
}
: { sessionId: existingId, fresh: false, coAttachMouse, coAttachAltScreen, tmuxClient, persistent }
if (resized) return Promise.resolve(base) // tmux is redrawing this client — do not paint twice
+ // A live link's watcher never paints from this screen (its keyframe is a VISIBLE-only capture —
+ // this one is history on SSH and the session host), so it is not captured for one (R64/M4): on SSH
+ // that was a `-S -200` capture over the master on every viewer join and rejoin, thrown away.
+ if (isWatcherCreate(options)) return Promise.resolve(base)
// An empty capture (plain shell — no tmux to capture; a tmux/ssh blip) is OMITTED, never sent
// as '': the renderer must not reset a terminal for nothing. A plain-shell joiner therefore
// still lands on a blank-but-live screen — there is no source of truth for its past output,
@@ -2562,6 +2566,10 @@ export class PtyManager {
// while an unflagged client is attached somewhere on the server; if the watcher is ever the only
// one, tmux sizes the window to it, so a wrong spawn size is a wrong window size. Unknown ⇒ refused
// ("not now": the link host backs off and asks again).
+ // The read runs INSIDE the node's in-flight barrier (`create`), on purpose: a second viewer's join
+ // waits for this client and then shares it, instead of spawning another. The cost, accepted: an
+ // owner opening the same node in that instant waits for the read too — bounded by the probe and
+ // process timeouts (`runAsync`) — and then spawns its own client as usual.
if (isWatcherCreate(options)) {
const windowSize = await this.readWindowSize(options.persistKey as string, options.sshRemote)
if (!windowSize) return { sessionId: '', fresh: false, unavailable: 'join-only' }
@@ -4913,8 +4921,9 @@ export class PtyManager {
* is the only one, tmux's `window-size latest` sizes the window to it. So the client is spawned at
* the window's CURRENT size, read immediately before the spawn and REFUSED when it cannot be read
* (`spawnNew`), and `syncWatcherClientSize` keeps it there while the link host has viewers. Residual:
- * the window can drift for up to one sync interval, and a read can race an owner resizing or leaving
- * (the window then keeps the size read a moment before).
+ * when the watcher becomes the only client, the window stays at the last-synced size until another
+ * client sizes it, and a read can race an owner resizing or leaving (the window then keeps the size
+ * read a moment before).
* A local tmux older than 3.2 has no client flags: refused. Only the named fields are forwarded, and
* the watcher rules are set after them. A remote node is never watched through the local tmux
* (`requireRemote` whenever `sshRemote` is given).
@@ -4940,10 +4949,12 @@ export class PtyManager {
: undefined
// The size this view starts at when it JOINS a client that already exists (it is told the
// authoritative size right after). It is never a spawn size: a watcher's own client is spawned only
- // at the window size `spawnNew` reads itself, or not at all.
+ // at the window size `spawnNew` reads itself, or not at all. For a HELD session that is the
+ // session's own size — no tmux read (R64/M4): the read took the CALLER's `sshRemote`, which is
+ // absent for a remote node whose master is down, and so asked the LOCAL tmux about a remote node.
const size =
given ??
- (held ? await this.readWindowSize(persistKey, sshRemote) : undefined) ??
+ (held && indexedId ? this.sessionSize(indexedId) : null) ??
this.watchSizeFor(persistKey) ?? { cols: 80, rows: 24 }
const options: WatcherCreateOptions = {
persistKey,
@@ -5044,10 +5055,15 @@ export class PtyManager {
}
/**
- * The CURRENT size of a node's tmux window (`#{window_width} #{window_height}`, exact target), read
- * from tmux rather than from memory: with no Session held there is nothing to remember it from.
- * Local, or over the ControlMaster for an SSH node (never the local tmux for a remote node).
- * undefined on any failure or an exact-target miss (tmux answers exit 0 with empty formats).
+ * The CURRENT size a client of a node's tmux window has, read from tmux rather than from memory:
+ * with no Session held there is nothing to remember it from. One `display-message` by exact target
+ * reads `#{window_width} #{window_height} #{status}`, and the status lines are ADDED to the height
+ * (`parseWindowSize`): a client is window + status rows tall, so a client spawned at the bare window
+ * height would make tmux shrink the window. With the production conf (`status off`) the two agree.
+ * Local, or over the ControlMaster for an SSH node (never the local tmux for a remote node: the
+ * caller passes the node's `sshRemote`, and a remote node with no master is not read at all).
+ * undefined on any failure, an exact-target miss (tmux answers exit 0 with empty formats) or a
+ * status value it does not know.
*/
async readWindowSize(
persistKey: string,
diff --git a/src/core/pty-watch-join.test.ts b/src/core/pty-watch-join.test.ts
index c94772f53..ac7810716 100644
--- a/src/core/pty-watch-join.test.ts
+++ b/src/core/pty-watch-join.test.ts
@@ -264,14 +264,42 @@ describe('joinAsWatcher', () => {
expect([spawned[0].cols, spawned[0].rows]).toEqual([150, 45])
})
- it('reads the window size only when it has to', async () => {
+ // R64/M4: joining a HELD session reads nothing from tmux — the session's own size is the answer.
+ // The read used to take the CALLER's sshRemote, which is absent for a remote node whose master is
+ // down, and so asked the LOCAL tmux about a remote node's name.
+ it('reads the window size only to SPAWN a client — never to join a held session', async () => {
const m = await tmuxManager(['nt-n1'], { window: { cols: 132, rows: 43 } })
const read = (m as unknown as { readWindowSize: ReturnType<typeof vi.fn> }).readWindowSize
- await create(OWNER, { cols: 120, rows: 40 })
+ const a = await create(OWNER, { cols: 120, rows: 40 })
await m.joinAsWatcher(WATCHER, WATCH) // a live Session is held and the caller gave a size
+ await m.joinAsWatcher(WATCHER + 1, { persistKey: 'n1', viewerId: 'watch-s2', requireRemote: true }) // no size
expect(read).not.toHaveBeenCalled()
- await m.joinAsWatcher(WATCHER + 1, { persistKey: 'n1', viewerId: 'watch-s2' }) // no caller size
- expect(read).toHaveBeenCalledTimes(1)
+ // The view is shown the held session's own size (nothing to correct, so nothing more is sent).
+ expect(fake.sent.filter((x) => x.channel === IPC.ptySize(a.sessionId) && x.to === WATCHER + 1)).toEqual([])
+ // With nothing held, the spawn reads it — once, by the node's exact target.
+ const m2 = await tmuxManager(['nt-n2'], { window: { cols: 132, rows: 43 } })
+ const read2 = (m2 as unknown as { readWindowSize: ReturnType<typeof vi.fn> }).readWindowSize
+ await m2.joinAsWatcher(WATCHER, { persistKey: 'n2', viewerId: 'watch-s3' })
+ expect(read2).toHaveBeenCalledTimes(1)
+ expect(read2.mock.calls[0][0]).toBe('n2')
+ })
+
+ // R64/M4: a watcher never paints from the co-attach screen (its keyframe is a visible-only capture),
+ // so a join captures nothing for it. On SSH that was a `-S -200` history capture per viewer join.
+ it("a watcher's join takes no co-attach capture; a second owner view still does (control)", async () => {
+ const m = await tmuxManager(['nt-n1'])
+ const spies = m as unknown as { captureForResync: (s: string) => Promise<string>; paneCursor: (s: string) => Promise<unknown> }
+ const capture = vi.spyOn(spies, 'captureForResync').mockResolvedValue('SCREEN')
+ const cursor = vi.spyOn(spies, 'paneCursor').mockResolvedValue(undefined)
+ await create(OWNER, { cols: 120, rows: 40 })
+ const w = await m.joinAsWatcher(WATCHER, WATCH)
+ expect(w.unavailable).toBeUndefined()
+ expect(w.screen).toBeUndefined()
+ expect(capture).not.toHaveBeenCalled()
+ expect(cursor).not.toHaveBeenCalled()
+ const second = await create(VIEWER, { cols: 120, rows: 40 })
+ expect(second.screen).toBe('SCREEN')
+ expect(capture).toHaveBeenCalledTimes(1)
})
it('local tmux < 3.2 has no client flags: FAIL CLOSED, nothing spawned, logged once', async () => {
diff --git a/src/core/relay/hosted-scheduler.test.ts b/src/core/relay/hosted-scheduler.test.ts
index a4a9c607d..325d76ece 100644
--- a/src/core/relay/hosted-scheduler.test.ts
+++ b/src/core/relay/hosted-scheduler.test.ts
@@ -647,6 +647,16 @@ describe('hosted scheduler maxBridged', () => {
}
})
+ // 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()
diff --git a/src/core/relay/hosted-scheduler.ts b/src/core/relay/hosted-scheduler.ts
index 2d3901783..ea709776f 100644
--- a/src/core/relay/hosted-scheduler.ts
+++ b/src/core/relay/hosted-scheduler.ts
@@ -71,7 +71,9 @@ export interface SchedulerDeps {
clearTimeout(h: unknown): void
onStatus?(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. */
+ * 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
}
@@ -86,6 +88,9 @@ const clampDelay = (ms: number): number => Math.min(MAX_DELAY_MS, ms)
const errorText = (err: unknown): string => (err instanceof Error ? err.message : String(err))
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 = null
let opening = false
diff --git a/src/core/ui-sink-registry.ts b/src/core/ui-sink-registry.ts
index 56da044e4..751d8677c 100644
--- a/src/core/ui-sink-registry.ts
+++ b/src/core/ui-sink-registry.ts
@@ -29,7 +29,12 @@ const PTY_RECYCLED_PREFIX = 'pty:recycled:'
* 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). */
+ * (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
@@ -147,6 +152,11 @@ export class UiSinkRegistry {
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)
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)
@@ -210,6 +220,21 @@ 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). */
@@ -315,8 +340,9 @@ 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 the `ids()` SNAPSHOT (an 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 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.
this.sinks.delete(uiId)
this.failures.delete(uiId)
this.options.delete(uiId)
diff --git a/src/core/ui-sink-registry.watcher.test.ts b/src/core/ui-sink-registry.watcher.test.ts
index b2b75e9d4..b2fe7e444 100644
--- a/src/core/ui-sink-registry.watcher.test.ts
+++ b/src/core/ui-sink-registry.watcher.test.ts
@@ -117,6 +117,36 @@ describe('sink options follow the sink', () => {
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()
diff --git a/src/core/watch-link/link-host.ts b/src/core/watch-link/link-host.ts
index 3314154c4..9c1a02d2c 100644
--- a/src/core/watch-link/link-host.ts
+++ b/src/core/watch-link/link-host.ts
@@ -46,8 +46,9 @@
// tmux 3.4): when the watcher is the only client, tmux's `window-size latest` sizes the window to it.
// So `syncSize` (PtyManager.syncWatcherClientSize, serialized per session there — R24) keeps that
// client at the window's size: before every keyframe capture (the screen then matches the size) and
-// every WATCHER_SIZE_SYNC_MS while this link has a joined viewer. Residual: the window lands on the
-// last-synced size until another client sizes it, for up to one interval.
+// every WATCHER_SIZE_SYNC_MS while this link has a joined viewer. Residual: when the watcher becomes the
+// only client, the window stays at the last-synced size until another client sizes it (an owner resize
+// in the last interval before leaving is not caught).
//
// SPLIT PANES: a keyframe captures the session's ACTIVE pane only (`=nt-<id>:`); the stream, which is
// the tmux client's own output, repairs the rest as tmux redraws it.
diff --git a/src/core/watch-link/watcher-client.realtty.test.ts b/src/core/watch-link/watcher-client.realtty.test.ts
index 3d54586c6..bf5baa714 100644
--- a/src/core/watch-link/watcher-client.realtty.test.ts
+++ b/src/core/watch-link/watcher-client.realtty.test.ts
@@ -287,7 +287,10 @@ describe("keeping a watcher's own client at the window size (sync)", () => {
await until(() => win(name) === '200x50')
seen.push(win(name))
if (sync) {
- // syncWatcherClientSize: read the window, resize the watcher's OWN pty to exactly that.
+ // syncWatcherClientSize's step, restated here: read the window, resize the watcher's OWN pty to
+ // exactly that. This file measures the TMUX rule the step relies on; the production step itself
+ // (one read, the client resized only when the size changed, never a vote, serialized per
+ // session) is pinned in src/core/pty-watch-join.test.ts ("syncWatcherClientSize").
const now = readSize(name)
watcher.proc.resize(now.cols, now.rows)
await sleep(200)