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 tmux client never resizes, creates or re-scopes
review8183ab76045d
diff --git a/src/core/pty-manager.capture-visible.test.ts b/src/core/pty-manager.capture-visible.test.tsindex c957b5105..d083c1223 100644--- a/src/core/pty-manager.capture-visible.test.ts+++ b/src/core/pty-manager.capture-visible.test.ts@@ -190,3 +190,57 @@ describe('captureVisible — SSH project', () => {expect(await m.captureVisible('sess-1')).toEqual(unavailableCapture())})})++describe('readWindowSize — the size a watcher client is spawned at', () => {+ async function bare(tmux: string | null = '/usr/bin/tmux') {+ const { PtyManager } = await import('./pty-manager')+ const mgr = new PtyManager() as unknown as {+ tmuxPath: string | null+ readWindowSize(k: string, ssh?: unknown): Promise<unknown>+ }+ mgr.tmuxPath = tmux+ return mgr+ }++ it('asks the local tmux for exactly this session and parses the reply', async () => {+ script.answer = () => ({ stdout: '120 39\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}']+ }+ ])+ })++ it('asks the REMOTE tmux over the ControlMaster for an SSH node', async () => {+ script.answer = () => ({ stdout: '100 30\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}'`+ )+ })++ it('an exact-target miss (every format empty), a failure or no tmux is undefined', async () => {+ script.answer = () => ({ stdout: ' \n' })+ expect(await (await bare()).readWindowSize(NODE)).toBeUndefined()+ script.answer = () => {+ throw Object.assign(new Error('no server running'), { code: 1 })+ }+ expect(await (await bare()).readWindowSize(NODE)).toBeUndefined()+ calls.length = 0+ expect(await (await bare(null)).readWindowSize(NODE)).toBeUndefined()+ expect(calls).toEqual([])+ })++ it('a remote node with no ssh binary is undefined — never read from the local tmux', async () => {+ ssh.path = null+ const m = await bare()+ expect(await m.readWindowSize(NODE, SSH_REMOTE)).toBeUndefined()+ expect(calls).toEqual([])+ })+})diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 65c62a904..770378676 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -34,6 +34,8 @@ import {remotePasteDelivery,remoteCapturePaneArgs,remoteCaptureVisibleArgs,+ remoteTmuxWatcherArgs,+ remoteWindowSizeArgs,remotePaneCommandArgs,remotePaneCwdArgs,remoteSessionAgeArgs,@@ -62,6 +64,13 @@ import {visibleCaptureRoute,type VisibleCapture} from './watch-link/capture-route'+import {+ localWatcherAttachArgs,+ localWindowSizeArgs,+ parseTmuxVersion,+ parseWindowSize,+ supportsWatcherClient+} from './watch-link/watcher-client'import {recordFreshSpawnOwner,forgetPaneOwner,@@ -631,6 +640,18 @@ function releaseSpawnSlotOnOutput(session: Session | undefined, release: SpawnSl}}+/**+ * Marks a create as a live link WATCHER's (`joinAsWatcher`), and nothing else sets it. A symbol, not a+ * `PtyCreateOptions` field: that type is the `pty:create` wire payload, and a symbol cannot arrive over+ * IPC, the WS bridge or the relay — so no renderer, browser tab or peer can ask for a watcher client+ * (or opt out of one). Object spread copies it, so it survives spawnNew's option rewrites.+ */+const WATCHER_CLIENT: unique symbol = Symbol('nodeterm.watcherClient')+type WatcherCreateOptions = PtyCreateOptions & { readonly [WATCHER_CLIENT]?: true }+function isWatcherCreate(options: PtyCreateOptions): boolean {+ return (options as WatcherCreateOptions)[WATCHER_CLIENT] === true+}+interface Session {proc: pty.IPtynativeWindowsPane?: NativeWindowsPane@@ -746,6 +767,13 @@ interface Session {* already branches on `sshRemote`.*/sessionHost?: boolean+ /**+ * A live link watcher's OWN tmux client (`attach-session -E -f ignore-size,read-only`, spawned by+ * `joinAsWatcher` when no Session was held). Never indexed, and invisible to the persistKey lookups+ * (`sessionByPersistKey`, `liveSessionForNode`): it is read-only, so an owner joining it, or a+ * background write going through it, would lose every keystroke. Only watchers ever reach it.+ */+ watcherClient?: boolean}/** Sinks for a detached session whose output is served somewhere other than the renderer@@ -1186,7 +1214,9 @@ export class PtyManager {// enforced (so the pane is not left to reflow), and whether this node's tmux was REMOTE (so it// is never shadowed against our local socket). The `Session` holding both goes with `forget`// below; this is the record that survives it.- if (session.persistKey)+ // Not for a watcher's own client: its size is whatever it was spawned at, never the size an owner+ // enforced, and a later shadow would push that size into the pane (`shadowAttach`).+ if (session.persistKey && !session.watcherClient)this.released.set(session.persistKey, {sessionId,size: session.appliedSize,@@ -2073,6 +2103,7 @@ export class PtyManager {const hit = indexed ? this.sessions.get(indexed) : undefinedif (indexed && hit) return [indexed, hit]for (const [id, s] of this.sessions) {+ if (s.watcherClient) continueif (s.persistKey === persistKey || s.nodeId === persistKey) return [id, s]}return undefined@@ -2239,8 +2270,15 @@ export class PtyManager {options: PtyCreateOptions,persistKey: string): Promise<PtyCreateResult> | undefined {- const existingId = this.byPersistKey.get(persistKey)- const existing = existingId ? this.sessions.get(existingId) : undefined+ let existingId = this.byPersistKey.get(persistKey)+ let existing = existingId ? this.sessions.get(existingId) : undefined+ // A second live link viewer of a node no owner Session is held for shares the first viewer's own+ // tmux client (unindexed, see `watcherClient`) rather than opening another — each one is a tmux+ // client, and over SSH an ssh channel against the host's MaxSessions. Only a watcher may join it.+ if ((!existingId || !existing) && isWatcherCreate(options)) {+ existingId = this.watcherClientSessionId(persistKey)+ existing = existingId ? this.sessions.get(existingId) : undefined+ }if (!existingId || !existing) return undefined// The joining VIEW's composite key: a second client, OR the SAME client's second view (the// kanban card modal). Either way it is a distinct subscriber of the one shared session/pty.@@ -2412,6 +2450,12 @@ export class PtyManager {// the renderer's sentence claims only that no running terminal was found.if (options.joinOnly && (fresh || freshUnverified || joinOnlyLocalVerdict === 'unknown'))return { sessionId: '', fresh: false, unavailable: 'join-only' }+ // A watcher's own LOCAL client needs client flags (tmux >= 3.2). Without them it would either fail+ // to attach or — worse, spelled without the flags — resize the owner's window. Refused the same+ // way as a session that cannot be confirmed. Over SSH the host's version is unknown here: the+ // 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' }// 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()@@ -2683,10 +2727,19 @@ export class PtyManager {}})+ /** A live link watcher's own tmux client for this node, if one is running (see `watcherClient`). */+ private watcherClientSessionId(persistKey: string): string | undefined {+ for (const [id, session] of this.sessions) {+ if (session.watcherClient && session.persistKey === persistKey) return id+ }+ return undefined+ }+/** Find the live session registered under a node id (persistKey), if any. */private sessionByPersistKey(persistKey: string): Session | undefined {for (const session of this.sessions.values()) {- if (session.persistKey === persistKey) return session+ // A watcher's read-only client is not the node's session for anyone (see `watcherClient`).+ if (session.persistKey === persistKey && !session.watcherClient) return session}return undefined}@@ -3021,7 +3074,9 @@ 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.- if (options.persistKey) {+ // 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.+ 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// nothing, and a line per terminal anyone opens is noise in the report it exists for.@@ -3313,7 +3368,18 @@ export class PtyManager {// holds the ssh client. Only when BOTH sshRemote and persistKey are set and ssh resolves —// otherwise this falls through to the unchanged local-tmux / plain-shell branches below.const remoteSsh = options.sshRemote && options.persistKey ? findSsh() : null- if (options.sshRemote && options.persistKey && remoteSsh) {+ if (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+ // (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+ if (process.env.NODETERM_APP_AGENT_SOCK) env.SSH_AUTH_SOCK = process.env.NODETERM_APP_AGENT_SOCK+ args = remoteTmuxWatcherArgs(+ options.sshRemote.conn,+ options.sshRemote.controlPath,+ sessionName(options.persistKey)+ )+ } else if (options.sshRemote && options.persistKey && remoteSsh) {file = remoteSsh// The remote twin of the local `ensureNodeToken` above: materialise THIS node's token on the// host before the attach. The connect path writes one for every node the canvas had AT@@ -3475,6 +3541,10 @@ export class PtyManager {'-t',sessionName(options.persistKey)]+ } else if (isWatcherCreate(options)) {+ // A live link watcher's own client: attach-only, `-E`, `ignore-size,read-only`, exact target+ // (see `watch-link/watcher-client.ts`). No `-f <conf>`: attach never starts a server.+ args = localWatcherAttachArgs(TMUX_SOCKET, sessionName(options.persistKey))} else {// The hook-server env (port/token/node id/agent id) is passed explicitly via `-e`// (one `-e KEY=VALUE` per key) since the shared tmux server can't rely on inherited env.@@ -3656,7 +3726,7 @@ export class PtyManager {// The spawn's claim went to the backend unbounded (a renderer view adapts to any size).appliedBounding: false,nodeId: options.persistKey,- indexKey: options.persistKey && !sinks ? options.persistKey : undefined,+ indexKey: options.persistKey && !sinks && !isWatcherCreate(options) ? options.persistKey : undefined,onData: sinks?.onData,onExit: sinks?.onExit,onSinkSize: sinks?.onSize,@@ -3677,7 +3747,8 @@ export class PtyManager {unwatchedSince: null,pausedBy: new Set<string>(),accountFallback,- sessionHost: useSessionHost+ sessionHost: useSessionHost,+ ...(isWatcherCreate(options) ? { watcherClient: true } : {})}// Both shared timers are armed by the first session that needs them: the scrollback snapshots// and the idle reap are both about tmux-backed sessions and nothing else.@@ -4456,22 +4527,115 @@ export class PtyManager {}/**- * Join a node's RUNNING session as a live link's viewer: never spawns (`joinOnly`), never votes on- * the shared pty's size (`sizeVote: false`). Both are forced AFTER the caller's options, so nothing- * a caller passes can turn either off.+ * 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).*/- joinAsWatcher(+ async joinAsWatcher(clientId: ClientId,opts: {persistKey: stringviewerId: string- cols: number- rows: number+ cols?: number+ rows?: numbersshRemote?: PtyCreateOptions['sshRemote']requireRemote?: boolean}): Promise<PtyCreateResult> {- return this.create(clientId, { ...opts, joinOnly: true, sizeVote: false })+ 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.+ const indexedId = this.byPersistKey.get(persistKey)+ const held = indexedId ? this.sessions.get(indexedId) : undefined+ const given =+ Number.isInteger(opts.cols) && Number.isInteger(opts.rows) && opts.cols! > 0 && opts.rows! > 0+ ? { cols: opts.cols!, rows: opts.rows! }+ : undefined+ const size =+ (held && given) ||+ (await this.readWindowSize(persistKey, sshRemote)) ||+ given ||+ this.watchSizeFor(persistKey) || { cols: 80, rows: 24 }+ const options: WatcherCreateOptions = {+ persistKey,+ viewerId,+ cols: size.cols,+ rows: size.rows,+ ...(sshRemote ? { sshRemote } : {}),+ ...(opts.requireRemote || sshRemote ? { requireRemote: true } : {}),+ joinOnly: true,+ sizeVote: false,+ [WATCHER_CLIENT]: true+ }+ return this.create(clientId, options)+ }++ /**+ * 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).+ */+ async readWindowSize(+ persistKey: string,+ sshRemote?: PtyCreateOptions['sshRemote']+ ): Promise<{ cols: number; rows: number } | undefined> {+ const target = sessionName(persistKey)+ try {+ if (sshRemote) {+ const ssh = findSsh()+ if (!ssh) return undefined+ const { stdout } = await runAsync(ssh, remoteWindowSizeArgs(sshRemote.conn, sshRemote.controlPath, target), {+ encoding: 'utf-8'+ })+ return parseWindowSize(stdout)+ }+ if (!this.tmuxPath) return undefined+ const { stdout } = await runAsync(this.tmuxPath, localWindowSizeArgs(TMUX_SOCKET, target), {+ encoding: 'utf-8',+ timeout: PROBE_TIMEOUT_MS+ })+ return parseWindowSize(stdout)+ } catch {+ return undefined+ }+ }++ /** `tmux -V` for the LOCAL binary, asked once per binary path (a watcher client needs >= 3.2). */+ private watcherTmuxProbe: { path: string; ok: Promise<boolean> } | null = null+ /** The refusal is logged once per app run, not once per viewer. */+ private watcherTmuxRefusalLogged = false++ private localTmuxSupportsWatcherClient(): Promise<boolean> {+ const tmuxPath = this.tmuxPath+ if (!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`+ )+ }+ return supported+ })+ this.watcherTmuxProbe = { path: tmuxPath, ok }+ return ok}/**diff --git a/src/core/pty-watch-join.test.ts b/src/core/pty-watch-join.test.tsindex f5769e9d1..3a2dd7df0 100644--- a/src/core/pty-watch-join.test.ts+++ b/src/core/pty-watch-join.test.ts@@ -1,5 +1,4 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'-import { initPlatform, resetPlatformForTests } from './platform'import { fakePlatform, type FakePlatform } from './platform-fake'import { IPC } from '../shared/ipc'import type { PtyCreateOptions, PtyCreateResult } from '../shared/types'@@ -12,7 +11,11 @@ import type { PtyCreateOptions, PtyCreateResult } from '../shared/types'*/interface FakePty {+ file: stringargs: string[]+ cols: number+ rows: number+ writes: string[]onDataCb?: (d: string) => voidonExitCb?: (e: { exitCode: number }) => voidresizes: Array<{ cols: number; rows: number }>@@ -25,8 +28,16 @@ vi.mock('./session-host-backend', async () =>)vi.mock('node-pty', () => ({- spawn: (_file: string, args: string[], _opts: unknown) => {- const p: FakePty = { args: [...(args ?? [])], resizes: [], killed: false }+ spawn: (file: string, args: string[], opts: { cols: number; rows: number }) => {+ const p: FakePty = {+ file,+ args: [...(args ?? [])],+ cols: opts.cols,+ rows: opts.rows,+ writes: [],+ resizes: [],+ killed: false+ }spawned.push(p)return {onData: (cb: (d: string) => void) => {@@ -35,7 +46,7 @@ vi.mock('node-pty', () => ({onExit: (cb: (e: { exitCode: number }) => void) => {p.onExitCb = cb},- write: () => {},+ write: (d: string) => p.writes.push(d),resize: (cols: number, rows: number) => p.resizes.push({ cols, rows }),pause: () => {},resume: () => {},@@ -52,21 +63,44 @@ vi.mock('./pty-devices', async (importOriginal) => ({readPtyDevices: () => ({ ceiling: 511, inUse: 8 })}))+// `ssh` is found or not per test (`findSsh` memoizes per module, hence `vi.resetModules` below).+const ssh = vi.hoisted(() => ({ path: '/usr/bin/ssh' as string | null }))+vi.mock('./exec-path', async (importOriginal) => {+ const real = await importOriginal<typeof import('./exec-path')>()+ return {+ ...real,+ findExecutableSync: (bin: string, fallbacks?: string[]) =>+ bin === 'ssh' ? ssh.path : real.findExecutableSync(bin, fallbacks)+ }+})+vi.mock('./remote-ssh/agent-probe', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./remote-ssh/agent-probe')>()),+ probeAgentSockToPin: async () => undefined+}))+const OWNER = 1const WATCHER = 7+const VIEWER = 2const REFUSED: PtyCreateResult = { sessionId: '', fresh: false, unavailable: 'join-only' }let fake: FakePlatform-beforeEach(() => {+let platformModule: typeof import('./platform')++beforeEach(async () => {spawned.length = 0+ ssh.path = '/usr/bin/ssh'+ // A fresh module graph per test (`findSsh` memoizes per module), so the platform the manager+ // reads is the one initialised here — imported AFTER the reset, never the static copy.+ vi.resetModules()+ platformModule = await import('./platform')fake = fakePlatform()- initPlatform(fake)+ platformModule.initPlatform(fake)vi.useFakeTimers()})afterEach(() => {vi.useRealTimers()- resetPlatformForTests()+ platformModule.resetPlatformForTests()})type ConfirmedProcessRun = (file: string, args: readonly string[], opts?: object) => Promise<unknown>@@ -85,13 +119,29 @@ function hasSession(live: string[], args: readonly string[]): boolean {return live.some((s) => s === target || s.startsWith(target))}-/** A tmux-backed manager whose probes answer from `live` without touching a tmux socket. */-async function tmuxManager(live: string[]) {+/** Every `tmux -V` the manager asked (the watcher client's version probe). */+const versionAsks: string[] = []++/** 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. */+async function tmuxManager(+ live: string[],+ { version = 'tmux 3.4\n', window }: { version?: string; window?: { cols: number; rows: number } } = {}+) {+ versionAsks.length = 0const confirmedProcessRun: ConfirmedProcessRun = async (_file, args) => {+ if (args[0] === '-V') {+ versionAsks.push(version)+ return { stdout: version, stderr: '' }+ }if (hasSession(live, args)) return { stdout: '', stderr: '' }throw Object.assign(new Error("can't find session"), { code: 1 })}const m = await manager({ confirmedProcessRun })+ vi.spyOn(+ m as unknown as { readWindowSize: (k: string) => Promise<unknown> },+ 'readWindowSize'+ ).mockResolvedValue(window);(m as unknown as { tmuxPath: string }).tmuxPath = '/usr/bin/tmux'vi.spyOn(m as unknown as { tmuxSessionExists: (k: string) => Promise<boolean> },@@ -143,16 +193,196 @@ describe('joinAsWatcher', () => {expect(sizes[0].args[0]).toEqual({ cols: 120, rows: 40 })})- it('warm-reattaches a running tmux session as a mirror (no -D), never creating one', async () => {+ it('with no Session held, spawns its OWN client: attach-session -E -f ignore-size,read-only, exact target', async () => {const m = await tmuxManager(['nt-n1'])const w = await m.joinAsWatcher(WATCHER, WATCH)expect(w.unavailable).toBeUndefined()expect(w.fresh).toBe(false)expect(spawned).toHaveLength(1)+ expect(spawned[0].file).toBe('/usr/bin/tmux')+ expect(spawned[0].args).toEqual([+ '-L',+ 'node-terminal',+ 'attach-session',+ '-E',+ '-f',+ 'ignore-size,read-only',+ '-t',+ '=nt-n1:'+ ])+ })++ it('control: a hosted Viewer (joinOnly, not a watcher) keeps its new-session -A mirror, byte-identical', async () => {+ await tmuxManager(['nt-n1'])+ await create(VIEWER, { joinOnly: true, sizeVote: false })+ expect(spawned[0].args).toContain('new-session')expect(spawned[0].args).toContain('-A')- expect(spawned[0].args).not.toContain('-D')+ expect(spawned[0].args).not.toContain('attach-session')+ expect(versionAsks).toEqual([]) // no version probe on that path either})+ it('spawns its client at the window CURRENT size, not the caller-reported one', async () => {+ const m = await tmuxManager(['nt-n1'], { window: { cols: 132, rows: 43 } })+ await m.joinAsWatcher(WATCHER, WATCH)+ 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('reads the window size only when it has to', 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 })+ await m.joinAsWatcher(WATCHER, WATCH) // a live Session is held and the caller gave a size+ expect(read).not.toHaveBeenCalled()+ await m.joinAsWatcher(WATCHER + 1, { persistKey: 'n1', viewerId: 'watch-s2' }) // no caller size+ expect(read).toHaveBeenCalledTimes(1)+ })++ it('local tmux < 3.2 has no client flags: FAIL CLOSED, nothing spawned, logged once', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const m = await tmuxManager(['nt-n1'], { version: 'tmux 3.1c\n' })+ expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)+ expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)+ expect(spawned).toHaveLength(0)+ expect(versionAsks).toHaveLength(1) // memoized+ const lines = warn.mock.calls.filter((c) => String(c[0]).includes('live link'))+ expect(lines).toHaveLength(1)+ expect(String(lines[0][0])).toContain('3.2')+ warn.mockRestore()+ })++ it('an unreadable local tmux version fails closed too', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const m = await tmuxManager(['nt-n1'], { version: 'tmux master\n' })+ expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)+ expect(spawned).toHaveLength(0)+ 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)+ await m.joinAsWatcher(WATCHER + 1, { ...WATCH, persistKey: 'n2', viewerId: 'watch-s2' })+ expect(spawned).toHaveLength(2)+ expect(versionAsks).toHaveLength(1)+ })++ it("a second viewer of the same node shares the first viewer's client instead of opening another", async () => {+ const m = await tmuxManager(['nt-n1'])+ const a = await m.joinAsWatcher(WATCHER, WATCH)+ const b = await m.joinAsWatcher(WATCHER + 1, { ...WATCH, viewerId: 'watch-s2' })+ expect(b.sessionId).toBe(a.sessionId)+ expect(spawned).toHaveLength(1)+ })++ it("a watcher client's release never overwrites the owner's released size (a shadow would push it)", async () => {+ const m = await tmuxManager(['nt-n1'])+ 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])+ m.kill(WATCHER, w.sessionId, 'watch-s1') // the watcher's own view: its client is released+ expect(spawned.at(-1)!.killed).toBe(true)+ expect(m.watchSizeFor('n1')).toEqual({ cols: 132, rows: 43 })+ })++ it("the watcher's client is never the node's Session for anyone else: the owner spawns its own", async () => {+ const m = await tmuxManager(['nt-n1'])+ const w = await m.joinAsWatcher(WATCHER, WATCH)+ const a = await create(OWNER, { cols: 120, rows: 40 })+ expect(a.sessionId).not.toBe(w.sessionId)+ expect(spawned).toHaveLength(2)+ expect(spawned[1].args).toContain('new-session')+ expect(spawned[1].args).toContain('-D')+ })++ it("a watcher's client is not a painter: it does not retire the node's background-write clients", async () => {+ const m = await tmuxManager(['nt-n1'])+ const shadow = vi.spyOn(m as unknown as { shadowDispose: (k: string) => void }, 'shadowDispose')+ const shared = vi.spyOn(m as unknown as { sharedDisposeOn: (k: string) => void }, 'sharedDisposeOn')+ await m.joinAsWatcher(WATCHER, WATCH)+ expect(shadow).not.toHaveBeenCalled()+ expect(shared).not.toHaveBeenCalled()+ // Control: an owner's painter does retire them.+ await create(OWNER, { cols: 120, rows: 40 })+ expect(shadow).toHaveBeenCalledWith('n1')+ })++ it("a background write never goes into the watcher's read-only client", async () => {+ const m = await tmuxManager(['nt-n1'])+ await m.joinAsWatcher(WATCHER, WATCH)+ await m.backgroundWrite('n1', 'echo hi\r')+ expect(spawned[0].writes).toEqual([])+ })++ it('forwards only the named fields — nothing else a caller passes reaches create()', async () => {+ const m = await tmuxManager(['nt-n1'])+ const spy = vi.spyOn(m as unknown as { create: (...a: unknown[]) => Promise<unknown> }, 'create')+ await m.joinAsWatcher(WATCHER, { ...WATCH, shell: 'sh', agentId: 'claude', accountId: 'a1' } as never)+ const passed = spy.mock.calls[0][1] as Record<string, unknown>+ expect(Object.keys(passed).sort()).toEqual(['cols', 'joinOnly', 'persistKey', 'rows', 'sizeVote', 'viewerId'])+ expect(passed.joinOnly).toBe(true)+ expect(passed.sizeVote).toBe(false)+ })+})++describe('joinAsWatcher over SSH', () => {+ const SSH_REMOTE = { controlPath: '/tmp/nt-test-cm', conn: { host: 'h', user: 'u' }, remoteCwd: '/srv/app' }++ async function sshManager(verdict: 'present' | 'absent' | 'unknown') {+ const m = await tmuxManager([])+ vi.spyOn(+ m as unknown as { remoteSessionVerdict: () => Promise<string> },+ 'remoteSessionVerdict'+ ).mockResolvedValue(verdict)+ return m+ }++ it('spawns a tty-allocating ssh child that ATTACHES with the watcher flags, no local version probe', async () => {+ const m = await sshManager('present')+ const w = await m.joinAsWatcher(WATCHER, { ...WATCH, sshRemote: SSH_REMOTE })+ expect(w.unavailable).toBeUndefined()+ expect(spawned).toHaveLength(1)+ expect(spawned[0].file).toBe('/usr/bin/ssh')+ expect(spawned[0].args[0]).toBe('-t')+ const remote = spawned[0].args.at(-1)!+ expect(remote).toContain("attach-session -E -f 'ignore-size,read-only' -t '=nt-n1:'")+ expect(remote).not.toContain('new-session')+ expect(versionAsks).toEqual([])+ })++ 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)+ expect(spawned).toHaveLength(0)+ })++ it('a remote node with no ssh binary is NEVER watched through the local tmux', async () => {+ ssh.path = null+ const m = await sshManager('present')+ const w = await m.joinAsWatcher(WATCHER, { ...WATCH, sshRemote: SSH_REMOTE })+ expect(w.sessionId).toBe('')+ expect(w.unavailable).toBe('ssh')+ expect(spawned).toHaveLength(0)+ })+})++describe('joinAsWatcher (continued)', () => {it('the join-only, non-voting rules are FORCED — a caller cannot turn them off', async () => {const m = await manager()const smuggled = { ...WATCH, joinOnly: false, sizeVote: true } as neverdiff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.tsindex b6648808e..1fc930c62 100644--- a/src/core/remote-ssh/control-master.test.ts+++ b/src/core/remote-ssh/control-master.test.ts@@ -9,6 +9,8 @@ import {probeSaysAbsent,remoteCapturePaneArgs,remoteCaptureVisibleArgs,+ remoteTmuxWatcherArgs,+ remoteWindowSizeArgs,remotePaneCommandArgs,remotePaneCwdArgs,remotePaneProcessArgs,@@ -279,6 +281,34 @@ describe('remoteCaptureVisibleArgs', () => {})})+describe('remoteTmuxWatcherArgs', () => {+ it('a tty-allocating child that ATTACHES read-only and size-neutral, never creates', () => {+ const args = remoteTmuxWatcherArgs(conn, '/s.sock', 'nt-x')+ expect(args[0]).toBe('-t')+ expect(args.slice(1, 1 + childPrefix.length)).toEqual(childPrefix)+ expect(args[args.length - 1]).toBe(+ `${TP}tmux -L ${RMT_TMUX_SOCKET} attach-session -E -f 'ignore-size,read-only' -t '=nt-x:'`+ )+ })++ it('has no create path and no plain-shell fallback — a watcher never gets a shell', () => {+ const cmd = remoteTmuxWatcherArgs(conn, '/s.sock', 'nt-x').at(-1)!+ expect(cmd).not.toContain('new-session')+ expect(cmd).not.toContain('SHELL')+ expect(cmd).not.toContain('exec')+ })+})++describe('remoteWindowSizeArgs', () => {+ it('reads the window size of exactly this session on the host', () => {+ 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}'`+ )+ })+})+describe('remotePaneCommandArgs', () => {it('asks the remote tmux for the pane_current_command of the session', () => {const args = remotePaneCommandArgs(conn, '/s.sock', 'nt-x')diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.tsindex 5bd3daad4..aa48bf8af 100644--- a/src/core/remote-ssh/control-master.ts+++ b/src/core/remote-ssh/control-master.ts@@ -21,6 +21,7 @@ import { sanitizePasteText } from '../paste-injection'import { canControlCanvas } from '../../shared/agents/config'import { COMBINED_PANE_MARKER, PANE_OWNER_FMT, PS_FOREGROUND_FLAGS } from '../agents/pane-owner'import { VISIBLE_CAPTURE_FORMAT, exactPaneTarget } from '../watch-link/capture-route'+import { WATCHER_CLIENT_FLAGS, WINDOW_SIZE_FORMAT } from '../watch-link/watcher-client'// Dependency-free (no node-pty): safe to import from these pure builders./** Dedicated remote tmux socket so an SSH project never collides with the user's own tmux. */@@ -538,6 +539,41 @@ 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+ * 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.ts+ * and on a real tty in watcher-client.realtty.test.ts.+ */+export function remoteTmuxWatcherArgs(conn: SshConnection, controlPath: string, sessionId: string): string[] {+ return [+ '-t',+ ...childArgs(+ conn,+ controlPath,+ tmuxCmd(+ `tmux -L ${RMT_TMUX_SOCKET} attach-session -E -f ${posixQuote(WATCHER_CLIENT_FLAGS)} ` ++ `-t ${posixQuote(exactPaneTarget(sessionId))}`+ )+ )+ ]+}++/** The REMOTE window size of exactly this session, so a watcher's client is spawned at it. */+export function remoteWindowSizeArgs(conn: SshConnection, controlPath: string, sessionId: string): string[] {+ return childArgs(+ conn,+ controlPath,+ tmuxCmd(+ `tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${posixQuote(exactPaneTarget(sessionId))} ` ++ posixQuote(WINDOW_SIZE_FORMAT)+ )+ )+}/*** Ask the REMOTE tmux when a node's session was created, AND what the host's clock says now — in* one round trip, because the caller wants an AGE and the two clocks are not the same clock.diff --git a/src/core/remote-ssh/watcher-attach.realsh.test.ts b/src/core/remote-ssh/watcher-attach.realsh.test.tsnew file mode 100644index 000000000..d84b1499e--- /dev/null+++ b/src/core/remote-ssh/watcher-attach.realsh.test.ts@@ -0,0 +1,154 @@+// A live link watcher's REMOTE tmux client, and the remote window-size read, executed by a real+// /bin/sh — the remote shell is what reads these lines.+//+// What only execution can prove:+// - the client flags (`-f ignore-size,read-only`) and the exact target reach tmux as their own argv+// elements;+// - an OLD remote tmux that rejects the flags (< 3.2) ends the command with a failure and nothing+// else: no retry with other flags, no create, and above all NO plain-shell fallback (the owner's+// interactive command execs a login shell when tmux is missing; a watcher must never get one);+// - the window-size read answers through a real tmux, and an exact-target miss answers nothing.+// Private socket in a private TMUX_TMPDIR; the delegating stub re-points `-L nodeterm-rmt` at it.+import { describe, expect, it, beforeAll, afterAll } from 'vitest'+import { execFileSync } from 'child_process'+import fs from 'fs'+import path from 'path'+import { remoteTmuxWatcherArgs, remoteWindowSizeArgs, RMT_TMUX_SOCKET } from './control-master'+import { WINDOW_SIZE_FORMAT, parseWindowSize } from '../watch-link/watcher-client'+import { testTmpDir } from '../test-tmp'+import { makeTmuxTmpdir } from '../tmux-test-socket'++const conn = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile: '/k/id' }+const SOCKET = `nt-wlwa-${process.pid}`+const REAL_TMUX = (() => {+ if (process.platform === 'win32') return null+ try {+ return execFileSync('/bin/sh', ['-c', 'command -v tmux'], { encoding: 'utf8' }).trim() || null+ } catch {+ return null+ }+})()++let root: string+let recordDir: string+let oldDir: string+let emptyDir: string+let delegateDir: string+let markerDir: string+let tmuxTmp = ''++const watcherLine = (id: string): string => remoteTmuxWatcherArgs(conn, '/cm/p1', id).at(-1)!+const sizeLine = (id: string): string => remoteWindowSizeArgs(conn, '/cm/p1', id).at(-1)!++function runUnder(binDir: string, line: string): { status: number; stdout: string; stderr: string } {+ try {+ const stdout = execFileSync('/bin/sh', ['-c', line], {+ env: {+ PATH: binDir,+ HOME: '/home/u',+ // A watcher that fell back to a shell would exec $SHELL: make that a canary.+ SHELL: path.join(root, 'shell-canary'),+ ...(tmuxTmp ? { TMUX_TMPDIR: tmuxTmp } : {})+ },+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe']+ })+ return { status: 0, stdout, stderr: '' }+ } catch (e) {+ const err = e as { status?: number; stdout?: string; stderr?: string }+ return { status: err.status ?? -1, stdout: String(err.stdout ?? ''), stderr: String(err.stderr ?? '') }+ }+}++const markers = (): string[] => fs.readdirSync(markerDir).sort()++beforeAll(() => {+ root = testTmpDir('ntwas-')+ recordDir = path.join(root, 'record')+ oldDir = path.join(root, 'old')+ emptyDir = path.join(root, 'empty')+ delegateDir = path.join(root, 'delegate')+ markerDir = path.join(root, 'markers')+ for (const d of [recordDir, oldDir, emptyDir, delegateDir, markerDir]) fs.mkdirSync(d)+ fs.writeFileSync(path.join(root, 'shell-canary'), `#!/bin/sh\n: > '${markerDir}/shell'\n`, { mode: 0o755 })+ fs.writeFileSync(path.join(recordDir, 'tmux'), `#!/bin/sh\nfor a in "$@"; do printf '%s\\0' "$a"; done\n`, {+ mode: 0o755+ })+ // tmux 3.1c's own answer to `attach-session -f …`: a usage line and exit 1. Every call is counted.+ fs.writeFileSync(+ path.join(oldDir, 'tmux'),+ `#!/bin/sh\n: > "${markerDir}/old-tmux-$$"\necho 'usage: attach-session [-dErx] [-c working-directory] [-t target-session]' >&2\nexit 1\n`,+ { mode: 0o755 }+ )+ if (!REAL_TMUX) return+ tmuxTmp = makeTmuxTmpdir('ntwa-', SOCKET)+ fs.writeFileSync(+ path.join(delegateDir, 'tmux'),+ `#!/bin/sh\n[ "$1" = "-L" ] && [ "$2" = "${RMT_TMUX_SOCKET}" ] || exit 99\nshift 2\nexec '${REAL_TMUX}' -L '${SOCKET}' "$@"\n`,+ { mode: 0o755 }+ )+ execFileSync(REAL_TMUX, ['-L', SOCKET, '-f', '/dev/null', 'new-session', '-d', '-s', 'nt-w-12', '-x', '100', '-y', '30', 'sleep 60'], {+ env: { ...process.env, TMUX_TMPDIR: tmuxTmp },+ stdio: 'ignore'+ })+})++afterAll(() => {+ if (!REAL_TMUX || !tmuxTmp) return+ try {+ execFileSync(REAL_TMUX, ['-L', SOCKET, 'kill-session', '-t', '=nt-w-12'], {+ env: { ...process.env, TMUX_TMPDIR: tmuxTmp },+ stdio: 'ignore'+ })+ } catch {+ /* already gone */+ }+ fs.rmSync(tmuxTmp, { recursive: true, force: true })+})++describe('remoteTmuxWatcherArgs (real /bin/sh)', () => {+ it('the client flags and the exact target reach the remote tmux as their own argv elements', () => {+ const { status, stdout } = runUnder(recordDir, watcherLine('nt-abc'))+ expect(status).toBe(0)+ const argv = stdout.split('\0')+ expect(argv.pop()).toBe('')+ expect(argv).toEqual(['-L', RMT_TMUX_SOCKET, 'attach-session', '-E', '-f', 'ignore-size,read-only', '-t', '=nt-abc:'])+ })++ it('an OLD remote tmux (< 3.2) rejects the flags: the command fails, once, and no shell runs', () => {+ fs.readdirSync(markerDir).forEach((f) => fs.unlinkSync(path.join(markerDir, f)))+ const { status, stderr } = runUnder(oldDir, watcherLine('nt-abc'))+ expect(status).not.toBe(0)+ expect(stderr).toContain('usage: attach-session')+ const calls = markers().filter((m) => m.startsWith('old-tmux-'))+ expect(calls).toHaveLength(1)+ expect(markers()).not.toContain('shell')+ })++ it('a host with no tmux at all: the command fails and no shell runs', () => {+ fs.readdirSync(markerDir).forEach((f) => fs.unlinkSync(path.join(markerDir, f)))+ const { status } = runUnder(emptyDir, watcherLine('nt-abc'))+ expect(status).not.toBe(0)+ expect(markers()).toEqual([])+ })+})++describe('remoteWindowSizeArgs (real /bin/sh)', () => {+ it('the target and the format reach the remote tmux intact', () => {+ const { status, stdout } = runUnder(recordDir, sizeLine('nt-abc'))+ expect(status).toBe(0)+ const argv = stdout.split('\0')+ expect(argv.pop()).toBe('')+ expect(argv).toEqual(['-L', RMT_TMUX_SOCKET, 'display-message', '-p', '-t', '=nt-abc:', WINDOW_SIZE_FORMAT])+ })++ it.skipIf(!REAL_TMUX)('end to end through a real tmux: the window size of exactly this session', () => {+ // 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 })+ // 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.tsnew file mode 100644index 000000000..da2d1f47e--- /dev/null+++ b/src/core/watch-link/watcher-client.realtty.test.ts@@ -0,0 +1,239 @@+// A LIVE LINK WATCHER'S OWN TMUX CLIENT, ON A REAL TTY (controller ruling R19).+//+// 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+// for that client shrank the owner's 120x39 window to 40x9 (tmux's default `window-size latest`+// 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;+// - 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);+// - attach-session (never new-session -A): a session that is gone is not re-created bare;+// - the exact target: a prefix of a live session's name attaches to nothing.+// The SSH arm is proven the same way: the generated remote line runs under a real /bin/sh inside a+// real pty, with a stub that re-points `-L nodeterm-rmt` at this file's private socket.+//+// Private socket in a private TMUX_TMPDIR; sessions killed by exact target. Skipped (with the reason)+// where there is no tmux binary or node-pty cannot load.+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { execFileSync } from 'child_process'+import fs from 'fs'+import path from 'path'+import { localWatcherAttachArgs, localWindowSizeArgs, parseWindowSize } from './watcher-client'+import { remoteTmuxWatcherArgs, RMT_TMUX_SOCKET } from '../remote-ssh/control-master'+import { makeTmuxTmpdir } from '../tmux-test-socket'+import { testTmpDir } from '../test-tmp'++let pty: typeof import('node-pty') | null = null+try {+ pty = await import('node-pty')+} catch {+ pty = null+}+const REAL_TMUX = (() => {+ if (process.platform === 'win32') return null+ try {+ return execFileSync('/bin/sh', ['-c', 'command -v tmux'], { encoding: 'utf8' }).trim() || null+ } catch {+ return null+ }+})()+// Needs both: the measurement is of tmux, and only a real tty can be a sized tmux client.+const itReal = it.skipIf(!REAL_TMUX || !pty)++const SOCKET = `nt-wlrt-${process.pid}`+/** A variable the conf lists in `update-environment`, like the account-scope names production lists. */+const SCOPED = 'CLAUDE_CONFIG_DIR'+let tmp = ''+let delegateDir = ''+const sessions: string[] = []+const clients: Array<import('node-pty').IPty> = []++function baseEnv(): Record<string, string> {+ const env = { ...process.env, TMUX_TMPDIR: tmp } as Record<string, string>+ delete env.TMUX+ delete env.TMUX_PANE+ delete env[SCOPED]+ return env+}++function tmux(args: string[], env = baseEnv()): string {+ return execFileSync(REAL_TMUX!, ['-L', SOCKET, ...args], { env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })+}+function tryTmux(args: string[]): { ok: boolean; out: string } {+ try {+ return { ok: true, out: tmux(args) }+ } catch (e) {+ return { ok: false, out: String((e as { stderr?: string }).stderr ?? '') }+ }+}++const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))+async function until(check: () => boolean, ms = 3000): Promise<void> {+ const start = Date.now()+ while (!check() && Date.now() - start < ms) await sleep(25)+}++interface Client {+ proc: import('node-pty').IPty+ exit: { exitCode: number } | null+ out: string+}+function spawnClient(file: string, args: string[], cols: number, rows: number, env: Record<string, string>): Client {+ const proc = pty!.spawn(file, args, { name: 'xterm-256color', cols, rows, env })+ clients.push(proc)+ const c: Client = { proc, exit: null, out: '' }+ proc.onData((d) => (c.out += d))+ proc.onExit((e) => (c.exit = e))+ return c+}++const windowSize = (name: string): string =>+ tmux(['display-message', '-p', '-t', `=${name}:`, '#{window_width}x#{window_height}']).trim()+const clientsOf = (name: string): string[] =>+ tmux(['list-clients', '-t', `=${name}`, '-F', '#{client_width}x#{client_height} #{client_flags}'])+ .split('\n')+ .filter(Boolean)++/** The owner: a normal attached client at 120x40 whose env carries the scoped variable. */+async function ownerOf(name: string): Promise<Client> {+ const owner = spawnClient(REAL_TMUX!, ['-L', SOCKET, 'attach-session', '-t', `=${name}`], 120, 40, {+ ...baseEnv(),+ [SCOPED]: '/accounts/a1'+ })+ await until(() => windowSize(name) === '120x39')+ return owner+}++function newSession(name: string, script: string): void {+ tmux(['new-session', '-d', '-s', name, '-x', '120', '-y', '40', script], { ...baseEnv(), [SCOPED]: '/accounts/a1' })+ sessions.push(name)+}++beforeAll(() => {+ if (!REAL_TMUX || !pty) return+ tmp = makeTmuxTmpdir('ntwr-', SOCKET)+ // Boot the private server with a session that keeps it alive, then list the scoped name in+ // `update-environment` exactly as the production conf does for the account scope.+ tmux(['-f', '/dev/null', 'new-session', '-d', '-s', 'keepalive', 'sleep 120'])+ sessions.push('keepalive')+ tmux(['set', '-g', 'update-environment', SCOPED])+ delegateDir = path.join(testTmpDir('ntwrd-'), 'bin')+ fs.mkdirSync(delegateDir)+ fs.writeFileSync(+ path.join(delegateDir, 'tmux'),+ `#!/bin/sh\n[ "$1" = "-L" ] && [ "$2" = "${RMT_TMUX_SOCKET}" ] || exit 99\nshift 2\nexec '${REAL_TMUX}' -L '${SOCKET}' "$@"\n`,+ { mode: 0o755 }+ )+})++afterAll(() => {+ for (const c of clients) {+ try {+ c.kill()+ } catch {+ /* already gone */+ }+ }+ if (!REAL_TMUX || !pty) return+ // Every session on this file's PRIVATE socket, each by exact target — including one a regression+ // might have CREATED (a watcher spelled `new-session -A` makes a login shell that never exits and+ // would keep the server alive after the directory is gone).+ const listed = tryTmux(['list-sessions', '-F', '#{session_name}'])+ const names = new Set([...sessions, ...(listed.ok ? listed.out.split('\n').filter(Boolean) : [])])+ for (const name of names) tryTmux(['kill-session', '-t', `=${name}`])+ fs.rmSync(tmp, { recursive: true, force: true })+})++describe("a watcher's own tmux client (local)", () => {+ itReal('never resizes the owner: the window stays 120x39 and the owner keeps its view', async () => {+ newSession('nt-own', 'sleep 120')+ await ownerOf('nt-own')+ const before = clientsOf('nt-own')+ const watcher = spawnClient(REAL_TMUX!, localWatcherAttachArgs(SOCKET, 'nt-own'), 40, 10, baseEnv())+ await until(() => clientsOf('nt-own').length === 2)+ await sleep(200)+ expect(watcher.exit).toBeNull()+ expect(windowSize('nt-own')).toBe('120x39')+ const after = clientsOf('nt-own')+ expect(after).toContain(before[0]) // the owner's client: same size, same flags+ expect(after.some((c) => c.includes('ignore-size') && c.includes('read-only'))).toBe(true)+ watcher.proc.kill()+ })++ itReal('does not strip the session env the watcher lacks (-E: no update-environment)', async () => {+ newSession('nt-env', 'sleep 120')+ await ownerOf('nt-env')+ expect(tmux(['show-environment', '-t', '=nt-env', SCOPED]).trim()).toBe(`${SCOPED}=/accounts/a1`)+ const watcher = spawnClient(REAL_TMUX!, localWatcherAttachArgs(SOCKET, 'nt-env'), 40, 10, baseEnv())+ await until(() => clientsOf('nt-env').length === 2)+ await sleep(200)+ expect(watcher.exit).toBeNull()+ expect(tmux(['show-environment', '-t', '=nt-env', SCOPED]).trim()).toBe(`${SCOPED}=/accounts/a1`)+ watcher.proc.kill()+ })++ itReal('read-only: what reaches the watcher client never reaches the pane', async () => {+ newSession('nt-ro', 'cat')+ const owner = await ownerOf('nt-ro')+ const watcher = spawnClient(REAL_TMUX!, localWatcherAttachArgs(SOCKET, 'nt-ro'), 40, 10, baseEnv())+ await until(() => clientsOf('nt-ro').length === 2)+ watcher.proc.write('FROM-WATCHER\r')+ await sleep(300)+ expect(tmux(['capture-pane', '-p', '-t', '=nt-ro:'])).not.toContain('FROM-WATCHER')+ // Control: the owner's client does type.+ owner.proc.write('FROM-OWNER\r')+ await until(() => tmux(['capture-pane', '-p', '-t', '=nt-ro:']).includes('FROM-OWNER'))+ expect(tmux(['capture-pane', '-p', '-t', '=nt-ro:'])).toContain('FROM-OWNER')+ watcher.proc.kill()+ })++ itReal('a session that is gone is not created: the client exits and nothing appears', async () => {+ const watcher = spawnClient(REAL_TMUX!, localWatcherAttachArgs(SOCKET, 'nt-gone'), 40, 10, baseEnv())+ await until(() => watcher.exit !== null)+ expect(watcher.exit?.exitCode).not.toBe(0)+ expect(tryTmux(['has-session', '-t', '=nt-gone']).ok).toBe(false)+ })++ itReal('a prefix of a live session name attaches to nothing', async () => {+ newSession('nt-p-12', 'sleep 120')+ const watcher = spawnClient(REAL_TMUX!, localWatcherAttachArgs(SOCKET, 'nt-p-1'), 40, 10, baseEnv())+ await until(() => watcher.exit !== null)+ expect(watcher.exit?.exitCode).not.toBe(0)+ expect(clientsOf('nt-p-12')).toEqual([])+ expect(tryTmux(['has-session', '-t', '=nt-p-1']).ok).toBe(false)+ })++ 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 })+ 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 () => {+ newSession('nt-rw', 'sleep 120')+ await ownerOf('nt-rw')+ const line = remoteTmuxWatcherArgs({ host: 'h', user: 'u' }, '/cm/p1', 'nt-rw').at(-1)!+ const watcher = spawnClient('/bin/sh', ['-c', line], 40, 10, { ...baseEnv(), PATH: `${delegateDir}:/usr/bin:/bin` })+ await until(() => clientsOf('nt-rw').length === 2)+ await sleep(200)+ expect(watcher.exit).toBeNull()+ expect(windowSize('nt-rw')).toBe('120x39')+ expect(clientsOf('nt-rw').some((c) => c.includes('ignore-size') && c.includes('read-only'))).toBe(true)+ expect(tmux(['show-environment', '-t', '=nt-rw', SCOPED]).trim()).toBe(`${SCOPED}=/accounts/a1`)+ watcher.proc.kill()+ })++ itReal('a gone remote session is not created', async () => {+ const line = remoteTmuxWatcherArgs({ host: 'h', user: 'u' }, '/cm/p1', 'nt-rgone').at(-1)!+ const watcher = spawnClient('/bin/sh', ['-c', line], 40, 10, { ...baseEnv(), PATH: `${delegateDir}:/usr/bin:/bin` })+ await until(() => watcher.exit !== null)+ expect(watcher.exit?.exitCode).not.toBe(0)+ expect(tryTmux(['has-session', '-t', '=nt-rgone']).ok).toBe(false)+ })+})diff --git a/src/core/watch-link/watcher-client.test.ts b/src/core/watch-link/watcher-client.test.tsnew file mode 100644index 000000000..c50993081--- /dev/null+++ b/src/core/watch-link/watcher-client.test.ts@@ -0,0 +1,81 @@+import { describe, it, expect } from 'vitest'+import {+ WATCHER_CLIENT_FLAGS,+ WINDOW_SIZE_FORMAT,+ localWatcherAttachArgs,+ localWindowSizeArgs,+ parseTmuxVersion,+ parseWindowSize,+ supportsWatcherClient+} from './watcher-client'++describe('localWatcherAttachArgs', () => {+ const args = localWatcherAttachArgs('sock', 'nt-abc')++ it('attaches (never creates), skips update-environment, and never sizes or types into the window', () => {+ 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')+ })++ it('has no create or take-over flag', () => {+ expect(args).not.toContain('new-session')+ expect(args).not.toContain('-A')+ expect(args).not.toContain('-D')+ expect(args).not.toContain('-d')+ })++ it('targets the session EXACTLY', () => {+ expect(args.filter((a) => a.includes('nt-abc'))).toEqual(['=nt-abc:'])+ })+})++describe('localWindowSizeArgs / parseWindowSize', () => {+ it('reads the window size of exactly this session', () => {+ expect(WINDOW_SIZE_FORMAT).toBe('#{window_width} #{window_height}')+ expect(localWindowSizeArgs('sock', 'nt-abc')).toEqual([+ '-L',+ 'sock',+ 'display-message',+ '-p',+ '-t',+ '=nt-abc:',+ '#{window_width} #{window_height}'+ ])+ })++ 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('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']) {+ expect(parseWindowSize(out)).toBeUndefined()+ }+ })+})++describe('parseTmuxVersion / supportsWatcherClient', () => {+ it('reads the versions tmux actually prints', () => {+ expect(parseTmuxVersion('tmux 3.4\n')).toEqual({ major: 3, minor: 4 })+ expect(parseTmuxVersion('tmux 3.2a\n')).toEqual({ major: 3, minor: 2 })+ expect(parseTmuxVersion('tmux 3.1c')).toEqual({ major: 3, minor: 1 })+ expect(parseTmuxVersion('tmux next-3.6')).toEqual({ major: 3, minor: 6 })+ expect(parseTmuxVersion('tmux 2.9a')).toEqual({ major: 2, minor: 9 })+ expect(parseTmuxVersion('tmux 10.0')).toEqual({ major: 10, minor: 0 })+ })++ it('an unreadable version is null', () => {+ for (const out of ['', 'tmux master', 'not tmux', 'tmux 3']) expect(parseTmuxVersion(out)).toBeNull()+ })++ it('client flags (-f ignore-size,read-only) need tmux 3.2; unknown fails closed', () => {+ expect(supportsWatcherClient({ major: 3, minor: 2 })).toBe(true)+ expect(supportsWatcherClient({ major: 3, minor: 4 })).toBe(true)+ expect(supportsWatcherClient({ major: 4, minor: 0 })).toBe(true)+ expect(supportsWatcherClient({ major: 3, minor: 1 })).toBe(false)+ expect(supportsWatcherClient({ major: 2, minor: 9 })).toBe(false)+ expect(supportsWatcherClient(null)).toBe(false)+ })+})diff --git a/src/core/watch-link/watcher-client.ts b/src/core/watch-link/watcher-client.tsnew file mode 100644index 000000000..241b951f1--- /dev/null+++ b/src/core/watch-link/watcher-client.ts@@ -0,0 +1,65 @@+// A live link watcher's OWN tmux client — the one it spawns when no Session is held for the node+// (after an app restart, for a closed project, for a released node). Pure: argv builders and parsers.+//+// The owner's spelling for a client, `new-session -A`, is wrong here in three ways, each measured on+// 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.+// - 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.+// - CREATION. `new-session -A` creates when the session is gone, so a session that died between the+// strict existence verdict and the spawn would be re-created bare, by a viewer. `attach-session`+// never creates: it exits 1 ("can't find session") and nothing appears.+// `read-only` is a belt: nothing is ever written into a watcher's pty, and if something were, tmux+// drops input from a read-only client.+//+// The target is exact, `=nt-<id>:` (a bare name prefix-matches another node's session; measured, see+// capture-route.ts). For attach-session both `=name` and `=name:` are exact; `=name:` is kept so every+// watch-link target is spelled one way.+//+// Client flags (`-f`) need tmux 3.2. Locally the version is probed (`supportsWatcherClient`) and an+// older or unreadable one refuses the watcher; over SSH the remote tmux rejects the flags itself.+import { exactPaneTarget } from './capture-route'++export const WATCHER_CLIENT_FLAGS = 'ignore-size,read-only'++/** The local tmux argv (after the binary) for a watcher's own client. */+export function localWatcherAttachArgs(socket: string, sessionName: string): string[] {+ return ['-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}'++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. */+export function parseWindowSize(stdout: string): { cols: number; rows: number } | undefined {+ const m = /^(\d+) (\d+)$/.exec(stdout.replace(/\r?\n$/, ''))+ if (!m) return undefined+ const cols = Number(m[1])+ const rows = Number(m[2])+ return cols > 0 && rows > 0 ? { cols, rows } : undefined+}++export interface TmuxVersion {+ major: number+ minor: number+}++/** `tmux -V` → `{major, minor}`: `tmux 3.4`, `tmux 3.2a`, `tmux next-3.6`. null when unreadable+ * (`tmux master`, a failed probe). */+export function parseTmuxVersion(stdout: string): TmuxVersion | null {+ const m = /(\d+)\.(\d+)/.exec(stdout)+ return m ? { major: Number(m[1]), minor: Number(m[2]) } : null+}++/** Client flags (`attach-session -f`) first shipped in tmux 3.2. An unknown version fails closed. */+export function supportsWatcherClient(v: TmuxVersion | null): boolean {+ return !!v && (v.major > 3 || (v.major === 3 && v.minor >= 2))+}