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): sweep the buffer on a failed paste, and test the real composition
enes2ccf93694c30
diff --git a/src/core/agents/agent-message.ts b/src/core/agents/agent-message.tsindex 9cad218e3..92d19a273 100644--- a/src/core/agents/agent-message.ts+++ b/src/core/agents/agent-message.ts@@ -93,7 +93,11 @@ export interface DeliveryRequest {export interface DeliveryDeps {/** Kernel truth about the target's pane. Unbounded by contract — this module bounds it. */paneOwner(nodeId: string): Promise<PaneOwner | null>- /** tmux's `#{bracket_paste_flag}` for the target's pane. */+ /**+ * Did the target's pane request bracketed paste? UNIMPLEMENTED — nothing wires this yet, and+ * `PtyManager.bracketPasteRequested` (which read `#{bracket_paste_flag}`, a tmux-3.7+ format) was+ * deleted when `sendText` stopped needing to ask. See the long note at the refusal that uses it.+ */bracketPasteRequested(nodeId: string): Promise<boolean>/** ONE write: the framed text and the Enter together. Resolves false when the pane is gone. */sendFramed(nodeId: string, payload: string): Promise<boolean>@@ -360,27 +364,27 @@ export async function deliverAgentMessage(// herdr :260 — a multi-line envelope on the UNFRAMED fallback would be submitted line by line// as separate turns. It is refused, never sent and hoped for.//- // ── ROLLOUT BLOCKER, MEASURED — DO NOT SHIP THE VERBS WITHOUT READING THIS ──────────────────+ // ── THE ROLLOUT BLOCKER THAT USED TO BE HERE IS GONE; THIS PROBE IS NOW THE ONLY ONE LEFT ───//- // `PtyManager.bracketPasteRequested` reads tmux's `#{bracket_paste_flag}`, and that format- // FIRST SHIPPED IN TMUX 3.7 (2026-06-26). On every earlier tmux the name is unknown and expands- // to the empty string, which compares unequal to '1' — so the probe answers false for every- // pane and this refusal fires for every delivery. Measured here on tmux 3.4: the format is- // absent from the binary's format table and from the man page's FORMATS list, and behaves- // exactly like a bogus name.+ // It used to read: `PtyManager.bracketPasteRequested` reads `#{bracket_paste_flag}`, a format+ // that FIRST SHIPPED IN TMUX 3.7, so on Ubuntu 24.04 (3.4), 22.04 (3.2a), Debian 12/13+ // (3.3a/3.5a), Ubuntu 26.04 (3.6a), every SSH target and the Server Edition it expanded to ''+ // and this refusal fired for every delivery — messaging inert on most Linux hosts.//- // Who that is: Ubuntu 24.04 LTS ships 3.4, Ubuntu 22.04 → 3.2a, Debian 12 → 3.3a, Debian 13 →- // 3.5a, Ubuntu 26.04 → 3.6a. Plus EVERY SSH target (the REMOTE host's tmux decides) and the- // Server Edition. The bundled 3.7b does not rescue it: `extraResources` places it under "mac"- // only, and `bundledTmuxPath` is deliberately the LAST candidate after the system one.+ // That method no longer exists. `sendText` stopped asking whether to frame and hands the+ // payload to `tmux paste-buffer -p`, which consults the pane's real bracketed-paste state+ // inside tmux and has done since tmux 1.7 (2012). There is no version floor on the DELIVERY.//- // The refusal is the correct fail direction — sending a multi-line envelope unframed is herdr- // :260, which is worse. But it means messaging is INERT on most Linux hosts, and PR 5 owes:- // a three-way probe ('1' = aware, '0' = genuinely unaware, '' or error = FORMAT UNSUPPORTED), a- // distinct outcome carrying `tmux -V` and the fix, and an explicit decision on whether the- // feature ships to Linux and SSH at all without either a Linux tmux bundle or a single-line- // envelope fallback. `targetNotPasteAware` cannot carry that today: it says the pane did not- // ask, when the truth is that we could not ask.+ // WHAT IS STILL OWED HERE, and why this is not simply deleted: this gate is not the delivery,+ // it is a REFUSAL — messaging declines to send a multi-line envelope into a pane that would+ // submit it line by line (herdr :260). Answering that still needs to know whether the target+ // asked for bracketed paste, and `DeliveryDeps.bracketPasteRequested` is still declared with+ // no implementation wired anywhere. Whoever wires it inherits the same three-way problem the+ // old note described ('1' = aware, '0' = genuinely unaware, '' or error = CANNOT ASK), because+ // `targetNotPasteAware` says "the pane did not ask" when the truth may be "we could not ask".+ // The cheap way out now exists and did not before: this module could stop probing and instead+ // let the same `paste-buffer -p` delivery carry the envelope, since tmux frames it correctly+ // or not at all — but that is a decision for the PR that ships the verbs, not this one.if (!(await deps.bracketPasteRequested(req.targetNodeId)))return refuse({ kind: 'targetNotPasteAware' })diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 9ab30d35a..3da510954 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -26,8 +26,7 @@ import {localKillSockets,localTmuxKillArgs,remoteTmuxPtyArgs,- remoteTmuxPasteArgs,- remoteTmuxEnterArgs,+ remotePasteDelivery,remoteCapturePaneArgs,remotePaneCommandArgs,remotePaneOwnerArgs,@@ -51,12 +50,10 @@ import {TMUX_SOCKET,sessionName,isSessionName,- localTmuxPasteArgs,- localTmuxEnterArgs,- pasteBufferName+ localPasteDelivery,+ runPasteDelivery} from './tmux-naming'import { encodeSendKeysHex } from './tmux-control'-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'@@ -2835,47 +2832,39 @@ export class PtyManager {* 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.+ * ── WHY THIS METHOD IS ONLY A DISPATCHER ───────────────────────────────────────────────────────*- * 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.+ * Everything decided per write — `sanitizePasteText`, the empty-body case, the per-call buffer+ * name, and the buffer sweep when the paste fails — lives in `localPasteDelivery` /+ * `remotePasteDelivery` / `runPasteDelivery`, which a real-tmux test drives DIRECTLY.+ *+ * That is a correction, not a preference. The first version of this change inlined those+ * decisions here and let the test rebuild them in its own helper. Both sides were green and two+ * mutations survived a full run: deleting the empty-body branch, and deleting the sanitize call.+ * A test that re-implements what it is testing cannot notice the original being removed. So the+ * composition is exported, both callers use it, and the only thing left in this method is which+ * transport runs it.*/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)?.sshRemote- if (sshRemote) {- const ssh = findSsh()- if (!ssh) return false- try {- 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- }- }- if (!this.tmuxPath) return falsetry {- if (body.length === 0) {- if (enter) await runAsync(this.tmuxPath, localTmuxEnterArgs(TMUX_SOCKET, target))- return true+ if (sshRemote) {+ const ssh = findSsh()+ if (!ssh) return false+ const plan = remotePasteDelivery(sshRemote.conn, sshRemote.controlPath, target, text, enter)+ if (!plan) return true+ return await runPasteDelivery(plan, (args, input) => runWithStdin(ssh, args, input))}- await runWithStdin(this.tmuxPath, localTmuxPasteArgs(TMUX_SOCKET, target, buffer, enter), body)- return true+ if (!this.tmuxPath) return false+ const tmuxPath = this.tmuxPath+ const plan = localPasteDelivery(TMUX_SOCKET, target, text, enter)+ if (!plan) return true+ return await runPasteDelivery(plan, (args, input) => runWithStdin(tmuxPath, args, input))} catch {+ // Only a builder throwing (an unsafe target) reaches here — `runPasteDelivery` answers false+ // rather than throwing, precisely so the sweep cannot be skipped by an early exit.return false}}diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.tsindex f508fc91c..d7699c181 100644--- a/src/core/remote-ssh/control-master.ts+++ b/src/core/remote-ssh/control-master.ts@@ -4,7 +4,14 @@ import os from 'os'import path from 'path'import { createHash } from 'crypto'import { posixQuote, quoteRemotePath, remoteTmuxCommand, type SshConnection } from '../../shared/ssh'-import { TMUX_SOCKET, assertPasteTarget } from '../tmux-naming'+import {+ TMUX_SOCKET,+ assertPasteTarget,+ assertPasteBuffer,+ pasteBufferName,+ type PasteDelivery+} from '../tmux-naming'+import { sanitizePasteText } from '../paste-injection'import { canControlCanvas } from '../../shared/agents/config'import { PANE_OWNER_FMT, foregroundArgvArgs } from '../agents/pane-owner'// Dependency-free (no node-pty): safe to import from these pure builders.@@ -267,14 +274,57 @@ export function remoteTmuxPasteArgs(* 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.+ *+ * `sessionId` is spliced unquoted like every sibling, and — as of review — asserted like every+ * sibling. It was the one new builder in this change that opted out. Unreachable today, because+ * `sessionName()` sanitises to `[A-Za-z0-9_-]` before anything gets here, but a splice that is+ * safe only because some caller upstream happens to be strict is one refactor from an injection,+ * and this PR's own rule is that the guarantee lives at the splice.*/export function remoteTmuxEnterArgs(conn: SshConnection,controlPath: string,sessionId: string): string[] {+ assertPasteTarget(sessionId)return childArgs(conn, controlPath, `tmux -L ${RMT_TMUX_SOCKET} send-keys -t ${sessionId} Enter`)}++/** `delete-buffer` on the REMOTE server — the sweep for a remote paste that never ran. */+export function remoteDeleteBufferArgs(+ conn: SshConnection,+ controlPath: string,+ buffer: string+): string[] {+ assertPasteBuffer(buffer)+ return childArgs(conn, controlPath, `tmux -L ${RMT_TMUX_SOCKET} delete-buffer -b ${buffer}`)+}++/**+ * The plan for a REMOTE delivery — the exact mirror of `localPasteDelivery`, and deliberately the+ * same three decisions (sanitize, empty body, per-call buffer) taken by calling the SAME code+ * rather than by writing them out again here. Drift between the two legs is how the ESC rule+ * survived being missing on one of them once already.+ */+export function remotePasteDelivery(+ conn: SshConnection,+ controlPath: string,+ sessionId: string,+ text: string,+ enter: boolean+): PasteDelivery | null {+ const body = sanitizePasteText(text)+ if (body.length === 0) {+ if (!enter) return null+ return { args: remoteTmuxEnterArgs(conn, controlPath, sessionId), body: '', cleanup: null }+ }+ const buffer = pasteBufferName()+ return {+ args: remoteTmuxPasteArgs(conn, controlPath, sessionId, buffer, enter),+ body,+ cleanup: remoteDeleteBufferArgs(conn, controlPath, buffer)+ }+}/*** 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 deaddiff --git a/src/core/tmux-naming.ts b/src/core/tmux-naming.tsindex 376f0f931..58ac892cf 100644--- a/src/core/tmux-naming.ts+++ b/src/core/tmux-naming.ts@@ -1,6 +1,7 @@// 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'+import { sanitizePasteText } from './paste-injection'export const TMUX_SOCKET = 'node-terminal'@@ -47,8 +48,13 @@ export function isSessionName(target: string): boolean {* 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.+ *+ * Asserts its target like every other builder in this delivery, even though this one quotes+ * nothing: the rule is "every splice is checked at the splice", and the two builders that had no+ * buffer of their own were the two that quietly opted out of it.*/export function localTmuxEnterArgs(socket: string, target: string): string[] {+ assertPasteTarget(target)return ['-L', socket, 'send-keys', '-t', target, 'Enter']}@@ -176,8 +182,110 @@ export function localTmuxPasteArgs(* 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 {+export function assertPasteTarget(target: string, buffer?: string): void {if (!isSessionName(target)) throw new Error(`unsafe tmux paste target: ${JSON.stringify(target)}`)+ if (buffer !== undefined) assertPasteBuffer(buffer)+}++/** The buffer half on its own, for the one builder that has a buffer and no pane target. */+export function assertPasteBuffer(buffer: string): void {if (!/^nt-paste-[a-z0-9-]+$/.test(buffer))throw new Error(`unsafe tmux buffer name: ${JSON.stringify(buffer)}`)}++/** `delete-buffer` for a delivery whose paste never ran. See `runPasteDelivery`. */+export function localTmuxDeleteBufferArgs(socket: string, buffer: string): string[] {+ assertPasteBuffer(buffer)+ return ['-L', socket, 'delete-buffer', '-b', buffer]+}++/**+ * ── EVERYTHING `sendText` DECIDES, IN ONE TESTED PLACE ──────────────────────────────────────────+ *+ * A plan is what to run, what to put on its stdin, and how to clean up if it fails. `sendText` is+ * a two-line dispatcher over this; a test drives THIS, not a copy of it.+ *+ * That split is not decoration. The first version of this change left the composition — sanitize,+ * empty-body, buffer name — inlined in `sendText`, and the real-tmux test rebuilt the same three+ * steps in its own helper before calling the argv builder. Both halves were green, and TWO+ * mutations survived a full suite run: deleting the empty-body branch, and deleting+ * `sanitizePasteText` at the caller. A test that re-implements the thing it tests cannot see the+ * thing it tests being deleted. It is a weakening against the version this replaces, where the+ * sanitize was structural inside `bracketedInjection`; now it is structural here instead.+ */+export interface PasteDelivery {+ /** argv for the delivery process (tmux locally, ssh remotely). */+ args: string[]+ /** what goes on its stdin — the payload, or '' when there is none. */+ body: string+ /**+ * argv that removes the private buffer this delivery created, or null when it created none.+ *+ * MEASURED LEAK, and the reason this field exists: `load-buffer` succeeds, then `paste-buffer`+ * fails (a node closed while the write was in flight — "can't find pane"), tmux abandons the+ * rest of the command list, and the `-d` that would have dropped the buffer never runs. The+ * payload then sits in the tmux server's buffer stack, which is USER-VISIBLE (`prefix-=`,+ * `list-buffers`, a phone attaching), for as long as the server lives — days, on a host with+ * dozens of sessions. `buffer-limit` does not save it: named buffers are not reaped (measured —+ * 60 named buffers under `buffer-limit 50`, all 60 survived). The payload can be a note push or+ * a 300 KB scrollback paste. Same story on the remote `nodeterm-rmt` server.+ */+ cleanup: string[] | null+}++/**+ * The plan for a LOCAL delivery, or null when there is nothing to run at all.+ *+ * Three decisions live here and nowhere else:+ * - `sanitizePasteText`, so no payload byte can express paste structure. tmux writing the markers+ * does not change that: a payload-supplied `ESC[201~` would still close the frame early and+ * turn its tail into KEY INPUT.+ * - the EMPTY body. `load-buffer -` given zero bytes creates no buffer, so the `paste-buffer`+ * after it fails and tmux abandons the list — the Enter with it. `sendText('', { enter: true })`+ * is a live call (`Canvas.tsx`'s write verb, `args.text ?? ''`) and means "submit whatever is+ * composed", which is what the legacy two-step did, so it becomes a bare Enter.+ * - a per-call buffer name, so two concurrent deliveries cannot overwrite each other's payload.+ */+export function localPasteDelivery(+ socket: string,+ target: string,+ text: string,+ enter: boolean+): PasteDelivery | null {+ const body = sanitizePasteText(text)+ if (body.length === 0) {+ if (!enter) return null+ return { args: localTmuxEnterArgs(socket, target), body: '', cleanup: null }+ }+ const buffer = pasteBufferName()+ return {+ args: localTmuxPasteArgs(socket, target, buffer, enter),+ body,+ cleanup: localTmuxDeleteBufferArgs(socket, buffer)+ }+}++/**+ * Run a plan. The runner is injected so this is the same code in production and under a real tmux.+ *+ * The sweep is fire-and-forget: the delivery has already failed, the caller is already on its+ * error path, and awaiting a second call would double the worst-case stall (a dead ControlMaster+ * takes the full `PROC_TIMEOUT_MS` to fail, twice). Its own failure is ignored — `delete-buffer`+ * against a buffer `-d` already dropped is an expected error, not a problem.+ */+export async function runPasteDelivery(+ plan: PasteDelivery,+ run: (args: string[], input: string) => Promise<unknown>+): Promise<boolean> {+ try {+ await run(plan.args, plan.body)+ return true+ } catch {+ if (plan.cleanup) {+ void Promise.resolve(run(plan.cleanup as string[], '')).catch(() => {+ // best effort: the buffer outliving one failed write is bad, throwing here is worse+ })+ }+ return false+ }+}diff --git a/src/core/tmux-paste.realtmux.test.ts b/src/core/tmux-paste.realtmux.test.tsindex 4d4f7a92c..6ee472045 100644--- a/src/core/tmux-paste.realtmux.test.ts+++ b/src/core/tmux-paste.realtmux.test.ts@@ -18,14 +18,19 @@// 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 { describe, it, expect, beforeAll, beforeEach, 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'+import {+ localPasteDelivery,+ localTmuxPasteArgs,+ pasteBufferName,+ runPasteDelivery,+ type PasteDelivery+} from './tmux-naming'+import { remotePasteDelivery } from './remote-ssh/control-master'const ESC = '\x1b'const START = `${ESC}[200~`@@ -58,10 +63,9 @@ function tmux(args: string[], input?: string): string {}/**- * `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.)+ * `tmux`, ignoring the exit status — for the CONTROL cases and the buffer scrubbing, which are+ * about what reached the application (or what is left in the server), not about what tmux told+ * its client. Where a control's exit status IS the point, the test asserts it explicitly.*/function tryTmux(args: string[], input?: string): void {try {@@ -167,30 +171,66 @@ function drain(session: string, out: string): string {}/**- * 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.+ * ── THE DELIVERY UNDER TEST IS THE PRODUCTION ONE, NOT A COPY OF IT ─────────────────────────────+ *+ * `PtyManager.sendText` is a dispatcher over `localPasteDelivery` / `remotePasteDelivery` ++ * `runPasteDelivery`, and so is this. That is the whole point: an earlier revision of this file+ * re-implemented the composition here — it called `sanitizePasteText` and `pasteBufferName`+ * itself and then invoked the argv builder — and two mutations survived a green suite as a+ * result (deleting the empty-body branch, and deleting the sanitize call). A test that rebuilds+ * the thing it tests cannot see the thing it tests being deleted.+ *+ * Only the RUNNER differs per leg, which is exactly the part `sendText` also supplies: a local+ * plan's argv goes to the tmux binary; a remote plan's argv is an `ssh` command line whose last+ * element is the remote command, so it goes through a real /bin/sh with the shim on PATH. Both+ * carry the payload on stdin.*/-function send(pathName: 'local' | 'ssh', session: string, text: string, enter = true): void {- const body = sanitizePasteText(text)- const buffer = pasteBufferName()+function runnerFor(pathName: 'local' | 'ssh'): (args: string[], input: string) => Promise<unknown> {if (pathName === 'local') {- tmux(localTmuxPasteArgs(SOCKET, session, buffer, enter), body)- return+ return async (args, input) => tmux(args, input)}- 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'- })+ return async (args, input) =>+ execFileSync('/bin/sh', ['-c', args[args.length - 1]], {+ env: { PATH: `${binDir}:/usr/bin:/bin`, HOME: work },+ input,+ encoding: 'utf8'+ })+}++function planFor(+ pathName: 'local' | 'ssh',+ session: string,+ text: string,+ enter: boolean+): PasteDelivery | null {+ return pathName === 'local'+ ? localPasteDelivery(SOCKET, session, text, enter)+ : remotePasteDelivery(CONN, '/s.sock', session, text, enter)+}++/** Exactly `sendText`'s body for one leg: plan, then run. Returns what `sendText` would return. */+async function send(+ pathName: 'local' | 'ssh',+ session: string,+ text: string,+ enter = true+): Promise<boolean> {+ const plan = planFor(pathName, session, text, enter)+ if (!plan) return true+ return runPasteDelivery(plan, runnerFor(pathName))+}++/** Every buffer the tmux server is holding, by name. */+function bufferNames(): string[] {+ const out = tmux(['-L', SOCKET, 'list-buffers', '-F', '#{buffer_name}']).trim()+ return out.length === 0 ? [] : out.split('\n')}const suite = TMUX ? describe : describe.skipconst 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', () => {+ it('MEASURED: `#{bracket_paste_flag}` is EMPTY on this tmux even for a pane that DID request it', async () => {// 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.@@ -206,11 +246,11 @@ suite('REAL tmux: the version floor is real, and paste-buffer -p removes it', ()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')+ await 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', () => {+ it('CONTROL: the pre-fix delivery mangles the very same write into raw newlines', async () => {// 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.@@ -223,41 +263,42 @@ suite('REAL tmux: the version floor is real, and paste-buffer -p removes it', ()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`, () => {+ it(`${p}: a pane whose app REQUESTED bracketed paste gets a framed multi-line write`, async () => {const out = recorderPane(`nt-aw-${p}`, 'aware')- send(p, `nt-aw-${p}`, 'line1\nline2\nline3')+ await 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`, () => {+ it(`${p}: a pane whose app did NOT request it gets the legacy bytes, unframed and unchanged`, async () => {// 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')+ await 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`, () => {+ it(`${p}: enter:false (dictation insert) sends the frame and NO submit`, async () => {const out = recorderPane(`nt-ne-${p}`, 'aware')- send(p, `nt-ne-${p}`, 'draft me', false)+ await 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.+ it(`${p}: an empty payload with enter still submits (and never silently drops the Enter)`, async () => {+ // `Canvas.tsx`'s write verb calls `sendText(node, args.text ?? '')`, so this is a live+ // caller, not a defensive branch. `load-buffer -` given zero bytes creates NO buffer, so a+ // plan that tried to paste would fail and tmux would abandon the 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(await send(p, `nt-mt-${p}`, '')).toBe(true)expect(drain(`nt-mt-${p}`, out)).toBe('\r')})++ it(`${p}: an empty payload WITHOUT enter is nothing at all — no process, no buffer`, () => {+ expect(planFor(p, 'nt-x', '', false)).toBeNull()+ expect(planFor(p, 'nt-x', '', true)).not.toBeNull()+ })}- it('CONTROL: the naive empty-payload delivery loses the Enter entirely', () => {+ it('CONTROL: the naive empty-payload delivery loses the Enter entirely', async () => {const out = recorderPane('nt-mt-ctl', 'aware')const buffer = pasteBufferName()// Same argv the non-empty case uses, but with nothing on stdin.@@ -269,23 +310,23 @@ suite('REAL tmux: tmux decides the framing from the pane, on both paths', () =>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', () => {+ it('the two paths are byte-identical for the same payload', async () => {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)+ await send('local', 'nt-par-l', text)+ await 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', () => {+ it('a pane in a session that is NOT the current one, with no client attached, is framed too', async () => {// 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')+ await 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('')})@@ -293,18 +334,18 @@ suite('REAL tmux: tmux decides the framing from the pane, on both paths', () =>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`, () => {+ it(`${p}: a pane the user scrolled back in still receives a FRAMED write, and the submit`, async () => {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')+ await 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', () => {+ it('CONTROL: without the gated cancel, copy mode unframes the paste', async () => {// 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')@@ -320,7 +361,7 @@ suite('REAL tmux: copy mode', () => {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', () => {+ it('CONTROL: an UNGATED cancel breaks every ordinary write — which is why `if-shell -F` gates it', async () => {// 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.@@ -335,17 +376,19 @@ suite('REAL tmux: copy mode', () => {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', () => {+ it('CONTROL: today, a write into a scrolled-back pane delivers NO TEXT — at best nothing, at worst a bare submit', async () => {// 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.+ //+ // Measured in isolation, 20/20 runs: both sends exit 0 and the pane receives ZERO bytes — so+ // `sendText` returns TRUE having typed nothing. Inside this file, where one tmux server+ // carries many sessions and earlier tests deliberately fail commands against it, the same+ // sequence sometimes lands a bare `\r` (the payload's own `\n` is `copy-selection-and-cancel`+ // in the copy-mode table, which changes what the keys after it do). Both outcomes are bad in+ // the same direction and the stable, assertable property covers both: the TEXT never lands,+ // while a bare submit still can — i.e. the write can submit whatever the human had composed+ // and type none of the payload. Exit status is not asserted because it is not what harms the+ // user; the bytes are.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')@@ -361,7 +404,7 @@ suite('REAL tmux: copy mode', () => {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"', () => {+ it('CONTROL: the same payload as ONE argument is "Argument list too long"', async () => {// 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(@@ -370,9 +413,9 @@ suite('REAL tmux: the payload does not ride a command line', () => {})for (const p of PATHS) {- it(`${p}: 300 KB over stdin arrives complete and framed`, () => {+ it(`${p}: 300 KB over stdin arrives complete and framed`, async () => {const out = recorderPane(`nt-big-${p}`, 'aware')- send(p, `nt-big-${p}`, BIG, false)+ await 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)@@ -381,17 +424,17 @@ suite('REAL tmux: the payload does not ride a command line', () => {})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", () => {+ it("leaves the numbered buffer stack untouched and deletes its own private buffer", async () => {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')+ await 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)', () => {+ it('two concurrent deliveries do not swap payloads (the buffer name is per-call)', async () => {// 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')@@ -407,7 +450,7 @@ suite("REAL tmux: the delivery does not disturb the user's own tmux state", () =expect(drain('nt-race-b', b)).toBe(`${START}BBB${END}`)})- it('CONTROL: with ONE shared buffer name the same interleaving crosses the payloads', () => {+ it('CONTROL: with ONE shared buffer name the same interleaving crosses the payloads', async () => {const a = recorderPane('nt-race2-a', 'aware')const b = recorderPane('nt-race2-b', 'aware')const shared = pasteBufferName()@@ -420,8 +463,63 @@ suite("REAL tmux: the delivery does not disturb the user's own tmux state", () =})})+suite('REAL tmux: a FAILED delivery leaves no payload behind in the buffer stack', () => {+ // ── THE LEAK, MEASURED ─────────────────────────────────────────────────────────────────────────+ //+ // `load-buffer` succeeds, `paste-buffer` fails ("can't find pane" — a node closed while the+ // write was in flight), tmux abandons the rest of the command list, and the `-d` that would have+ // dropped the buffer never runs. The payload then sits in the server's buffer stack, which is+ // USER-VISIBLE (`prefix-=`, `list-buffers`, a phone attaching), for as long as the server lives:+ // days, on a host with dozens of sessions. `buffer-limit` does not rescue it — named buffers are+ // not reaped. And the payload can be a note push or a 300 KB scrollback paste.+ const GONE = 'nt-nosuch-pane'++ beforeEach(() => {+ for (const b of bufferNames()) tryTmux(['-L', SOCKET, 'delete-buffer', '-b', b])+ })++ it('MEASURED: `buffer-limit` does not reap NAMED buffers, so nothing else will clean this up', () => {+ tmux(['-L', SOCKET, 'set-option', '-g', 'buffer-limit', '5'])+ try {+ for (let i = 0; i < 20; i++) tmux(['-L', SOCKET, 'load-buffer', '-b', `nt-paste-limit${i}`, '-'], 'x')+ expect(bufferNames().filter((b) => b.startsWith('nt-paste-limit'))).toHaveLength(20)+ } finally {+ tmux(['-L', SOCKET, 'set-option', '-g', 'buffer-limit', '50'])+ }+ })++ for (const p of PATHS) {+ it(`${p}: a paste that fails sweeps its own buffer`, async () => {+ expect(await send(p, GONE, 'a secret note push')).toBe(false)+ waitFor(() => bufferNames().length === 0, 'the failed delivery to sweep its buffer')+ })+ }++ it('CONTROL: without the sweep, the full payload is left in the stack', async () => {+ const plan = planFor('local', GONE, 'a secret note push', true) as PasteDelivery+ // The shipped plan with its cleanup removed — i.e. the code before this fix.+ const leaky: PasteDelivery = { args: plan.args, body: plan.body, cleanup: null }+ expect(await runPasteDelivery(leaky, runnerFor('local'))).toBe(false)+ const left = bufferNames()+ expect(left, 'the leak is gone by construction — the sweep is dead weight').toHaveLength(1)+ expect(tmux(['-L', SOCKET, 'show-buffer', '-b', left[0]])).toContain('a secret note push')+ tryTmux(['-L', SOCKET, 'delete-buffer', '-b', left[0]])+ })++ it('a SUCCESSFUL delivery needs no sweep — `-d` already dropped the buffer', async () => {+ const out = recorderPane('nt-sweep-ok', 'aware')+ expect(await send('local', 'nt-sweep-ok', 'hello')).toBe(true)+ drain('nt-sweep-ok', out)+ expect(bufferNames()).toHaveLength(0)+ })++ it('the bare-Enter plan has nothing to sweep', () => {+ for (const p of PATHS) expect(planFor(p, 'nt-x', '', true)?.cleanup).toBeNull()+ })+})+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', () => {+ it('CONTROL: without -r, tmux rewrites every \\n to \\r — one submit per line, the bug itself', async () => {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')@@ -477,26 +575,26 @@ function bashDrain(session: string, tag: string): void {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`, () => {+ it(`${p}: a payload closing the frame early does NOT execute its tail`, async () => {bashPane(`nt-sec-${p}`)const m = path.join(work, `pwn-${p}`)- send(p, `nt-sec-${p}`, `hello${END}\rtouch ${m}\r`, false)+ await 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 survivesexpect(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`, () => {+ it(`${p}: an early close plus ctrl-u does not wipe the line and run a command`, async () => {bashPane(`nt-sec2-${p}`)const m = path.join(work, `pwn2-${p}`)- send(p, `nt-sec2-${p}`, `SAFE${END}\x15touch ${m} #`, true)+ await 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', () => {+ it('CONTROL: the same attack DOES run when the payload is not sanitized', async () => {// 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')@@ -508,19 +606,25 @@ suite('REAL bash through REAL tmux: the payload cannot become key input', () =>})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)', () => {+ it('refuses a target that this app did not generate (it is spliced into a tmux command string)', async () => {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(+ expect(() => remotePasteDelivery(CONN, '/s.sock', bad, 'body', true)).toThrow(+ /unsafe tmux paste target/+ )+ expect(() => localPasteDelivery('s', bad, 'body', true)).toThrow(/unsafe tmux paste target/)+ // …including the bare-Enter plan, which was the one builder that opted out of the rule.+ expect(() => remotePasteDelivery(CONN, '/s.sock', bad, '', true)).toThrow(/unsafe tmux paste target/)+ expect(() => localPasteDelivery('s', bad, '', true)).toThrow(/unsafe tmux paste target/)}})- it('refuses a buffer name that is not one of ours', () => {+ it('refuses a buffer name that is not one of ours', async () => {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', () => {+ it('accepts every name `sessionName` can produce', async () => {expect(() => localTmuxPasteArgs('s', 'nt-term-mabc-3', pasteBufferName(), true)).not.toThrow()})})