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
fix(pty): a watcher's own client is spawned at, and kept at, the window size
review3e64d3937fa4
diff --git a/src/core/pty-manager.capture-visible.test.ts b/src/core/pty-manager.capture-visible.test.tsindex d083c1223..d8f1dc6df 100644--- a/src/core/pty-manager.capture-visible.test.ts+++ b/src/core/pty-manager.capture-visible.test.ts@@ -203,25 +203,25 @@ describe('readWindowSize — the size a watcher client is spawned at', () => {}it('asks the local tmux for exactly this session and parses the reply', async () => {- script.answer = () => ({ stdout: '120 39\n' })+ script.answer = () => ({ stdout: '120 39 off\n' })const m = await bare()expect(await m.readWindowSize(NODE)).toEqual({ cols: 120, rows: 39 })expect(calls).toEqual([{file: '/usr/bin/tmux',- args: ['-L', TMUX_SOCKET, 'display-message', '-p', '-t', TARGET, '#{window_width} #{window_height}']+ args: ['-L', TMUX_SOCKET, 'display-message', '-p', '-t', TARGET, '#{window_width} #{window_height} #{status}']}])})it('asks the REMOTE tmux over the ControlMaster for an SSH node', async () => {- script.answer = () => ({ stdout: '100 30\n' })+ script.answer = () => ({ stdout: '100 30 off\n' })const m = await bare(null)expect(await m.readWindowSize(NODE, SSH_REMOTE)).toEqual({ cols: 100, rows: 30 })expect(calls).toHaveLength(1)expect(calls[0].file).toBe('/usr/bin/ssh')expect(calls[0].args.at(-1)).toContain(- `tmux -L ${RMT_TMUX_SOCKET} display-message -p -t '${TARGET}' '#{window_width} #{window_height}'`+ `tmux -L ${RMT_TMUX_SOCKET} display-message -p -t '${TARGET}' '#{window_width} #{window_height} #{status}'`)})diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 770378676..9e60fcc81 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -2456,6 +2456,16 @@ export class PtyManager {// flags are passed and an old remote tmux rejects them (see `remoteTmuxWatcherArgs`).if (isWatcherCreate(options) && !options.sshRemote && !(await this.localTmuxSupportsWatcherClient()))return { sessionId: '', fresh: false, unavailable: 'join-only' }+ // A watcher's own client is spawned at the window's CURRENT size, read here, just before the spawn+ // — never at a guessed one (the caller's, a remembered size, a default). `ignore-size` only holds+ // 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).+ if (isWatcherCreate(options)) {+ const windowSize = await this.readWindowSize(options.persistKey as string, options.sshRemote)+ if (!windowSize) return { sessionId: '', fresh: false, unavailable: 'join-only' }+ options = { ...options, cols: windowSize.cols, rows: windowSize.rows }+ }// Ensure the login-shell PATH is resolved (prewarmed in init(); usually already settled)// so the session env below picks it up — awaiting keeps the event loop free either way.await resolveShellPath()@@ -3074,8 +3084,8 @@ export class PtyManager {// pre-flight above is the one thing that CAN, which is exactly why it runs before this.)// The shared background-write client goes too, for the same reason, when it is this node's// session it happens to be attached to.- // A watcher's own client is not a painter: read-only and ignore-size, it neither types nor sizes,- // so a background-write client may stay attached beside it.+ // A watcher's own client is not a painter: read-only, it never types, and it is kept at the+ // window's own size (`syncWatcherClientSize`), so a background-write client may stay beside it.if (options.persistKey && !isWatcherCreate(options)) {// The other half of the swap log (see `shadowAttach`), and only when there is really// something to retire: a painter arriving at a session no control client held swapped@@ -3369,7 +3379,7 @@ export class PtyManager {// otherwise this falls through to the unchanged local-tmux / plain-shell branches below.const remoteSsh = options.sshRemote && options.persistKey ? findSsh() : nullif (isWatcherCreate(options) && options.sshRemote && options.persistKey && remoteSsh) {- // A live link watcher's own client on the host: attach-only, read-only, size-neutral, no env+ // A live link watcher's own client on the host: attach-only, read-only, ignore-size, no env// (see `remoteTmuxWatcherArgs`). Nothing the owner's branch below does — tokens, hook/account// env, the session-env file, `markPresent` — belongs to a client that creates nothing.file = remoteSsh@@ -4528,18 +4538,22 @@ export class PtyManager {/*** Join a node's RUNNING session as a live link's viewer. It never starts one (`joinOnly`: a session- * that cannot be confirmed is refused `unavailable: 'join-only'`), and it never sizes one, at either- * layer:- * - in this process it casts no size vote (`sizeVote: false`) — joining a held Session leaves the- * pty at its owners' size;- * - when no Session is held and it has to spawn its OWN tmux client, that client is- * `attach-session -E -f ignore-size,read-only` on the exact target (see- * `watch-link/watcher-client.ts`): tmux's `window-size latest` does not count it, it never- * creates, never strips the session env, and cannot type. It is spawned at the window's CURRENT- * size (`readWindowSize`), so what it paints is what the owner sees. 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).+ * that cannot be confirmed is refused `unavailable: 'join-only'`), and it never votes on its size:+ * - joining a Session held in this process casts no size vote (`sizeVote: false`) — the pty stays+ * at its owners' size;+ * - when no Session is held it spawns its OWN tmux client (shared by later viewers of the node):+ * `attach-session -E -f ignore-size,read-only` on the exact target (`watch-link/watcher-client.ts`)+ * — never creating, never stripping the session env, unable to type.+ * `ignore-size` is NOT unconditional (measured, tmux 3.4): tmux honours it only while at least one+ * client WITHOUT the flag is attached to some session on the same server. When the watcher's client+ * 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).+ * 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).*/async joinAsWatcher(clientId: ClientId,@@ -4553,19 +4567,20 @@ export class PtyManager {}): Promise<PtyCreateResult> {const { persistKey, viewerId, sshRemote } = opts- // The Session a watcher create would JOIN (`join` reads the index). With none, it spawns its own- // client, which must be sized to the window it will show.+ // The Session a watcher create would JOIN (`join` reads the index).const indexedId = this.byPersistKey.get(persistKey)const held = indexedId ? this.sessions.get(indexedId) : undefinedconst given =Number.isInteger(opts.cols) && Number.isInteger(opts.rows) && opts.cols! > 0 && opts.rows! > 0? { cols: opts.cols!, rows: opts.rows! }: 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.const size =- (held && given) ||- (await this.readWindowSize(persistKey, sshRemote)) ||- given ||- this.watchSizeFor(persistKey) || { cols: 80, rows: 24 }+ given ??+ (held ? await this.readWindowSize(persistKey, sshRemote) : undefined) ??+ this.watchSizeFor(persistKey) ?? { cols: 80, rows: 24 }const options: WatcherCreateOptions = {persistKey,viewerId,@@ -4580,6 +4595,42 @@ export class PtyManager {return this.create(clientId, options)}+ /**+ * Keep a watcher's OWN tmux client at the window's current size, so that if it becomes the only+ * client on the server (when tmux stops honouring `ignore-size`) the window keeps its latest size+ * instead of snapping to the size the client was spawned at. The link host calls it on every+ * keyframe and on a timer while the node has viewers.+ *+ * Reads the window size by exact target (locally, or over the ControlMaster) and resizes THIS+ * client's pty to exactly that — not a size vote (`sizes` is untouched), never a viewer-supplied+ * size — then tells the viewers the size they render, as `applySize` does. A no-op answering false+ * for anything that is not a watcher's own client, an unreadable size, or a session that went away+ * during the read. With the production conf (`status off`) the window IS the client size, so a+ * client of the window's size leaves the window where it is.+ */+ async syncWatcherClientSize(sessionId: string): Promise<boolean> {+ const session = this.sessions.get(sessionId)+ if (!session?.watcherClient || !session.persistKey) return false+ const size = await this.readWindowSize(session.persistKey, session.sshRemote)+ if (!size || this.sessions.get(sessionId) !== session) return false+ if (session.appliedSize?.cols !== size.cols || session.appliedSize?.rows !== size.rows) {+ try {+ session.proc.resize(size.cols, size.rows)+ } catch {+ return false // the client already exited+ }+ session.appliedSize = size+ }+ const channel = IPC.ptySize(sessionId)+ for (const sub of session.subscribers) {+ const shown = session.shown.get(sub)+ if (shown && shown.cols === size.cols && shown.rows === size.rows) continue+ session.shown.set(sub, size)+ this.send(subClient(sub), channel, size)+ }+ return true+ }+/*** 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.@@ -4611,7 +4662,9 @@ export class PtyManager {}}- /** `tmux -V` for the LOCAL binary, asked once per binary path (a watcher client needs >= 3.2). */+ /** `tmux -V` for the LOCAL binary, per binary path (a watcher client needs >= 3.2). Only a DEFINITE+ * answer — tmux printed a version, supported or not — is kept; a probe that failed (spawn error,+ * timeout) is dropped, so the next watcher join asks again. Concurrent joins share one probe. */private watcherTmuxProbe: { path: string; ok: Promise<boolean> } | null = null/** The refusal is logged once per app run, not once per viewer. */private watcherTmuxRefusalLogged = false@@ -4620,22 +4673,30 @@ export class PtyManager {const tmuxPath = this.tmuxPathif (!tmuxPath) return Promise.resolve(false)if (this.watcherTmuxProbe?.path === tmuxPath) return this.watcherTmuxProbe.ok- const ok = this.confirmedProcessRun(tmuxPath, ['-V'], { timeout: PROBE_TIMEOUT_MS, encoding: 'utf-8' })- .then((res) => String((res as { stdout?: unknown })?.stdout ?? ''))- .catch(() => '')- .then((stdout) => {- const supported = supportsWatcherClient(parseTmuxVersion(stdout))- if (!supported && !this.watcherTmuxRefusalLogged) {- this.watcherTmuxRefusalLogged = true- const seen = stdout.trim().slice(0, 40) || 'unknown'- console.warn(- `[pty] live link watchers refused: the local tmux (${seen}) has no client flags; tmux 3.2 or newer is needed`- )+ const probe: { path: string; ok: Promise<boolean> } = {+ path: tmuxPath,+ ok: this.confirmedProcessRun(tmuxPath, ['-V'], { timeout: PROBE_TIMEOUT_MS, encoding: 'utf-8' }).then(+ (res) => {+ const stdout = String((res as { stdout?: unknown })?.stdout ?? '')+ const supported = supportsWatcherClient(parseTmuxVersion(stdout))+ if (!supported && !this.watcherTmuxRefusalLogged) {+ this.watcherTmuxRefusalLogged = true+ const seen = stdout.trim().slice(0, 40) || 'unknown'+ console.warn(+ `[pty] live link watchers refused: the local tmux (${seen}) has no client flags; tmux 3.2 or newer is needed`+ )+ }+ return supported+ },+ () => {+ // Not an answer: forget this probe (unless a newer one replaced it) and refuse this join.+ if (this.watcherTmuxProbe === probe) this.watcherTmuxProbe = null+ return false}- return supported- })- this.watcherTmuxProbe = { path: tmuxPath, ok }- return ok+ )+ }+ this.watcherTmuxProbe = probe+ return probe.ok}/**diff --git a/src/core/pty-watch-join.test.ts b/src/core/pty-watch-join.test.tsindex 3a2dd7df0..52a716fab 100644--- a/src/core/pty-watch-join.test.ts+++ b/src/core/pty-watch-join.test.ts@@ -122,17 +122,27 @@ function hasSession(live: string[], args: readonly string[]): boolean {/** Every `tmux -V` the manager asked (the watcher client's version probe). */const versionAsks: string[] = []+/** A `tmux -V` that could not run at all (spawn error, timeout) — not an answer. */+const PROBE_FAILS = 'PROBE_FAILS'+/** A tmux-backed manager whose probes answer from `live` without touching a tmux socket. `version`- * is what `tmux -V` answers; `window` what the window-size read answers. */+ * is what `tmux -V` answers (a list is consumed in order, the last answer repeating); `window` what+ * the window-size read answers, `null` = unreadable. */async function tmuxManager(live: string[],- { version = 'tmux 3.4\n', window }: { version?: string; window?: { cols: number; rows: number } } = {}+ {+ version = 'tmux 3.4\n',+ window = { cols: 120, rows: 39 }+ }: { version?: string | string[]; window?: { cols: number; rows: number } | null } = {}) {versionAsks.length = 0+ const answers = Array.isArray(version) ? [...version] : [version]const confirmedProcessRun: ConfirmedProcessRun = async (_file, args) => {if (args[0] === '-V') {- versionAsks.push(version)- return { stdout: version, stderr: '' }+ const answer = answers.length > 1 ? answers.shift()! : answers[0]+ versionAsks.push(answer)+ if (answer === PROBE_FAILS) throw Object.assign(new Error('spawn tmux ETIMEDOUT'), { code: 'ETIMEDOUT' })+ return { stdout: answer, stderr: '' }}if (hasSession(live, args)) return { stdout: '', stderr: '' }throw Object.assign(new Error("can't find session"), { code: 1 })@@ -141,7 +151,7 @@ async function tmuxManager(vi.spyOn(m as unknown as { readWindowSize: (k: string) => Promise<unknown> },'readWindowSize'- ).mockResolvedValue(window)+ ).mockResolvedValue(window ?? undefined);(m as unknown as { tmuxPath: string }).tmuxPath = '/usr/bin/tmux'vi.spyOn(m as unknown as { tmuxSessionExists: (k: string) => Promise<boolean> },@@ -227,19 +237,31 @@ describe('joinAsWatcher', () => {expect([spawned[0].cols, spawned[0].rows]).toEqual([132, 43])})- it('an unreadable window size falls back to the caller size, then to the last known size', async () => {- const m = await tmuxManager(['nt-n1', 'nt-n2', 'nt-n3'])- await m.joinAsWatcher(WATCHER, WATCH)- expect([spawned[0].cols, spawned[0].rows]).toEqual([40, 10])- // No caller size, no read, and a watcher's own client is not a size source → the default.- await m.joinAsWatcher(WATCHER + 1, { persistKey: 'n2', viewerId: 'watch-s2' })- expect([spawned[1].cols, spawned[1].rows]).toEqual([80, 24])- // With an owner's released size on record, that is the fallback.- const { sessionId } = await create(OWNER, { cols: 132, rows: 43, persistKey: 'n3' })- kill(OWNER, sessionId) // the last subscriber out releases it: no Session is held for n3 now- await m.joinAsWatcher(WATCHER + 2, { persistKey: 'n3', viewerId: 'watch-s3' })- expect(spawned.at(-1)!.args).toContain('attach-session')- expect([spawned.at(-1)!.cols, spawned.at(-1)!.rows]).toEqual([132, 43])+ it('an unreadable window size REFUSES the spawn — never a guessed size (caller, remembered, default)', async () => {+ const m = await tmuxManager(['nt-n1'], { window: null })+ // The caller's size is not used...+ expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)+ // ...nor the default...+ expect(await m.joinAsWatcher(WATCHER, { persistKey: 'n1', viewerId: 'watch-s1' })).toEqual(REFUSED)+ expect(spawned).toHaveLength(0)+ // ...nor a remembered (released) size.+ const own = await create(OWNER, { cols: 132, rows: 43 })+ kill(OWNER, own.sessionId)+ expect(m.watchSizeFor('n1')).toEqual({ cols: 132, rows: 43 })+ expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)+ expect(spawned).toHaveLength(1) // the owner's own client, nothing for the watcher+ })++ it('the refusal is "not now": once the window can be read, the next join spawns', async () => {+ const m = await tmuxManager(['nt-n1'], { window: null })+ expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)+ ;(m as unknown as { readWindowSize: ReturnType<typeof vi.fn> }).readWindowSize.mockResolvedValue({+ cols: 150,+ rows: 45+ })+ const w = await m.joinAsWatcher(WATCHER, WATCH)+ expect(w.unavailable).toBeUndefined()+ expect([spawned[0].cols, spawned[0].rows]).toEqual([150, 45])})it('reads the window size only when it has to', async () => {@@ -273,6 +295,28 @@ describe('joinAsWatcher', () => {warn.mockRestore()})+ it('a FAILED version probe is not an answer: not memoized, the next join asks again', async () => {+ const m = await tmuxManager(['nt-n1'], { version: [PROBE_FAILS, 'tmux 3.4\n'] })+ expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)+ expect(spawned).toHaveLength(0)+ const w = await m.joinAsWatcher(WATCHER, WATCH)+ expect(w.unavailable).toBeUndefined()+ expect(spawned).toHaveLength(1)+ expect(versionAsks).toEqual([PROBE_FAILS, 'tmux 3.4\n'])+ // A definite answer IS kept.+ await m.joinAsWatcher(WATCHER + 1, { ...WATCH, persistKey: 'n1', viewerId: 'watch-s2' })+ expect(versionAsks).toHaveLength(2)+ })++ it('a definite OLD answer is kept (no re-probe per viewer)', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const m = await tmuxManager(['nt-n1'], { version: ['tmux 3.1c\n', 'tmux 3.4\n'] })+ expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)+ expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)+ expect(versionAsks).toEqual(['tmux 3.1c\n'])+ warn.mockRestore()+ })+it('the version is probed once, however many watchers spawn', async () => {const m = await tmuxManager(['nt-n1', 'nt-n2'])await m.joinAsWatcher(WATCHER, WATCH)@@ -294,8 +338,8 @@ describe('joinAsWatcher', () => {const own = await create(OWNER, { cols: 132, rows: 43 })kill(OWNER, own.sessionId)expect(m.watchSizeFor('n1')).toEqual({ cols: 132, rows: 43 })- const w = await m.joinAsWatcher(WATCHER, WATCH) // no Session held → its own client, at 40x10- expect([spawned.at(-1)!.cols, spawned.at(-1)!.rows]).toEqual([40, 10])+ const w = await m.joinAsWatcher(WATCHER, WATCH) // no Session held → its own client, at the window (120x39)+ expect([spawned.at(-1)!.cols, spawned.at(-1)!.rows]).toEqual([120, 39])m.kill(WATCHER, w.sessionId, 'watch-s1') // the watcher's own view: its client is releasedexpect(spawned.at(-1)!.killed).toBe(true)expect(m.watchSizeFor('n1')).toEqual({ cols: 132, rows: 43 })@@ -366,6 +410,13 @@ describe('joinAsWatcher over SSH', () => {expect(versionAsks).toEqual([])})+ it('a remote window size that cannot be read: refused, nothing spawned', async () => {+ const m = await sshManager('present')+ ;(m as unknown as { readWindowSize: ReturnType<typeof vi.fn> }).readWindowSize.mockResolvedValue(undefined)+ expect(await m.joinAsWatcher(WATCHER, { ...WATCH, sshRemote: SSH_REMOTE })).toEqual(REFUSED)+ expect(spawned).toHaveLength(0)+ })+it('a remote session the host says is gone: refused, nothing spawned', async () => {const m = await sshManager('absent')expect(await m.joinAsWatcher(WATCHER, { ...WATCH, sshRemote: SSH_REMOTE })).toEqual(REFUSED)@@ -395,6 +446,89 @@ describe('joinAsWatcher (continued)', () => {})})+describe('syncWatcherClientSize', () => {+ type Read = ReturnType<typeof vi.fn>+ const readOf = (m: object): Read => (m as unknown as { readWindowSize: Read }).readWindowSize+ const sessionOf = (m: object, id: string) =>+ (m as unknown as { sessions: Map<string, { sizes: Map<unknown, unknown>; appliedSize?: unknown }> }).sessions.get(id)!++ it("resizes the watcher's OWN client to exactly the window size read now, and tells its viewers", async () => {+ const m = await tmuxManager(['nt-n1'])+ const w = await m.joinAsWatcher(WATCHER, WATCH) // spawned at the window, 120x39+ readOf(m).mockResolvedValue({ cols: 200, rows: 50 }) // the owner (elsewhere) resized the window+ fake.sent.length = 0+ expect(await m.syncWatcherClientSize(w.sessionId)).toBe(true)+ expect(spawned[0].resizes).toEqual([{ cols: 200, rows: 50 }])+ const sizes = fake.sent.filter((x) => x.channel === IPC.ptySize(w.sessionId))+ expect(sizes.map((x) => x.to)).toEqual([WATCHER])+ expect(sizes[0].args[0]).toEqual({ cols: 200, rows: 50 })+ })++ it('is never a size vote, and never a viewer-supplied size', async () => {+ const m = await tmuxManager(['nt-n1'])+ const w = await m.joinAsWatcher(WATCHER, WATCH)+ await m.joinAsWatcher(WATCHER + 1, { persistKey: 'n1', viewerId: 'watch-s2', cols: 33, rows: 7 })+ readOf(m).mockResolvedValue({ cols: 200, rows: 50 })+ await m.syncWatcherClientSize(w.sessionId)+ expect(spawned[0].resizes).toEqual([{ cols: 200, rows: 50 }])+ expect(sessionOf(m, w.sessionId).sizes.size).toBe(0)+ })++ it('an unchanged window resizes nothing (a full redraw is not free)', async () => {+ const m = await tmuxManager(['nt-n1'])+ const w = await m.joinAsWatcher(WATCHER, WATCH)+ expect(await m.syncWatcherClientSize(w.sessionId)).toBe(true)+ expect(spawned[0].resizes).toEqual([])+ })++ it('an unreadable size changes nothing', async () => {+ const m = await tmuxManager(['nt-n1'])+ const w = await m.joinAsWatcher(WATCHER, WATCH)+ readOf(m).mockResolvedValue(undefined)+ expect(await m.syncWatcherClientSize(w.sessionId)).toBe(false)+ expect(spawned[0].resizes).toEqual([])+ })++ it("never touches a session that is not a watcher's own client (the owner's pty is never resized)", async () => {+ const m = await tmuxManager(['nt-n1'])+ const own = await create(OWNER, { cols: 120, rows: 40 })+ await m.joinAsWatcher(WATCHER, WATCH) // co-attaches to the owner's Session+ readOf(m).mockClear()+ readOf(m).mockResolvedValue({ cols: 200, rows: 50 })+ expect(await m.syncWatcherClientSize(own.sessionId)).toBe(false)+ expect(readOf(m)).not.toHaveBeenCalled()+ expect(spawned[0].resizes).toEqual([])+ expect(await m.syncWatcherClientSize('no-such-session')).toBe(false)+ })++ it('a client that went away during the read is left alone', async () => {+ const m = await tmuxManager(['nt-n1'])+ const w = await m.joinAsWatcher(WATCHER, WATCH)+ let answer: (v: unknown) => void = () => {}+ readOf(m).mockImplementation(() => new Promise((r) => (answer = r)))+ const pending = m.syncWatcherClientSize(w.sessionId)+ m.kill(WATCHER, w.sessionId, 'watch-s1')+ answer({ cols: 200, rows: 50 })+ expect(await pending).toBe(false)+ expect(spawned[0].resizes).toEqual([])+ })++ it('an SSH watcher client is synced from the HOST read', async () => {+ const m = await tmuxManager([])+ vi.spyOn(+ m as unknown as { remoteSessionVerdict: () => Promise<string> },+ 'remoteSessionVerdict'+ ).mockResolvedValue('present')+ const SSH_REMOTE = { controlPath: '/tmp/nt-test-cm', conn: { host: 'h', user: 'u' }, remoteCwd: '/srv/app' }+ const w = await m.joinAsWatcher(WATCHER, { ...WATCH, sshRemote: SSH_REMOTE })+ readOf(m).mockClear()+ readOf(m).mockResolvedValue({ cols: 210, rows: 55 })+ expect(await m.syncWatcherClientSize(w.sessionId)).toBe(true)+ expect(readOf(m)).toHaveBeenCalledWith('n1', expect.objectContaining({ controlPath: '/tmp/nt-test-cm' }))+ expect(spawned[0].resizes).toEqual([{ cols: 210, rows: 55 }])+ })+})+describe('watchSizeFor', () => {it('is the size the live pty runs at, whatever the watcher reported', async () => {const m = await manager()diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.tsindex 1fc930c62..c1ca6a104 100644--- a/src/core/remote-ssh/control-master.test.ts+++ b/src/core/remote-ssh/control-master.test.ts@@ -282,7 +282,7 @@ describe('remoteCaptureVisibleArgs', () => {})describe('remoteTmuxWatcherArgs', () => {- it('a tty-allocating child that ATTACHES read-only and size-neutral, never creates', () => {+ it('a tty-allocating child that ATTACHES read-only and ignore-size, never creates', () => {const args = remoteTmuxWatcherArgs(conn, '/s.sock', 'nt-x')expect(args[0]).toBe('-t')expect(args.slice(1, 1 + childPrefix.length)).toEqual(childPrefix)@@ -304,7 +304,7 @@ describe('remoteWindowSizeArgs', () => {const args = remoteWindowSizeArgs(conn, '/s.sock', 'nt-x')expect(args.slice(0, childPrefix.length)).toEqual(childPrefix)expect(args[args.length - 1]).toBe(- `${TP}tmux -L ${RMT_TMUX_SOCKET} display-message -p -t '=nt-x:' '#{window_width} #{window_height}'`+ `${TP}tmux -L ${RMT_TMUX_SOCKET} display-message -p -t '=nt-x:' '#{window_width} #{window_height} #{status}'`)})})diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.tsindex aa48bf8af..58a5ec04b 100644--- a/src/core/remote-ssh/control-master.ts+++ b/src/core/remote-ssh/control-master.ts@@ -542,8 +542,9 @@ export function remoteCaptureVisibleArgs(conn: SshConnection, controlPath: strin/*** A live link watcher's OWN client on the host, for a node no Session is held for: a tty-allocating* ssh child (`-t`, like `remoteTmuxPtyArgs`) running `attach-session -E -f ignore-size,read-only` on- * the exact target — never creating, never resizing the owner's window, never touching the session- * env (why each flag: `watch-link/watcher-client.ts`). Deliberately NOT wrapped like the owner's+ * the exact target — never creating, never touching the session env, and out of the window's sizing+ * while an unflagged client is attached anywhere on the server (tmux honours `ignore-size` only then;+ * the caller spawns it at the window's current size and keeps it synced — `watch-link/watcher-client.ts`). Deliberately NOT wrapped like the owner's* interactive command: a host without tmux gets a failed command, never a plain login shell — a* watcher must not get a shell. An old remote tmux (< 3.2) rejects `-f` with a usage error: the* command fails and nothing attaches. Proven under a real /bin/sh in watcher-attach.realsh.test.tsdiff --git a/src/core/remote-ssh/watcher-attach.realsh.test.ts b/src/core/remote-ssh/watcher-attach.realsh.test.tsindex d84b1499e..3423e877d 100644--- a/src/core/remote-ssh/watcher-attach.realsh.test.ts+++ b/src/core/remote-ssh/watcher-attach.realsh.test.ts@@ -146,7 +146,8 @@ describe('remoteWindowSizeArgs (real /bin/sh)', () => {// Skipped without a tmux binary: the proof is tmux's own reply.const hit = runUnder(delegateDir, sizeLine('nt-w-12'))expect(hit.status).toBe(0)- expect(parseWindowSize(hit.stdout)).toEqual({ cols: 100, rows: 30 })+ // `-f /dev/null` = tmux defaults, status on: the client size for a 100x30 window is 100x31.+ expect(parseWindowSize(hit.stdout)).toEqual({ cols: 100, rows: 31 })// A prefix of a live session's name: exit 0 with every format empty — no size, never 12's.const miss = runUnder(delegateDir, sizeLine('nt-w-1'))expect(parseWindowSize(miss.stdout)).toBeUndefined()diff --git a/src/core/watch-link/watcher-client.realtty.test.ts b/src/core/watch-link/watcher-client.realtty.test.tsindex da2d1f47e..3d54586c6 100644--- a/src/core/watch-link/watcher-client.realtty.test.ts+++ b/src/core/watch-link/watcher-client.realtty.test.ts@@ -1,4 +1,4 @@-// A LIVE LINK WATCHER'S OWN TMUX CLIENT, ON A REAL TTY (controller ruling R19).+// A LIVE LINK WATCHER'S OWN TMUX CLIENT, ON A REAL TTY (controller rulings R19, R20).//// When no Session is held for a node (an app restart, a closed project, a released node), a watcher// joins by spawning its OWN tmux client. Measured on tmux 3.4, the owner's `new-session -A` spelling@@ -6,7 +6,10 @@// makes the newest client the size) — SIGWINCH to a running agent, because somebody opened a link.// The watcher's client is therefore `attach-session -E -f ignore-size,read-only -t =nt-<id>:`, and// each word is load-bearing; this file measures each one on a real pty:-// - ignore-size: the owner's window and the owner's own client keep their size;+// - ignore-size: while the owner is attached, the owner's window and its own client keep their size.+// NOT unconditional: tmux 3.4 honours it only while an unflagged client is attached+// somewhere on the server; alone, the watcher sizes the window like any client — the+// last describe measures that rule and the sync that keeps the window where it was;// - read-only: bytes typed into the watcher's client never reach the pane;// - -E: attaching does not run `update-environment`, which would STRIP every listed name the// watcher's own env lacks (the account scope, CLAUDE_CONFIG_DIR — CLAUDE.md #419);@@ -148,7 +151,7 @@ afterAll(() => {})describe("a watcher's own tmux client (local)", () => {- itReal('never resizes the owner: the window stays 120x39 and the owner keeps its view', async () => {+ itReal('with the owner attached, the watcher does not resize the window: 120x39, owner view unchanged', async () => {newSession('nt-own', 'sleep 120')await ownerOf('nt-own')const before = clientsOf('nt-own')@@ -209,13 +212,14 @@ describe("a watcher's own tmux client (local)", () => {itReal('the window-size read answers the live window, and nothing for a miss', async () => {newSession('nt-sz', 'sleep 120')await ownerOf('nt-sz')- expect(parseWindowSize(tmux(localWindowSizeArgs(SOCKET, 'nt-sz').slice(2)))).toEqual({ cols: 120, rows: 39 })+ // The owner's 120x40 client with tmux's default status line: window 120x39, client size 120x40.+ expect(parseWindowSize(tmux(localWindowSizeArgs(SOCKET, 'nt-sz').slice(2)))).toEqual({ cols: 120, rows: 40 })expect(parseWindowSize(tmux(localWindowSizeArgs(SOCKET, 'nt-s').slice(2)))).toBeUndefined()})})describe("a watcher's own tmux client (SSH arm, the generated remote line under a real /bin/sh)", () => {- itReal('attaches read-only and size-neutral: the owner window stays 120x39, env intact', async () => {+ itReal('attaches read-only and ignore-size: with the owner attached the window stays 120x39, env intact', async () => {newSession('nt-rw', 'sleep 120')await ownerOf('nt-rw')const line = remoteTmuxWatcherArgs({ host: 'h', user: 'u' }, '/cm/p1', 'nt-rw').at(-1)!@@ -237,3 +241,70 @@ describe("a watcher's own tmux client (SSH arm, the generated remote line underexpect(tryTmux(['has-session', '-t', '=nt-rgone']).ok).toBe(false)})})++// R20 — `ignore-size` is honoured only while an UNFLAGGED client is attached somewhere on the server.+// Its own private server (not SOCKET above, where the owner clients of the tests before stay attached+// until afterAll and would keep `ignore-size` honoured). Sessions carry the production conf's+// `status off`, so the window IS the client size.+describe("keeping a watcher's own client at the window size (sync)", () => {+ const SYNC_SOCKET = `nt-wlsy-${process.pid}`+ const syncSessions: string[] = []+ const tx = (args: string[]): string =>+ execFileSync(REAL_TMUX!, ['-L', SYNC_SOCKET, ...args], {+ env: baseEnv(),+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe']+ })+ const win = (name: string): string =>+ tx(['display-message', '-p', '-t', `=${name}:`, '#{window_width}x#{window_height}']).trim()+ /** Exactly what `readWindowSize` + the spawn/sync do: the production argv, parsed. */+ const readSize = (name: string): { cols: number; rows: number } =>+ parseWindowSize(tx(localWindowSizeArgs(SYNC_SOCKET, name).slice(2)))!++ afterAll(() => {+ if (!REAL_TMUX || !pty) return+ for (const name of syncSessions) {+ try {+ tx(['kill-session', '-t', `=${name}`])+ } catch {+ /* gone */+ }+ }+ })++ async function scenario(name: string, sync: boolean): Promise<string[]> {+ const seen: string[] = []+ // `-f /dev/null` on the first call boots this private server with tmux defaults.+ tx(['-f', '/dev/null', 'new-session', '-d', '-s', name, '-x', '120', '-y', '40', 'sleep 120', ';', 'set-option', 'status', 'off'])+ syncSessions.push(name)+ // The watcher's own client, spawned at the window size read just before (spawnNew).+ const size = readSize(name)+ seen.push(`${size.cols}x${size.rows}`)+ const watcher = spawnClient(REAL_TMUX!, localWatcherAttachArgs(SYNC_SOCKET, name), size.cols, size.rows, baseEnv())+ await until(() => tx(['list-clients', '-t', `=${name}`]).trim().split('\n').filter(Boolean).length === 1)+ // An owner-style (unflagged) client joins and sizes the window to 200x50.+ const owner = spawnClient(REAL_TMUX!, ['-L', SYNC_SOCKET, 'attach-session', '-t', `=${name}`], 200, 50, baseEnv())+ await until(() => win(name) === '200x50')+ seen.push(win(name))+ if (sync) {+ // syncWatcherClientSize: read the window, resize the watcher's OWN pty to exactly that.+ const now = readSize(name)+ watcher.proc.resize(now.cols, now.rows)+ await sleep(200)+ }+ owner.proc.kill()+ await until(() => tx(['list-clients', '-t', `=${name}`]).trim().split('\n').filter(Boolean).length === 1)+ await sleep(300)+ seen.push(win(name))+ watcher.proc.kill()+ return seen+ }++ itReal('control, WITHOUT sync: once the unflagged client leaves, the window snaps to the watcher (120x40)', async () => {+ expect(await scenario('nt-nosync', false)).toEqual(['120x40', '200x50', '120x40'])+ })++ itReal('WITH sync: the window keeps its latest size (200x50) after the unflagged client leaves', async () => {+ expect(await scenario('nt-sync', true)).toEqual(['120x40', '200x50', '200x50'])+ })+})diff --git a/src/core/watch-link/watcher-client.test.ts b/src/core/watch-link/watcher-client.test.tsindex c50993081..062e3f330 100644--- a/src/core/watch-link/watcher-client.test.ts+++ b/src/core/watch-link/watcher-client.test.ts@@ -12,7 +12,7 @@ import {describe('localWatcherAttachArgs', () => {const args = localWatcherAttachArgs('sock', 'nt-abc')- it('attaches (never creates), skips update-environment, and never sizes or types into the window', () => {+ it('attaches (never creates), skips update-environment, ignore-size and read-only', () => {expect(args).toEqual(['-L', 'sock', 'attach-session', '-E', '-f', 'ignore-size,read-only', '-t', '=nt-abc:'])expect(WATCHER_CLIENT_FLAGS).toBe('ignore-size,read-only')})@@ -30,8 +30,8 @@ describe('localWatcherAttachArgs', () => {})describe('localWindowSizeArgs / parseWindowSize', () => {- it('reads the window size of exactly this session', () => {- expect(WINDOW_SIZE_FORMAT).toBe('#{window_width} #{window_height}')+ it('reads the window size of exactly this session, with its status lines', () => {+ expect(WINDOW_SIZE_FORMAT).toBe('#{window_width} #{window_height} #{status}')expect(localWindowSizeArgs('sock', 'nt-abc')).toEqual(['-L','sock',@@ -39,18 +39,21 @@ describe('localWindowSizeArgs / parseWindowSize', () => {'-p','-t','=nt-abc:',- '#{window_width} #{window_height}'+ '#{window_width} #{window_height} #{status}'])})- it('parses a real reply, CRLF included', () => {- expect(parseWindowSize('120 39\n')).toEqual({ cols: 120, rows: 39 })- expect(parseWindowSize('80 24')).toEqual({ cols: 80, rows: 24 })- expect(parseWindowSize('80 24\r\n')).toEqual({ cols: 80, rows: 24 })+ it('answers the CLIENT size that leaves the window where it is: window + status lines', () => {+ // The production conf has `status off`: the client size IS the window size.+ expect(parseWindowSize('120 40 off\n')).toEqual({ cols: 120, rows: 40 })+ // tmux defaults (`status on`): a client one row taller than the window, or the window loses a row.+ expect(parseWindowSize('120 39 on\n')).toEqual({ cols: 120, rows: 40 })+ expect(parseWindowSize('120 37 3\n')).toEqual({ cols: 120, rows: 40 })+ expect(parseWindowSize('80 24 off\r\n')).toEqual({ cols: 80, rows: 24 })})it('an exact-target miss (exit 0, every format empty) is no size, never 0x0', () => {- for (const out of ['', ' \n', '\n', '0 24\n', '80 0\n', 'a b\n', '80\n', '80 24 1\n', ' 80 24\n']) {+ for (const out of ['', ' \n', '\n', '0 24 off\n', '80 0 off\n', 'a b off\n', '80 24\n', '80 24 7\n', '80 24 yes\n', ' 80 24 off\n']) {expect(parseWindowSize(out)).toBeUndefined()}})diff --git a/src/core/watch-link/watcher-client.ts b/src/core/watch-link/watcher-client.tsindex 241b951f1..d3131e0eb 100644--- a/src/core/watch-link/watcher-client.ts+++ b/src/core/watch-link/watcher-client.ts@@ -5,7 +5,15 @@// tmux 3.4 (watcher-client.realtty.test.ts):// - SIZE. Under tmux's default `window-size latest` the newest client sets the window size: a watcher// at 40x10 shrank the owner's 120x39 window to 40x9 — a SIGWINCH to the agent running there, because-// somebody opened a link. `-f ignore-size` leaves the window at 120x39 and the owner's client as it was.+// somebody opened a link. With `-f ignore-size` the window stayed at 120x39 and the owner's client as+// it was — BUT only because the owner was attached: tmux 3.4 honours `ignore-size` only while at least+// one client WITHOUT the flag is attached to some session on the same server. A watcher that is the+// only client sizes the window like any other (measured: spawned at 40x10 alone → window 40x10; spawned+// at 120x40, an owner joins at 200x50 and leaves → the window snaps back to 120x40). So the client is+// spawned at the window's CURRENT size, read just before the spawn, and refused when that read fails+// (`PtyManager.spawnNew`); `PtyManager.syncWatcherClientSize` keeps it at the window's size while the+// link has viewers. Residual: drift for up to one sync interval, and a read racing an owner's resize+// or departure (the window then keeps the size read a moment before).// - ENVIRONMENT. Attaching runs `update-environment`, which copies every listed name from the attaching// client's env into the session and STRIPS the ones that client lacks — the account scope// (CLAUDE_CONFIG_DIR, …, CLAUDE.md #419) included. `-E` skips it; the session env is untouched.@@ -30,21 +38,29 @@ export function localWatcherAttachArgs(socket: string, sessionName: string): strreturn ['-L', socket, 'attach-session', '-E', '-f', WATCHER_CLIENT_FLAGS, '-t', exactPaneTarget(sessionName)]}-/** The window's size, so a watcher's client is spawned at what the owner sees. */-export const WINDOW_SIZE_FORMAT = '#{window_width} #{window_height}'+/**+ * What a watcher's client must be sized to so it leaves the window exactly where it is: the window's+ * width and height, plus the status lines tmux draws under it on that session (`#{status}`: `off`,+ * `on` = 1, or `2`–`5`). With the production conf (`set -g status off`) that is the window size itself;+ * a host whose server runs tmux's defaults (status on — a remote conf that was never sourced) would+ * otherwise lose one row to the status line every time the watcher, as the only client, set the size.+ */+export const WINDOW_SIZE_FORMAT = '#{window_width} #{window_height} #{status}'export function localWindowSizeArgs(socket: string, sessionName: string): string[] {return ['-L', socket, 'display-message', '-p', '-t', exactPaneTarget(sessionName), WINDOW_SIZE_FORMAT]}-/** `"<cols> <rows>"`, both positive. An exact-target miss answers exit 0 with every format EMPTY, so- * anything else is no size — never 0x0. */+/** `"<width> <height> <status>"` → the client size for that window (see `WINDOW_SIZE_FORMAT`), both+ * positive. An exact-target miss answers exit 0 with every format EMPTY, so anything else is no size,+ * never 0x0; an unknown status value is no size too. */export function parseWindowSize(stdout: string): { cols: number; rows: number } | undefined {- const m = /^(\d+) (\d+)$/.exec(stdout.replace(/\r?\n$/, ''))+ const m = /^(\d+) (\d+) (off|on|[0-5])$/.exec(stdout.replace(/\r?\n$/, ''))if (!m) return undefinedconst cols = Number(m[1])- const rows = Number(m[2])- return cols > 0 && rows > 0 ? { cols, rows } : undefined+ const height = Number(m[2])+ const statusLines = m[3] === 'off' ? 0 : m[3] === 'on' ? 1 : Number(m[3])+ return cols > 0 && height > 0 ? { cols, rows: height + statusLines } : undefined}export interface TmuxVersion {