Skip to content

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

fix(pty): a local send-keys payload can no longer be read as tmux FLAGS

Claude Code628f8c950489
diff --git a/src/core/local-send-keys.realtmux.test.ts b/src/core/local-send-keys.realtmux.test.ts
new file mode 100644
index 000000000..588827acc
--- /dev/null
+++ b/src/core/local-send-keys.realtmux.test.ts
@@ -0,0 +1,161 @@
+// 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.
+// `-R`, `-K`, `-l` and `--` are all accepted flags that exit 0, so the delivery reported success,
+// typed nothing at all — and then sent its Enter anyway, submitting whatever the human had already
+// composed in that pane.
+//
+// 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.
+//
+// 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
+// is the witness for what the Enter did.
+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 { localTmuxSendKeysArgs, localTmuxEnterArgs } 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'
+
+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
+
+/** `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' })
+}
+
+/** Type `body` into the probe pane the way the HARNESS does it — always safely quoted. */
+function compose(body: string): void {
+ tmux(['-L', SOCKET, 'send-keys', '-t', SESSION, '-l', '--', body])
+}
+
+/**
+ * Wait for bash to have consumed everything sent so far.
+ *
+ * A sentinel, not a sleep: bash reads its input strictly in order, so once the sentinel's file
+ * exists, every keystroke queued before it has already been acted on.
+ */
+function drain(tag: string): void {
+ const sentinel = path.join(work, `sentinel-${tag}`)
+ compose(`touch ${sentinel}`)
+ tmux(['-L', SOCKET, 'send-keys', '-t', SESSION, 'Enter'])
+ const deadline = Date.now() + 10_000
+ while (!fs.existsSync(sentinel)) {
+ if (Date.now() > deadline) throw new Error(`bash never reached the sentinel for ${tag}`)
+ execFileSync('sleep', ['0.05'])
+ }
+}
+
+function freshPane(): void {
+ try {
+ // Quiet: on the first run there is no server yet and tmux says so on stderr.
+ execFileSync(TMUX as string, ['-L', SOCKET, 'kill-session', '-t', SESSION], { stdio: 'ignore' })
+ } catch {
+ // no session yet
+ }
+ tmux([
+ '-L',
+ SOCKET,
+ 'new-session',
+ '-d',
+ '-s',
+ SESSION,
+ '-x',
+ '200',
+ '-y',
+ '40',
+ '-e',
+ 'HISTFILE=/dev/null',
+ '-c',
+ work,
+ 'bash --norc --noprofile -i'
+ ])
+ // Ready = bash has painted SOMETHING (its prompt). Not a fixed string: `--norc` bash keeps its
+ // own default PS1 whatever the environment says, and the prompt's text is not what this proves.
+ const deadline = Date.now() + 10_000
+ for (;;) {
+ const pane = tmux(['-L', SOCKET, 'capture-pane', '-p', '-t', SESSION]).trim()
+ if (pane.length > 0) return
+ if (Date.now() > deadline) throw new Error('bash prompt never appeared')
+ execFileSync('sleep', ['0.05'])
+ }
+}
+
+beforeAll(() => {
+ if (!TMUX) return
+ work = fs.mkdtempSync(path.join(os.tmpdir(), 'ntsendkeys-'))
+})
+
+afterAll(() => {
+ if (TMUX) {
+ try {
+ tmux(['-L', SOCKET, 'kill-server'])
+ } catch {
+ // already gone
+ }
+ }
+ if (work) fs.rmSync(work, { recursive: true, force: true })
+})
+
+const suite = TMUX ? describe : describe.skip
+
+suite('REAL tmux: a payload starting with `-` is text, never a flag', () => {
+ it('a `-R` payload lands in the pane as characters instead of resetting it', () => {
+ freshPane()
+ const danger = path.join(work, 'danger')
+ // 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))
+ drain('minus-r')
+ expect(
+ fs.existsSync(danger),
+ "the write typed NOTHING and its Enter submitted the human's composed line"
+ ).toBe(false)
+ // …and the payload really did arrive, appended to what was composed.
+ expect(fs.existsSync(`${danger}-R`), 'the payload never reached the pane').toBe(true)
+ })
+
+ it('control: WITHOUT `--` tmux eats the payload as a flag, exits 0, and the Enter still fires', () => {
+ // The mutation check, run rather than described — this is the shipped argv with `--` removed.
+ // If this ever stops firing the composed line, the test above proves nothing.
+ freshPane()
+ const danger = path.join(work, 'danger-control')
+ compose(`touch ${danger}`)
+ const before = ['-L', SOCKET, 'send-keys', '-t', SESSION, '-l', '-R']
+ // Exit 0: the caller (`sendText`) is told the text was delivered.
+ expect(() => tmux(before)).not.toThrow()
+ tmux(localTmuxEnterArgs(SOCKET, SESSION))
+ drain('control')
+ expect(fs.existsSync(danger), 'the pre-fix argv no longer submits the composed line').toBe(true)
+ expect(fs.existsSync(`${danger}-R`)).toBe(false)
+ })
+
+ it('a framed body (which starts with ESC, not `-`) is unaffected either way', () => {
+ 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))
+ drain('framed')
+ expect(fs.existsSync(ok)).toBe(true)
+ })
+})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 2fe805c4f..124082c5a 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -42,7 +42,13 @@ import {
} from './pty-devices'
import { REAP_SWEEP_MS, shouldReap } from './pty-reap'
import { ControlModeClient, type ControlSpawn } from './tmux-control-client'
-import { TMUX_SOCKET, sessionName, isSessionName } from './tmux-naming'
+import {
+ TMUX_SOCKET,
+ sessionName,
+ isSessionName,
+ localTmuxSendKeysArgs,
+ localTmuxEnterArgs
+} from './tmux-naming'
import { encodeSendKeysHex } from './tmux-control'
import { bracketedInjection, sanitizePasteText } from './paste-injection'
import { releasePty, type ReleasablePty } from './pty-release'
@@ -2809,32 +2815,24 @@ export class PtyManager {
// 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, [
- '-L',
- TMUX_SOCKET,
- 'send-keys',
- '-t',
- target,
- '-l',
- bracketedInjection(text, enter)
- ])
+ await runAsync(
+ this.tmuxPath,
+ localTmuxSendKeysArgs(TMUX_SOCKET, target, bracketedInjection(text, enter))
+ )
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`).
- await runAsync(this.tmuxPath, [
- '-L',
- TMUX_SOCKET,
- 'send-keys',
- '-t',
- target,
- '-l',
- sanitizePasteText(text)
- ])
+ //
+ // `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, ['-L', TMUX_SOCKET, 'send-keys', '-t', target, 'Enter'])
+ await runAsync(this.tmuxPath, localTmuxEnterArgs(TMUX_SOCKET, target))
}
return true
} catch {
diff --git a/src/core/tmux-naming.test.ts b/src/core/tmux-naming.test.ts
new file mode 100644
index 000000000..e30771189
--- /dev/null
+++ b/src/core/tmux-naming.test.ts
@@ -0,0 +1,50 @@
+import { describe, it, expect } from 'vitest'
+import {
+ localTmuxSendKeysArgs,
+ localTmuxEnterArgs,
+ sessionName,
+ isSessionName,
+ TMUX_SOCKET
+} from './tmux-naming'
+
+describe('sessionName / isSessionName', () => {
+ it('round-trips a plain node id', () => {
+ expect(isSessionName(sessionName('abc-123'))).toBe(true)
+ })
+ it('refuses a target that did not come from sessionName', () => {
+ expect(isSessionName('nt-a b')).toBe(false)
+ expect(isSessionName('other')).toBe(false)
+ })
+})
+
+/**
+ * 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', () => {
+ for (const body of ['-R', '-K', '--', '-l', '-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', () => {
+ expect(localTmuxEnterArgs('sock', 'nt-x')).toEqual([
+ '-L',
+ 'sock',
+ 'send-keys',
+ '-t',
+ 'nt-x',
+ 'Enter'
+ ])
+ })
+})
diff --git a/src/core/tmux-naming.ts b/src/core/tmux-naming.ts
index 527f54ea4..bbe004d04 100644
--- a/src/core/tmux-naming.ts
+++ b/src/core/tmux-naming.ts
@@ -22,3 +22,35 @@ export function sessionName(persistKey: string): string {
export function isSessionName(target: string): boolean {
return /^nt-[A-Za-z0-9_-]+$/.test(target)
}
+
+/**
+ * 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 several of them exit
+ * 0: `-R` (reset terminal state), `-K`, `-l`, `--`. The delivery then reported SUCCESS having
+ * typed nothing — 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.
+ *
+ * `--` 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.
+ */
+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.)
+ */
+export function localTmuxEnterArgs(socket: string, target: string): string[] {
+ return ['-L', socket, 'send-keys', '-t', target, 'Enter']
+}