diff --git a/CLAUDE.md b/CLAUDE.md index adb38400..e78de085 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -124,7 +124,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph ### Key Patterns -**Input**: `session.writeViaMux()` for programmatic/curl input via tmux `send-keys -l` + `send-keys Enter`, single-line only. Interactive **browser** input goes through a durable **exactly-once** layer: a stable `clientId` + monotonic per-session `seq` persisted to localStorage until the server ACKs, so a dropped link cannot lose or double-deliver a prompt. `ws-connection-registry.ts` supersedes only same-TAB reconnects, so two tabs on one session coexist. → [architecture-invariants#input-delivery-and-ws-resilience](docs/architecture-invariants.md#input-delivery-and-ws-resilience) +**Input**: `session.writeViaMux()` for programmatic/curl input via one tmux bracketed paste (`paste-buffer -p`) + `send-keys Enter`, single-line only. Interactive **browser** input goes through a durable **exactly-once** layer: a stable `clientId` + monotonic per-session `seq` persisted to localStorage until the server ACKs, so a dropped link cannot lose or double-deliver a prompt. `ws-connection-registry.ts` supersedes only same-TAB reconnects, so two tabs on one session coexist. → [architecture-invariants#input-delivery-and-ws-resilience](docs/architecture-invariants.md#input-delivery-and-ws-resilience) **Agent wait primitives**: bounded long-polls: `GET /api/sessions/:id/wait`, `GET .../wait-output` (literal substring, **never** regex) and `wait`/`waitTimeout` on `POST .../input`. Registry `session-wait-registry.ts` (pure), bounds `config/agent-wait.ts`. ⚠️ A timeout is a 200 (`wait.timedOut`). ⚠️ `stop`/`blocked` exist for `claude` and `deepseek` ONLY (rule lives in `hooksAvailableForMode()`): explicit request elsewhere is a 400. ⚠️ Send-and-wait registers the waiter BEFORE the write; teardown must `notifySignal('exit')` BEFORE `cancelAll()`; hangup abort listens on `reply.raw` (guarded by `writableFinished`), never `req.raw`; liveness comes from `isPaneDead`, never `session.pid`. ⚠️ Signals are edge-triggered with no history: gather fan-outs via send-and-wait or `wait-output` markers. Packaged as the `skills/codeman` skill (`codeman skill install`, plugin marketplace, or injection behind `agentSkillEnabled`, SYNCED, default OFF, into the directory each CLI scans: `capabilities.agentSkillDir`, `.claude/skills` for claude, `.agents/skills` for the others, none for pi): injection is add-only, marker-owned (`applyAgentSkill`), refuses symlinks, and refreshes a marker-owned user-level copy (`refreshUserAgentSkill`). → [architecture-invariants#agent-wait-primitives](docs/architecture-invariants.md#agent-wait-primitives), `docs/api-reference.md` diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 1836d1bf..4bd4864a 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -119,7 +119,7 @@ Spawn commands are pinned as literal strings in `test/cli-registry-spawn-golden. ### Input delivery and WS resilience -**Input**: `session.writeViaMux()` for programmatic/curl input — tmux `send-keys -l` (literal) + `send-keys Enter`. Single-line only (fire-and-once). Interactive **browser** input goes through a durable **exactly-once** layer: each frame carries a stable `clientId` + monotonic per-session `seq`, persisted to localStorage until the server ACKs (`{t:'ia',seq}` over WS, or HTTP 2xx), so a dropped link/reconnect can't lose or double-deliver a prompt. A duplicate is ACKed as `{t:'ia',seq,dup:true,last}` so a client whose persisted counter rolled back below the server's watermark can lift itself out instead of typing into a silently dead terminal (`docs/reliable-input-delivery.md`). **WS resilience** (#149): the upgrade URL carries `cid = clientId + ':' + perTabNonce`, and `ws-connection-registry.ts` supersedes only same-TAB reconnects (two tabs on one session coexist; input frames keep the bare `clientId` for seq dedup); reconnects back off exponentially (attempts preserved across `_connectWs`), and the header connection chip renders from a real `_wsState` lifecycle (`connecting`/`connected`/`fallback`/`reconnecting`/`disconnected`). +**Input**: `session.writeViaMux()` for programmatic/curl input — the text as one tmux bracketed paste (`paste-buffer -p`, so Codex cannot fold the Enter into a paste burst) + `send-keys Enter`. Single-line only (fire-and-once). Interactive **browser** input goes through a durable **exactly-once** layer: each frame carries a stable `clientId` + monotonic per-session `seq`, persisted to localStorage until the server ACKs (`{t:'ia',seq}` over WS, or HTTP 2xx), so a dropped link/reconnect can't lose or double-deliver a prompt. A duplicate is ACKed as `{t:'ia',seq,dup:true,last}` so a client whose persisted counter rolled back below the server's watermark can lift itself out instead of typing into a silently dead terminal (`docs/reliable-input-delivery.md`). **WS resilience** (#149): the upgrade URL carries `cid = clientId + ':' + perTabNonce`, and `ws-connection-registry.ts` supersedes only same-TAB reconnects (two tabs on one session coexist; input frames keep the bare `clientId` for seq dedup); reconnects back off exponentially (attempts preserved across `_connectWs`), and the header connection chip renders from a real `_wsState` lifecycle (`connecting`/`connected`/`fallback`/`reconnecting`/`disconnected`). ### Per-session env overrides: exact-key allowlist and CLAUDE_CONFIG_DIR diff --git a/docs/cron-guide.md b/docs/cron-guide.md index 92ba3320..4e93a58b 100644 --- a/docs/cron-guide.md +++ b/docs/cron-guide.md @@ -204,7 +204,7 @@ trailing carriage return: | Mode | Mechanism | Use when | | ------- | --------------------------------------------------------------- | ------------------------------------------------ | -| `typed` | `session.writeViaMux()` — tmux `send-keys -l` (literal) + Enter | Default; behaves like a human typing the prompt. | +| `typed` | `session.writeViaMux()` — the text as a tmux bracketed paste + Enter | Default; like a human pasting the prompt and pressing Enter. | | `paste` | `session.write()` — writes directly to the PTY/mux | Bulk paste-style delivery. | > ⚠️ **Single-line only — enforced.** Like all programmatic input in Codeman, diff --git a/src/session-submit-verifier.ts b/src/session-submit-verifier.ts index eb39edc8..063ad6ce 100644 --- a/src/session-submit-verifier.ts +++ b/src/session-submit-verifier.ts @@ -4,7 +4,7 @@ * * Claude Code 2.1.277 (auto-installed 2026-09-18) takes typed text the moment its * composer paints but ignores Enter for the first 30 to 50 seconds after it, so the - * `send-keys -l ` + `send-keys Enter` pair `TmuxManager.sendInput()` sends 50 ms + * text + `send-keys Enter` pair `TmuxManager.sendInput()` sends 50 ms * apart leaves the prompt sitting on the composer with `0 tokens`, and every caller * that then waits for the turn (send-and-wait, the agent skill, the maintainer bot, * cron, Ralph) burns its whole timeout on a turn that never started. Measured through diff --git a/src/session.ts b/src/session.ts index 5a2bb677..6e461267 100644 --- a/src/session.ts +++ b/src/session.ts @@ -4527,7 +4527,7 @@ export class Session extends EventEmitter { * * More reliable than direct PTY write for programmatic input, especially * with Claude CLI which uses Ink (React for terminals). - * Uses tmux `send-keys -l` to inject text + Enter. + * Uses tmux to inject the text (one bracketed paste) + Enter. * * @param data - Input data with optional `\r` for Enter * @returns true if input was sent, false if no mux session or PTY diff --git a/src/tmux-manager.ts b/src/tmux-manager.ts index cd0d07c1..9931f487 100644 --- a/src/tmux-manager.ts +++ b/src/tmux-manager.ts @@ -436,6 +436,65 @@ export function resolveTmuxPaneTarget(muxName: string, paneTarget?: string): str return `${muxName}.${paneTarget}`; } +let submitBufferSeq = 0; + +/** The tmux commands of one bracketed paste, see buildPasteTextCommands(). */ +export interface PasteTextCommands { + /** Fills a buffer of its own with the text. */ + set: string; + /** Pastes that buffer into the target, bracketed, and deletes it (`-d`). */ + paste: string; + /** Deletes the buffer when `paste` failed; `-d` only runs on a successful paste. */ + discard: string; +} + +/** + * tmux commands that type `text` into `target` as ONE bracketed paste, ahead of a + * separately sent `Enter` that submits it. Exported for unit testing. + * + * Why a paste and not `send-keys -l`: Codex detects a paste that arrives WITHOUT + * bracketed-paste markers heuristically, from characters arriving in a fast burst, + * and folds an Enter that lands inside that burst window into the paste as a + * newline. `send-keys -l` types exactly such an unmarked burst, so a text+Enter + * pair sat in Codex's composer unsubmitted: always for long text (Codex shows it as + * `[Pasted Content N chars]`, which SubmitVerifier cannot match against the prompt, + * so nothing re-presses Enter), intermittently for short text at the 50 ms gap. + * `paste-buffer -p` wraps the text in the markers (only when the pane asked for + * them, so an app without bracketed paste sees the same bytes as before) and the + * Enter after it is unambiguous. + * + * Each call gets its own named buffer so concurrent sends cannot paste each other's + * text. tmux keeps a named buffer until something deletes it (`buffer-limit` trims + * only automatic ones), hence `discard` for a paste that fails. + * + * tmux splits commands on an argument that ENDS in `;` (`set-buffer -- 'a;'` stores + * `a`, a lone `;` fails with "no data specified"); a final `\;` is its escape for a + * literal `;`. + */ +export function buildPasteTextCommands(tmux: string, target: string, text: string): PasteTextCommands { + const buffer = `codeman-submit-${process.pid}-${++submitBufferSeq}`; + const data = text.endsWith(';') ? `${text.slice(0, -1)}\\;` : text; + return { + set: `${tmux} set-buffer -b ${buffer} -- ${shellescape(data)}`, + paste: `${tmux} paste-buffer -p -d -b ${buffer} -t ${shellescape(target)}`, + discard: `${tmux} delete-buffer -b ${buffer}`, + }; +} + +/** + * Run a bracketed paste. A failed paste (the pane or the server is gone) deletes + * the buffer before the paste's own error propagates; a failing delete is ignored. + */ +export async function pasteText(run: (cmd: string) => Promise, cmds: PasteTextCommands): Promise { + await run(cmds.set); + try { + await run(cmds.paste); + } catch (err) { + await run(cmds.discard).catch(() => undefined); + throw err; + } +} + /** * Pick the active pane id from `tmux list-panes -F '#{pane_id}:#{pane_active}'` * output (lines like `%0:1`). Returns the pane id whose active flag is 1. @@ -3738,10 +3797,11 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { } /** - * Send input directly to a tmux session using `send-keys`. + * Send input directly to a tmux session. * - * Uses tmux send-keys for reliable input delivery: - * - `-l` flag sends literal text (no key interpretation) + * - Text followed by `\r` goes in as ONE bracketed paste (buildPasteTextCommands), + * so Codex cannot fold the Enter into a paste burst + * - Text without `\r` is typed literally with `send-keys -l` (no key interpretation) * - `Enter` key is sent as a SEPARATE tmux invocation after a small delay * - Ink (Claude CLI) needs text and Enter split to avoid treating Enter as a newline */ @@ -3776,10 +3836,13 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { // Send text first, then Enter as a SEPARATE tmux command after a short delay. // Ink (Claude CLI's terminal framework) needs them split — sending both in a // single tmux invocation (via \;) causes Ink to interpret Enter as a newline - // character in the input buffer rather than as form submission. - await execAsync(`${this.tmux()} send-keys -t "${session.muxName}" -l ${shellescape(textPart)}`, { - timeout: EXEC_TIMEOUT_MS, - }); + // character in the input buffer rather than as form submission. The text goes + // in as a bracketed paste so Codex cannot fold the Enter into it either + // (see buildPasteTextCommands). + await pasteText( + (cmd) => execAsync(cmd, { timeout: EXEC_TIMEOUT_MS }), + buildPasteTextCommands(this.tmux(), session.muxName, textPart) + ); await new Promise((resolve) => setTimeout(resolve, 50)); await execAsync(`${this.tmux()} send-keys -t "${session.muxName}" Enter`, { timeout: EXEC_TIMEOUT_MS, diff --git a/src/web/routes/session-routes.ts b/src/web/routes/session-routes.ts index 953cc553..a325bc30 100644 --- a/src/web/routes/session-routes.ts +++ b/src/web/routes/session-routes.ts @@ -2014,7 +2014,7 @@ export function registerSessionRoutes( const stopDeathWatch = wantsWait ? watchForDeadWorker(ctx.mux, session, id) : () => {}; // Write input to PTY. Direct write is synchronous; writeViaMux - // (tmux send-keys) is fire-and-forget to avoid blocking the HTTP response. + // (tmux paste + Enter) is fire-and-forget to avoid blocking the HTTP response. // Every write here is `fromUser`: this route carries a person's prompt, or an // agent's on their behalf, so it may name the tab (Ralph, respawn, cron and // approvals write through the session directly and never say so). @@ -2037,7 +2037,7 @@ export function registerSessionRoutes( // A plain prompt (`\r`) goes through the mux even when the caller did not // ask for it: written straight into the pane it arrives as one burst, and Claude // Code takes a long burst as a paste whose `\r` becomes a newline, so the prompt - // sat unsent (see isPlainPromptInput). The mux path types the text, presses Enter + // sat unsent (see isPlainPromptInput). The mux path pastes the text, presses Enter // separately and arms the SubmitVerifier. An explicit `useMux: false` keeps the // raw write for a caller that really wants it. const autoMux = useMux === undefined && isPlainPromptInput(inputStr); diff --git a/test/tmux-submit-paste.test.ts b/test/tmux-submit-paste.test.ts new file mode 100644 index 00000000..7832f79e --- /dev/null +++ b/test/tmux-submit-paste.test.ts @@ -0,0 +1,129 @@ +/** + * Covers `buildPasteTextCommands()` and `pasteText()`: the text half of a text+Enter + * submit (`sendInput`) goes in as ONE bracketed paste. + * + * Why: `send-keys -l` typed the text as an unmarked burst, and Codex's paste-burst + * heuristic folded the Enter that followed 50 ms later into the paste as a newline, + * so the prompt sat in the composer unsubmitted (always at 1500 chars, sometimes for + * a one-line prompt). With `paste-buffer -p` the paste is marked and the separate + * Enter submits. + * + * Strategy: pure command shape, plus a round trip through a real shell with a fake + * `tmux` that prints its argv, so quoting and tmux's trailing-`;` rule are checked + * on the bytes a shell actually hands over. `pasteText` runs against a recording + * runner. No real tmux. + * + * Port: N/A (no server / no real tmux) + */ +import { execSync } from 'node:child_process'; +import { describe, expect, it } from 'vitest'; +import { buildPasteTextCommands, pasteText } from '../src/tmux-manager.js'; + +const FAKE_TMUX = `${JSON.stringify(process.execPath)} -e 'console.log(JSON.stringify(process.argv.slice(1)))' --`; + +function argvOf(cmd: string): string[] { + return JSON.parse(execSync(cmd, { encoding: 'utf-8' })) as string[]; +} + +describe('buildPasteTextCommands', () => { + it('fills a buffer, pastes it bracketed into the target and deletes it', () => { + const { set, paste, discard } = buildPasteTextCommands('tmux -L codeman', 'codeman-abc12345', 'hello'); + const buffer = /set-buffer -b (\S+) -- /.exec(set)?.[1]; + expect(buffer).toMatch(/^codeman-submit-\d+-\d+$/); + expect(set).toBe(`tmux -L codeman set-buffer -b ${buffer} -- 'hello'`); + expect(paste).toBe(`tmux -L codeman paste-buffer -p -d -b ${buffer} -t 'codeman-abc12345'`); + expect(discard).toBe(`tmux -L codeman delete-buffer -b ${buffer}`); + }); + + it('never types the text with send-keys (the unmarked burst Codex misreads)', () => { + for (const cmd of Object.values(buildPasteTextCommands('tmux', 'codeman-abc12345', 'read your inbox'))) { + expect(cmd).not.toContain('send-keys'); + } + }); + + it('uses a fresh buffer per call, so concurrent sends cannot paste each other', () => { + const a = buildPasteTextCommands('tmux', 't', 'a').set; + const b = buildPasteTextCommands('tmux', 't', 'b').set; + expect(/-b (\S+)/.exec(a)?.[1]).not.toBe(/-b (\S+)/.exec(b)?.[1]); + }); + + it.each([ + ['quotes and shell syntax', `it's "quoted" $HOME \`id\` $(id) & | > <`], + ['tmux format syntax', '#{session_name} #S'], + ['leading dash', '-t other --help'], + ['non-ASCII', 'Mailbox lesen — äöü “x”'], + ['a long prompt', 'x'.repeat(1500)], + ])('hands the text to tmux unchanged through the shell: %s', (_label, text) => { + const { set } = buildPasteTextCommands(FAKE_TMUX, 't', text); + expect(argvOf(set).at(-1)).toBe(text); + }); + + it.each([ + ['x;', 'x\\;'], + [';', '\\;'], + ['x;;', 'x;\\;'], + ['x\\;', 'x\\\\;'], + ])('escapes a trailing ";" (tmux command separator): %s', (text, expected) => { + const { set } = buildPasteTextCommands(FAKE_TMUX, 't', text); + expect(argvOf(set).at(-1)).toBe(expected); + }); + + it('leaves a ";" inside the text alone', () => { + const { set } = buildPasteTextCommands(FAKE_TMUX, 't', 'a; b'); + expect(argvOf(set).at(-1)).toBe('a; b'); + }); +}); + +describe('pasteText', () => { + const cmds = { set: 'SET', paste: 'PASTE', discard: 'DISCARD' }; + + function recorder(failOn: string[] = []) { + const ran: string[] = []; + const run = async (cmd: string) => { + ran.push(cmd); + if (failOn.includes(cmd)) throw new Error(`${cmd} failed`); + }; + return { ran, run }; + } + + it('fills the buffer, then pastes it; the paste deletes it, so nothing else runs', async () => { + const { ran, run } = recorder(); + await pasteText(run, cmds); + expect(ran).toEqual(['SET', 'PASTE']); + }); + + it('deletes the buffer when the paste fails, and reports the paste error', async () => { + const { ran, run } = recorder(['PASTE']); + await expect(pasteText(run, cmds)).rejects.toThrow('PASTE failed'); + expect(ran).toEqual(['SET', 'PASTE', 'DISCARD']); + }); + + it('still reports the paste error when the delete fails too', async () => { + const { ran, run } = recorder(['PASTE', 'DISCARD']); + await expect(pasteText(run, cmds)).rejects.toThrow('PASTE failed'); + expect(ran).toEqual(['SET', 'PASTE', 'DISCARD']); + }); + + it('does not paste when filling the buffer failed', async () => { + const { ran, run } = recorder(['SET']); + await expect(pasteText(run, cmds)).rejects.toThrow('SET failed'); + expect(ran).toEqual(['SET']); + }); +}); + +describe('sendInput wiring', () => { + // sendInput() returns before touching tmux under vitest (IS_TEST_MODE), so the + // branch that submits text is pinned on the source instead. + it('submits text through pasteText, not send-keys -l', async () => { + const { readFileSync } = await import('node:fs'); + const src = readFileSync(new URL('../src/tmux-manager.ts', import.meta.url), 'utf-8'); + const body = src.slice(src.indexOf('async sendInput('), src.indexOf('// ========== Pane Methods')); + const submitBranch = body.slice( + body.indexOf('if (textPart && hasCarriageReturn)'), + body.indexOf('} else if (textPart)') + ); + expect(submitBranch).toContain('pasteText('); + expect(submitBranch).toContain('buildPasteTextCommands('); + expect(submitBranch).not.toMatch(/send-keys[^`]*-l/); + }); +});