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(tmux): let tmux frame the paste, removing the 3.7 version floor
enes11b8aacc2787
diff --git a/src/core/local-send-keys.realtmux.test.ts b/src/core/local-send-keys.realtmux.test.tsindex 832ceb2ed..59f743554 100644--- a/src/core/local-send-keys.realtmux.test.ts+++ b/src/core/local-send-keys.realtmux.test.ts@@ -1,8 +1,8 @@// SECURITY — the LOCAL delivery argv, run against a real tmux driving a real bash.//-// `paste-injection.realtty.test.ts` proves what the framed BODY does to a reader. This file proves-// what the ARGV does to tmux, which is a different parser and had a different hole: `send-keys -l`-// does not stop option parsing, so a payload beginning with `-` was consumed by tmux as FLAGS.+// This file proves what the ARGV does to TMUX, which is a different parser from the receiving+// app's and had a different hole: `send-keys -l` does not stop option parsing, so a payload+// beginning with `-` was consumed by tmux as FLAGS.// Measured on tmux 3.4, every one of `-R -K -l -- -H -F -N 3` exits 0 while typing nothing,// so the delivery reported success — and then sent its Enter anyway, submitting whatever the human// had already composed in that pane.@@ -12,9 +12,11 @@// holds it. The human sees an empty prompt; the Enter that follows submits the line they can no// longer see.//-// The remote counterpart (`remoteTmuxSendKeysArgs`) has carried `--` since it was written; the-// local one never did. Same rule, one implementation missing it — the drift `sanitizePasteText`'s-// own header names as how a hole survives.+// The delivery no longer defends against that class — it cannot reach it. `sendText` hands the+// payload to `tmux load-buffer -` on STDIN, so the text is never an argument of anything and+// there is no option parser between it and the pane. The tests below run the same `-R` payload+// through the CURRENT delivery, and keep the pre-fix argv as a control so "structurally+// impossible" stays a measurement rather than a claim.//// A hand-rolled assertion on the argv array cannot see any of this: tmux's option parser is the// only thing that knows which leading dashes it eats. So tmux is the judge, and a real bash pane@@ -24,12 +26,12 @@ import { execFileSync } from 'child_process'import fs from 'fs'import os from 'os'import path from 'path'-import { localTmuxSendKeysArgs, localTmuxEnterArgs } from './tmux-naming'+import { localTmuxPasteArgs, localTmuxEnterArgs, pasteBufferName } from './tmux-naming'import { sanitizePasteText } from './paste-injection'/** A private socket, never `TMUX_SOCKET` — this must not touch a running nodeterm's tmux server. */const SOCKET = `nt-sendkeys-test-${process.pid}`-const SESSION = 'probe'+const SESSION = 'nt-probe'/*** The socket lives in the test's OWN temp dir, not `/tmp/tmux-<uid>/`.@@ -53,8 +55,8 @@ const TMUX = findTmux()let work: string/** `tmux <args>`, throwing on a non-zero exit exactly as `PtyManager`'s `runAsync` would. */-function tmux(args: string[]): string {- return execFileSync(TMUX as string, args, { encoding: 'utf8', env: tmuxEnv() })+function tmux(args: string[], input?: string): string {+ return execFileSync(TMUX as string, args, { encoding: 'utf8', env: tmuxEnv(), input })}/** Type `body` into the probe pane the way the HARNESS does it — always safely quoted. */@@ -142,8 +144,11 @@ suite('REAL tmux: a payload starting with `-` is text, never a flag', () => {// The human has half-typed a command and has NOT pressed Enter yet.compose(`touch ${danger}`)// The agent's `write` verb arrives. `-R` is a real `send-keys` flag ("reset terminal state").- tmux(localTmuxSendKeysArgs(SOCKET, SESSION, sanitizePasteText('-R')))- tmux(localTmuxEnterArgs(SOCKET, SESSION))+ // Through the current delivery it is buffer CONTENT, so tmux's option parser never sees it.+ tmux(+ localTmuxPasteArgs(SOCKET, SESSION, pasteBufferName(), true),+ sanitizePasteText('-R')+ )drain('minus-r')expect(fs.existsSync(danger),@@ -168,12 +173,10 @@ suite('REAL tmux: a payload starting with `-` is text, never a flag', () => {expect(fs.existsSync(`${danger}-R`)).toBe(false)})- it('a framed body (which starts with ESC, not `-`) is unaffected either way', () => {+ it('an ordinary payload still types and submits normally', () => {freshPane()const ok = path.join(work, 'framed')- // Not the paste framer's job here — just that a normal payload still types normally.- tmux(localTmuxSendKeysArgs(SOCKET, SESSION, `touch ${ok}`))- tmux(localTmuxEnterArgs(SOCKET, SESSION))+ tmux(localTmuxPasteArgs(SOCKET, SESSION, pasteBufferName(), true), `touch ${ok}`)drain('framed')expect(fs.existsSync(ok)).toBe(true)})diff --git a/src/core/paste-injection.realtty.test.ts b/src/core/paste-injection.realtty.test.tsindex 0a83bc299..7011fefe3 100644--- a/src/core/paste-injection.realtty.test.ts+++ b/src/core/paste-injection.realtty.test.ts@@ -2,19 +2,20 @@//// The sibling `paste-injection.test.ts` asserts on the produced BYTES. This file trusts no parser// of ours: it spawns a real pty running a real bash (readline turns bracketed paste on and-// announces it with `ESC[?2004h`, which is exactly the `bracket_paste_flag` the delivery paths-// probe for), writes the framed body into it, and then asks the filesystem whether the attacker's-// trailing bytes were executed as KEYS.+// announces it with `ESC[?2004h`), writes the framed body into it, and then asks the filesystem+// whether the attacker's trailing bytes were executed as KEYS.//// It exists for the reason `control-master.realsh.test.ts` exists: a structural test can only// catch the tricks it was taught, and this repo has twice shipped a defect that a hand-rolled// parser passed and the real thing caught. A paste frame is a promise made to somebody else's// parser, so somebody else's parser has to be the judge.//-// The SSH case goes the whole way: the remote command line `remoteTmuxSendKeysArgs` builds is run-// through a real /bin/sh with a stub `tmux` on PATH, and the bytes that stub receives — what the-// remote tmux would inject into the pane — are what get delivered to bash. Real quoting, then a-// real reader.+// SCOPE, since it changed: `bracketedInjection` is no longer how `sendText` delivers. Both of its+// paths hand the payload to tmux and let `paste-buffer -p` insert the markers, which is what+// removed the tmux-3.7 version floor — `tmux-paste.realtmux.test.ts` is where THAT is proven,+// against a real tmux, on both the local and the SSH command lines, including these same escape+// payloads. What remains here is the one caller that still builds a frame in JS:+// `agents/agent-message.ts`, which frames a message envelope before handing it to `sendFramed`.import { describe, it, expect, beforeAll, afterAll } from 'vitest'import { execFileSync } from 'child_process'import fs from 'fs'@@ -22,7 +23,6 @@ import os from 'os'import path from 'path'import * as pty from 'node-pty'import { bracketedInjection, PASTE_END } from './paste-injection'-import { remoteTmuxSendKeysArgs } from './remote-ssh/control-master'const ESC = '\x1b'/** readline says "I have requested bracketed paste" with this — the same DECSET tmux tracks. */@@ -56,30 +56,11 @@ const BASH = findPasteAwareBash()let work: stringlet markerDir: string-let binDir: stringbeforeAll(() => {work = fs.mkdtempSync(path.join(os.tmpdir(), 'ntpaste-'))markerDir = path.join(work, 'm')- binDir = path.join(work, 'bin')fs.mkdirSync(markerDir)- fs.mkdirSync(binDir)- // Stub tmux for the SSH path: answers the bracket_paste_flag probe with 1 and prints the body- // of a `send-keys` verbatim — i.e. exactly the bytes the remote tmux would put in the pane.- fs.writeFileSync(- path.join(binDir, 'tmux'),- [- '#!/bin/sh',- 'for a in "$@"; do',- ' last="$a"',- ' case "$a" in display-message) dm=1;; send-keys) sk=1;; esac',- 'done',- '[ -n "$dm" ] && { printf 1; exit 0; }',- '[ -n "$sk" ] && { if [ "$last" = Enter ]; then printf "\\r"; else printf %s "$last"; fi; }',- 'exit 0'- ].join('\n') + '\n',- { mode: 0o755 }- )})afterAll(() => {@@ -146,27 +127,11 @@ function deliver(bytes: string): Promise<string> {})}-/** The local delivery: `PtyManager.sendText`'s framed branch hands exactly this to send-keys. */+/** The one surviving JS framer: `agent-message.ts` builds exactly this for `sendFramed`. */const localBody = (text: string, enter: boolean): string => bracketedInjection(text, enter)-/** The SSH delivery: build the remote line, run it through a real sh, keep what tmux received. */-function sshBody(text: string, enter: boolean): string {- const cmd = remoteTmuxSendKeysArgs(- { host: 'h.example.com', user: 'deploy', port: 22, identityFile: '/k/id' },- '/s.sock',- 'nt-x',- text,- enter- ).slice(-1)[0]- return execFileSync('/bin/sh', ['-c', cmd], {- env: { PATH: `${binDir}:/usr/bin:/bin`, HOME: work },- encoding: 'utf8'- })-}-const PATHS: Record<string, (text: string, enter: boolean) => string> = {- local: localBody,- ssh: sshBody+ envelope: localBody}const suite = BASH ? describe : describe.skipdiff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex a6f3656d9..9ab30d35a 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -26,7 +26,8 @@ import {localKillSockets,localTmuxKillArgs,remoteTmuxPtyArgs,- remoteTmuxSendKeysArgs,+ remoteTmuxPasteArgs,+ remoteTmuxEnterArgs,remoteCapturePaneArgs,remotePaneCommandArgs,remotePaneOwnerArgs,@@ -50,11 +51,12 @@ import {TMUX_SOCKET,sessionName,isSessionName,- localTmuxSendKeysArgs,- localTmuxEnterArgs+ localTmuxPasteArgs,+ localTmuxEnterArgs,+ pasteBufferName} from './tmux-naming'import { encodeSendKeysHex } from './tmux-control'-import { bracketedInjection, sanitizePasteText } from './paste-injection'+import { sanitizePasteText } from './paste-injection'import { releasePty, type ReleasablePty } from './pty-release'import { effectiveSize, type PtySize } from './pty-size'import { machOArch, archMismatch } from './macho-arch'@@ -122,6 +124,32 @@ const runAsync = ((file: string, args: readonly string[], opts?: object) =>...(opts ?? {})} as never)) as unknown as typeof execFileAsync+/**+ * `runAsync`, with a payload written to the child's STDIN.+ *+ * The delivery path (`sendText`) puts the text in `tmux load-buffer -`'s stdin rather than in an+ * argument — no payload on a command line, and no MAX_ARG_STRLEN ceiling (measured: 300 KB in one+ * argument is "Argument list too long"; the same over stdin lands intact).+ *+ * `execFile`'s promise carries the ChildProcess as `.child`, so this stays inside the one bounded+ * wrapper every other side-call uses instead of hand-rolling a spawn: same `PROC_TIMEOUT_MS`, same+ * rejection on a non-zero exit. An EPIPE on the write (the child died before reading) is swallowed+ * here on purpose — the process result is the authority, and an unhandled 'error' on the stream+ * would take the main process down instead of failing this one call.+ */+function runWithStdin(file: string, args: readonly string[], input: string): Promise<unknown> {+ const p = execFileAsync(file, args as string[], { timeout: PROC_TIMEOUT_MS } as never)+ const child = (p as unknown as { child: import('child_process').ChildProcess }).child+ const stdin = child.stdin+ if (stdin) {+ stdin.on('error', () => {+ /* child gone; the exit code below is what decides success */+ })+ stdin.end(input)+ }+ return p as unknown as Promise<unknown>+}+// Minimal tmux config so the user's ~/.tmux.conf never interferes. The tmux server// (under our socket) keeps sessions alive while no client is attached, which is what// gives us continuity across node remounts and full app restarts.@@ -1015,7 +1043,7 @@ export class PtyManager {* is a name we have no claim to (a remote node's local orphan, another machine's idea of it, a* session someone else made). An unknown key is not evidence of a session.* - a node whose record says `remote`: its tmux is on the far host. Reaching it means the- * project's ControlMaster (`remoteTmuxSendKeysArgs`), not this channel; refusing is the honest+ * project's ControlMaster (`remoteTmuxPasteArgs`), not this channel; refusing is the honest* answer until that exists.*/async backgroundWrite(persistKey: string, data: string): Promise<boolean> {@@ -2793,21 +2821,47 @@ export class PtyManager {** An SSH-project node has no LOCAL tmux session to target (its pty program is `ssh -t '<remote* attach>'`) — so if the node's LIVE session is registered with `sshRemote`, this runs the- * remote counterpart instead (`remoteTmuxSendKeysArgs`, over the project's ControlMaster),+ * remote counterpart instead (`remoteTmuxPasteArgs`, over the project's ControlMaster),* mirroring how `remoteSessionExists` reuses `findSsh()` + `runAsync`. A node with no live* session at all (nothing mounted right now) still falls through to the local path and returns* false there, same as before this change — reaching a currently-unmounted SSH node's remote* session is not supported.+ *+ * ── DELIVERY: TMUX FRAMES THE PASTE, WE DO NOT ─────────────────────────────────────────────────+ *+ * Both paths are now one `tmux load-buffer - ; … ; paste-buffer -d -p -r ; send-keys Enter`+ * invocation with the payload on STDIN. `localTmuxPasteArgs` carries the whole measurement: the+ * old `#{bracket_paste_flag}` probe needed tmux 3.7 and, on every older tmux, quietly delivered+ * raw newlines into the app instead of a paste; `paste-buffer -p` asks the pane itself and has+ * done since tmux 1.7.+ *+ * `sanitizePasteText` still runs, ONCE, here, for both paths — the payload must not be able to+ * close the frame and become key input, and tmux inserting the markers does not change that.+ *+ * An EMPTY payload is handled before the buffer: `load-buffer -` with no bytes creates no+ * buffer, the `paste-buffer` that follows fails, and tmux aborts the rest of the list — so the+ * Enter would be lost. Measured. A caller sending `''` with `enter` means "just submit", which+ * is what the legacy two-step did, so that is what happens.*/async sendText(persistKey: string, text: string, opts?: { enter?: boolean }): Promise<boolean> {const enter = opts?.enter ?? trueconst target = sessionName(persistKey)+ const body = sanitizePasteText(text)+ const buffer = pasteBufferName()const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemoteif (sshRemote) {const ssh = findSsh()if (!ssh) return falsetry {- await runAsync(ssh, remoteTmuxSendKeysArgs(sshRemote.conn, sshRemote.controlPath, target, text, enter))+ if (body.length === 0) {+ if (enter) await runAsync(ssh, remoteTmuxEnterArgs(sshRemote.conn, sshRemote.controlPath, target))+ return true+ }+ await runWithStdin(+ ssh,+ remoteTmuxPasteArgs(sshRemote.conn, sshRemote.controlPath, target, buffer, enter),+ body+ )return true} catch {return false@@ -2815,29 +2869,11 @@ export class PtyManager {}if (!this.tmuxPath) return falsetry {- if (await this.bracketPasteRequested(target)) {- // Paste-aware target (agent TUIs, multiplexers like herdr): one atomic write — the- // text framed in paste markers plus the Enter — so the composer sees a definitive- // paste boundary and the Enter can never be re-chunked into the paste (issue #47).- await runAsync(- this.tmuxPath,- localTmuxSendKeysArgs(TMUX_SOCKET, target, bracketedInjection(text, enter))- )+ if (body.length === 0) {+ if (enter) await runAsync(this.tmuxPath, localTmuxEnterArgs(TMUX_SOCKET, target))return true}- // The literal text and the Enter (when sent) must go in order, so await sequentially.- // Sanitized like the framed body: which branch runs is decided by a runtime probe of the- // RECEIVER, so a payload must not become key input just because the target happens not to- // have requested bracketed paste (`sanitizePasteText`).- //- // `localTmuxSendKeysArgs` is what ends tmux's option parsing before the payload (`--`). This- // branch is the one that needed it: a framed body starts with ESC, but the legacy body is- // the caller's own text, and a `-R`/`-K`/`-l` payload was silently eaten as a FLAG — no- // characters typed, exit 0, and then the Enter below submitting the pane's composed line.- await runAsync(this.tmuxPath, localTmuxSendKeysArgs(TMUX_SOCKET, target, sanitizePasteText(text)))- if (enter) {- await runAsync(this.tmuxPath, localTmuxEnterArgs(TMUX_SOCKET, target))- }+ await runWithStdin(this.tmuxPath, localTmuxPasteArgs(TMUX_SOCKET, target, buffer, enter), body)return true} catch {return false@@ -2952,28 +2988,17 @@ export class PtyManager {}/**- * Did the application in this pane request bracketed-paste mode? tmux tracks the DECSET- * 2004 state per pane and exposes it as `bracket_paste_flag`. Unknown — query fails, old- * tmux without the format — reads as false, so delivery degrades to the legacy two-step- * path rather than sending paste markers an unaware app would render as garbage input.+ * DELETED: `bracketPasteRequested`.+ *+ * It read `#{bracket_paste_flag}`, a format that first shipped in TMUX 3.7 (2026-06-26). On+ * every earlier tmux — Ubuntu 24.04's 3.4, 22.04's 3.2a, Debian 12/13's 3.3a/3.5a, Ubuntu+ * 26.04's 3.6a, and whatever an SSH target happens to run — it expanded to the empty string,+ * so the probe answered "not paste-aware" for every pane on earth and the delivery mangled+ * every multi-line write. `paste-buffer -p` asks the pane's real state, inside tmux, with no+ * version floor; there is nothing left for this method to be right about. Do not reintroduce+ * it as a "capability check": on a pre-3.7 tmux it cannot distinguish "the app did not ask"+ * from "I cannot ask", which is exactly the confusion that shipped the bug.*/- private async bracketPasteRequested(target: string): Promise<boolean> {- if (!this.tmuxPath) return false- try {- const { stdout } = await runAsync(this.tmuxPath, [- '-L',- TMUX_SOCKET,- 'display-message',- '-p',- '-t',- target,- '#{bracket_paste_flag}'- ])- return stdout.trim() === '1'- } catch {- return false- }- }/*** List the names of all live nodeterm tmux sessions (on our dedicated socket). Used by thediff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.tsindex 4c1a42991..82191e71a 100644--- a/src/core/remote-ssh/control-master.test.ts+++ b/src/core/remote-ssh/control-master.test.ts@@ -5,7 +5,8 @@ import {masterArgs,childArgs,remoteTmuxHasSessionArgs,- remoteTmuxSendKeysArgs,+ remoteTmuxPasteArgs,+ remoteTmuxEnterArgs,probeSaysAbsent,remoteCapturePaneArgs,remotePaneCommandArgs,@@ -140,72 +141,79 @@ describe('remoteTmuxHasSessionArgs', () => {})})-describe('remoteTmuxSendKeysArgs', () => {+describe('remoteTmuxPasteArgs', () => {const TMUX = `tmux -L ${RMT_TMUX_SOCKET}`- /** The remote command is a paste-aware conditional: framed atomic send when the pane's app- * requested bracketed paste, the legacy two-step send otherwise (issue #47). */- const conditional = (session: string, framed: string, legacy: string): string =>- `if [ "$(${TMUX} display-message -p -t ${session} '#{bracket_paste_flag}' 2>/dev/null)" = 1 ]; then ${framed}; else ${legacy}; fi`-- it('sends literal text with -l -- (no Enter) when enter is false', () => {- const args = remoteTmuxSendKeysArgs(conn, '/s.sock', 'nt-x', 'hello', false)- expect(args).toEqual([+ const BUF = 'nt-paste-deadbeef'+ const cmd = (session: string, enter: boolean): string =>+ remoteTmuxPasteArgs(conn, '/s.sock', session, BUF, enter).slice(-1)[0]++ it('is ONE remote tmux invocation: buffer from stdin, gated copy-mode cancel, paste, Enter', () => {+ expect(remoteTmuxPasteArgs(conn, '/s.sock', 'nt-x', BUF, true)).toEqual([...childPrefix,- conditional(- 'nt-x',- `${TMUX} send-keys -t nt-x -l -- '\x1b[200~hello\x1b[201~'`,- `${TMUX} send-keys -t nt-x -l -- 'hello'`- )+ `${TMUX} load-buffer -b ${BUF} - ';' ` ++ `if-shell -F -t nt-x '#{pane_in_mode}' 'send-keys -t nt-x -X cancel' ';' ` ++ `paste-buffer -d -p -r -b ${BUF} -t nt-x ';' send-keys -t nt-x Enter`])})- it('appends Enter inside the framed write; legacy branch keeps the && two-step', () => {- const args = remoteTmuxSendKeysArgs(conn, '/s.sock', 'nt-x', 'hello', true)- expect(args[args.length - 1]).toBe(- conditional(- 'nt-x',- `${TMUX} send-keys -t nt-x -l -- '\x1b[200~hello\x1b[201~\r'`,- `${TMUX} send-keys -t nt-x -l -- 'hello' && ${TMUX} send-keys -t nt-x Enter`- )++ it('omits the Enter for a dictation insert (enter:false)', () => {+ expect(cmd('nt-x', false)).not.toContain('send-keys -t nt-x Enter')+ expect(cmd('nt-x', false).endsWith(`paste-buffer -d -p -r -b ${BUF} -t nt-x`)).toBe(true)+ })++ // The rule this PR is here to enforce: the payload is not on the command line at all, so there+ // is no `posixQuote` of an attacker-influenced body left to get wrong, and no MAX_ARG_STRLEN.+ it('carries NO payload — the text reaches the remote tmux over stdin', () => {+ const line = cmd('nt-x', true)+ expect(line).toContain(`load-buffer -b ${BUF} -`)+ expect(line).not.toContain('send-keys -t nt-x -l')+ expect(line).not.toContain('set-buffer')+ })++ // The version floor, stated as a negative. `#{bracket_paste_flag}` first shipped in tmux 3.7;+ // on the REMOTE host's older tmux it expanded to '' and the old conditional took its `else`+ // branch, delivering raw newlines. Nothing may reintroduce a dependency on it.+ it('never probes #{bracket_paste_flag} — the framing decision belongs to `paste-buffer -p`', () => {+ const line = cmd('nt-x', true)+ expect(line).not.toContain('bracket_paste_flag')+ expect(line).not.toContain('display-message')+ expect(line).toContain('paste-buffer -d -p -r')+ })++ // `-r` is load-bearing: without it tmux rewrites every `\n` in the buffer to `\r`, which is a+ // submit per line — the exact bug the frame exists to prevent.+ it('keeps -r so a newline stays a newline', () => {+ expect(cmd('nt-x', true)).toContain('-p -r')+ })++ // `#{...}` at the start of a word is a COMMENT to the remote sh; the inner command must arrive+ // as one tmux argument. Both are single-quoted, and `control-master.realsh.test.ts`'s sibling+ // (`tmux-paste.realtmux.test.ts`) runs this very line through a real sh into a real tmux.+ it('quotes the format and the inner command so the remote shell passes them through', () => {+ expect(cmd('nt-x', true)).toContain(`if-shell -F -t nt-x '#{pane_in_mode}' 'send-keys -t nt-x -X cancel'`)+ })++ it('refuses a session id this app did not generate — it is spliced unquoted', () => {+ expect(() => remoteTmuxPasteArgs(conn, '/s.sock', 'nt-x; kill-server', BUF, true)).toThrow(+ /unsafe tmux paste target/+ )+ expect(() => remoteTmuxPasteArgs(conn, '/s.sock', 'nt-x', "buf'; id; #", true)).toThrow(+ /unsafe tmux buffer name/)})- it('single-quote-escapes a single quote in the text (the \'\\\'\' idiom)', () => {- const args = remoteTmuxSendKeysArgs(conn, '/s.sock', 'nt-x', `it's`, false)- expect(args[args.length - 1]).toContain(`${TMUX} send-keys -t nt-x -l -- 'it'\\''s'`)- expect(args[args.length - 1]).toContain(`'\x1b[200~it'\\''s\x1b[201~'`)- })- it('keeps a multiline text as one literal token (single-quoted, newlines preserved)', () => {- const args = remoteTmuxSendKeysArgs(conn, '/s.sock', 'nt-x', 'line one\nline two', false)- expect(args[args.length - 1]).toContain(`${TMUX} send-keys -t nt-x -l -- 'line one\nline two'`)- })- it('guards leading-dash text from being read as a send-keys option (-l --)', () => {- const args = remoteTmuxSendKeysArgs(conn, '/s.sock', 'nt-x', '-not-an-option', false)- expect(args[args.length - 1]).toContain(`${TMUX} send-keys -t nt-x -l -- '-not-an-option'`)- })- // SECURITY: a payload carrying the paste-END marker would close the frame early and turn the- // rest into key input. BOTH branches sanitize — which one runs is decided by a probe of the- // RECEIVER, so the payload must not become keys just because the target never asked for- // bracketed paste. `paste-injection.realtty.test.ts` proves the framed body against a real bash.- it('strips a payload ESC from BOTH branches — the frame is the only structure left', () => {- const cmd = remoteTmuxSendKeysArgs(conn, '/s.sock', 'nt-x', 'a\x1b[201~\rid\r', true).slice(-1)[0]- expect(cmd).toContain(`${TMUX} send-keys -t nt-x -l -- '\x1b[200~a[201~\rid\r\x1b[201~\r'`)- expect(cmd).toContain(`${TMUX} send-keys -t nt-x -l -- 'a[201~\rid\r' && ${TMUX} send-keys -t nt-x Enter`)- // Only the frame's own two escapes survive anywhere in the remote line.- expect(cmd.split('\x1b')).toHaveLength(3)- })- // SECURITY, the other half, stated as a NON-guarantee: line breaks are NOT stripped by either- // branch and must not be — a pasted transcript and a note push both carry newlines legitimately- // (which is why the sanitizer above removes ESC and leaves `\n` alone). A `\r` in the text- // therefore survives the quoting and reaches the remote pane as a KEY. That is exactly why a- // caller that believed it was sending ONE line (`/rename <title>`, built from an agent-supplied- // title) has to be fixed where it COMPOSES that line, not here. See `@shared/one-line` and- // `renderer/lib/sessionRename.ts`.- it('carries a CR in the text through to the pane — the delivery is not where a splice is fixed', () => {- const cmd = remoteTmuxSendKeysArgs(conn, '/s.sock', 'nt-x', 'one\rtwo', true).slice(-1)[0]- // Legacy branch: the CR is inside the quoted literal, and the submit is a SEPARATE send-keys.- expect(cmd).toContain(`${TMUX} send-keys -t nt-x -l -- 'one\rtwo' && ${TMUX} send-keys -t nt-x Enter`)- // Framed branch: same CR, still content of the payload.- expect(cmd).toContain(`'\x1b[200~one\rtwo\x1b[201~\r'`)+})++describe('remoteTmuxEnterArgs', () => {+ // `sendText('', { enter: true })` means "submit what is composed". It cannot ride the paste+ // command list: `load-buffer -` with zero bytes creates no buffer, the paste fails, and tmux+ // abandons the rest of the list — the Enter with it.+ it('sends a bare Enter and nothing else', () => {+ expect(remoteTmuxEnterArgs(conn, '/s.sock', 'nt-x')).toEqual([+ ...childPrefix,+ '[email protected]',+ `tmux -L ${RMT_TMUX_SOCKET} send-keys -t nt-x Enter`+ ])})})diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.tsindex 7cf8180d1..f508fc91c 100644--- a/src/core/remote-ssh/control-master.ts+++ b/src/core/remote-ssh/control-master.ts@@ -4,9 +4,8 @@ import os from 'os'import path from 'path'import { createHash } from 'crypto'import { posixQuote, quoteRemotePath, remoteTmuxCommand, type SshConnection } from '../../shared/ssh'-import { TMUX_SOCKET } from '../tmux-naming'+import { TMUX_SOCKET, assertPasteTarget } from '../tmux-naming'import { canControlCanvas } from '../../shared/agents/config'-import { bracketedInjection, sanitizePasteText } from '../paste-injection'import { PANE_OWNER_FMT, foregroundArgvArgs } from '../agents/pane-owner'// Dependency-free (no node-pty): safe to import from these pure builders.@@ -211,41 +210,71 @@ export function parseRemoteSessionNames(stdout: string): string[] {}/**- * Send literal text (and optionally Enter) into a node's REMOTE tmux session — the remote- * counterpart of `PtyManager.sendText`'s local `tmux send-keys` path (dictation insert, /rename,- * /branch, note pushes). Built as ONE remote command so everything runs strictly in order on- * the remote host without a second network round trip: `-l --` sends the text literally (`-l`)- * and stops option parsing first (`--`, so text starting with `-` is never read as another- * send-keys flag); `text` is single-quoted (`posixQuote`) so it survives the remote shell as one- * token verbatim, multiline included.+ * Deliver text (and optionally Enter) into a node's REMOTE tmux session — the remote counterpart+ * of `PtyManager.sendText`'s local path (dictation insert, /rename, /branch, note pushes). ONE+ * remote command, so everything runs strictly in order on the remote host with no second network+ * round trip.*- * Mirrors the local path's paste-aware delivery (`PtyManager.sendText`, issue #47): when the- * remote pane's application requested bracketed-paste mode (`bracket_paste_flag`), the text is- * framed in paste markers with the Enter appended in the SAME send-keys, so a re-chunking- * middle layer (e.g. the herdr multiplexer) can never absorb the Enter into the paste. The- * quoted body carries raw ESC/CR bytes — inside single quotes they reach tmux verbatim.- * Otherwise the legacy two-step send runs, joined with `&&`, not `;`: Enter only fires if the- * text send actually succeeded, so a failed text send can never leave a lone Enter to submit- * whatever was already composed in a live agent prompt.+ * THE TEXT IS NOT IN THIS ARGV. It rides the ssh child's STDIN into `tmux load-buffer -b … -`.+ * Two reasons, and both of them bit the previous version:*- * BOTH branches run the payload through `sanitizePasteText` — the same one function the local- * path calls — so the remote and local deliveries cannot drift on the rule that keeps a payload- * from escaping its paste frame and being read as key input. Drift is how that survived here.+ * - ARG_MAX. `set-buffer -- "$text"` / `send-keys -l -- '<text>'` puts the whole payload in one+ * argument, and a single argument is capped at MAX_ARG_STRLEN (128 KB). Measured locally: a+ * 300 KB payload dies with "Argument list too long"; the same payload through `load-buffer -`+ * lands intact. A scrollback paste or a long note push is not a hypothetical size.+ * - This repo's standing rule: no payload on a command line. It also retires the `posixQuote`+ * of an attacker-influenced body into a remote shell line entirely — there is nothing left to+ * quote.+ *+ * FRAMING is tmux's job now, not ours. See `localTmuxPasteArgs` for the whole measurement: the+ * old `#{bracket_paste_flag}` conditional needed tmux 3.7 on the REMOTE host and silently+ * degraded to a raw-newline mangle on every older one, while `paste-buffer -p` has consulted the+ * pane's real bracketed-paste state since tmux 1.7 (2012). The remote host's tmux version stops+ * being something this feature depends on.+ *+ * `sanitizePasteText` still runs — at the CALLER (`PtyManager.sendText`), once, for both paths,+ * on the bytes that go down stdin. tmux inserting the frame does not make a payload-supplied+ * `ESC[201~` harmless: it would still close the frame early and turn the rest into key input.+ *+ * The `#{pane_in_mode}` format and the inner `send-keys` command string are single-quoted so the+ * remote SHELL passes them through verbatim — `#…` at the start of a word is a comment to sh, and+ * the inner command is one tmux argument. `sessionId` is spliced unquoted, exactly as every+ * sibling builder here does, and that is safe only because `sessionName()` sanitises to+ * `[A-Za-z0-9_-]`; `localTmuxPasteArgs` asserts it for both paths (`assertPasteTarget`).*/-export function remoteTmuxSendKeysArgs(+export function remoteTmuxPasteArgs(conn: SshConnection,controlPath: string,sessionId: string,- text: string,+ buffer: string,enter: boolean): string[] {+ assertPasteTarget(sessionId, buffer)const tmux = `tmux -L ${RMT_TMUX_SOCKET}`- const framed = `${tmux} send-keys -t ${sessionId} -l -- ${posixQuote(bracketedInjection(text, enter))}`- let legacy = `${tmux} send-keys -t ${sessionId} -l -- ${posixQuote(sanitizePasteText(text))}`- if (enter) legacy += ` && ${tmux} send-keys -t ${sessionId} Enter`- const cmd = `if [ "$(${tmux} display-message -p -t ${sessionId} '#{bracket_paste_flag}' 2>/dev/null)" = 1 ]; then ${framed}; else ${legacy}; fi`+ let cmd =+ `${tmux} load-buffer -b ${buffer} - ';' ` ++ `if-shell -F -t ${sessionId} '#{pane_in_mode}' 'send-keys -t ${sessionId} -X cancel' ';' ` ++ `paste-buffer -d -p -r -b ${buffer} -t ${sessionId}`+ if (enter) cmd += ` ';' send-keys -t ${sessionId} Enter`return childArgs(conn, controlPath, cmd)}++/**+ * A bare Enter into the remote pane — the remote half of `sendText`'s empty-payload case.+ *+ * It is not a special case invented here: `sendText('', { enter: true })` means "submit whatever+ * is composed", and the legacy two-step did exactly this (an empty literal send is a no-op, then+ * the Enter). It has to bypass `remoteTmuxPasteArgs` because `load-buffer -` given zero bytes+ * creates NO buffer, so the `paste-buffer` after it fails and tmux abandons the rest of the+ * command list — including the Enter. Measured.+ */+export function remoteTmuxEnterArgs(+ conn: SshConnection,+ controlPath: string,+ sessionId: string+): string[] {+ return childArgs(conn, controlPath, `tmux -L ${RMT_TMUX_SOCKET} send-keys -t ${sessionId} Enter`)+}/*** Did a FAILED `tmux has-session` probe actually say the session is absent? Only tmux's own* exit 1 ("can't find session" / "no server running") does. Anything else — ssh's 255 (a dead@@ -353,7 +382,7 @@ export function remoteCapturePaneArgs(conn: SshConnection, controlPath: string,* Ask the REMOTE tmux which command is in the foreground of a node's pane — the remote* counterpart of `PtyManager.paneCommand`'s local `display-message` path. The format is* single-quoted so `#{…}` survives the remote shell verbatim (same idiom as the- * `bracket_paste_flag` probe in `remoteTmuxSendKeysArgs`).+ * `#{pane_in_mode}` gate in `remoteTmuxPasteArgs`).*/export function remotePaneCommandArgs(conn: SshConnection, controlPath: string, sessionId: string): string[] {return childArgs(diff --git a/src/core/tmux-naming.test.ts b/src/core/tmux-naming.test.tsindex d1a401ac9..7cb428a54 100644--- a/src/core/tmux-naming.test.ts+++ b/src/core/tmux-naming.test.ts@@ -1,7 +1,8 @@import { describe, it, expect } from 'vitest'import {- localTmuxSendKeysArgs,localTmuxEnterArgs,+ localTmuxPasteArgs,+ pasteBufferName,sessionName,isSessionName,TMUX_SOCKET@@ -17,29 +18,10 @@ describe('sessionName / isSessionName', () => {})})-/**- * SECURITY — the payload must not be able to become an OPTION.- *- * `send-keys -l <text>` stops being "type this literally" the moment `<text>` begins with `-`:- * tmux is still in option-parsing mode, so the payload is read as flags. `--` is what ends option- * parsing, and the remote path has always had it (`remoteTmuxSendKeysArgs`) while the local one- * did not — the exact drift `sanitizePasteText`'s own header warns about.- */-describe('localTmuxSendKeysArgs', () => {- it('ends option parsing before the payload', () => {- const args = localTmuxSendKeysArgs('sock', 'nt-x', 'hello')- expect(args).toEqual(['-L', 'sock', 'send-keys', '-t', 'nt-x', '-l', '--', 'hello'])- })- it('puts `--` immediately before the body, whatever the body is', () => {- // Every payload here exits 0 as a FLAG on tmux 3.4 — i.e. was accepted, typed nothing, and let- // the caller believe it had been delivered. `-R` additionally resets the pane display.- for (const body of ['-R', '-K', '-l', '--', '-H', '-F', '-N 3', '\x1b[200~x\x1b[201~\r']) {- const args = localTmuxSendKeysArgs(TMUX_SOCKET, 'nt-x', body)- expect(args[args.length - 2]).toBe('--')- expect(args[args.length - 1]).toBe(body)- }- })- it('the Enter is a separate command and carries no literal body to protect', () => {+describe('localTmuxEnterArgs', () => {+ // The bare submit, used only for `sendText('', { enter: true })` now that the ordinary path is+ // one atomic tmux command list. It carries no literal body, so it needs no `--`.+ it('is a plain Enter with no payload', () => {expect(localTmuxEnterArgs('sock', 'nt-x')).toEqual(['-L','sock',@@ -48,5 +30,59 @@ describe('localTmuxSendKeysArgs', () => {'nt-x','Enter'])+ expect(localTmuxEnterArgs(TMUX_SOCKET, 'nt-x')).not.toContain('-l')+ })+})++/**+ * The delivery `sendText` actually uses. Structure only — `tmux-paste.realtmux.test.ts` is where+ * the same argv is handed to a real tmux driving a real application and the BYTES are judged.+ */+describe('localTmuxPasteArgs', () => {+ const BUF = 'nt-paste-deadbeef'++ it('is one invocation: stdin buffer, gated cancel, framed paste, Enter — in that order', () => {+ expect(localTmuxPasteArgs('sock', 'nt-x', BUF, true)).toEqual([+ '-L', 'sock',+ 'load-buffer', '-b', BUF, '-',+ ';', 'if-shell', '-F', '-t', 'nt-x', '#{pane_in_mode}', 'send-keys -t nt-x -X cancel',+ ';', 'paste-buffer', '-d', '-p', '-r', '-b', BUF, '-t', 'nt-x',+ ';', 'send-keys', '-t', 'nt-x', 'Enter'+ ])+ })++ it('omits the Enter for a dictation insert', () => {+ expect(localTmuxPasteArgs('sock', 'nt-x', BUF, false)).not.toContain('Enter')+ })++ // The version floor this PR removes. `#{bracket_paste_flag}` first shipped in tmux 3.7; every+ // older tmux expanded it to '' and the delivery mangled the write. Nothing here may depend on it.+ it('never reads #{bracket_paste_flag} — `-p` asks the pane instead, and has since tmux 1.7', () => {+ const args = localTmuxPasteArgs('sock', 'nt-x', BUF, true)+ expect(args).not.toContain('#{bracket_paste_flag}')+ expect(args).not.toContain('display-message')+ expect(args).toContain('-p')+ })++ // Everything the payload could have been is absent: it goes down stdin, which is both the+ // MAX_ARG_STRLEN fix and the repo rule that no payload rides a command line.+ it('carries no payload of any kind', () => {+ const args = localTmuxPasteArgs('sock', 'nt-x', BUF, true)+ expect(args).not.toContain('set-buffer')+ expect(args).not.toContain('-l')+ expect(args.filter((a) => a === '-')).toHaveLength(1) // load-buffer's stdin marker+ })++ it('gives every call its own buffer, so two concurrent deliveries cannot overwrite each other', () => {+ const names = new Set(Array.from({ length: 200 }, () => pasteBufferName()))+ expect(names.size).toBe(200)+ for (const n of names) expect(n).toMatch(/^nt-paste-[0-9a-f]{12}$/)+ })++ it('refuses anything spliced unquoted that this app did not generate', () => {+ expect(() => localTmuxPasteArgs('sock', 'nt-x; kill-server', BUF, true)).toThrow(/paste target/)+ expect(() => localTmuxPasteArgs('sock', sessionName(''), BUF, true)).toThrow(/paste target/)+ expect(() => localTmuxPasteArgs('sock', 'nt-x', 'buffer0', true)).toThrow(/buffer name/)+ expect(() => localTmuxPasteArgs('sock', sessionName('term-mabc-3'), pasteBufferName(), true)).not.toThrow()})})diff --git a/src/core/tmux-naming.ts b/src/core/tmux-naming.tsindex e7dbce385..376f0f931 100644--- a/src/core/tmux-naming.ts+++ b/src/core/tmux-naming.ts@@ -1,5 +1,6 @@// Pure tmux naming helpers shared by the PTY manager and the context-link backend.// No native/electron imports, so this module is safe to import from unit tests.+import { randomBytes } from 'crypto'export const TMUX_SOCKET = 'node-terminal'@@ -24,39 +25,159 @@ export function isSessionName(target: string): boolean {}/**- * SECURITY — the literal-text `send-keys` argv for a LOCAL pane, with option parsing ENDED.- *- * `-l` means "these are literal characters", but it does NOT stop tmux reading further arguments- * as options. A payload beginning with `-` is therefore taken as flags, and on tmux 3.4 every one- * of `-R -K -l -- -H -F -N 3` exits 0 while typing nothing. The delivery then reported- * SUCCESS — and `sendText`'s legacy branch went on to send its Enter, submitting whatever the- * human had already composed in that pane. An agent's `write --text -R` was a remote "press Enter- * on whatever is half-typed in that terminal" with no text of its own to show the approver, and- * `-R` resets the pane DISPLAY as well, so the line being submitted had just been wiped off the- * screen while readline still held it.- *- * The other direction of the same bug is the everyday one: any legitimate text starting with `-`- * — a dictation insert, a note push, a `/rename` of a title beginning with a dash — was silently- * not typed at all.- *- * `--` is the whole fix, and the remote path (`remoteTmuxSendKeysArgs`) has always had it — its- * doc comment even says why. Only the local path was missing it. This function exists so the two- * cannot drift again: every local literal send goes through here, the way every framed body goes- * through `bracketedInjection`.- *- * The socket is a PARAMETER rather than `TMUX_SOCKET` read from module scope so a test can drive- * a real tmux on a private socket without touching a running app's server.+ * ── DELETED: `localTmuxSendKeysArgs` ────────────────────────────────────────────────────────────+ *+ * It built `send-keys -t <t> -l -- <body>`, and the `--` was load-bearing: `-l` means "literal+ * characters" but does NOT stop tmux reading further arguments as options, so a payload beginning+ * with `-` was taken as FLAGS. Measured on tmux 3.4, every one of `-R -K -l -- -H -F -N 3`+ * exited 0 while typing nothing — the delivery reported success and then sent its Enter, which+ * submitted whatever the human had already composed in that pane (and `-R` had wiped it off the+ * screen first).+ *+ * `sendText` no longer puts the payload in an argument at all: it goes down `load-buffer -`'s+ * stdin. The entire leading-dash class is structurally gone rather than defended against, which+ * is why the builder is gone with it. `local-send-keys.realtmux.test.ts` still runs the `-R`+ * payload through the CURRENT delivery, and still runs the pre-fix argv as a control.*/-export function localTmuxSendKeysArgs(socket: string, target: string, body: string): string[] {- return ['-L', socket, 'send-keys', '-t', target, '-l', '--', body]-}/**- * The separate Enter of the legacy (non-bracketed) two-step delivery. It carries no literal body,- * so it needs no `--` — but it must stay a sibling of `localTmuxSendKeysArgs` because the ORDER is- * the contract: the text send must succeed before this runs, or the Enter submits somebody else's- * line. (The remote path spells the same rule as `&&` between the two commands.)+ * A bare Enter. One caller left: `sendText('', { enter: true })`, i.e. "submit whatever is+ * composed". It cannot ride the paste command list, because `load-buffer -` given zero bytes+ * creates no buffer, the `paste-buffer` after it fails, and tmux abandons the rest of the list —+ * the Enter with it (measured). Every non-empty write puts the text and the Enter in ONE tmux+ * invocation, which is also what makes "the Enter can never fire after a failed text send"+ * structural rather than a rule the caller has to remember.*/export function localTmuxEnterArgs(socket: string, target: string): string[] {return ['-L', socket, 'send-keys', '-t', target, 'Enter']}++/**+ * ── WHY THE DELIVERY BELOW EXISTS, AND WHAT IT REPLACED ─────────────────────────────────────────+ *+ * A multi-line write must reach a paste-aware TUI INSIDE a bracketed-paste frame. Framed, the app+ * reads the whole thing as one pasted block; unframed, every `\n` is a submit, so a three-line+ * note push becomes three turns (herdr :260) and the last one races the Enter that follows it.+ *+ * The previous design asked tmux WHETHER to frame — `display-message -p '#{bracket_paste_flag}'`+ * — and framed the body itself. Measured: that format FIRST SHIPPED IN TMUX 3.7 (2026-06-26,+ * CHANGES "FROM 3.6b TO 3.7"). On every earlier tmux it is an unknown name that expands to the+ * empty string, so the probe answered false for EVERY pane. And a false answer did not refuse —+ * it fell through to the legacy two-step, which delivered `line1\nline2\nline3` + `\r` raw into+ * the app. Measured on this host (tmux 3.4): exactly those bytes. Ubuntu 24.04 ships 3.4, 22.04+ * → 3.2a, Debian 12/13 → 3.3a/3.5a, Ubuntu 26.04 → 3.6a — plus every SSH target, where the+ * REMOTE host's tmux decides. So the mangle was the norm, not the exception.+ *+ * `paste-buffer -p` removes the question. tmux inserts the bracket codes "if the application has+ * requested bracketed paste mode" — it consults the pane's REAL DECSET 2004 state itself, the+ * state it has tracked since long before it could format it. Introduced 2012-03-03, shipped in+ * TMUX 1.7. There is no version floor left to hit.+ *+ * Measured on tmux 3.4, against a raw-mode reader that records the bytes its stdin actually got:+ * - app requested 2004 → `ESC[200~ … ESC[201~` then the Enter's `\r`+ * - app did not → the text, unframed, byte-identical to the legacy two-step+ * - a NON-ACTIVE pane → still framed correctly+ * - `-r` → `\n` survives as `\n` (WITHOUT it tmux rewrites every `\n` to `\r`,+ * which is the per-line submit this whole thing exists to avoid)+ * - `-d` + a private buffer name → the user's own numbered buffer stack is untouched+ */++/**+ * A tmux buffer name owned by ONE delivery.+ *+ * Unique per call, not a constant: tmux interleaves command lists from DIFFERENT clients, so two+ * concurrent `sendText`s sharing one buffer name would have the second `load-buffer` overwrite+ * the first's payload before its `paste-buffer` ran — one pane gets the other's text, and the+ * loser's write vanishes. The name is `[a-z0-9-]` only, because it is spliced into a tmux command+ * string and (on the SSH leg) a remote shell line.+ */+export function pasteBufferName(rand: () => string = () => randomBytes(6).toString('hex')): string {+ return `nt-paste-${rand()}`+}++/**+ * The ONE tmux invocation that delivers `sendText`'s payload: load the buffer from STDIN, leave+ * copy mode if the pane is in it, let tmux paste-and-frame it, then Enter. The text itself is not+ * here — it goes over stdin, which is both the ARG_MAX fix and this repo's standing rule.+ *+ * ARG_MAX, measured on this host: `set-buffer -- "$text"` with a 300 KB payload dies with+ * "Argument list too long" (a single argument is capped at MAX_ARG_STRLEN = 128 KB, well under+ * the 2 MB `getconf ARG_MAX`). The same 300 KB through `load-buffer -` lands intact and framed.+ *+ * ── COPY MODE, AND WHY THE CANCEL IS GATED INSIDE TMUX ──────────────────────────────────────────+ *+ * With `#{pane_in_mode}` = 1 (a wheel scroll is enough — nodeterm's tmux has the mouse on),+ * `paste-buffer -p` delivers UNFRAMED: tmux checks the copy-mode screen rather than the app. So+ * the per-line-submit bug comes straight back for a user who happened to be scrolled up. Worse,+ * measured: the trailing `send-keys Enter` is eaten by the copy-mode key table and never reaches+ * the app at all. `send-keys -X cancel` first restores both.+ *+ * The cancel is NOT unconditional. Measured on 3.4: `send-keys -X cancel` against a pane that is+ * NOT in a mode FAILS ("not in a mode", exit 1) and ABORTS THE REST OF THE COMMAND LIST — nothing+ * is pasted, no Enter, and the delivery reports failure. An unconditional cancel would therefore+ * break every ordinary write, which is the opposite of the bug being fixed.+ *+ * `if-shell -F` evaluates a FORMAT (no shell, no fork) and runs its command only when the format+ * is non-zero, so the gate rides inside the same single invocation: no extra round trip, and no+ * probe of ours that a future tmux could change the answer to.+ *+ * The user-visible cost is real but bounded to the case that already misbehaved: a human reading+ * scrollback is scrolled back to the live view. It is not a regression, because TODAY that same+ * pane gets NOTHING — measured: `send-keys -l --` + `send-keys Enter` into a copy-mode pane exits+ * 0 and delivers zero bytes, so `sendText` returns true having written nothing at all.+ *+ * The target is spliced UNQUOTED into the `if-shell` command string (tmux's own lexer parses it),+ * so it must be a name this app generated; `isSessionName` is asserted rather than assumed.+ */+export function localTmuxPasteArgs(+ socket: string,+ target: string,+ buffer: string,+ enter: boolean+): string[] {+ assertPasteTarget(target, buffer)+ const args = [+ '-L',+ socket,+ // stdin, so no payload on a command line and no ARG_MAX ceiling+ 'load-buffer',+ '-b',+ buffer,+ '-',+ ';',+ 'if-shell',+ '-F',+ '-t',+ target,+ '#{pane_in_mode}',+ `send-keys -t ${target} -X cancel`,+ ';',+ // -d: drop our private buffer afterwards, so the user's paste stack is untouched+ // -p: tmux decides framing from the pane's REAL bracketed-paste state+ // -r: keep `\n` as `\n` instead of tmux's default `\n`→`\r` rewrite+ 'paste-buffer',+ '-d',+ '-p',+ '-r',+ '-b',+ buffer,+ '-t',+ target+ ]+ // Same invocation as the paste, so the Enter can never be re-chunked into it — and, because+ // tmux aborts a command list at the first failure, a paste that did not happen can never leave+ // a lone Enter behind to submit whatever the human had composed.+ if (enter) args.push(';', 'send-keys', '-t', target, 'Enter')+ return args+}++/**+ * Shared by the local argv builder and the remote command builder so the two cannot drift on the+ * rule that makes the unquoted splices safe. Throws rather than sanitizing: a caller holding a+ * target this app did not generate is a bug, and `sendText` already turns a throw into `false`.+ */+export function assertPasteTarget(target: string, buffer: string): void {+ if (!isSessionName(target)) throw new Error(`unsafe tmux paste target: ${JSON.stringify(target)}`)+ if (!/^nt-paste-[a-z0-9-]+$/.test(buffer))+ throw new Error(`unsafe tmux buffer name: ${JSON.stringify(buffer)}`)+}diff --git a/src/core/tmux-paste.realtmux.test.ts b/src/core/tmux-paste.realtmux.test.tsnew file mode 100644index 000000000..4d4f7a92c--- /dev/null+++ b/src/core/tmux-paste.realtmux.test.ts@@ -0,0 +1,526 @@+// THE DELIVERY, PROVEN AGAINST A REAL TMUX DRIVING A REAL APPLICATION.+//+// The subject is `sendText`'s one-round-trip paste: `load-buffer -` over stdin, a copy-mode+// cancel gated by `if-shell -F`, then `paste-buffer -d -p -r`, then Enter. Both the LOCAL argv+// (`localTmuxPasteArgs`) and the REMOTE command line (`remoteTmuxPasteArgs`, run through a real+// /bin/sh) are driven here, against the same panes, and asserted to produce the SAME bytes —+// parity is the property that kept breaking when the two paths were written twice.+//+// WHAT JUDGES. Not a parser of ours, and not tmux's own `#{bracket_paste_flag}` (which is the+// thing being removed, and which does not even exist on this host's tmux 3.4). The pane runs a+// program that puts its tty in RAW mode and appends every byte it receives to a file: the frame+// either arrives on the application's stdin or it does not. For the security cases the pane runs+// a real interactive bash — readline's own bracketed-paste implementation — and the verdict is+// whether a file the payload asked for exists.+//+// WHY THIS FILE EXISTS AT ALL. The previous delivery asked tmux "did the app request bracketed+// paste?" via `#{bracket_paste_flag}`, a format that first shipped in TMUX 3.7 (2026-06-26). On+// anything older it expands to '' and the code read that as "no" — then delivered the text with+// RAW NEWLINES, one submit per line. Every assertion below that names the version floor is a+// measurement of that, taken here, on this tmux.+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { execFileSync } from 'child_process'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { localTmuxPasteArgs, pasteBufferName } from './tmux-naming'+import { remoteTmuxPasteArgs, remoteTmuxEnterArgs } from './remote-ssh/control-master'+import { sanitizePasteText } from './paste-injection'++const ESC = '\x1b'+const START = `${ESC}[200~`+const END = `${ESC}[201~`+/** A private socket — never `TMUX_SOCKET`/`nodeterm-rmt`, which carry live user sessions. */+const SOCKET = `nt-paste-test-${process.pid}`+const CONN = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile: '/k/id' }++function findTmux(): string | null {+ for (const c of ['/usr/bin/tmux', '/usr/local/bin/tmux', '/opt/homebrew/bin/tmux', '/bin/tmux']) {+ if (fs.existsSync(c)) return c+ }+ return null+}+const TMUX = findTmux()++let work: string+let binDir: string++/**+ * The socket file lives in the test's OWN dir: `kill-server` does not unlink it, so a per-pid name+ * under the shared `/tmp/tmux-<uid>/` would leave one stale entry behind per run, forever.+ */+function env(): NodeJS.ProcessEnv {+ return { ...process.env, TMUX_TMPDIR: work }+}++function tmux(args: string[], input?: string): string {+ return execFileSync(TMUX as string, args, { encoding: 'utf8', env: env(), input })+}++/**+ * `tmux`, ignoring the exit status — for the CONTROL cases, which are about what reached the+ * application, not about what tmux told its client. (A tmux server shared by several clients+ * hands a failing command's error to whichever client is listening, so an exit code here is not+ * a property of the command that produced it.)+ */+function tryTmux(args: string[], input?: string): void {+ try {+ tmux(args, input)+ } catch {+ // the bytes are the witness+ }+}++beforeAll(() => {+ if (!TMUX) return+ work = fs.mkdtempSync(path.join(os.tmpdir(), 'ntpb-'))+ binDir = path.join(work, 'bin')+ fs.mkdirSync(binDir)+ // The SSH path's shim. `remoteTmuxPasteArgs` hard-codes `-L nodeterm-rmt`, which on a real host+ // is the socket a remote nodeterm owns; here the first two arguments are dropped and the real+ // tmux is re-invoked on the test's private socket. `exec` keeps stdin, which is the whole point+ // of the path being tested.+ fs.writeFileSync(+ path.join(binDir, 'tmux'),+ `#!/bin/sh\nexport TMUX_TMPDIR=${work}\nshift 2\nexec ${TMUX} -L ${SOCKET} "$@"\n`,+ { mode: 0o755 }+ )+ // A pane program that records the RAW bytes its stdin receives. `stty raw` matters: in cooked+ // mode the line discipline rewrites CR to NL on input, which would hide exactly the `\n` vs+ // `\r` distinction this file is about.+ fs.writeFileSync(+ path.join(binDir, 'recorder'),+ [+ '#!/bin/sh',+ 'stty raw -echo',+ // $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 }+ )+})++afterAll(() => {+ if (TMUX) {+ try {+ tmux(['-L', SOCKET, 'kill-server'])+ } catch {+ // already gone+ }+ }+ if (work) fs.rmSync(work, { recursive: true, force: true })+})++function waitFor(predicate: () => boolean, what: string, ms = 10_000): void {+ const deadline = Date.now() + ms+ while (!predicate()) {+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`)+ execFileSync('sleep', ['0.03'])+ }+}++/** A fresh single-pane session running the byte recorder. Returns the file it writes to. */+function recorderPane(session: string, kind: 'aware' | 'unaware'): string {+ const out = path.join(work, `${session}.bytes`)+ try {+ execFileSync(TMUX as string, ['-L', SOCKET, 'kill-session', '-t', `=${session}`], {+ stdio: 'ignore',+ env: env()+ })+ } catch {+ // no such session yet+ }+ tmux([+ '-L',+ SOCKET,+ 'new-session',+ '-d',+ '-s',+ session,+ '-x',+ '200',+ '-y',+ '40',+ '-c',+ work,+ `${binDir}/recorder ${out} ${kind}`+ ])+ waitFor(() => fs.existsSync(`${out}.ready`), `${session} recorder to come up`)+ return out+}++/**+ * Everything sent before this call has reached the application.+ *+ * A sentinel, not a sleep, and deliberately delivered by a DIFFERENT mechanism than the subject+ * (a plain literal `send-keys`): if the subject delivered nothing at all, the marker still shows+ * up and the assertion sees an empty payload rather than hanging.+ */+const MARK = '<<NTEND>>'+function drain(session: string, out: string): string {+ tmux(['-L', SOCKET, 'send-keys', '-t', session, '-l', '--', MARK])+ waitFor(() => fs.readFileSync(out, 'utf8').includes(MARK), `${session} to receive the marker`)+ const all = fs.readFileSync(out, 'utf8')+ return all.slice(0, all.lastIndexOf(MARK))+}++/**+ * The delivery under test, exactly as `PtyManager.sendText` performs it — including the one thing+ * that stays OURS: `sanitizePasteText`, applied to the payload before it enters the buffer. tmux+ * inserting the frame does not make a payload-supplied `ESC[201~` harmless.+ */+function send(pathName: 'local' | 'ssh', session: string, text: string, enter = true): void {+ const body = sanitizePasteText(text)+ const buffer = pasteBufferName()+ if (pathName === 'local') {+ tmux(localTmuxPasteArgs(SOCKET, session, buffer, enter), body)+ return+ }+ const cmd = remoteTmuxPasteArgs(CONN, '/s.sock', session, buffer, enter).slice(-1)[0]+ execFileSync('/bin/sh', ['-c', cmd], {+ env: { PATH: `${binDir}:/usr/bin:/bin`, HOME: work },+ input: body,+ encoding: 'utf8'+ })+}++const suite = TMUX ? describe : describe.skip+const PATHS: Array<'local' | 'ssh'> = ['local', 'ssh']++suite('REAL tmux: the version floor is real, and paste-buffer -p removes it', () => {+ it('MEASURED: `#{bracket_paste_flag}` is EMPTY on this tmux even for a pane that DID request it', () => {+ // This is the whole bug in one assertion. The app below announces DECSET 2004; the format the+ // deleted probe read still comes back '' (it first shipped in tmux 3.7), and '' !== '1', so+ // the old code concluded "not paste-aware" and mangled the write.+ const out = recorderPane('nt-floor', 'aware')+ expect(fs.existsSync(`${out}.ready`)).toBe(true)+ const flag = tmux(['-L', SOCKET, 'display-message', '-p', '-t', 'nt-floor', '#{bracket_paste_flag}'])+ const version = tmux(['-V']).trim()+ if (/tmux (3\.[7-9]|[4-9]\.)/.test(version)) {+ // On a host that DOES have 3.7+, the old probe would have worked — the point of the fix is+ // that we no longer care either way, so assert the new path instead of the floor.+ expect(flag.trim()).toBe('1')+ } else {+ expect(flag.trim(), `${version} should not know #{bracket_paste_flag}`).toBe('')+ }+ // …and the new delivery frames it regardless of what that format said.+ send('local', 'nt-floor', 'a\nb')+ expect(drain('nt-floor', out)).toBe(`${START}a\nb${END}\r`)+ })++ it('CONTROL: the pre-fix delivery mangles the very same write into raw newlines', () => {+ // The legacy two-step, reproduced: `send-keys -l --` then `send-keys Enter`, which is what the+ // shipped code ran once the probe above answered ''. If this ever stops producing unframed+ // newlines, the test above is not measuring a fix.+ const out = recorderPane('nt-legacy', 'aware')+ tmux(['-L', SOCKET, 'send-keys', '-t', 'nt-legacy', '-l', '--', 'a\nb'])+ tmux(['-L', SOCKET, 'send-keys', '-t', 'nt-legacy', 'Enter'])+ expect(drain('nt-legacy', out)).toBe('a\nb\r')+ })+})++suite('REAL tmux: tmux decides the framing from the pane, on both paths', () => {+ for (const p of PATHS) {+ it(`${p}: a pane whose app REQUESTED bracketed paste gets a framed multi-line write`, () => {+ const out = recorderPane(`nt-aw-${p}`, 'aware')+ send(p, `nt-aw-${p}`, 'line1\nline2\nline3')+ expect(drain(`nt-aw-${p}`, out)).toBe(`${START}line1\nline2\nline3${END}\r`)+ })++ it(`${p}: a pane whose app did NOT request it gets the legacy bytes, unframed and unchanged`, () => {+ // Not a regression to guard against — a deliberate non-change. An app that never asked for+ // bracketed paste must keep receiving exactly what it received before this PR.+ const out = recorderPane(`nt-un-${p}`, 'unaware')+ send(p, `nt-un-${p}`, 'line1\nline2\nline3')+ expect(drain(`nt-un-${p}`, out)).toBe('line1\nline2\nline3\r')+ })++ it(`${p}: enter:false (dictation insert) sends the frame and NO submit`, () => {+ const out = recorderPane(`nt-ne-${p}`, 'aware')+ send(p, `nt-ne-${p}`, 'draft me', false)+ expect(drain(`nt-ne-${p}`, out)).toBe(`${START}draft me${END}`)+ })++ it(`${p}: an empty payload with enter still submits (and never silently drops the Enter)`, () => {+ // `load-buffer -` given zero bytes creates NO buffer, so a naive implementation's+ // `paste-buffer` fails and tmux abandons the rest of the command list — Enter included.+ const out = recorderPane(`nt-mt-${p}`, 'aware')+ if (p === 'local') {+ tmux(['-L', SOCKET, 'send-keys', '-t', `nt-mt-${p}`, 'Enter'])+ } else {+ const cmd = remoteTmuxEnterArgs(CONN, '/s.sock', `nt-mt-${p}`).slice(-1)[0]+ execFileSync('/bin/sh', ['-c', cmd], { env: { PATH: `${binDir}:/usr/bin:/bin` } })+ }+ expect(drain(`nt-mt-${p}`, out)).toBe('\r')+ })+ }++ it('CONTROL: the naive empty-payload delivery loses the Enter entirely', () => {+ const out = recorderPane('nt-mt-ctl', 'aware')+ const buffer = pasteBufferName()+ // Same argv the non-empty case uses, but with nothing on stdin.+ try {+ tmux(localTmuxPasteArgs(SOCKET, 'nt-mt-ctl', buffer, true), '')+ } catch {+ // tmux reports "no buffer …" — the point is what did NOT reach the pane+ }+ expect(drain('nt-mt-ctl', out), 'the empty-payload special case is no longer needed').toBe('')+ })++ it('the two paths are byte-identical for the same payload', () => {+ const a = recorderPane('nt-par-l', 'aware')+ const b = recorderPane('nt-par-s', 'aware')+ const text = "mixed 'quotes' $HOME `id` #hash;\nsecond line\tand a tab"+ send('local', 'nt-par-l', text)+ send('ssh', 'nt-par-s', text)+ expect(drain('nt-par-s', b)).toBe(drain('nt-par-l', a))+ })++ it('a pane in a session that is NOT the current one, with no client attached, is framed too', () => {+ // The everyday shape: nodeterm's tmux server holds one session per node, nothing is attached,+ // and the write is aimed at a session that is not the server's most-recent one. Nothing in the+ // delivery may depend on the target being "current" — the deleted `#{bracket_paste_flag}`+ // probe and the paste both resolve their own target, and only one of them is still ours.+ const out = recorderPane('nt-other', 'aware')+ const decoy = recorderPane('nt-decoy', 'aware') // created last ⇒ tmux's current session+ send('local', 'nt-other', 'x\ny')+ expect(drain('nt-other', out)).toBe(`${START}x\ny${END}\r`)+ expect(fs.readFileSync(decoy, 'utf8'), 'the write leaked into the current session').toBe('')+ })+})++suite('REAL tmux: copy mode', () => {+ for (const p of PATHS) {+ it(`${p}: a pane the user scrolled back in still receives a FRAMED write, and the submit`, () => {+ const out = recorderPane(`nt-cm-${p}`, 'aware')+ tmux(['-L', SOCKET, 'copy-mode', '-t', `nt-cm-${p}`])+ expect(tmux(['-L', SOCKET, 'display-message', '-p', '-t', `nt-cm-${p}`, '#{pane_in_mode}']).trim()).toBe('1')+ send(p, `nt-cm-${p}`, 'a\nb')+ expect(drain(`nt-cm-${p}`, out)).toBe(`${START}a\nb${END}\r`)+ // The user-visible cost, asserted rather than described: they are back at the live view.+ expect(tmux(['-L', SOCKET, 'display-message', '-p', '-t', `nt-cm-${p}`, '#{pane_in_mode}']).trim()).toBe('0')+ })+ }++ it('CONTROL: without the gated cancel, copy mode unframes the paste', () => {+ // Why the cancel is in the command list at all. `paste-buffer -p` consults the copy-mode+ // SCREEN, not the application, so a wheel scroll silently restores the one-turn-per-line bug.+ const out = recorderPane('nt-cm-ctl', 'aware')+ tmux(['-L', SOCKET, 'copy-mode', '-t', 'nt-cm-ctl'])+ expect(tmux(['-L', SOCKET, 'display-message', '-p', '-t', 'nt-cm-ctl', '#{pane_in_mode}']).trim()).toBe('1')+ const buffer = pasteBufferName()+ tmux(+ ['-L', SOCKET, 'load-buffer', '-b', buffer, '-', ';', 'paste-buffer', '-d', '-p', '-r', '-b', buffer, '-t', 'nt-cm-ctl', ';', 'send-keys', '-t', 'nt-cm-ctl', 'Enter'],+ 'a\nb'+ )+ // The Enter never reached the app either: in copy mode it is `copy-selection-and-cancel`,+ // which is also why the pane is out of copy mode again by now.+ expect(drain('nt-cm-ctl', out), 'copy mode no longer unframes — the if-shell gate is dead weight').toBe('a\nb')+ })++ it('CONTROL: an UNGATED cancel breaks every ordinary write — which is why `if-shell -F` gates it', () => {+ // Measured: `send-keys -X cancel` against a pane not in a mode exits 1 and tmux ABANDONS the+ // rest of the command list. Prepending it unconditionally would have replaced a mangle with a+ // total failure.+ const out = recorderPane('nt-nc-ctl', 'aware')+ const buffer = pasteBufferName()+ expect(() =>+ tmux(+ ['-L', SOCKET, 'send-keys', '-t', 'nt-nc-ctl', '-X', 'cancel', ';', 'load-buffer', '-b', buffer, '-', ';', 'paste-buffer', '-d', '-p', '-r', '-b', buffer, '-t', 'nt-nc-ctl'],+ 'a\nb'+ )+ ).toThrow()+ expect(drain('nt-nc-ctl', out)).toBe('')+ })++ it('CONTROL: today, a write into a scrolled-back pane delivers NO TEXT — at best nothing, at worst a bare submit', () => {+ // The honest baseline for the user-visible cost above: cancelling copy mode is not a+ // regression against a working behaviour, it replaces a silent drop of the whole payload.+ // The copy-mode key table eats the literal send; what happens to the trailing Enter depends+ // on whether the payload's own `\n` already cancelled the mode, so the ROBUST property — and+ // the alarming one — is that the text never lands while a bare Enter still can, i.e. the+ // delivery can submit whatever the human had composed and type none of the payload.+ // Exit status is deliberately not asserted: a tmux server shared by several clients hands a+ // failing command's error to whichever client is listening (observed in this very file), so+ // the bytes are the only reliable witness. Measured in an isolated shell, both sends exit 0+ // and `sendText` therefore returns TRUE.+ const out = recorderPane('nt-cm-legacy', 'aware')+ tmux(['-L', SOCKET, 'copy-mode', '-t', 'nt-cm-legacy'])+ expect(tmux(['-L', SOCKET, 'display-message', '-p', '-t', 'nt-cm-legacy', '#{pane_in_mode}']).trim()).toBe('1')+ tryTmux(['-L', SOCKET, 'send-keys', '-t', 'nt-cm-legacy', '-l', '--', 'a\nb'])+ tryTmux(['-L', SOCKET, 'send-keys', '-t', 'nt-cm-legacy', 'Enter'])+ tryTmux(['-L', SOCKET, 'send-keys', '-t', 'nt-cm-legacy', '-X', 'cancel'])+ const got = drain('nt-cm-legacy', out)+ expect(got, 'the legacy path now reaches a scrolled-back pane').not.toMatch(/[ab]/)+ expect(got.replace(/\r/g, '')).toBe('')+ })+})++suite('REAL tmux: the payload does not ride a command line', () => {+ const BIG = 'A'.repeat(300_000)++ it('CONTROL: the same payload as ONE argument is "Argument list too long"', () => {+ // MAX_ARG_STRLEN is 128 KB per argument, far below `getconf ARG_MAX`. This is why the text+ // goes over stdin and not through `set-buffer --`.+ expect(() => tmux(['-L', SOCKET, 'set-buffer', '-b', 'nt-argmax', '--', BIG])).toThrow(+ /too long|E2BIG|ENAMETOOLONG/i+ )+ })++ for (const p of PATHS) {+ it(`${p}: 300 KB over stdin arrives complete and framed`, () => {+ const out = recorderPane(`nt-big-${p}`, 'aware')+ send(p, `nt-big-${p}`, BIG, false)+ const got = drain(`nt-big-${p}`, out)+ expect(got.length).toBe(BIG.length + START.length + END.length)+ expect(got.startsWith(START) && got.endsWith(END)).toBe(true)+ })+ }+})++suite("REAL tmux: the delivery does not disturb the user's own tmux state", () => {+ it("leaves the numbered buffer stack untouched and deletes its own private buffer", () => {+ const out = recorderPane('nt-buf', 'aware')+ tmux(['-L', SOCKET, 'set-buffer', 'USER-A'])+ tmux(['-L', SOCKET, 'set-buffer', 'USER-B'])+ const before = tmux(['-L', SOCKET, 'list-buffers'])+ send('local', 'nt-buf', 'hello')+ drain('nt-buf', out)+ expect(tmux(['-L', SOCKET, 'list-buffers'])).toBe(before)+ })++ it('two concurrent deliveries do not swap payloads (the buffer name is per-call)', () => {+ // tmux interleaves command lists from different clients, so a shared buffer name is a real+ // race: the second `load-buffer` overwrites the first before its `paste-buffer` runs.+ const a = recorderPane('nt-race-a', 'aware')+ const b = recorderPane('nt-race-b', 'aware')+ const ba = pasteBufferName()+ const bb = pasteBufferName()+ expect(ba).not.toBe(bb)+ tmux(['-L', SOCKET, 'load-buffer', '-b', ba, '-'], 'AAA')+ tmux(['-L', SOCKET, 'load-buffer', '-b', bb, '-'], 'BBB')+ tmux(['-L', SOCKET, 'paste-buffer', '-d', '-p', '-r', '-b', ba, '-t', 'nt-race-a'])+ tmux(['-L', SOCKET, 'paste-buffer', '-d', '-p', '-r', '-b', bb, '-t', 'nt-race-b'])+ expect(drain('nt-race-a', a)).toBe(`${START}AAA${END}`)+ expect(drain('nt-race-b', b)).toBe(`${START}BBB${END}`)+ })++ it('CONTROL: with ONE shared buffer name the same interleaving crosses the payloads', () => {+ const a = recorderPane('nt-race2-a', 'aware')+ const b = recorderPane('nt-race2-b', 'aware')+ const shared = pasteBufferName()+ tmux(['-L', SOCKET, 'load-buffer', '-b', shared, '-'], 'AAA')+ tmux(['-L', SOCKET, 'load-buffer', '-b', shared, '-'], 'BBB')+ tmux(['-L', SOCKET, 'paste-buffer', '-p', '-r', '-b', shared, '-t', 'nt-race2-a'])+ tmux(['-L', SOCKET, 'paste-buffer', '-d', '-p', '-r', '-b', shared, '-t', 'nt-race2-b'])+ expect(drain('nt-race2-a', a), 'a shared buffer name is no longer a race').toBe(`${START}BBB${END}`)+ expect(drain('nt-race2-b', b)).toBe(`${START}BBB${END}`)+ })+})++suite('REAL tmux: -r is what keeps a newline a newline', () => {+ it('CONTROL: without -r, tmux rewrites every \\n to \\r — one submit per line, the bug itself', () => {+ const out = recorderPane('nt-nor', 'aware')+ const buffer = pasteBufferName()+ tmux(['-L', SOCKET, 'load-buffer', '-b', buffer, '-', ';', 'paste-buffer', '-d', '-p', '-b', buffer, '-t', 'nt-nor'], 'a\nb')+ expect(drain('nt-nor', out)).toBe(`${START}a\rb${END}`)+ })+})++// ── SECURITY: a real bash, a real readline, and a filesystem verdict ────────────────────────────+//+// The frame is a promise to somebody else's parser that everything between the markers is CONTENT.+// tmux inserting the markers changes who writes them, not that promise — a payload carrying+// `ESC[201~` would still close the frame early and turn its tail into KEY INPUT. `sanitizePasteText`+// is untouched by this PR and this is where that is proven for the new delivery.+function bashPane(session: string): string {+ const marker = path.join(work, `${session}-ready`)+ try {+ execFileSync(TMUX as string, ['-L', SOCKET, 'kill-session', '-t', `=${session}`], {+ stdio: 'ignore',+ env: env()+ })+ } catch {+ // none yet+ }+ tmux([+ '-L',+ SOCKET,+ 'new-session',+ '-d',+ '-s',+ session,+ '-x',+ '200',+ '-y',+ '40',+ '-e',+ 'HISTFILE=/dev/null',+ '-c',+ work,+ 'bash --norc --noprofile -i'+ ])+ waitFor(() => tmux(['-L', SOCKET, 'capture-pane', '-p', '-t', session]).trim().length > 0, 'bash prompt')+ return marker+}++/** ctrl-c, then a sentinel command: once its file exists, everything queued before it has run. */+function bashDrain(session: string, tag: string): void {+ const sentinel = path.join(work, `sent-${tag}`)+ tmux(['-L', SOCKET, 'send-keys', '-t', session, 'C-c'])+ tmux(['-L', SOCKET, 'send-keys', '-t', session, '-l', '--', `touch ${sentinel}`])+ tmux(['-L', SOCKET, 'send-keys', '-t', session, 'Enter'])+ waitFor(() => fs.existsSync(sentinel), `bash to reach the ${tag} sentinel`)+}++suite('REAL bash through REAL tmux: the payload cannot become key input', () => {+ for (const p of PATHS) {+ it(`${p}: a payload closing the frame early does NOT execute its tail`, () => {+ bashPane(`nt-sec-${p}`)+ const m = path.join(work, `pwn-${p}`)+ send(p, `nt-sec-${p}`, `hello${END}\rtouch ${m}\r`, false)+ bashDrain(`nt-sec-${p}`, `nt-sec-${p}`)+ expect(fs.existsSync(m), 'the payload ESCAPED the frame and ran').toBe(false)+ // and the text still arrived as content: ESC has no glyph, its printable tail survives+ expect(tmux(['-L', SOCKET, 'capture-pane', '-p', '-t', `nt-sec-${p}`])).toContain('hello[201~')+ })++ it(`${p}: an early close plus ctrl-u does not wipe the line and run a command`, () => {+ bashPane(`nt-sec2-${p}`)+ const m = path.join(work, `pwn2-${p}`)+ send(p, `nt-sec2-${p}`, `SAFE${END}\x15touch ${m} #`, true)+ bashDrain(`nt-sec2-${p}`, `nt-sec2-${p}`)+ expect(fs.existsSync(m), 'ctrl-u was read as a KEY').toBe(false)+ })+ }++ it('CONTROL: the same attack DOES run when the payload is not sanitized', () => {+ // Run, not described. If this stops creating the marker the two tests above prove nothing.+ bashPane('nt-sec-ctl')+ const m = path.join(work, 'pwn-ctl')+ const buffer = pasteBufferName()+ tmux(localTmuxPasteArgs(SOCKET, 'nt-sec-ctl', buffer, false), `hello${END}\rtouch ${m}\r`)+ bashDrain('nt-sec-ctl', 'nt-sec-ctl')+ expect(fs.existsSync(m), 'the attack no longer works — these tests are vacuous').toBe(true)+ })+})++suite('the unquoted splices are asserted, not assumed', () => {+ it('refuses a target that this app did not generate (it is spliced into a tmux command string)', () => {+ for (const bad of ['nt-x; kill-server', 'nt-x y', "nt-x'", '#{pane_id}', '', 'other-session']) {+ expect(() => localTmuxPasteArgs('s', bad, pasteBufferName(), true)).toThrow(/unsafe tmux paste target/)+ expect(() => remoteTmuxPasteArgs(CONN, '/s.sock', bad, pasteBufferName(), true)).toThrow(+ /unsafe tmux paste target/+ )+ }+ })+ it('refuses a buffer name that is not one of ours', () => {+ expect(() => localTmuxPasteArgs('s', 'nt-x', 'buffer0', true)).toThrow(/unsafe tmux buffer name/)+ expect(() => localTmuxPasteArgs('s', 'nt-x', 'nt-paste-a b', true)).toThrow(/unsafe tmux buffer name/)+ })+ it('accepts every name `sessionName` can produce', () => {+ expect(() => localTmuxPasteArgs('s', 'nt-term-mabc-3', pasteBufferName(), true)).not.toThrow()+ })+})