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(session-host): frame an injected prompt from the pane's own paste state

enes466a9b8d20bf
diff --git a/CLAUDE.md b/CLAUDE.md
index 71feec2a4..774bb5ab1 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -889,6 +889,20 @@ pane running `sleep 30`. It never toggled across pane switches, window switches,
co-attach. A constant is not a signal — so `term.modes.bracketedPasteMode` cannot stand in for the
pane's state, however tempting the symmetry with `mouseTrackingMode` looks.
+**That paragraph is about a tmux CLIENT, and the SESSION HOST is the opposite case** (issue #686).
+On Windows there is no tmux, so nothing sits between the pane's app and the host's headless
+emulator: a `?2004h` it sees was written by the app itself, which is exactly the fact
+`paste-buffer -p` asks tmux for. `HostSession.bracketedPasteRequested()` reads it (behind
+`outputTail`, like `serialize` — xterm applies writes asynchronously, so an early read answers "no"
+for the turn that just enabled it) and `sendKeysWrites` (`session-host/send-keys-delivery.ts`)
+mirrors the tmux plan: `sanitizePasteText` ALWAYS, the frame only when the app asked, and the Enter
+as its own write AFTER the close marker — never inside the framed burst, which is the shape #453
+measured as mangled. Unframed it stays one write, byte-identical to the pre-fix path. Before this
+the host answered `sendKeys` with a single raw `text + '\r'`, so an injected prompt landed in a
+paste-aware composer (Codex, Claude) and was never submitted. **NOT verified on a device**: whether
+ConPTY re-emits an app's `?2004h` into the pty stream the host reads. If it does not, the mode is
+always false and every write is the old one — no fix, never a regression.
+
**The actual fix is older than the problem: `paste-buffer -p`.** From tmux's own man page — *"If
`-p` is specified, paste bracket control codes are inserted around the buffer **if the application
has requested bracketed paste mode**."* Introduced 2012-03-03, shipped in **tmux 1.7**, so it is
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index f414ff8e3..68c45ac66 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -167,6 +167,17 @@ lane unaffected.
on POSIX a backslash is legal filename text — do not treat both separators as interchangeable
unless the owning filesystem is known to be Windows.
+- **Anything tmux does for us on POSIX, the session host owes on Windows.** The two delivery paths
+ are not symmetric and the missing half fails in the direction that LOOKS like success: `sendText`
+ rides `tmux paste-buffer -p` on POSIX, which frames the payload from the pane's real
+ bracketed-paste state and submits with a separate `send-keys Enter`; the session host answered the
+ same call with one raw `text + '\r'`, so a paste-aware composer swallowed the Enter as pasted
+ content and an injected prompt sat there unsubmitted (issue #686). Before adding a delivery, a
+ probe or a pane query, check what the tmux leg does with it and write the host's equivalent in the
+ same change. The host can usually answer more precisely than tmux, because its headless emulator
+ sees the pane app's own bytes — see CLAUDE.md's "We have our own VT emulator" for the one place
+ that reasoning is inverted.
+
- **Normalize BOTH sides of a path comparison, through one function.** A marker normalized where
it is built and matched raw where it is used is a no-op on the machine you wrote it on and a
silent defect on Windows. That is issue #558: the managed-hook marker was folded to `/` while
diff --git a/src/session-host/host.ts b/src/session-host/host.ts
index da262ce20..6c0d89c4d 100644
--- a/src/session-host/host.ts
+++ b/src/session-host/host.ts
@@ -30,6 +30,7 @@ import {
type ListSessionsResult
} from './protocol'
import { HostSession } from './session'
+import { sendKeysWrites } from './send-keys-delivery'
import { paneCommand as readPaneCommand } from './process-tree'
import { terminateWindowsProcessTree } from './windows-process-tree'
import { publishSessionHostState } from './state-file'
@@ -804,7 +805,13 @@ async function main(): Promise<void> {
case 'sendKeys': {
const s = sessions.get(req.name)
if (!s || s.exited) return { ok: false, error: 'no such session' }
- s.proc.write(req.text + (req.enter ? '\r' : ''))
+ // Framed from the pane's REAL bracketed-paste state, with the Enter as its own write —
+ // the session host's equivalent of tmux's `paste-buffer -p` + `send-keys Enter`. See
+ // send-keys-delivery.ts; the mode read crosses the emulator tail, so re-check liveness
+ // after it rather than writing into a session that exited meanwhile.
+ const bracketed = await s.bracketedPasteRequested()
+ if (s.exited || sessions.get(req.name) !== s) return { ok: false, error: 'no such session' }
+ for (const chunk of sendKeysWrites(req.text, req.enter, bracketed)) s.proc.write(chunk)
return { ok: true }
}
case 'paneCommand': {
diff --git a/src/session-host/send-keys-delivery.test.ts b/src/session-host/send-keys-delivery.test.ts
new file mode 100644
index 000000000..124c26d4a
--- /dev/null
+++ b/src/session-host/send-keys-delivery.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it } from 'vitest'
+import { sendKeysWrites } from './send-keys-delivery'
+import { TerminalEmulator } from './terminal-emulator'
+import { PASTE_END, PASTE_START } from '../core/paste-injection'
+
+describe('sendKeysWrites', () => {
+ it('keeps the legacy single write when the app never requested bracketed paste', () => {
+ // Byte-identical to the pre-#686 `text + (enter ? '\r' : '')`, so a plain shell sees no change.
+ expect(sendKeysWrites('npm test', true, false)).toEqual(['npm test\r'])
+ expect(sendKeysWrites('npm test', false, false)).toEqual(['npm test'])
+ })
+
+ it('frames the payload and submits with a SEPARATE write when the app asked for paste', () => {
+ // The separation is the fix: an Enter inside the framed burst is what a paste-aware composer
+ // absorbs as pasted content (#686), leaving the prompt sitting there unsubmitted.
+ expect(sendKeysWrites('review this', true, true)).toEqual([
+ `${PASTE_START}review this${PASTE_END}`,
+ '\r'
+ ])
+ })
+
+ it('frames without submitting when enter is false', () => {
+ // `settled-envelope.ts` pastes with enter:false and submits separately; dictation never submits.
+ expect(sendKeysWrites('half a thought', false, true)).toEqual([
+ `${PASTE_START}half a thought${PASTE_END}`
+ ])
+ })
+
+ it('sends a bare Enter for an empty payload, framed or not', () => {
+ // `sendText('', { enter: true })` means "submit whatever is composed" — it must not become an
+ // empty paste frame, which some composers insert as a literal marker pair.
+ expect(sendKeysWrites('', true, true)).toEqual(['\r'])
+ expect(sendKeysWrites('', true, false)).toEqual(['\r'])
+ expect(sendKeysWrites('', false, true)).toEqual([])
+ })
+
+ it('strips ESC from the payload on BOTH paths, so it can never become structure', () => {
+ // A payload-supplied close marker would end the frame early and turn its tail into KEY INPUT;
+ // the unframed path is sanitized too so the contract does not depend on the receiver's mode.
+ const hostile = `ok${PASTE_END} rm -rf /`
+
+ const unframed = sendKeysWrites(hostile, false, false).join('')
+ expect(unframed).not.toContain('\x1b')
+ // Not lossy: every printable character survives, the way real terminals treat pasted text.
+ expect(unframed).toBe('ok[201~ rm -rf /')
+
+ const framed = sendKeysWrites(hostile, false, true).join('')
+ // The only ESC bytes are OUR two markers — the payload cannot express paste structure.
+ expect(framed.split('\x1b')).toHaveLength(3)
+ expect(framed).toBe(`${PASTE_START}ok[201~ rm -rf /${PASTE_END}`)
+ })
+
+ it('preserves multiline payloads as paste content', () => {
+ expect(sendKeysWrites('line one\nline two', true, true)).toEqual([
+ `${PASTE_START}line one\nline two${PASTE_END}`,
+ '\r'
+ ])
+ })
+})
+
+describe('TerminalEmulator.bracketedPasteRequested', () => {
+ // The whole decision above rests on this being observable from the session's own output. Read
+ // from a real emulator rather than assumed: this is the fact `paste-buffer -p` asks tmux for.
+ const emulator = (): TerminalEmulator =>
+ new TerminalEmulator({ cols: 80, rows: 24, scrollback: 100 })
+
+ it('is false for a session whose app never asked', async () => {
+ const t = emulator()
+ await t.write('$ ')
+ expect(t.bracketedPasteRequested()).toBe(false)
+ t.dispose()
+ })
+
+ it('turns on for CSI ?2004h and off again for ?2004l', async () => {
+ const t = emulator()
+ await t.write('\x1b[?2004h')
+ expect(t.bracketedPasteRequested()).toBe(true)
+ await t.write('\x1b[?2004l')
+ expect(t.bracketedPasteRequested()).toBe(false)
+ t.dispose()
+ })
+})
diff --git a/src/session-host/send-keys-delivery.ts b/src/session-host/send-keys-delivery.ts
new file mode 100644
index 000000000..63e5a58fe
--- /dev/null
+++ b/src/session-host/send-keys-delivery.ts
@@ -0,0 +1,44 @@
+// What the session host actually writes into a pty for one `sendKeys` request — the Windows
+// equivalent of `localPasteDelivery`'s tmux plan (`src/core/tmux-naming.ts`).
+//
+// WHY THIS EXISTS (#686). The host used to answer `sendKeys` with a single raw write,
+// `text + (enter ? '\r' : '')`. That is the exact shape `paste-injection.ts` opens by describing
+// as the bug: an unmarked burst with the Enter guaranteed to be INSIDE it. A composer that treats
+// a rapid unmarked burst as a paste absorbs the trailing Enter as pasted content, so an injected
+// prompt (context link, agent message, canvas-control `write`) lands in the composer and is never
+// submitted. On Windows there is no tmux, so this is the only delivery path and nothing did what
+// `paste-buffer -p` does on POSIX.
+//
+// The shape mirrors the tmux plan exactly, because that shape is the measured-correct one:
+//
+// - The payload is `sanitizePasteText`'d ALWAYS, framed or not, so `sendText`'s contract does not
+// depend on what the receiver requested. A payload carrying its own `ESC[201~` would otherwise
+// close the frame early and turn its tail into KEY INPUT — and the canvas-control `write` verb
+// hands an AGENT's text to this same path.
+// - The frame is written only when the app REQUESTED bracketed paste. Writing markers at an app
+// that never asked puts literal `[200~` in its input.
+// - The Enter is its OWN write, after the close marker — not appended inside the framed burst.
+// This is where the tmux leg moved after #453: a paste-aware composer cannot re-chunk a key
+// event that arrives after a definitive close marker, while the "Enter inside the same write"
+// shape the older comment described is the one that was mangled. Unframed, the Enter stays
+// inside the single write, which is byte-identical to what this path did before.
+// - An empty payload with `enter` is a bare Enter — `sendText('', { enter: true })` is a live
+// call meaning "submit whatever is composed" (`Canvas.tsx`'s write verb, `settled-envelope.ts`).
+//
+// NOT VERIFIED ON A DEVICE: whether ConPTY re-emits an app's `CSI ?2004h` into the pty output
+// stream this host's emulator reads. If it does not, `bracketed` is always false and every write
+// here is byte-identical to the pre-#686 behaviour — the failure mode is "no fix", never a
+// regression.
+import { PASTE_END, PASTE_START, sanitizePasteText } from '../core/paste-injection'
+
+/**
+ * The writes, in order, for one `sendKeys` request. Each element is one `pty.write` — the split
+ * is the point, not an implementation detail.
+ */
+export function sendKeysWrites(text: string, enter: boolean, bracketed: boolean): string[] {
+ const body = sanitizePasteText(text)
+ if (body.length === 0) return enter ? ['\r'] : []
+ if (!bracketed) return [body + (enter ? '\r' : '')]
+ const framed = PASTE_START + body + PASTE_END
+ return enter ? [framed, '\r'] : [framed]
+}
diff --git a/src/session-host/send-keys-host.test.ts b/src/session-host/send-keys-host.test.ts
new file mode 100644
index 000000000..983fe957d
--- /dev/null
+++ b/src/session-host/send-keys-host.test.ts
@@ -0,0 +1,237 @@
+// The wiring test for #686: it drives the REAL bundled host over its real socket protocol and
+// reads the bytes a fake node-pty received. `send-keys-delivery.test.ts` pins what the plan says;
+// this pins that `sendKeys` still runs it. Without one of these two, deleting the call (or the
+// framing inside it) leaves a green suite and an injected prompt that never submits again.
+import { afterEach, describe, expect, it } from 'vitest'
+import { spawn, type ChildProcess } from 'child_process'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
+import net, { type Socket } from 'net'
+import os from 'os'
+import path from 'path'
+import { build, type Plugin } from 'esbuild'
+import {
+ LineFramer,
+ encodeFrame,
+ type SessionHostFrame,
+ type SessionHostResponse,
+ type SessionHostSpawnOptions
+} from './protocol'
+import { sessionHostPaths, type SessionHostState } from './paths'
+import { PASTE_END, PASTE_START } from '../core/paste-injection'
+
+/**
+ * A node-pty stand-in that logs every write to a file (the host runs in its own process, so a
+ * spy object cannot be shared) and replays a canned output stream — `CSI ?2004h` for the
+ * bracketed-paste case, i.e. what an agent TUI's composer does when it starts.
+ */
+function fakePtyPlugin(): Plugin {
+ return {
+ name: 'session-host-send-keys-fake-pty',
+ setup(bundle) {
+ bundle.onResolve({ filter: /^node-pty$/ }, () => ({
+ path: 'node-pty',
+ namespace: 'send-keys'
+ }))
+ bundle.onLoad({ filter: /^node-pty$/, namespace: 'send-keys' }, () => ({
+ loader: 'js',
+ contents: `
+ const fs = require('fs')
+ export function spawn() {
+ let onExit
+ const log = process.env.NT_TEST_WRITE_LOG
+ const announce = process.env.NT_TEST_PTY_OUTPUT
+ return {
+ pid: 4242,
+ onData(cb) {
+ // Repeated so the announcement cannot be lost to the host registering late; a
+ // DECSET is idempotent, and every repeat crosses the same emulator tail.
+ if (announce) for (let i = 1; i <= 5; i++) setTimeout(() => cb(announce), i * 20)
+ },
+ onExit(cb) { onExit = cb },
+ write(data) { fs.appendFileSync(log, JSON.stringify(data) + '\\n') },
+ resize() {},
+ pause() {},
+ resume() {},
+ kill() { setTimeout(() => onExit?.({ exitCode: 0 }), 20) }
+ }
+ }
+ `
+ }))
+ }
+ }
+}
+
+async function waitForIdentity(dataDir: string): Promise<{ state: SessionHostState; token: string }> {
+ const paths = sessionHostPaths(dataDir)
+ for (let attempt = 0; attempt < 200; attempt++) {
+ try {
+ const state = JSON.parse(readFileSync(paths.statePath, 'utf8')) as SessionHostState
+ const token = readFileSync(paths.tokenPath, 'utf8').trim()
+ if (state.endpoint && token) return { state, token }
+ } catch {
+ /* publication is asynchronous by design; keep polling within the test bound */
+ }
+ await new Promise((resolve) => setTimeout(resolve, 20))
+ }
+ throw new Error('session host did not publish its identity')
+}
+
+function connectFrames(endpoint: string): Promise<{
+ socket: Socket
+ response(id: number): Promise<SessionHostResponse>
+}> {
+ return new Promise((resolve, reject) => {
+ const socket = net.connect(endpoint)
+ const framer = new LineFramer()
+ const received = new Map<number, SessionHostResponse>()
+ const waiters = new Map<number, (frame: SessionHostResponse) => void>()
+ socket.on('data', (chunk: Buffer) => {
+ for (const frame of framer.push<SessionHostFrame>(chunk.toString('utf8'))) {
+ if (!('id' in frame)) continue
+ const waiter = waiters.get(frame.id)
+ if (waiter) {
+ waiters.delete(frame.id)
+ waiter(frame)
+ } else {
+ received.set(frame.id, frame)
+ }
+ }
+ })
+ socket.once('error', reject)
+ socket.once('connect', () =>
+ resolve({
+ socket,
+ response: (id) => {
+ const frame = received.get(id)
+ if (frame) {
+ received.delete(id)
+ return Promise.resolve(frame)
+ }
+ return new Promise<SessionHostResponse>((resolveResponse, rejectResponse) => {
+ const timer = setTimeout(
+ () => rejectResponse(new Error(`timed out waiting for response ${id}`)),
+ 4_000
+ )
+ waiters.set(id, (next) => {
+ clearTimeout(timer)
+ resolveResponse(next)
+ })
+ })
+ }
+ })
+ )
+ })
+}
+
+function waitForExit(child: ChildProcess): Promise<void> {
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve()
+ return new Promise((resolve) => child.once('exit', () => resolve()))
+}
+
+const SPAWN_OPTIONS: SessionHostSpawnOptions = {
+ cwd: '.',
+ shell: 'fake-shell',
+ args: [],
+ env: {},
+ cols: 80,
+ rows: 24
+}
+
+const cleanupPaths: string[] = []
+afterEach(() => {
+ for (const target of cleanupPaths.splice(0)) {
+ rmSync(target, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 })
+ }
+})
+
+/** Boot the real bundled host against the fake pty and return the writes one sendKeys produced. */
+async function writesForSendKeys(opts: {
+ announce?: string
+ text: string
+ enter: boolean
+ /** Poll `capture` until the serialized screen proves this mode reached the emulator. */
+ awaitMode?: string
+}): Promise<string[]> {
+ const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'nt-session-host-send-keys-'))
+ cleanupPaths.push(fixtureDir)
+ const dataDir = path.join(fixtureDir, 'user-data')
+ mkdirSync(dataDir)
+ const paths = sessionHostPaths(dataDir)
+ if (process.platform !== 'win32') cleanupPaths.push(paths.endpoint)
+ const writeLog = path.join(fixtureDir, 'writes.log')
+ writeFileSync(writeLog, '')
+ const bundlePath = path.join(fixtureDir, 'host.cjs')
+ await build({
+ absWorkingDir: process.cwd(),
+ entryPoints: ['src/session-host/host.ts'],
+ outfile: bundlePath,
+ bundle: true,
+ platform: 'node',
+ format: 'cjs',
+ plugins: [fakePtyPlugin()],
+ logLevel: 'silent'
+ })
+ const child = spawn(process.execPath, [bundlePath, dataDir], {
+ cwd: process.cwd(),
+ stdio: 'ignore',
+ windowsHide: true,
+ env: { ...process.env, NT_TEST_WRITE_LOG: writeLog, NT_TEST_PTY_OUTPUT: opts.announce ?? '' }
+ })
+ let socket: Socket | null = null
+ try {
+ const { state, token } = await waitForIdentity(dataDir)
+ const connected = await connectFrames(state.endpoint)
+ socket = connected.socket
+ socket.write(encodeFrame({ id: 0, cmd: 'hello', token }))
+ await expect(connected.response(0)).resolves.toMatchObject({ id: 0, ok: true })
+ socket.write(
+ encodeFrame({ id: 1, cmd: 'attach', name: 'keys', spawn: SPAWN_OPTIONS, scrollback: 100 })
+ )
+ await expect(connected.response(1)).resolves.toMatchObject({ id: 1, ok: true })
+
+ if (opts.awaitMode) {
+ // `serialize()` restores DEC private modes, so the captured screen is the observable proof
+ // that the announcement crossed the emulator tail — no sleep-and-hope.
+ let seen = false
+ for (let attempt = 2; attempt < 60 && !seen; attempt++) {
+ socket.write(encodeFrame({ id: attempt, cmd: 'capture', name: 'keys', full: true }))
+ const frame = (await connected.response(attempt)) as { result?: { text?: string } }
+ seen = (frame.result?.text ?? '').includes(opts.awaitMode)
+ if (!seen) await new Promise((resolve) => setTimeout(resolve, 25))
+ }
+ expect(seen).toBe(true)
+ }
+
+ socket.write(
+ encodeFrame({ id: 900, cmd: 'sendKeys', name: 'keys', text: opts.text, enter: opts.enter })
+ )
+ await expect(connected.response(900)).resolves.toMatchObject({ id: 900, ok: true })
+ return readFileSync(writeLog, 'utf8')
+ .split('\n')
+ .filter(Boolean)
+ .map((line) => JSON.parse(line) as string)
+ } finally {
+ socket?.destroy()
+ child.kill()
+ await waitForExit(child)
+ }
+}
+
+describe('session-host sendKeys delivery', () => {
+ it('frames the payload and sends Enter separately once the pane asked for bracketed paste', async () => {
+ // The #686 failure: with the Enter inside an unmarked burst, a paste-aware composer (Codex,
+ // Claude) keeps the whole thing as pasted content and the prompt is never submitted.
+ const writes = await writesForSendKeys({
+ announce: '\x1b[?2004h',
+ awaitMode: '\x1b[?2004h',
+ text: 'summarise the linked context',
+ enter: true
+ })
+ expect(writes).toEqual([`${PASTE_START}summarise the linked context${PASTE_END}`, '\r'])
+ }, 30_000)
+
+ it('leaves a pane that never asked byte-identical to the pre-fix single write', async () => {
+ const writes = await writesForSendKeys({ text: 'npm test', enter: true })
+ expect(writes).toEqual(['npm test\r'])
+ }, 30_000)
+})
diff --git a/src/session-host/session.ts b/src/session-host/session.ts
index f4a35d954..493de4b5e 100644
--- a/src/session-host/session.ts
+++ b/src/session-host/session.ts
@@ -265,6 +265,17 @@ export class HostSession {
return this.term.serialize(scrollback)
}
+ /**
+ * Has the app in this pane requested bracketed paste? Behind `outputTail` for the same reason
+ * `serialize` is: xterm applies writes asynchronously, so a mode set by output we have already
+ * observed is not in `modes` yet. Reading it early answers "no" for the turn that just enabled
+ * it — which is exactly the injected-prompt delivery this gates (see send-keys-delivery.ts).
+ */
+ async bracketedPasteRequested(): Promise<boolean> {
+ await this.outputTail
+ return this.term.bracketedPasteRequested()
+ }
+
/** Stage an attach's explicit flow state and per-socket geometry before the warm screen barrier.
* The returned commit is the only operation that activates live delivery. */
async prepareAttachment(
diff --git a/src/session-host/terminal-emulator.ts b/src/session-host/terminal-emulator.ts
index bceb5c521..3f777e253 100644
--- a/src/session-host/terminal-emulator.ts
+++ b/src/session-host/terminal-emulator.ts
@@ -74,6 +74,24 @@ export class TerminalEmulator {
return out
}
+ /**
+ * Has the app running in this session REQUESTED bracketed paste (`CSI ?2004h`)?
+ *
+ * This is the session host's answer to the question `paste-buffer -p` asks tmux's pane state,
+ * and it is answerable here for a reason the tmux side cannot claim: the emulator is fed the
+ * session's OWN pty output, so a `?2004h` it saw was written by the app in the pane. (The
+ * tombstone in `pty-manager.ts` for `bracketPasteRequested` and CLAUDE.md's "the emulator is
+ * NOT the answer here" both concern a RENDERER xterm attached as a tmux CLIENT, where the mode
+ * it observes is tmux's own paste-through on the outer terminal and reads true for every pane.
+ * No tmux sits between this emulator and the pane's app.)
+ *
+ * Read through `HostSession.bracketedPasteRequested()`, never directly: emulator writes are
+ * queued, so the answer is only current behind `outputTail`.
+ */
+ bracketedPasteRequested(): boolean {
+ return this.term.modes.bracketedPasteMode
+ }
+
dispose(): void {
try {
this.serializer.dispose()