Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(live-links): deliver controller input to the pane, never a tmux client

review2799f1b325d0
diff --git a/src/core/pty-manager.control-input.test.ts b/src/core/pty-manager.control-input.test.ts
new file mode 100644
index 000000000..5b23bf91e
--- /dev/null
+++ b/src/core/pty-manager.control-input.test.ts
@@ -0,0 +1,370 @@
+// `PtyManager.watcherInputRoute` / `controlInput` / `nodeControlSupport` — a live link controller's
+// input: WHICH route a session gets, WHICH binary is asked with WHICH argv and WHICH stdin, the
+// per-session order, and the never-rejects contract. What the plans MEAN on a real tmux (bytes
+// exact, the prefix inert, a mode cancelled first, the exact session only) is
+// `watch-link/pane-input.realtmux.test.ts`; this file pins dispatch, in the style of
+// `pty-manager.capture-visible.test.ts`. It is its own file because the runner here must carry
+// STDIN (`runWithStdin` reads the child off execFile's promise, as Node's own promisified execFile
+// provides it), which the capture-visible harness has no reason to fake.
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform } from './platform-fake'
+import { TMUX_SOCKET, sessionName } from './tmux-naming'
+import { keysCommandText, remoteKeysArgs } from './watch-link/pane-input'
+import { DEFAULT_SETTINGS } from '../shared/types'
+
+type Call = { file: string; args: string[]; input: string | undefined }
+const calls = vi.hoisted(() => [] as Array<{ file: string; args: string[]; input: string | undefined }>)
+/** What each `execFile` resolves to. A promise lets a test HOLD a call; a throw rejects it. */
+const script = vi.hoisted(() => ({
+ answer: (() => ({ stdout: '' })) as (file: string, args: string[]) => { stdout: string } | Promise<{ stdout: string }>
+}))
+
+vi.mock('child_process', async () => {
+ const { promisify } = await import('util')
+ type Cb = (err: Error | null, res?: { stdout: string; stderr: string }) => void
+ const execFile = (file: string, args: string[], a?: unknown, b?: unknown): unknown => {
+ const cb = (typeof a === 'function' ? a : b) as Cb | undefined
+ calls.push({ file, args, input: undefined })
+ Promise.resolve()
+ .then(() => script.answer(file, args))
+ .then(
+ (r) => cb?.(null, { stdout: r.stdout, stderr: '' }),
+ (e) => cb?.(e as Error)
+ )
+ return {}
+ }
+ // `runWithStdin` reads the ChildProcess off the promise (`.child`) and ends its stdin with the
+ // payload, exactly as Node's real promisified execFile carries it.
+ ;(execFile as unknown as Record<symbol, unknown>)[promisify.custom] = (file: string, args: string[]) => {
+ const call = { file, args, input: undefined as string | undefined }
+ calls.push(call)
+ // Answered at CALL time, so a test can hold exactly the n-th call.
+ let answer: { stdout: string } | Promise<{ stdout: string }>
+ try {
+ answer = script.answer(file, args)
+ } catch (e) {
+ answer = Promise.reject(e)
+ }
+ const p = Promise.resolve(answer).then((r) => ({ stdout: r.stdout, stderr: '' }))
+ const child = { stdin: { on: () => undefined, end: (input: string) => void (call.input = input) } }
+ return Object.assign(p, { child })
+ }
+ return { execFile, execFileSync: (): string => '' }
+})
+
+const ssh = vi.hoisted(() => ({ path: '/usr/bin/ssh' as string | null }))
+vi.mock('./exec-path', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./exec-path')>()),
+ findExecutableSync: (bin: string) => (bin === 'ssh' ? ssh.path : null),
+ shellPathNow: () => '/usr/bin:/bin',
+ resolveShellPath: async () => '/usr/bin:/bin'
+}))
+
+vi.mock('node-pty', () => ({ spawn: () => ({}) }))
+
+const hostSendKeys = vi.hoisted(() => vi.fn(async (): Promise<boolean | 'pasted-not-submitted'> => true))
+vi.mock('./session-host-backend', async (original) => ({
+ ...(await original<typeof import('./session-host-backend')>()),
+ sessionHostSendKeys: hostSendKeys
+}))
+
+const NODE = 'node-1'
+const NAME = sessionName(NODE)
+const SSH_REMOTE = { conn: { host: 'h', user: 'u' }, controlPath: '/tmp/cm-abc', remoteCwd: '/srv' }
+
+type Mgr = {
+ tmuxPath: string | null
+ sessions: Map<string, Record<string, unknown>>
+ byPersistKey: Map<string, string>
+ zellijKeys: Set<string>
+ released: Map<string, unknown>
+ getSettings: () => typeof DEFAULT_SETTINGS
+ watcherInputRoute(id: string): string
+ controlInput(id: string, chunk: unknown): Promise<boolean>
+ nodeControlSupport(persistKey: string): string
+}
+
+/** A manager with one registered session, built without `create` — these methods read only the
+ * session's backend fields and its pty, so a spawn harness would be noise. */
+async function manager(session: Record<string, unknown> | null, tmux: string | null = '/usr/bin/tmux') {
+ const { PtyManager } = await import('./pty-manager')
+ const mgr = new PtyManager() as unknown as Mgr
+ mgr.tmuxPath = tmux
+ const write = vi.fn()
+ if (session) {
+ mgr.sessions.set('sess-1', { persistKey: NODE, indexKey: NODE, nodeId: NODE, tmuxBacked: true, proc: { write }, ...session })
+ mgr.byPersistKey.set(NODE, 'sess-1')
+ }
+ return { mgr, write }
+}
+
+const flush = () => new Promise((r) => setTimeout(r, 0))
+
+beforeEach(() => {
+ calls.length = 0
+ ssh.path = '/usr/bin/ssh'
+ hostSendKeys.mockReset()
+ hostSendKeys.mockImplementation(async () => true)
+ script.answer = () => ({ stdout: '' })
+ // `findSsh` memoizes per module; a fresh module per test lets one test say "no ssh here".
+ vi.resetModules()
+ initPlatform(fakePlatform())
+})
+afterEach(() => resetPlatformForTests())
+
+describe('watcherInputRoute', () => {
+ it('routes each backend to the pane, or refuses', async () => {
+ const cases: Array<[Record<string, unknown> | null, string | null, string]> = [
+ [{ zellij: true }, '/usr/bin/tmux', 'none'], // session-wide key bindings: refused
+ [{ sshRemote: SSH_REMOTE }, '/usr/bin/tmux', 'ssh'],
+ [{ sshRemote: SSH_REMOTE }, null, 'ssh'], // the HOST's tmux, never the local one
+ [{ sshRemote: SSH_REMOTE, tmuxBacked: false }, '/usr/bin/tmux', 'none'],
+ [{ sessionHost: true }, null, 'write'],
+ [{ nativeWindowsPane: {}, tmuxBacked: false }, null, 'write'],
+ [{}, '/usr/bin/tmux', 'tmux'],
+ [{}, null, 'none'], // tmux-backed but no tmux to ask
+ [{ tmuxBacked: false, persistKey: undefined }, '/usr/bin/tmux', 'write'], // plain shell: the pty IS the shell
+ [{ watcherClient: true }, '/usr/bin/tmux', 'tmux'], // a watcher's read-only client: the PANE, never the client
+ [null, '/usr/bin/tmux', 'none']
+ ]
+ for (const [session, tmux, route] of cases) {
+ const { mgr } = await manager(session, tmux)
+ expect(mgr.watcherInputRoute('sess-1'), JSON.stringify(session)).toBe(route)
+ }
+ })
+
+ it('a watcher client that is somehow not tmux-backed is never written into (it is read-only)', async () => {
+ const { mgr } = await manager({ watcherClient: true, tmuxBacked: false, persistKey: undefined })
+ expect(mgr.watcherInputRoute('sess-1')).toBe('none')
+ })
+})
+
+describe('controlInput — local tmux', () => {
+ it('keys: one `source-file -`, the command text on stdin, the name from the Session', async () => {
+ const { mgr, write } = await manager({})
+ expect(await mgr.controlInput('sess-1', { kind: 'keys', data: '\x02s' })).toBe(true)
+ expect(calls).toEqual([
+ { file: '/usr/bin/tmux', args: ['-L', TMUX_SOCKET, 'source-file', '-'], input: keysCommandText(NAME, '\x02s') }
+ ])
+ expect(write).not.toHaveBeenCalled() // never into the client's pty
+ })
+
+ it('paste: load-buffer from stdin, framed by tmux (-p), sanitized, no Enter', async () => {
+ const { mgr } = await manager({})
+ expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'a\x1b[201~b\nc' })).toBe(true)
+ expect(calls).toHaveLength(1)
+ const [c] = calls as Call[]
+ expect(c.file).toBe('/usr/bin/tmux')
+ expect(c.input).toBe('a[201~b\nc')
+ expect(c.args.slice(0, 7)).toEqual(['-L', TMUX_SOCKET, 'load-buffer', '-b', c.args[4], '-', ';'])
+ expect(c.args).toContain('-p')
+ expect(c.args).toContain(`=${NAME}:`)
+ expect(c.args).not.toContain('Enter')
+ })
+
+ it('a failed paste answers false and sweeps its own buffer', async () => {
+ script.answer = (_f, args) => {
+ if (args.includes('load-buffer')) throw Object.assign(new Error("can't find pane"), { code: 1 })
+ return { stdout: '' }
+ }
+ const { mgr } = await manager({})
+ expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'x' })).toBe(false)
+ await flush()
+ const buffer = calls[0].args[4]
+ expect(calls[1].args).toEqual(['-L', TMUX_SOCKET, 'delete-buffer', '-b', buffer])
+ })
+
+ it('a failed keys delivery answers false, never rejects', async () => {
+ script.answer = () => {
+ throw Object.assign(new Error("can't find session"), { code: 1 })
+ }
+ const { mgr } = await manager({})
+ await expect(mgr.controlInput('sess-1', { kind: 'keys', data: 'x' })).resolves.toBe(false)
+ })
+
+ it('an empty key chunk is refused without running anything; an empty paste has nothing to do', async () => {
+ const { mgr } = await manager({})
+ expect(await mgr.controlInput('sess-1', { kind: 'keys', data: '' })).toBe(false)
+ expect(await mgr.controlInput('sess-1', { kind: 'paste', text: '\x1b' })).toBe(true)
+ expect(calls).toEqual([])
+ })
+
+ it('a malformed chunk is refused without running anything', async () => {
+ const { mgr } = await manager({})
+ for (const bad of [null, {}, { kind: 'keys' }, { kind: 'keys', data: 5 }, { kind: 'paste', text: {} }, { kind: 'type', data: 'x' }]) {
+ expect(await mgr.controlInput('sess-1', bad)).toBe(false)
+ }
+ expect(calls).toEqual([])
+ })
+})
+
+describe('controlInput — ssh', () => {
+ it('keys: run on the HOST over the ControlMaster, the command text on stdin', async () => {
+ const { mgr } = await manager({ sshRemote: SSH_REMOTE })
+ expect(await mgr.controlInput('sess-1', { kind: 'keys', data: 'ls\r' })).toBe(true)
+ expect(calls).toEqual([
+ {
+ file: '/usr/bin/ssh',
+ args: remoteKeysArgs(SSH_REMOTE.conn, SSH_REMOTE.controlPath),
+ input: keysCommandText(NAME, 'ls\r')
+ }
+ ])
+ })
+
+ it('paste: the remote plan, sanitized text on stdin, no Enter', async () => {
+ const { mgr } = await manager({ sshRemote: SSH_REMOTE })
+ expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'p\x1bq' })).toBe(true)
+ expect(calls[0].file).toBe('/usr/bin/ssh')
+ expect(calls[0].input).toBe('pq')
+ expect(calls[0].args.at(-1)).toContain('paste-buffer -d -p -r')
+ expect(calls[0].args.at(-1)).not.toContain('Enter')
+ })
+
+ it('no ssh binary: false, nothing run — never the local tmux', async () => {
+ ssh.path = null
+ const { mgr } = await manager({ sshRemote: SSH_REMOTE })
+ expect(await mgr.controlInput('sess-1', { kind: 'keys', data: 'x' })).toBe(false)
+ expect(calls).toEqual([])
+ })
+})
+
+describe('controlInput — the ordinary write path', () => {
+ it('plain shell: keys are written to the pty as they are', async () => {
+ const { mgr, write } = await manager({ tmuxBacked: false, persistKey: undefined })
+ expect(await mgr.controlInput('sess-1', { kind: 'keys', data: '\x1b[A' })).toBe(true)
+ expect(write).toHaveBeenCalledWith('\x1b[A')
+ expect(calls).toEqual([])
+ })
+
+ it('plain shell: a paste is written sanitized and unframed', async () => {
+ const { mgr, write } = await manager({ tmuxBacked: false, persistKey: undefined })
+ expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'a\x1b[201~b' })).toBe(true)
+ expect(write).toHaveBeenCalledWith('a[201~b')
+ })
+
+ it('a pty that throws on write is a failed delivery, not an exception', async () => {
+ const { mgr, write } = await manager({ tmuxBacked: false, persistKey: undefined })
+ write.mockImplementation(() => {
+ throw new Error('EIO')
+ })
+ await expect(mgr.controlInput('sess-1', { kind: 'keys', data: 'x' })).resolves.toBe(false)
+ })
+
+ it('session host: keys ride the pty; a paste goes through its no-Enter sendKeys, true only for true', async () => {
+ const { mgr, write } = await manager({ sessionHost: true })
+ expect(await mgr.controlInput('sess-1', { kind: 'keys', data: 'x' })).toBe(true)
+ expect(write).toHaveBeenCalledWith('x')
+ expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'a\nb' })).toBe(true)
+ expect(hostSendKeys).toHaveBeenCalledWith(NAME, 'a\nb', false)
+ hostSendKeys.mockImplementation(async () => 'pasted-not-submitted')
+ expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'c' })).toBe(false)
+ hostSendKeys.mockImplementation(async () => false)
+ expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'c' })).toBe(false)
+ expect(calls).toEqual([])
+ })
+
+ it('a direct Windows pane: a paste goes through the pane (framed only if its app asked), no Enter', async () => {
+ const sendText = vi.fn(async () => true)
+ const { mgr, write } = await manager({ nativeWindowsPane: { sendText }, tmuxBacked: false, persistKey: undefined })
+ expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'a\nb' })).toBe(true)
+ expect(sendText).toHaveBeenCalledWith('a\nb', false)
+ expect(await mgr.controlInput('sess-1', { kind: 'keys', data: '\x03' })).toBe(true)
+ expect(write).toHaveBeenCalledWith('\x03')
+ })
+})
+
+describe('controlInput — refusals and order', () => {
+ it("'none' resolves false without spawning anything", async () => {
+ for (const session of [{ zellij: true }, null]) {
+ const { mgr, write } = await manager(session)
+ expect(await mgr.controlInput('sess-1', { kind: 'keys', data: 'x' })).toBe(false)
+ expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'x' })).toBe(false)
+ // A refused route never reports "delivered", not even for a paste with nothing in it.
+ expect(await mgr.controlInput('sess-1', { kind: 'paste', text: '' })).toBe(false)
+ expect(write).not.toHaveBeenCalled()
+ }
+ expect(calls).toEqual([])
+ expect(hostSendKeys).not.toHaveBeenCalled()
+ })
+
+ it('two chunks on one session run strictly in order: the second starts only after the first settles', async () => {
+ let release!: () => void
+ const held = new Promise<{ stdout: string }>((r) => (release = () => r({ stdout: '' })))
+ let n = 0
+ script.answer = () => (++n === 1 ? held : { stdout: '' })
+ const { mgr } = await manager({})
+ const first = mgr.controlInput('sess-1', { kind: 'keys', data: 'a' })
+ const second = mgr.controlInput('sess-1', { kind: 'keys', data: 'b' })
+ for (let i = 0; i < 5; i++) await flush()
+ expect(calls).toHaveLength(1)
+ expect(calls[0].input).toBe(keysCommandText(NAME, 'a'))
+ release()
+ expect(await first).toBe(true)
+ expect(await second).toBe(true)
+ expect(calls.map((c) => c.input)).toEqual([keysCommandText(NAME, 'a'), keysCommandText(NAME, 'b')])
+ })
+
+ it('a failed chunk does not stall the chain', async () => {
+ let n = 0
+ script.answer = () => {
+ if (++n === 1) throw Object.assign(new Error('boom'), { code: 1 })
+ return { stdout: '' }
+ }
+ const { mgr } = await manager({})
+ const a = mgr.controlInput('sess-1', { kind: 'keys', data: 'a' })
+ const b = mgr.controlInput('sess-1', { kind: 'keys', data: 'b' })
+ expect(await a).toBe(false)
+ expect(await b).toBe(true)
+ })
+
+ it('the session is re-read inside the step: gone by then → false, nothing run', async () => {
+ let release!: () => void
+ const held = new Promise<{ stdout: string }>((r) => (release = () => r({ stdout: '' })))
+ script.answer = () => held
+ const { mgr } = await manager({})
+ const a = mgr.controlInput('sess-1', { kind: 'keys', data: 'a' })
+ const b = mgr.controlInput('sess-1', { kind: 'keys', data: 'b' })
+ await flush()
+ mgr.sessions.delete('sess-1')
+ release()
+ expect(await a).toBe(true)
+ expect(await b).toBe(false)
+ expect(calls).toHaveLength(1)
+ })
+
+ it('different sessions do not wait for each other', async () => {
+ const held = new Promise<{ stdout: string }>(() => undefined)
+ let n = 0
+ script.answer = () => (++n === 1 ? held : { stdout: '' })
+ const { mgr } = await manager({})
+ mgr.sessions.set('sess-2', { persistKey: 'node-2', tmuxBacked: true, proc: { write: vi.fn() } })
+ void mgr.controlInput('sess-1', { kind: 'keys', data: 'a' })
+ expect(await mgr.controlInput('sess-2', { kind: 'keys', data: 'b' })).toBe(true)
+ })
+})
+
+describe('nodeControlSupport', () => {
+ it('Zellij is unsupported, whether known from a record or from a live session', async () => {
+ const a = await manager(null)
+ a.mgr.zellijKeys.add(NODE)
+ expect(a.mgr.nodeControlSupport(NODE)).toBe('unsupported')
+ const b = await manager({ zellij: true })
+ expect(b.mgr.nodeControlSupport(NODE)).toBe('unsupported')
+ })
+
+ it('a live session, a released one, or a new tmux node is ok', async () => {
+ expect((await manager({})).mgr.nodeControlSupport(NODE)).toBe('ok')
+ const r = await manager(null, null)
+ r.mgr.released.set(NODE, { sessionId: 'old', remote: false })
+ expect(r.mgr.nodeControlSupport(NODE)).toBe('ok')
+ expect((await manager(null)).mgr.nodeControlSupport('node-new')).toBe('ok')
+ })
+
+ it('no session, no record, no tmux to make one: unknown', async () => {
+ expect((await manager(null, null)).mgr.nodeControlSupport('node-new')).toBe('unknown')
+ const off = await manager(null)
+ off.mgr.getSettings = () => ({ ...DEFAULT_SETTINGS, tmuxEnabled: false })
+ expect(off.mgr.nodeControlSupport('node-new')).toBe('unknown')
+ })
+})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 83bf106ad..abfc16771 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -67,6 +67,13 @@ import {
visibleCaptureRoute,
type VisibleCapture
} from './watch-link/capture-route'
+import {
+ controlInputPlan,
+ remoteControlInputPlan,
+ type ControlInputChunk,
+ type WatcherInputRoute
+} from './watch-link/pane-input'
+import { sanitizePasteText } from './paste-injection'
import {
localWatcherAttachArgs,
localWindowSizeArgs,
@@ -4932,6 +4939,116 @@ export class PtyManager {
return unavailableCapture()
}
+ /**
+ * How a live-link controller's input reaches this session's PANE (watch-link/pane-input.ts).
+ *
+ * Never through a tmux CLIENT: a byte written into a client's pty is that client's KEYBOARD, so
+ * the prefix would reach tmux (`C-b s` opens the session chooser) — and a watcher's own client is
+ * read-only besides. A tmux-backed session (local, or on the SSH host) is typed into with
+ * `send-keys -H` on the pane. The Windows session host, a direct Windows pane and the plain-shell
+ * fallback take PtyManager's ordinary write: there is no tmux client in between, so no key table.
+ * Zellij is refused: its key bindings are session-wide (zellij-backend.ts).
+ */
+ watcherInputRoute(sessionId: string): WatcherInputRoute {
+ const s = this.sessions.get(sessionId)
+ if (!s) return 'none'
+ if (s.zellij) return 'none' // session-wide key bindings: refused
+ if (s.sshRemote) return s.tmuxBacked ? 'ssh' : 'none'
+ if (s.sessionHost || s.nativeWindowsPane) return 'write'
+ if (s.tmuxBacked) return this.tmuxPath ? 'tmux' : 'none'
+ // A watcher's own client is read-only and always tmux-backed; were one ever not, writing into it
+ // would drop every byte, so it is refused rather than reported delivered.
+ if (s.watcherClient) return 'none'
+ return 'write' // the plain-shell fallback: the pty IS the shell
+ }
+
+ /**
+ * Deliver one chunk of a controller's input to the session's pane. Resolves whether it was
+ * delivered; never rejects. Serialized per session id: a second chunk starts only after the first
+ * settled, so keys and pastes reach the pane in the order they were typed. The Session is re-read
+ * inside each step (it can be gone by then → false), and the tmux name is resolved from it, never
+ * from the caller. A false is never retried here (a timed-out delivery may well have run).
+ */
+ controlInput(sessionId: string, chunk: ControlInputChunk): Promise<boolean> {
+ const prev = this.controlInputChains.get(sessionId) ?? Promise.resolve(true)
+ const step = prev.then(() => this.deliverControlInput(sessionId, chunk)).catch(() => false)
+ this.controlInputChains.set(sessionId, step)
+ void step.then(() => {
+ if (this.controlInputChains.get(sessionId) === step) this.controlInputChains.delete(sessionId)
+ })
+ return step
+ }
+
+ /** The tail of each session's `controlInput` chain; deleted when the tail settles. */
+ private readonly controlInputChains = new Map<string, Promise<boolean>>()
+
+ private async deliverControlInput(sessionId: string, chunk: ControlInputChunk): Promise<boolean> {
+ // The chunk arrives from a viewer over the network: its shape is checked, not assumed.
+ const c = chunk as { kind?: unknown; data?: unknown; text?: unknown } | null
+ const keys = c?.kind === 'keys' && typeof c.data === 'string'
+ const paste = c?.kind === 'paste' && typeof c.text === 'string'
+ if (!keys && !paste) return false
+ const s = this.sessions.get(sessionId)
+ const route = this.watcherInputRoute(sessionId)
+ if (!s || route === 'none') return false
+ // An empty key chunk is refused on every route (the tmux builder would have no bytes to type);
+ // a paste that sanitizes to nothing has nothing to do.
+ if (keys && (c.data as string).length === 0) return false
+ if (paste && sanitizePasteText(c.text as string).length === 0) return true
+ try {
+ switch (route) {
+ case 'tmux': {
+ const tmuxPath = this.tmuxPath
+ if (!tmuxPath || !s.persistKey) return false
+ const plan = controlInputPlan(TMUX_SOCKET, sessionName(s.persistKey), chunk)
+ if (!plan) return true
+ return await runPasteDelivery(plan, (args, input) => runWithStdin(tmuxPath, args, input))
+ }
+ case 'ssh': {
+ const ssh = findSsh()
+ if (!ssh || !s.sshRemote || !s.persistKey) return false
+ const { conn, controlPath } = s.sshRemote
+ const plan = remoteControlInputPlan(conn, controlPath, sessionName(s.persistKey), chunk)
+ if (!plan) return true
+ return await runPasteDelivery(plan, (args, input) => runWithStdin(ssh, args, input))
+ }
+ case 'write': {
+ if (chunk.kind === 'keys') {
+ this.write(null, sessionId, chunk.data)
+ return true
+ }
+ // A paste: framed only when the pane's app asked for bracketed paste, never with an Enter.
+ // The session host's and a direct Windows pane's no-Enter text path (core/settled-text.ts)
+ // writes at once — the screen-settle wait runs only before an Enter — and frames by the
+ // emulator's own `?2004h` state, which is `paste-buffer -p`'s contract.
+ if (s.nativeWindowsPane) return (await s.nativeWindowsPane.sendText(chunk.text, false)) === true
+ const name = s.persistKey ?? s.indexKey
+ if (s.sessionHost && name) return (await sessionHostSendKeys(sessionName(name), chunk.text, false)) === true
+ // A plain shell: no emulator here knows what the app asked for, so unframed (markers at an
+ // app that never asked would arrive as literal `[200~`).
+ this.write(null, sessionId, sanitizePasteText(chunk.text))
+ return true
+ }
+ }
+ } catch {
+ // A builder refusing a name it did not generate, or a pty that threw on write (it exited).
+ return false
+ }
+ }
+
+ /**
+ * Can a live link offer Control on this node? `unsupported` for a Zellij node (session-wide key
+ * bindings); `ok` when a session for it is live or released (its pane can be reached), or when a
+ * new node would be tmux-backed here; `unknown` otherwise (nothing to tell from yet).
+ */
+ nodeControlSupport(persistKey: string): 'ok' | 'unsupported' | 'unknown' {
+ const live = this.liveSessionForPersistKey(persistKey)
+ if (this.zellijKeys.has(persistKey) || live?.zellij) return 'unsupported'
+ if (live || this.released.has(persistKey)) return 'ok'
+ if (this.tmuxPath && this.getSettings().tmuxEnabled) return 'ok'
+ return 'unknown'
+ }
+
/**
* 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 votes on its size:
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index fdf071f12..04806638b 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -33,8 +33,10 @@ export const RMT_TMUX_SOCKET = 'nodeterm-rmt'
* `command not found` on any host whose ssh exec-channel PATH misses the install dir — most
* visibly macOS with Homebrew's tmux in `/opt/homebrew/bin`. The prologue is one assignment, so
* the command's own exit code (what `probeSaysAbsent` and every caller reads) is unchanged.
+ * Exported for the live link's pane-input builders (`watch-link/pane-input.ts`), which build their
+ * remote commands beside their local twins rather than here.
*/
-function tmuxCmd(body: string): string {
+export function tmuxCmd(body: string): string {
return `${remoteTmuxPathPrologue()}${body}`
}
diff --git a/src/core/watch-link/pane-input.realtmux.test.ts b/src/core/watch-link/pane-input.realtmux.test.ts
new file mode 100644
index 000000000..ca9894a60
--- /dev/null
+++ b/src/core/watch-link/pane-input.realtmux.test.ts
@@ -0,0 +1,318 @@
+// LIVE LINK CONTROL INPUT, PROVEN AGAINST A REAL TMUX DRIVING A REAL PANE.
+//
+// The subject is `controlInputPlan` / `remoteControlInputPlan` run through the production
+// `runPasteDelivery`, i.e. exactly what `PtyManager.controlInput` runs: keys as `source-file -` with
+// `send-keys -H` lines behind a mode cancel, pastes as `load-buffer -` + `paste-buffer -d -p -r`.
+// What judges is not a parser of ours: the pane runs a program that puts its tty in RAW mode and
+// appends every byte it receives to a file, so a byte either reached the application or it did not.
+//
+// The properties, each its own test:
+// - bytes arrive exactly (all 256 values, escape sequences, UTF-8);
+// - the prefix never reaches tmux — and the CONTROL beside it: the same two bytes typed INTO an
+// attached client DO open the session chooser, which is the hole this design closes;
+// - a mode is cancelled first (copy mode and tree mode both eat `send-keys` otherwise);
+// - only the exact session receives it (`nt-c-1` is a prefix of `nt-c-12`);
+// - a paste is framed only when the app asked, and is never submitted;
+// - the SSH command line, run by a real /bin/sh (the remote shell is what reads it), delivers the
+// same bytes. No real ssh: a stub `tmux` on PATH re-points `-L nodeterm-rmt` at the private socket.
+//
+// Private socket in a private TMUX_TMPDIR (`makeTmuxTmpdir`), never `node-terminal`/`nodeterm-rmt`;
+// each session is killed by exact target. Skipped where there is no tmux (Windows, a bare CI image):
+// the measurement is of tmux.
+import { describe, it, expect, beforeAll, afterAll } from 'vitest'
+import { execFileSync, spawn, spawnSync, type ChildProcess } from 'child_process'
+import fs from 'fs'
+import path from 'path'
+import { controlInputPlan, remoteControlInputPlan, type ControlInputChunk } from './pane-input'
+import { runPasteDelivery } from '../tmux-naming'
+import { RMT_TMUX_SOCKET } from '../remote-ssh/control-master'
+import { makeTmuxTmpdir } from '../tmux-test-socket'
+
+const SOCKET = `nt-ctl-test-${process.pid}`
+const CONN = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile: '/k/id' }
+const ESC = '\x1b'
+const START = `${ESC}[200~`
+const END = `${ESC}[201~`
+
+const TMUX = (() => {
+ if (process.platform === 'win32') return null
+ try {
+ return execFileSync('/bin/sh', ['-c', 'command -v tmux'], { encoding: 'utf8' }).trim() || null
+ } catch {
+ return null
+ }
+})()
+const PYTHON = (() => {
+ if (!TMUX) return null
+ try {
+ return execFileSync('/bin/sh', ['-c', 'command -v python3'], { encoding: 'utf8' }).trim() || null
+ } catch {
+ return null
+ }
+})()
+// Skipped where there is no tmux binary (Windows, a bare CI image): the measurement is of tmux.
+const itTmux = it.skipIf(!TMUX)
+// The prefix test also needs a REAL interactive client on a pty, which this file spawns through
+// python3's `pty` module (portable across Linux and macOS, unlike `script`'s two dialects).
+const itClient = it.skipIf(!TMUX || !PYTHON)
+
+let work = ''
+let binDir = ''
+const sessions: string[] = []
+const clients: ChildProcess[] = []
+
+const env = (): NodeJS.ProcessEnv => {
+ const e: NodeJS.ProcessEnv = { ...process.env, TMUX_TMPDIR: work, TERM: 'xterm-256color' }
+ delete e.TMUX
+ delete e.TMUX_PANE
+ return e
+}
+
+function tmux(args: string[]): { status: number | null; out: string } {
+ const r = spawnSync(TMUX as string, ['-L', SOCKET, ...args], { env: env(), encoding: 'utf8' })
+ return { status: r.status, out: r.stdout }
+}
+
+/** `runPasteDelivery`'s runner: the plan's argv against the private socket, its body on stdin. */
+function runLocal(args: string[], input: string): Promise<void> {
+ // The plans name their socket; the private one is what controlInputPlan was given.
+ const r = spawnSync(TMUX as string, args, { env: env(), input })
+ return r.status === 0 ? Promise.resolve() : Promise.reject(new Error(`tmux exit ${r.status}: ${r.stderr}`))
+}
+
+const deliver = (session: string, chunk: ControlInputChunk): Promise<boolean> => {
+ const plan = controlInputPlan(SOCKET, session, chunk)
+ return plan ? runPasteDelivery(plan, runLocal) : Promise.resolve(true)
+}
+
+/** The SSH leg: the remote command line (the last ssh argv element) executed by a real /bin/sh,
+ * with the plan's body on its stdin — the way sshd hands both to the user's shell. */
+function runRemoteLine(args: string[], input: string): Promise<void> {
+ const r = spawnSync('/bin/sh', ['-c', args.at(-1) as string], {
+ env: { ...env(), PATH: `${binDir}:/usr/bin:/bin` },
+ input
+ })
+ return r.status === 0 ? Promise.resolve() : Promise.reject(new Error(`sh exit ${r.status}: ${r.stderr}`))
+}
+
+const deliverRemote = (session: string, chunk: ControlInputChunk): Promise<boolean> => {
+ const plan = remoteControlInputPlan(CONN, '/cm/p1', session, chunk)
+ return plan ? runPasteDelivery(plan, runRemoteLine) : Promise.resolve(true)
+}
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
+async function waitFor(pred: () => boolean, what: string, ms = 5000): Promise<void> {
+ const end = Date.now() + ms
+ while (Date.now() < end) {
+ if (pred()) return
+ await sleep(10)
+ }
+ if (!pred()) throw new Error(`timed out waiting for ${what}`)
+}
+const fileOf = (session: string) => path.join(work, `${session}.bin`)
+const got = (session: string): Buffer => (fs.existsSync(fileOf(session)) ? fs.readFileSync(fileOf(session)) : Buffer.alloc(0))
+const inMode = (session: string) => tmux(['display-message', '-p', '-t', `=${session}:`, '#{pane_in_mode}']).out.trim()
+
+/** A pane whose program records every byte its tty delivers (raw mode: no CR→NL, no ^C, no ^S). */
+async function start(session: string, aware = false): Promise<void> {
+ const r = tmux([
+ '-f', '/dev/null', 'new-session', '-d', '-s', session, '-x', '80', '-y', '24',
+ `${path.join(binDir, 'recorder')} ${fileOf(session)}${aware ? ' aware' : ''}`
+ ])
+ if (r.status !== 0) throw new Error(`new-session ${session} failed`)
+ sessions.push(session)
+ await waitFor(() => fs.existsSync(`${fileOf(session)}.ready`), `${session} ready`)
+}
+
+/** An interactive-style client: a real pty attached to `session`, our stdin forwarded byte for byte. */
+async function attach(session: string): Promise<ChildProcess> {
+ const child = spawn(PYTHON as string, [path.join(binDir, 'client.py'), TMUX as string, '-L', SOCKET, 'attach', '-t', `=${session}`], {
+ env: env(),
+ stdio: ['pipe', 'ignore', 'ignore']
+ })
+ clients.push(child)
+ await waitFor(() => tmux(['list-clients', '-t', `=${session}`]).out.trim().length > 0, `a client on ${session}`)
+ return child
+}
+const clientSession = (session: string) => tmux(['list-clients', '-t', `=${session}`, '-F', '#{client_session}']).out.trim()
+
+beforeAll(() => {
+ if (!TMUX) return
+ work = makeTmuxTmpdir('ntci-', SOCKET)
+ binDir = path.join(work, 'bin')
+ fs.mkdirSync(binDir)
+ fs.writeFileSync(
+ path.join(binDir, 'recorder'),
+ [
+ '#!/bin/sh',
+ // -iexten as well: with IEXTEN on, ^V (LNEXT) and ^O can still be special in some line disciplines.
+ 'stty raw -echo -iexten',
+ // $2 = "aware": announce DECSET 2004, i.e. request bracketed paste, the way a TUI does.
+ '[ "$2" = aware ] && printf \'\\033[?2004h\'',
+ 'touch "$1.ready"',
+ 'exec cat > "$1"'
+ ].join('\n') + '\n',
+ { mode: 0o755 }
+ )
+ // The SSH leg's tmux: drops `-L nodeterm-rmt` and re-invokes the real tmux on the private socket,
+ // refusing anything else. `exec` keeps stdin, which is the whole point of the path being tested.
+ fs.writeFileSync(
+ path.join(binDir, 'tmux'),
+ `#!/bin/sh\n[ "$1" = "-L" ] && [ "$2" = "${RMT_TMUX_SOCKET}" ] || exit 99\nshift 2\nexec '${TMUX}' -L '${SOCKET}' "$@"\n`,
+ { mode: 0o755 }
+ )
+ fs.writeFileSync(
+ path.join(binDir, 'client.py'),
+ [
+ 'import fcntl, os, pty, select, struct, sys, termios',
+ 'pid, fd = pty.fork()',
+ 'if pid == 0:',
+ " fcntl.ioctl(0, termios.TIOCSWINSZ, struct.pack('HHHH', 24, 80, 0, 0))",
+ ' os.execvpe(sys.argv[1], sys.argv[1:], os.environ)',
+ "fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack('HHHH', 24, 80, 0, 0))",
+ 'while True:',
+ ' r, _, _ = select.select([0, fd], [], [])',
+ ' if fd in r:',
+ ' try:',
+ ' if not os.read(fd, 65536): break',
+ ' except OSError: break',
+ ' if 0 in r:',
+ ' d = os.read(0, 65536)',
+ ' if not d: break',
+ ' os.write(fd, d)',
+ 'try: os.kill(pid, 15)',
+ 'except OSError: pass'
+ ].join('\n') + '\n'
+ )
+})
+
+afterAll(() => {
+ for (const c of clients) {
+ c.stdin?.end()
+ c.kill()
+ }
+ if (TMUX) {
+ for (const name of sessions) tmux(['kill-session', '-t', `=${name}`])
+ }
+ if (work) fs.rmSync(work, { recursive: true, force: true })
+})
+
+describe('controller input on a real tmux', () => {
+ itTmux('bytes arrive exactly: every control and printable byte, escape sequences, UTF-8', async () => {
+ await start('nt-c-bytes')
+ // A controller's keys are TEXT, typed as its UTF-8: U+0000-U+007F are one byte each (every C0
+ // control, DEL, ESC, ^C, ^S, ^V included), U+0080-U+00FF and the rest arrive as their UTF-8.
+ const all = String.fromCharCode(...Array.from({ length: 256 }, (_, i) => i))
+ const chunks = [0, 64, 128, 192].map((i) => all.slice(i, i + 64))
+ chunks.push('\x1b[A', '\x1bOA', '\r', '\x03', '\x7f', 'ç', '漢', '🙂', 'é')
+ for (const data of chunks) expect(await deliver('nt-c-bytes', { kind: 'keys', data })).toBe(true)
+ const expected = Buffer.from(chunks.join(''), 'utf8')
+ await waitFor(() => got('nt-c-bytes').length >= expected.length, 'all bytes')
+ await sleep(100)
+ expect(got('nt-c-bytes').equals(expected)).toBe(true)
+ })
+
+ itTmux('a long chunk (16 KiB, 16 send-keys lines) arrives exactly and in order', async () => {
+ await start('nt-c-big')
+ const text = Array.from({ length: 16384 }, (_, i) => String.fromCharCode(0x20 + (i % 95))).join('')
+ expect(await deliver('nt-c-big', { kind: 'keys', data: text })).toBe(true)
+ await waitFor(() => got('nt-c-big').length >= 16384, '16 KiB')
+ expect(got('nt-c-big').toString('latin1')).toBe(text)
+ })
+
+ itClient(
+ 'the prefix never reaches tmux — while the same bytes typed INTO the client open the session chooser',
+ async () => {
+ await start('nt-c-prefix')
+ await start('nt-c-other')
+ const client = await attach('nt-c-prefix')
+ expect(await deliver('nt-c-prefix', { kind: 'keys', data: '\x02s' })).toBe(true)
+ await waitFor(() => got('nt-c-prefix').length >= 2, 'C-b s in the pane')
+ await sleep(150)
+ expect(got('nt-c-prefix').toString('latin1')).toBe('\x02s')
+ expect(inMode('nt-c-prefix')).toBe('0')
+ // CONTROL: the same two bytes written into the attached client's pty ARE its keyboard.
+ client.stdin!.write('\x02s')
+ await waitFor(() => inMode('nt-c-prefix') === '1', 'the chooser to open')
+ expect(tmux(['display-message', '-p', '-t', '=nt-c-prefix:', '#{pane_mode}']).out.trim()).toBe('tree-mode')
+ expect(got('nt-c-prefix').toString('latin1')).toBe('\x02s') // the client's keys never reached the app
+ // And with the chooser open: `j` + Enter would move to the other session and switch the
+ // client to it. Through the plan the chooser is closed first and both bytes reach the app.
+ expect(await deliver('nt-c-prefix', { kind: 'keys', data: 'j\r' })).toBe(true)
+ await waitFor(() => got('nt-c-prefix').length >= 4, 'j Enter in the pane')
+ await sleep(150)
+ expect(got('nt-c-prefix').toString('latin1')).toBe('\x02sj\r')
+ expect(inMode('nt-c-prefix')).toBe('0')
+ expect(clientSession('nt-c-prefix')).toBe('nt-c-prefix')
+ expect(got('nt-c-other').length).toBe(0)
+ },
+ 20_000
+ )
+
+ itTmux('a mode is cancelled first: copy mode and the tree chooser both left, the app gets the key', async () => {
+ await start('nt-c-mode')
+ // Copy mode — and the control: send-keys with no cancel is eaten by the copy-mode table.
+ tmux(['copy-mode', '-t', '=nt-c-mode:'])
+ expect(inMode('nt-c-mode')).toBe('1')
+ tmux(['send-keys', '-t', '=nt-c-mode:', '-H', '78'])
+ await sleep(200)
+ expect(got('nt-c-mode').length).toBe(0)
+ expect(await deliver('nt-c-mode', { kind: 'keys', data: 'a' })).toBe(true)
+ await waitFor(() => got('nt-c-mode').length >= 1, 'a after copy mode')
+ expect(got('nt-c-mode').toString('latin1')).toBe('a')
+ expect(inMode('nt-c-mode')).toBe('0')
+ // The tree chooser, opened without a client.
+ tmux(['choose-tree', '-t', '=nt-c-mode:'])
+ await waitFor(() => inMode('nt-c-mode') === '1', 'tree mode')
+ expect(await deliver('nt-c-mode', { kind: 'keys', data: 'b' })).toBe(true)
+ await waitFor(() => got('nt-c-mode').length >= 2, 'b after tree mode')
+ expect(got('nt-c-mode').toString('latin1')).toBe('ab')
+ expect(inMode('nt-c-mode')).toBe('0')
+ // A paste into copy mode: left first, so tmux frames by the APP's state, not the mode's.
+ tmux(['copy-mode', '-t', '=nt-c-mode:'])
+ expect(await deliver('nt-c-mode', { kind: 'paste', text: 'c' })).toBe(true)
+ await waitFor(() => got('nt-c-mode').length >= 3, 'c after copy mode')
+ expect(got('nt-c-mode').toString('latin1')).toBe('abc')
+ expect(inMode('nt-c-mode')).toBe('0')
+ })
+
+ itTmux('only the exact session receives it; a missing or killed target fails and reaches no prefix match', async () => {
+ await start('nt-c-1')
+ await start('nt-c-12')
+ expect(await deliver('nt-c-1', { kind: 'keys', data: 'Z' })).toBe(true)
+ await waitFor(() => got('nt-c-1').length >= 1, 'Z')
+ expect(await deliver('nt-c-9', { kind: 'keys', data: 'Q' })).toBe(false)
+ expect(await deliver('nt-c-9', { kind: 'paste', text: 'Q' })).toBe(false)
+ tmux(['kill-session', '-t', '=nt-c-1'])
+ expect(await deliver('nt-c-1', { kind: 'keys', data: 'R' })).toBe(false)
+ expect(await deliver('nt-c-1', { kind: 'paste', text: 'R' })).toBe(false)
+ await sleep(200)
+ expect(got('nt-c-1').toString('latin1')).toBe('Z')
+ expect(got('nt-c-12').length).toBe(0)
+ // A failed paste swept its own buffer: nothing of the payload is left in the server.
+ expect(tmux(['list-buffers', '-F', '#{buffer_name}']).out).not.toMatch(/nt-paste-/)
+ })
+
+ itTmux('a paste is framed only when the app asked, keeps \\n, drops ESC, and is never submitted', async () => {
+ await start('nt-c-aware', true)
+ await start('nt-c-plain')
+ expect(await deliver('nt-c-aware', { kind: 'paste', text: 'a\nb' })).toBe(true)
+ expect(await deliver('nt-c-plain', { kind: 'paste', text: 'a\nb' })).toBe(true)
+ expect(await deliver('nt-c-plain', { kind: 'paste', text: `x${ESC}[A${END}y` })).toBe(true)
+ await waitFor(() => got('nt-c-aware').length >= 15 && got('nt-c-plain').length >= 3 + 9, 'pastes')
+ await sleep(150)
+ expect(got('nt-c-aware').toString('latin1')).toBe(`${START}a\nb${END}`)
+ expect(got('nt-c-plain').toString('latin1')).toBe('a\nbx[A[201~y')
+ })
+
+ itTmux('the SSH command line, run by a real /bin/sh, delivers the same bytes', async () => {
+ await start('nt-c-remote', true)
+ expect(await deliverRemote('nt-c-remote', { kind: 'keys', data: `\x02s${ESC}[Aç` })).toBe(true)
+ expect(await deliverRemote('nt-c-remote', { kind: 'paste', text: 'p\nq' })).toBe(true)
+ const expected = `\x02s${ESC}[A${Buffer.from('ç', 'utf8').toString('latin1')}${START}p\nq${END}`
+ await waitFor(() => got('nt-c-remote').length >= expected.length, 'remote bytes')
+ expect(got('nt-c-remote').toString('latin1')).toBe(expected)
+ expect(inMode('nt-c-remote')).toBe('0')
+ expect(await deliverRemote('nt-c-remote-9', { kind: 'keys', data: 'x' })).toBe(false)
+ })
+})
diff --git a/src/core/watch-link/pane-input.test.ts b/src/core/watch-link/pane-input.test.ts
new file mode 100644
index 000000000..62c153284
--- /dev/null
+++ b/src/core/watch-link/pane-input.test.ts
@@ -0,0 +1,154 @@
+// The pure builders behind a live link controller's input. What they MEAN on a real tmux (bytes
+// exact, the prefix inert, a mode cancelled first, the exact session only) is proven in
+// `pane-input.realtmux.test.ts`; this file pins their shape and their refusals.
+import { describe, expect, it } from 'vitest'
+import {
+ KEYS_PER_COMMAND,
+ controlInputPlan,
+ exactPaneTarget,
+ keysCommandText,
+ localKeysArgs,
+ localPasteArgs,
+ remoteControlInputPlan,
+ remoteKeysArgs,
+ remotePasteArgs
+} from './pane-input'
+import { RMT_TMUX_SOCKET } from '../remote-ssh/control-master'
+import { remoteTmuxPathPrologue } from '../../shared/ssh'
+
+const CONN = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile: '/k/id' }
+const CM = '/cm/p1'
+
+describe('pane input builders', () => {
+ it('targets the session exactly, never a prefix', () => {
+ expect(exactPaneTarget('nt-abc')).toBe('=nt-abc:')
+ for (const bad of ['', 'nt abc', 'nt-a;b', "nt-a'b", '=nt-a', 'nt-a:', 's', 'nt-a\nkill-server'])
+ expect(() => exactPaneTarget(bad)).toThrow()
+ })
+
+ it('cancels any mode first, then types every byte as hex', () => {
+ expect(keysCommandText('nt-a', '\x1b[A')).toBe(
+ "if-shell -F -t =nt-a: '#{pane_in_mode}' 'copy-mode -q -t =nt-a:'\n" + 'send-keys -t =nt-a: -H 1b 5b 41\n'
+ )
+ })
+
+ it('encodes UTF-8 bytes, not code points', () => {
+ expect(keysCommandText('nt-s', 'ç🙂').split('\n')[1]).toBe('send-keys -t =nt-s: -H c3 a7 f0 9f 99 82')
+ })
+
+ it('splits long input into lines of KEYS_PER_COMMAND bytes, in order', () => {
+ const data = 'x'.repeat(KEYS_PER_COMMAND * 2 + 3)
+ const lines = keysCommandText('nt-s', data).trimEnd().split('\n').slice(1)
+ expect(lines).toHaveLength(3)
+ expect(lines.map((l) => l.split(' -H ')[1].split(' ').length)).toEqual([KEYS_PER_COMMAND, KEYS_PER_COMMAND, 3])
+ // Order: a byte that changes per position must come back in the same sequence.
+ const seq = Array.from({ length: KEYS_PER_COMMAND + 2 }, (_, i) => String.fromCharCode(0x41 + (i % 26))).join('')
+ const hex = keysCommandText('nt-s', seq)
+ .trimEnd()
+ .split('\n')
+ .slice(1)
+ .flatMap((l) => l.split(' -H ')[1].split(' '))
+ expect(hex.map((h) => String.fromCharCode(parseInt(h, 16))).join('')).toBe(seq)
+ })
+
+ it('every byte value is typed as exactly one two-digit hex token', () => {
+ const all = String.fromCharCode(...Array.from({ length: 128 }, (_, i) => i))
+ const tokens = keysCommandText('nt-s', all).split('\n')[1].split(' -H ')[1].split(' ')
+ expect(tokens).toHaveLength(128)
+ expect(tokens.every((t) => /^[0-9a-f]{2}$/.test(t))).toBe(true)
+ })
+
+ it('keeps every typed byte off the command line', () => {
+ expect(localKeysArgs('sock')).toEqual(['-L', 'sock', 'source-file', '-'])
+ const args = localPasteArgs('sock', 'nt-a', 'nt-paste-0a1b2c3d4e5f')
+ expect(args.join(' ')).toBe(
+ '-L sock load-buffer -b nt-paste-0a1b2c3d4e5f - ; if-shell -F -t =nt-a: #{pane_in_mode} copy-mode -q -t =nt-a: ; paste-buffer -d -p -r -b nt-paste-0a1b2c3d4e5f -t =nt-a:'
+ )
+ })
+
+ it('a paste never presses Enter and never names a target that is not exact', () => {
+ const args = localPasteArgs('sock', 'nt-a', 'nt-paste-0a')
+ expect(args).not.toContain('Enter')
+ expect(args).not.toContain('send-keys')
+ expect(() => localPasteArgs('sock', 'nt-a', 'nt-paste-0a; kill-server')).toThrow()
+ expect(() => localPasteArgs('sock', 'a', 'nt-paste-0a')).toThrow()
+ })
+
+ it('refuses an empty key chunk rather than build a send-keys with no bytes', () => {
+ expect(() => keysCommandText('nt-s', '')).toThrow(/no bytes/)
+ })
+})
+
+describe('the plan one chunk runs (local)', () => {
+ it('keys: source-file - with the command text on stdin, nothing to sweep', () => {
+ const plan = controlInputPlan('sock', 'nt-a', { kind: 'keys', data: 'ls\r' })
+ expect(plan).toEqual({ args: ['-L', 'sock', 'source-file', '-'], body: keysCommandText('nt-a', 'ls\r'), cleanup: null })
+ })
+
+ it('paste: the sanitized text rides stdin, framed by tmux (-p), and a failed paste sweeps its own buffer', () => {
+ const plan = controlInputPlan('sock', 'nt-a', { kind: 'paste', text: 'a\x1b[201~b\u009bc\nd' })!
+ expect(plan.body).toBe('a[201~bc\nd')
+ const buffer = plan.args[plan.args.indexOf('-b') + 1]
+ expect(buffer).toMatch(/^nt-paste-[a-z0-9]+$/)
+ expect(plan.args).toEqual(localPasteArgs('sock', 'nt-a', buffer))
+ expect(plan.cleanup).toEqual(['-L', 'sock', 'delete-buffer', '-b', buffer])
+ expect(plan.args.join(' ')).not.toContain('a[201~b')
+ })
+
+ it('paste: two plans never share a buffer', () => {
+ const a = controlInputPlan('sock', 'nt-a', { kind: 'paste', text: 'x' })!
+ const b = controlInputPlan('sock', 'nt-a', { kind: 'paste', text: 'x' })!
+ expect(a.cleanup).not.toEqual(b.cleanup)
+ })
+
+ it('paste: text that sanitizes to nothing has nothing to run', () => {
+ expect(controlInputPlan('sock', 'nt-a', { kind: 'paste', text: '\x1b\u009b' })).toBeNull()
+ expect(controlInputPlan('sock', 'nt-a', { kind: 'paste', text: '' })).toBeNull()
+ })
+
+ it('refuses a session name it did not generate, for both kinds', () => {
+ expect(() => controlInputPlan('sock', 'nt-a b', { kind: 'keys', data: 'x' })).toThrow()
+ expect(() => controlInputPlan('sock', 'nt-a b', { kind: 'paste', text: 'x' })).toThrow()
+ })
+})
+
+describe('the remote twins (over the ControlMaster)', () => {
+ it('keys: ssh runs `tmux -L nodeterm-rmt source-file -` on the host; the command text rides stdin', () => {
+ const args = remoteKeysArgs(CONN, CM)
+ expect(args).toContain(`ControlPath=${CM}`)
+ expect(args.at(-1)).toBe(`${remoteTmuxPathPrologue()}tmux -L ${RMT_TMUX_SOCKET} source-file -`)
+ expect(args.at(-2)).toBe('[email protected]')
+ })
+
+ it('paste: exact quoted target, mode cancel, -p, no Enter, and the text is not in argv', () => {
+ const cmd = remotePasteArgs(CONN, CM, 'nt-a', 'nt-paste-0a').at(-1)!
+ expect(cmd).toBe(
+ `${remoteTmuxPathPrologue()}tmux -L ${RMT_TMUX_SOCKET} load-buffer -b nt-paste-0a - ';' ` +
+ `if-shell -F -t '=nt-a:' '#{pane_in_mode}' 'copy-mode -q -t =nt-a:' ';' ` +
+ `paste-buffer -d -p -r -b nt-paste-0a -t '=nt-a:'`
+ )
+ expect(cmd).not.toContain('Enter')
+ expect(() => remotePasteArgs(CONN, CM, "nt-a'", 'nt-paste-0a')).toThrow()
+ expect(() => remotePasteArgs(CONN, CM, 'nt-a', 'nt-paste-0a;x')).toThrow()
+ })
+
+ it('a remote plan carries the same body as the local one and sweeps on the host', () => {
+ const keys = remoteControlInputPlan(CONN, CM, 'nt-a', { kind: 'keys', data: '\x02s' })
+ expect(keys).toEqual({ args: remoteKeysArgs(CONN, CM), body: keysCommandText('nt-a', '\x02s'), cleanup: null })
+ const paste = remoteControlInputPlan(CONN, CM, 'nt-a', { kind: 'paste', text: 'p\x1bq' })!
+ expect(paste.body).toBe('pq')
+ const buffer = /load-buffer -b (nt-paste-[a-z0-9]+) -/.exec(paste.args.at(-1)!)![1]
+ expect(paste.args).toEqual(remotePasteArgs(CONN, CM, 'nt-a', buffer))
+ expect(paste.cleanup!.at(-1)).toContain(`delete-buffer -b ${buffer}`)
+ expect(remoteControlInputPlan(CONN, CM, 'nt-a', { kind: 'paste', text: '\x1b' })).toBeNull()
+ })
+
+ it('no payload byte ever reaches the ssh argv', () => {
+ const secret = 'hunter2-PASSWORD'
+ const keys = remoteControlInputPlan(CONN, CM, 'nt-a', { kind: 'keys', data: secret })!
+ const paste = remoteControlInputPlan(CONN, CM, 'nt-a', { kind: 'paste', text: secret })!
+ for (const p of [keys, paste]) expect(p.args.join('\u0000')).not.toContain('hunter2')
+ const local = controlInputPlan('sock', 'nt-a', { kind: 'keys', data: secret })!
+ expect(local.args.join('\u0000')).not.toContain('hunter2')
+ })
+})
diff --git a/src/core/watch-link/pane-input.ts b/src/core/watch-link/pane-input.ts
new file mode 100644
index 000000000..06bd298c9
--- /dev/null
+++ b/src/core/watch-link/pane-input.ts
@@ -0,0 +1,209 @@
+// LIVE LINK CONTROL: a controller's typed bytes reach the node's PANE, never a tmux CLIENT.
+//
+// Why a pane and not a client. Writing into a tmux client's pty — the owner's painter, or the
+// watcher's own `attach-session` client — makes tmux read the bytes as that client's KEYBOARD:
+// they go through its key tables, so `C-b s` opens the session chooser and every other session on
+// the server is one keystroke away (`C-b s`, `j`, Enter). A watcher's own client is also read-only
+// and would drop every byte. So keys are injected into the pane with `send-keys -H`, which tmux
+// hands to the pane as `KEYC_LITERAL` bytes (`cmd-send-keys.c` → `window_pane_key` →
+// `input_key`: "Literal keys go as themselves"), with no client and no key table involved — the
+// same command the background-write path already types with (`encodeSendKeysHex`).
+//
+// THE TWO PLANS
+// - keys → `tmux -L <socket> source-file -`, the command TEXT on stdin:
+// if-shell -F -t =nt-x: '#{pane_in_mode}' 'copy-mode -q -t =nt-x:'
+// send-keys -t =nt-x: -H 1b 5b 41
+// `source-file -` keeps every typed byte (a password typed into the shell, say) off every
+// command line, local and SSH. The mode cancel comes first because `send-keys` into a pane in a
+// mode does NOT reach the app: copy mode dispatches its own key table, and tree mode (`C-b s`
+// opened by the owner) handles the keys itself — `j` then Enter would switch the owner's
+// client to another session. `copy-mode -q` leaves ANY mode, not just copy mode.
+// - paste → the paste plan `sendText` already uses (`load-buffer -` from stdin, the same mode
+// cancel, `paste-buffer -d -p -r`), with the text `sanitizePasteText`-ed, and NO Enter: tmux
+// frames it only when the pane's app asked for bracketed paste (`-p`), `-r` keeps `\n`.
+//
+// WHY NOT `paste-buffer` FOR EVERYTHING (the spec's first candidate). tmux 3.7 passes paste buffer
+// CONTENT through vis(3) (issue #453), so an ESC byte arrives as the two characters `^[`: an arrow
+// key arrives as the text `^[[A`, and Ctrl-C as `^C` (measured below, row x and 4e). Keys must never
+// ride a paste buffer.
+//
+// MEASURED (2026-10-04, Linux, private socket + private TMUX_TMPDIR, conf = `set -g prefix C-b`;
+// tmux 3.4 = /usr/bin/tmux, tmux 3.7b = the release the macOS app bundles, sha256-pinned, built
+// from source). The pane ran `stty raw -echo -iexten; cat > file`, i.e. the file is exactly what the
+// app's stdin received. SSH was NOT measured over a real ssh (no key for `ssh localhost` on the
+// measuring host); the remote command line is proven under a real /bin/sh in
+// pane-input.realtmux.test.ts instead.
+//
+// check 3.4 3.7b
+// 1 bytes exact: 0x00-0xff in 4 batches, ESC[A, 276/276 exact 276/276 exact
+// ESC O A, CR, ^C, DEL, ç 漢 🙂 é
+// 2 prefix inert: 02 73 via the keys plan, a real pane got 02 73, pane got 02 73,
+// client attached pane_in_mode 0 pane_in_mode 0
+// control: the SAME bytes typed INTO the client tree-mode opened tree-mode opened
+// 3 copy mode, then 61 mode left, pane got 61 mode left, got 61
+// control: send-keys -H with NO cancel eaten by copy mode eaten by copy mode
+// tree mode (C-b s on the client), then j Enter tree gone, pane got tree gone, pane got
+// 6a 0d, client stayed 6a 0d, client stayed
+// on its session on its session
+// tree mode via choose-tree -t, then 61 tree gone, got 61 tree gone, got 61
+// `copy-mode -q` exists yes yes
+// 4 paste a\nb, app asked for ?2004h ESC[200~ a \n b ESC[201~ (both)
+// paste a\nb, app did not a \n b (both)
+// paste x ESC[A y (sanitized first) x [A y (both)
+// paste ç漢🙂é intact (both)
+// paste into a pane in copy mode mode left, framed (both)
+// (info) paste p ^C q DEL r TAB z CR w bytes verbatim ^C → "^C", DEL → "^?",
+// TAB/CR verbatim
+// (info) UNSANITIZED ESC in a paste ESC verbatim "^[" (vis(3))
+// 5 =nt-a-1: with nt-a-12 alive only nt-a-1 got it (both)
+// =nt-a-9: (missing), keys and paste exit 1 "can't find session", nothing (both)
+// =nt-a-1: after nt-a-1 was killed exit 1, nt-a-12 untouched (both)
+// 6 16384 bytes in ONE source-file (16 lines) exact, 58 ms exact, 96 ms
+// 7 latency, 50 single bytes (spawn → bytes in median 3.1-3.3 ms, median 2.4 ms,
+// the file) p95 4.0-5.9 ms p95 12.1 ms
+// 8 SSH not measured over ssh (see above)
+// x (info) ESC[A through paste-buffer -r ESC[A "^[[A" (text)
+//
+// Also measured: a guard command tmux cannot PARSE (an unknown flag inside the if-shell string)
+// rejects the whole `source-file -` text before anything runs — exit 1, nothing typed — on both
+// versions; separate LINES are separate command groups at RUN time (a failing line does not stop
+// the next one), which is harmless here because every line names the same exact target.
+// Version floors: `source-file -` needs tmux 3.1 (CHANGES 3.0a→3.1); an older SSH host fails the
+// keys plan closed (exit 1). `copy-mode -q` is 3.2+ per the plan; untested below 3.4.
+// Read from tmux's source (window.c `window_pane_key`), not measured: `send-keys` honours a window's
+// `synchronize-panes` (the keys are copied to its other panes) and silently drops input to a pane
+// disabled with `select-pane -d` while still exiting 0. nodeterm's conf sets neither.
+import type { SshConnection } from '../../shared/ssh'
+import { posixQuote } from '../../shared/ssh'
+import { sanitizePasteText } from '../paste-injection'
+import {
+ assertPasteBuffer,
+ isSessionName,
+ localTmuxDeleteBufferArgs,
+ pasteBufferName,
+ type PasteDelivery
+} from '../tmux-naming'
+import { RMT_TMUX_SOCKET, childArgs, remoteDeleteBufferArgs, tmuxCmd } from '../remote-ssh/control-master'
+
+/** One unit of a controller's input. `keys` are typed byte for byte; `paste` is text tmux frames
+ * per the pane's own bracketed-paste state. */
+export type ControlInputChunk = { kind: 'keys'; data: string } | { kind: 'paste'; text: string }
+
+/**
+ * How a controller's input reaches a session's pane (`PtyManager.watcherInputRoute`):
+ * - `tmux` — the local tmux, by the plans in this file;
+ * - `ssh` — the same plans on the host, over the project's ControlMaster;
+ * - `write` — PtyManager's ordinary write path (the Windows session host, a direct Windows pane,
+ * the plain-shell fallback: there is no tmux client in between to reach a key table);
+ * - `none` — refused (Zellij: its key bindings are session-wide; an unknown session).
+ */
+export type WatcherInputRoute = 'tmux' | 'ssh' | 'write' | 'none'
+
+/** Bytes per `send-keys -H` line: 3 characters each on the line, so ~3 KiB a line. */
+export const KEYS_PER_COMMAND = 1024
+
+/**
+ * "Exactly this session, its active pane". Node ids end in a counter, so `nt-a-1` is a prefix of
+ * `nt-a-12`, and tmux resolves a bare target by prefix on a miss: a bare target would type into
+ * ANOTHER node. `=name:` is exact and resolves (capture-route.ts has the measurement). Throws for a
+ * name this app did not generate: the target is spliced UNQUOTED into tmux command text.
+ */
+export function exactPaneTarget(session: string): string {
+ if (!isSessionName(session)) throw new Error(`not a session name of ours: ${JSON.stringify(session)}`)
+ return `=${session}:`
+}
+
+/** The stdin of `tmux source-file -`: leave any mode, then type each byte literally. */
+export function keysCommandText(session: string, data: string): string {
+ const t = exactPaneTarget(session)
+ const bytes = Buffer.from(data, 'utf8')
+ if (bytes.length === 0) throw new Error('no bytes to type')
+ let out = `if-shell -F -t ${t} '#{pane_in_mode}' 'copy-mode -q -t ${t}'\n`
+ for (let i = 0; i < bytes.length; i += KEYS_PER_COMMAND) {
+ const hex = [...bytes.subarray(i, i + KEYS_PER_COMMAND)].map((b) => b.toString(16).padStart(2, '0'))
+ out += `send-keys -t ${t} -H ${hex.join(' ')}\n`
+ }
+ return out
+}
+
+/** argv (after the tmux binary) for the keys plan; the command text rides stdin. */
+export function localKeysArgs(socket: string): string[] {
+ return ['-L', socket, 'source-file', '-']
+}
+
+/** The text rides stdin (load-buffer -); tmux frames it only if the pane's app asked (-p). No Enter. */
+export function localPasteArgs(socket: string, session: string, buffer: string): string[] {
+ const t = exactPaneTarget(session)
+ assertPasteBuffer(buffer)
+ return [
+ '-L', socket,
+ 'load-buffer', '-b', buffer, '-', ';',
+ 'if-shell', '-F', '-t', t, '#{pane_in_mode}', `copy-mode -q -t ${t}`, ';',
+ // -d: drop our private buffer afterwards; -p: tmux decides framing from the pane's real state;
+ // -r: keep `\n` as `\n` instead of tmux's default `\n`→`\r` rewrite.
+ 'paste-buffer', '-d', '-p', '-r', '-b', buffer, '-t', t
+ ]
+}
+
+/** ssh args running `tmux -L nodeterm-rmt source-file -` on the host; the command text rides stdin. */
+export function remoteKeysArgs(conn: SshConnection, controlPath: string): string[] {
+ return childArgs(conn, controlPath, tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} source-file -`))
+}
+
+/**
+ * ssh args for the remote paste plan with an exact target; the text rides stdin. Every piece the
+ * remote SHELL would otherwise read is single-quoted: tmux's `;` (bare, it would end the tmux
+ * command), the `=name:` target, the `#{…}` format (`#` starts a comment) and the inner command,
+ * which is one tmux argument.
+ */
+export function remotePasteArgs(conn: SshConnection, controlPath: string, session: string, buffer: string): string[] {
+ const t = exactPaneTarget(session)
+ assertPasteBuffer(buffer)
+ const q = posixQuote(t)
+ return childArgs(
+ conn,
+ controlPath,
+ tmuxCmd(
+ `tmux -L ${RMT_TMUX_SOCKET} load-buffer -b ${buffer} - ';' ` +
+ `if-shell -F -t ${q} '#{pane_in_mode}' ${posixQuote(`copy-mode -q -t ${t}`)} ';' ` +
+ `paste-buffer -d -p -r -b ${buffer} -t ${q}`
+ )
+ )
+}
+
+/**
+ * EVERYTHING one chunk decides, in one tested place (the lesson in tmux-naming.ts's
+ * `localPasteDelivery`: a caller that re-composes sanitize / empty / buffer name lets a test pass
+ * while one of them is deleted). The argv to run, its stdin, and the buffer sweep for a paste whose
+ * `paste-buffer` never ran (run it with `runPasteDelivery`). null: a paste that sanitized to
+ * nothing — there is nothing to run. Throws for an empty key chunk or a name we did not generate.
+ */
+export function controlInputPlan(socket: string, session: string, chunk: ControlInputChunk): PasteDelivery | null {
+ if (chunk.kind === 'keys') {
+ return { args: localKeysArgs(socket), body: keysCommandText(session, chunk.data), cleanup: null }
+ }
+ const body = sanitizePasteText(chunk.text)
+ if (body.length === 0) return null
+ const buffer = pasteBufferName()
+ return { args: localPasteArgs(socket, session, buffer), body, cleanup: localTmuxDeleteBufferArgs(socket, buffer) }
+}
+
+/** `controlInputPlan` on the host, over the ControlMaster (the `nodeterm-rmt` socket there). */
+export function remoteControlInputPlan(
+ conn: SshConnection,
+ controlPath: string,
+ session: string,
+ chunk: ControlInputChunk
+): PasteDelivery | null {
+ if (chunk.kind === 'keys') {
+ return { args: remoteKeysArgs(conn, controlPath), body: keysCommandText(session, chunk.data), cleanup: null }
+ }
+ const body = sanitizePasteText(chunk.text)
+ if (body.length === 0) return null
+ const buffer = pasteBufferName()
+ return {
+ args: remotePasteArgs(conn, controlPath, session, buffer),
+ body,
+ cleanup: remoteDeleteBufferArgs(conn, controlPath, buffer)
+ }
+}