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
feat(chat): send chat-view prompts as typed text, not a paste
Paul Robertsonb27b38006752
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 7138ac7f5..180eea820 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -32,6 +32,8 @@ import {remoteTmuxPtyArgs,type RemoteSessionEnv,remotePasteDelivery,+ remoteTypedArgs,+ remoteTmuxEnterArgs,remoteCapturePaneArgs,remotePaneCommandArgs,remotePaneCwdArgs,@@ -78,8 +80,11 @@ import {sessionName,isSessionName,localPasteDelivery,+ localTmuxEnterArgs,+ pasteBufferName,runPasteDelivery} from './tmux-naming'+import { localTypedArgs, typeThenSubmitWhenSettled } from './typed-input'import { encodeSendKeysHex } from './tmux-control'import {ZELLIJ_NESTING_ENV,@@ -1920,8 +1925,12 @@ export class PtyManager {platform().handle(IPC.ptyReadScrollback, (persistKey: string) =>readScrollback(persistKey))- platform().handle(IPC.ptySendText, (persistKey: string, text: string, enter?: boolean) =>- this.sendText(persistKey, text, enter === undefined ? undefined : { enter })+ platform().handle(IPC.ptySendText, (persistKey: string, text: string, enter?: boolean, typed?: unknown) =>+ // `typed` crosses a process boundary: only a literal `true` opts in to keystroke delivery.+ this.sendText(persistKey, text, {+ ...(enter === undefined ? {} : { enter }),+ ...(typed === true ? { typed: true } : {})+ }))platform().handle(IPC.ptyTmuxStatus, () => this.tmuxStatus())platform().handle(IPC.ptyPaneCommand, (persistKey: string) => this.paneCommand(persistKey))@@ -4917,10 +4926,20 @@ export class PtyManager {* 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<TextDeliveryResult> {+ async sendText(+ persistKey: string,+ text: string,+ opts?: { enter?: boolean; typed?: boolean }+ ): Promise<TextDeliveryResult> {const enter = opts?.enter ?? trueconst target = sessionName(persistKey)const live = this.liveSessionForPersistKey(persistKey)+ // `typed` (the ⌘M chat view): deliver as keystrokes, not a paste — see core/typed-input.ts.+ // Only a SUBMITTED prompt on a tmux backend; everything else keeps the paste path below.+ if (opts?.typed === true && enter) {+ const typed = await this.sendTyped(persistKey, text)+ if (typed !== null) return typed+ }// A direct (non-persistent) Windows PTY has no session-host entry and no tmux: it is typed// into through the pane itself. Routing it to the session host below failed every time.if (live?.nativeWindowsPane) return live.nativeWindowsPane.sendText(text, enter)@@ -4958,6 +4977,61 @@ export class PtyManager {}}+ /** Targets with a typed delivery in flight: two interleaved typings would splice their lines. */+ private typedInFlight = new Set<string>()++ /**+ * The typed half of `sendText` — `null` when this session's backend has no typed path (a direct+ * Windows PTY, the Windows session host, Zellij, no tmux), so the caller falls back to the paste.+ * A delivery already in flight for the same pane answers `false` rather than typing into the+ * middle of it.+ */+ private async sendTyped(persistKey: string, text: string): Promise<TextDeliveryResult | null> {+ const target = sessionName(persistKey)+ const live = this.liveSessionForPersistKey(persistKey)+ if (live?.nativeWindowsPane || this.isZellij(persistKey, live)) return null+ const sshRemote = live?.sshRemote+ let type: (stdin: string) => Promise<unknown>+ let submit: () => Promise<unknown>+ if (sshRemote) {+ const ssh = findSsh()+ if (!ssh) return false+ type = (stdin) =>+ runWithStdin(ssh, remoteTypedArgs(sshRemote.conn, sshRemote.controlPath, target, pasteBufferName()), stdin)+ submit = () => runAsync(ssh, remoteTmuxEnterArgs(sshRemote.conn, sshRemote.controlPath, target))+ } else if (live?.sessionHost || !this.tmuxPath) {+ return null+ } else {+ const tmuxPath = this.tmuxPath+ type = (stdin) => runWithStdin('/bin/sh', localTypedArgs(tmuxPath, TMUX_SOCKET, target, pasteBufferName()), stdin)+ submit = () => runAsync(tmuxPath, localTmuxEnterArgs(TMUX_SOCKET, target))+ }+ if (this.typedInFlight.has(target)) return false+ this.typedInFlight.add(target)+ const ok = async (run: () => Promise<unknown>): Promise<boolean> => {+ try {+ await run()+ return true+ } catch {+ return false+ }+ }+ try {+ return await typeThenSubmitWhenSettled(text, {+ capture: async () => {+ const screen = await this.captureSession(persistKey)+ return screen === '' ? null : screen+ },+ type: (stdin) => ok(() => type(stdin)),+ submit: () => ok(submit)+ })+ } catch {+ return 'pasted-not-submitted'+ } finally {+ this.typedInFlight.delete(target)+ }+ }+/*** The command currently in the foreground of a node's tmux pane (e.g. 'claude', 'zsh') — how* the in-place agent restart observes that the CLI has exited and a shell owns the pane again.diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.tsindex 3315ece8d..947ebc612 100644--- a/src/core/remote-ssh/control-master.ts+++ b/src/core/remote-ssh/control-master.ts@@ -18,6 +18,7 @@ import {type PasteDelivery} from '../tmux-naming'import { sanitizePasteText } from '../paste-injection'+import { typedInputScript } from '../typed-input'import { canControlCanvas } from '../../shared/agents/config'import { COMBINED_PANE_MARKER, PANE_OWNER_FMT, PS_FOREGROUND_FLAGS } from '../agents/pane-owner'// Dependency-free (no node-pty): safe to import from these pure builders.@@ -356,6 +357,24 @@ export function remoteTmuxPasteArgs(* Enter, `PtyManager.sendEnvelope`), exactly like every other remote write.*/+/**+ * The TYPED delivery on the REMOTE server (see core/typed-input.ts): the same fixed script, run+ * under `sh -c` so it does not depend on the user's login shell, with the text on stdin — never on+ * the remote command line, where it would sit in the host's process list.+ */+export function remoteTypedArgs(+ conn: SshConnection,+ controlPath: string,+ sessionId: string,+ buffer: string+): string[] {+ return childArgs(+ conn,+ controlPath,+ tmuxCmd(`sh -c ${posixQuote(typedInputScript('tmux', RMT_TMUX_SOCKET, sessionId, buffer))}`)+ )+}+/*** A bare Enter into the remote pane — the remote half of `sendText`'s empty-payload case.*diff --git a/src/core/typed-input.realtmux.test.ts b/src/core/typed-input.realtmux.test.tsnew file mode 100644index 000000000..2c0a2e0ff--- /dev/null+++ b/src/core/typed-input.realtmux.test.ts@@ -0,0 +1,168 @@+// THE TYPED DELIVERY, PROVEN AGAINST A REAL TMUX.+//+// The subject is `typedInputScript` — the fixed script `sendText({ typed: true })` runs, with the+// prompt on stdin — driven both as the LOCAL `sh -c` argv (`localTypedArgs`) and as the REMOTE+// command line (`remoteTypedArgs`, through a real /bin/sh with a tmux shim on PATH), and judged by+// the raw bytes a pane receives. The pane program puts its tty in raw mode and appends everything+// to a file, so what is asserted is what an agent CLI would read. Harness: tmux-paste.realtmux.+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { execFileSync } from 'child_process'+import fs from 'fs'+import path from 'path'+import { pasteBufferName } from './tmux-naming'+import { localTypedArgs, typedLines, typedStdin, TYPED_TAB } from './typed-input'+import { remoteTypedArgs } from './remote-ssh/control-master'+import { makeTmuxTmpdir } from './tmux-test-socket'++const ESC = '\x1b'+/** M-Enter as the pane receives it: the "new line, don't submit" key. */+const NEWLINE_KEY = `${ESC}\r`+/** A private socket — never `TMUX_SOCKET`/`nodeterm-rmt`, which carry live user sessions. */+const SOCKET = `nt-typed-test-${process.pid}`+const CONN = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile: '/k/id' }++function findTmux(): string | null {+ for (const c of ['/usr/bin/tmux', '/usr/local/bin/tmux', '/opt/homebrew/bin/tmux', '/bin/tmux']) {+ if (fs.existsSync(c)) return c+ }+ return null+}+const TMUX = findTmux()++let work: string+let binDir: string++const env = (): NodeJS.ProcessEnv => ({ ...process.env, TMUX_TMPDIR: work })+const tmux = (args: string[]): string =>+ execFileSync(TMUX as string, args, { encoding: 'utf8', env: env() })++beforeAll(() => {+ if (!TMUX) return+ work = makeTmuxTmpdir('nttp-', SOCKET)+ binDir = path.join(work, 'bin')+ fs.mkdirSync(binDir)+ // The SSH leg's shim: the remote script says `tmux -L nodeterm-rmt …`; drop those two words and+ // re-invoke the real tmux on this test's private socket.+ fs.writeFileSync(+ path.join(binDir, 'tmux'),+ `#!/bin/sh\nexport TMUX_TMPDIR=${work}\nshift 2\nexec ${TMUX} -L ${SOCKET} "$@"\n`,+ { mode: 0o755 }+ )+ // Records the raw bytes it receives, and REQUESTS bracketed paste (DECSET 2004) the way Claude+ // Code does — without that, tmux would not frame even a `-p` paste, and this file could not tell+ // typing from pasting.+ fs.writeFileSync(+ path.join(binDir, 'recorder'),+ ['#!/bin/sh', 'stty raw -echo', "printf '\\033[?2004h'", 'touch "$1.ready"', 'exec cat > "$1"'].join('\n') + '\n',+ { mode: 0o755 }+ )+})++afterAll(() => {+ if (TMUX) {+ try {+ tmux(['-L', SOCKET, 'kill-server'])+ } catch {+ // already gone+ }+ }+ if (work) fs.rmSync(work, { recursive: true, force: true })+})++function waitFor(predicate: () => boolean, what: string, ms = 10_000): void {+ const deadline = Date.now() + ms+ while (!predicate()) {+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`)+ execFileSync('sleep', ['0.03'])+ }+}++function recorderPane(session: string): string {+ const out = path.join(work, `${session}.bytes`)+ tmux(['-L', SOCKET, 'new-session', '-d', '-s', session, '-x', '200', '-y', '40', `${binDir}/recorder ${out}`])+ waitFor(() => fs.existsSync(`${out}.ready`), `${session} recorder to come up`)+ return out+}++const MARK = '<<NTEND>>'+function drain(session: string, out: string): string {+ tmux(['-L', SOCKET, 'send-keys', '-t', session, '-l', '--', MARK])+ waitFor(() => fs.readFileSync(out, 'utf8').includes(MARK), `${session} to receive the marker`)+ const all = fs.readFileSync(out, 'utf8')+ return all.slice(0, all.lastIndexOf(MARK))+}++/** Exactly what `PtyManager.sendTyped` runs for one leg, with the prompt on stdin. */+function type(leg: 'local' | 'ssh', session: string, text: string): void {+ const stdin = typedStdin(typedLines(text))+ if (leg === 'local') {+ execFileSync('/bin/sh', localTypedArgs(TMUX as string, SOCKET, session, pasteBufferName()), {+ env: env(),+ input: stdin+ })+ return+ }+ const args = remoteTypedArgs(CONN, '/s.sock', session, pasteBufferName())+ execFileSync('/bin/sh', ['-c', args[args.length - 1]], {+ env: { PATH: `${binDir}:/usr/bin:/bin`, HOME: work },+ input: stdin+ })+}++describe.skipIf(TMUX === null || process.platform === 'win32')('typed delivery through a real tmux', () => {+ for (const leg of ['local', 'ssh'] as const) {+ describe(leg, () => {+ it('types each line and joins them with the new-line key, never a submit', () => {+ const session = `nt-ty-lines-${leg}`+ const out = recorderPane(session)++ type(leg, session, 'This is a test\nof a multiline message\n\n- said nobody ever')++ expect(drain(session, out)).toBe(+ `This is a test${NEWLINE_KEY}of a multiline message${NEWLINE_KEY}${NEWLINE_KEY}- said nobody ever`+ )+ })++ it('delivers what tmux argv parsing would mangle, byte for byte', () => {+ const session = `nt-ty-argv-${leg}`+ const out = recorderPane(session)+ // A trailing `;` is a command separator, `\;` loses its backslash and a leading `-` is an+ // option — all measured with `send-keys -l`. The text rides stdin, so none of it applies.+ const text = 'ends with semi;\n;\n-leading dash\nbackslash-semi \\;\nfor (;;) {} é 日本'++ type(leg, session, text)++ expect(drain(session, out)).toBe(text.split('\n').join(NEWLINE_KEY))+ })++ it('turns a tab into spaces and never sends a control key', () => {+ const session = `nt-ty-ctl-${leg}`+ const out = recorderPane(session)++ type(leg, session, 'a\tb\x03c\x1b[201~d')++ expect(drain(session, out)).toBe(`a${TYPED_TAB}bc[201~d`)+ })++ it('leaves copy mode first, so the keys reach the application', () => {+ const session = `nt-ty-copy-${leg}`+ const out = recorderPane(session)+ tmux(['-L', SOCKET, 'copy-mode', '-t', session])++ type(leg, session, 'after copy mode')++ expect(drain(session, out)).toBe('after copy mode')+ })++ it('leaves no buffer behind', () => {+ const session = `nt-ty-buf-${leg}`+ recorderPane(session)++ type(leg, session, 'one\ntwo\nthree')++ const buffers = tmux(['-L', SOCKET, 'list-buffers', '-F', '#{buffer_name}'])+ expect(buffers.split('\n').filter((b) => b.startsWith('nt-paste-'))).toEqual([])+ })+ })+ }+})diff --git a/src/core/typed-input.test.ts b/src/core/typed-input.test.tsnew file mode 100644index 000000000..2afeefa9d--- /dev/null+++ b/src/core/typed-input.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it, vi } from 'vitest'+import {+ TYPED_TAB,+ typeThenSubmitWhenSettled,+ typedInputScript,+ typedLines,+ typedStdin,+ type TypedSurface+} from './typed-input'++describe('typedLines', () => {+ it('splits on every line-ending style and keeps blank lines', () => {+ expect(typedLines('one\r\ntwo\rthree\n\nfive')).toEqual(['one', 'two', 'three', '', 'five'])+ })++ it('turns tabs into spaces, since a typed Tab is a composer shortcut', () => {+ expect(typedLines('a\tb')).toEqual([`a${TYPED_TAB}b`])+ })++ it('drops control characters, which would arrive as KEYS', () => {+ expect(typedLines('stop\x03 here\x1b[201~ and \x7f\x9b there')).toEqual(['stop here[201~ and there'])+ })++ it('leaves printable text alone, including the characters tmux argv parsing mangles', () => {+ expect(typedLines('- dash; \\; é 日本')).toEqual(['- dash; \\; é 日本'])+ })+})++describe('typedStdin', () => {+ it('terminates every line, so the script reads the last one too', () => {+ expect(typedStdin(['a', '', 'b'])).toBe('a\n\nb\n')+ })+})++describe('typedInputScript', () => {+ it('refuses a target or socket it would splice unsafely', () => {+ expect(() => typedInputScript('tmux', 'nodeterm-rmt', 'nt-x; rm -rf /', 'nt-paste-abc')).toThrow()+ expect(() => typedInputScript('tmux', 'bad socket', 'nt-abc', 'nt-paste-abc')).toThrow()+ })+})++/** A pane whose screen gains `text` once typed, after `lag` captures. */+function fakeSurface(opts: {+ screen?: string+ lag?: number+ typeOk?: boolean+ submitOk?: boolean+ captureNull?: boolean+}): TypedSurface & { submit: ReturnType<typeof vi.fn>; typed: string[] } {+ let screen = opts.screen ?? '> '+ let pendingText: string | null = null+ let lag = opts.lag ?? 0+ const typed: string[] = []+ return {+ typed,+ capture: async () => {+ if (opts.captureNull === true) return null+ if (pendingText !== null) {+ if (lag === 0) {+ screen += pendingText+ pendingText = null+ } else lag--+ }+ return screen+ },+ type: async (stdin) => {+ typed.push(stdin)+ if (opts.typeOk === false) return false+ pendingText = stdin+ return true+ },+ submit: vi.fn(async () => opts.submitOk ?? true)+ }+}++const noWait = { wait: async () => {} }++describe('typeThenSubmitWhenSettled', () => {+ it('submits once the text is on screen on two polls in a row', async () => {+ const surface = fakeSurface({ lag: 2 })++ const result = await typeThenSubmitWhenSettled('hello there', surface, noWait)++ expect(result).toBe(true)+ expect(surface.typed).toEqual(['hello there\n'])+ expect(surface.submit).toHaveBeenCalledTimes(1)+ })++ it('does not count an identical message that was already on screen', async () => {+ const surface = fakeSurface({ screen: '> continue\n> ', lag: 99 })++ const result = await typeThenSubmitWhenSettled('continue', surface, noWait)++ expect(result).toBe('pasted-not-submitted')+ expect(surface.submit).not.toHaveBeenCalled()+ })++ it('leaves the text unsubmitted when the pane cannot be read', async () => {+ const surface = fakeSurface({ captureNull: true })++ const result = await typeThenSubmitWhenSettled('hello', surface, noWait)++ expect(result).toBe('pasted-not-submitted')+ expect(surface.submit).not.toHaveBeenCalled()+ })++ it('reports a failed or partial type as possibly pasted, never as delivered', async () => {+ const surface = fakeSurface({ typeOk: false })++ const result = await typeThenSubmitWhenSettled('hello', surface, noWait)++ expect(result).toBe('pasted-not-submitted')+ expect(surface.submit).not.toHaveBeenCalled()+ })++ it('reports a failed Enter as possibly pasted', async () => {+ const surface = fakeSurface({ submitOk: false })++ const result = await typeThenSubmitWhenSettled('hello', surface, noWait)++ expect(result).toBe('pasted-not-submitted')+ })++ it('types nothing for a message with no visible characters', async () => {+ const surface = fakeSurface({})++ const result = await typeThenSubmitWhenSettled(' \n\t\x03 ', surface, noWait)++ expect(result).toBe(false)+ expect(surface.typed).toEqual([])+ })+})diff --git a/src/core/typed-input.ts b/src/core/typed-input.tsnew file mode 100644index 000000000..834a7b98a--- /dev/null+++ b/src/core/typed-input.ts@@ -0,0 +1,145 @@+import type { TextDeliveryResult } from '../shared/text-delivery'+import { posixQuote } from '../shared/ssh'+import { assertPasteTarget } from './tmux-naming'+import { ENVELOPE_SETTLE_POLLS, ENVELOPE_SETTLE_POLL_MS, type SettleOptions } from './settled-submit'++/**+ * ── TYPED DELIVERY: a prompt that arrives as TYPING, not as a paste ─────────────────────────────+ *+ * Why it exists. `sendText` delivers through a bracketed paste, and Claude Code records a+ * multi-line paste wrapped as `<pasted_content id="…">…</pasted_content id="…">` — content its own+ * instructions tell the model to treat as possibly not written by the user. For the ⌘M chat view,+ * where the text IS the user's prompt, that demoted every multi-line message. Measured against+ * claude 2.1.281 (2026-09-23): text typed as keystrokes, lines joined by M-Enter (ESC CR, the key+ * Shift+Enter sends in the terminal), is recorded as plain user text — idle, queued mid-turn, and+ * at 30 lines / 2.7 KB arriving in one burst.+ *+ * How, and the traps each choice avoids (all measured on tmux 3.6a):+ * - The text NEVER rides argv. It goes over stdin to a fixed shell script (no user bytes in it),+ * which pastes it one line at a time — out of the process list on a shared host, and immune to+ * `send-keys -l` argv parsing, where a trailing `;` is a command separator, `\;` loses its+ * backslash and a leading `-` is an option.+ * - Each line is pasted WITHOUT `-p`: raw bytes, no bracketed-paste markers, i.e. typing.+ * - Line breaks are the tmux KEY `M-Enter`, never an ESC byte in a buffer: tmux ≥ 3.7 passes+ * paste-buffer content through vis(3), which rewrites ESC into the literal text `^[` (the+ * tombstone in tmux-naming.ts has the measurement).+ * - Enter is a SEPARATE write, sent only once the pane shows the text. An Enter arriving in the+ * same burst as the text is read by Claude Code as a line break, and the message sits unsent.+ * - Tabs become spaces: a Tab keystroke is a shortcut to Claude Code's composer and the character+ * vanishes (measured).+ *+ * tmux backends only (local, SSH, Server Edition). The Windows backends keep the paste path: how+ * Claude Code on Windows reads M-Enter has not been measured.+ */++/** Tab width used when a typed prompt contains tabs (see above: a typed Tab is a shortcut). */+export const TYPED_TAB = ' '++/**+ * The lines to type. CR/CRLF become LF; tabs become spaces; every other control character (C0+ * except LF, DEL, C1 — ESC and the 8-bit CSI included) is dropped, because a typed control byte+ * is a KEY — a stray ^C in a chat message would interrupt the agent. Printable text is untouched.+ */+export function typedLines(text: string): string[] {+ return text+ .replace(/\r\n?/g, '\n')+ .replace(/\t/g, TYPED_TAB)+ // eslint-disable-next-line no-control-regex+ .replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g, '')+ .split('\n')+}++/**+ * The script that types stdin into the pane. `tmux` is a shell word that runs tmux (a quoted+ * absolute path locally, `tmux` on an SSH host); `target` and `buffer` are validated here, since+ * they are spliced in. Every failure exits non-zero, and a paste that fails after its load drops+ * the buffer rather than leaving the user's line in the server's buffer stack (see PasteDelivery).+ */+export function typedInputScript(tmux: string, socket: string, target: string, buffer: string): string {+ assertPasteTarget(target, buffer)+ if (!/^[A-Za-z0-9._-]+$/.test(socket)) throw new Error(`unsafe tmux socket: ${JSON.stringify(socket)}`)+ const t = `${tmux} -L ${socket}`+ return [+ // Leave copy mode first, like the paste path: keys typed into copy mode drive IT, not the app.+ `${t} if-shell -F -t ${target} '#{pane_in_mode}' 'send-keys -t ${target} -X cancel' || exit 1`,+ 'first=1',+ 'while IFS= read -r line; do',+ ` if [ "$first" = 1 ]; then first=0; else ${t} send-keys -t ${target} M-Enter || exit 1; fi`,+ ' if [ -n "$line" ]; then',+ ` printf '%s' "$line" | ${t} load-buffer -b ${buffer} - || exit 1`,+ ` ${t} paste-buffer -d -r -b ${buffer} -t ${target} || { ${t} delete-buffer -b ${buffer} 2>/dev/null; exit 1; }`,+ ' fi',+ 'done'+ ].join('\n')+}++/** The same script, as `sh -c` argv for a local run (stdin carries the text). */+export function localTypedArgs(tmuxPath: string, socket: string, target: string, buffer: string): string[] {+ return ['-c', typedInputScript(posixQuote(tmuxPath), socket, target, buffer)]+}++/** What stdin the script reads: one line per line, each LF-terminated so the last is read too. */+export function typedStdin(lines: readonly string[]): string {+ return `${lines.join('\n')}\n`+}++export interface TypedSurface {+ /** The pane's text now, or null when it cannot be read. Never throws. */+ capture(): Promise<string | null>+ /** Type the stdin into the pane WITHOUT submitting. False: it failed, possibly part-way. */+ type(stdin: string): Promise<boolean>+ /** Submit, in its own write. False: the Enter could not be sent. */+ submit(): Promise<boolean>+}++// eslint-disable-next-line no-control-regex+const visible = (s: string): string => s.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').replace(/\s+/g, '')++/** Non-overlapping occurrences of `needle` in `hay`. */+function occurrences(hay: string, needle: string): number {+ let n = 0+ for (let i = hay.indexOf(needle); i !== -1; i = hay.indexOf(needle, i + needle.length)) n+++ return n+}++/** How many trailing visible characters identify the message on screen. */+export const TYPED_NEEDLE_CHARS = 24++/**+ * Type `text`, then submit it once the pane shows it.+ *+ * "Shows it" is NOT "the screen stopped changing" (the envelope path's rule): while an agent works,+ * its spinner and token counter repaint constantly, so a stable screen never comes and a QUEUED+ * prompt would never be submitted. It is: the message's tail is on screen MORE times than before+ * the typing, on two polls in a row — more, so an identical earlier message already visible does+ * not count; twice, so the composer has finished taking the burst in.+ *+ * `pasted-not-submitted` whenever the text may be in the composer unsent — a failed or partial+ * type, an unconfirmed settle, a failed Enter. Callers surface it and never resend.+ */+export async function typeThenSubmitWhenSettled(+ text: string,+ surface: TypedSurface,+ options: SettleOptions = {}+): Promise<TextDeliveryResult> {+ const lines = typedLines(text)+ const joined = visible(lines.join(''))+ if (joined === '') return false+ const needle = joined.slice(-TYPED_NEEDLE_CHARS)+ const before = await surface.capture()+ if (!(await surface.type(typedStdin(lines)))) return 'pasted-not-submitted'+ if (before === null) return 'pasted-not-submitted'+ const baseline = occurrences(visible(before), needle)++ const wait = options.wait ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))+ const polls = Math.max(1, options.polls ?? ENVELOPE_SETTLE_POLLS)+ let seenOnce = false+ for (let i = 0; i < polls; i++) {+ await wait(ENVELOPE_SETTLE_POLL_MS)+ const now = await surface.capture()+ const shown = now !== null && occurrences(visible(now), needle) > baseline+ if (shown && seenOnce) return (await surface.submit()) ? true : 'pasted-not-submitted'+ seenOnce = shown+ }+ return 'pasted-not-submitted'+}diff --git a/src/preload/index.ts b/src/preload/index.tsindex b0eddc084..81b9913dd 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -101,7 +101,7 @@ const api: NodeTerminalApi = {sessionAge: (persistKey) => ipcRenderer.invoke(IPC.ptySessionAge, persistKey),readScrollback: (persistKey) => ipcRenderer.invoke(IPC.ptyReadScrollback, persistKey),sendText: (persistKey, text, opts) =>- ipcRenderer.invoke(IPC.ptySendText, persistKey, text, opts?.enter),+ ipcRenderer.invoke(IPC.ptySendText, persistKey, text, opts?.enter, opts?.typed),tmuxStatus: () => ipcRenderer.invoke(IPC.ptyTmuxStatus),paneCommand: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneCommand, persistKey),paneCwd: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneCwd, persistKey),diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex b3b46b081..4a7bdf629 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -271,7 +271,7 @@ export function buildRealApi(readScrollback: (persistKey) =>client.request(IPC.ptyReadScrollback, persistKey) as Promise<string>,sendText: (persistKey, text, opts) =>- client.request(IPC.ptySendText, persistKey, text, opts?.enter) as Promise<boolean>,+ client.request(IPC.ptySendText, persistKey, text, opts?.enter, opts?.typed) as Promise<boolean>,// A failed read is unknown, never evidence that persistence is available.tmuxStatus: () =>clientdiff --git a/src/renderer/lib/chatPaging.test.ts b/src/renderer/lib/chatPaging.test.tsindex 85d5e3a29..ee1b55552 100644--- a/src/renderer/lib/chatPaging.test.ts+++ b/src/renderer/lib/chatPaging.test.ts@@ -143,6 +143,15 @@ describe('applyTail — unconfirmed optimistic sends (live reads)', () => {expect(texts(applyTail(t2, ID, page([say(0, 'q'), say(300, rec2, 'user')], 0), { carryUnconfirmed: true }))).toEqual(['q', rec2])})+ it('a typed send recorded with its tabs as spaces still confirms it', () => {+ const t = base([say(0, 'q'), say(undefined, 'col1\tcol2\nnext line', 'user')], 0)++ const out = applyTail(t, ID, page([say(0, 'q'), say(300, 'col1 col2\nnext line', 'user')], 0), { carryUnconfirmed: true })++ expect(texts(out)).toEqual(['q', 'col1 col2\nnext line'])+ expect(out.messages.every((m) => m.key !== undefined)).toBe(true)+ })+it('matches one-for-one, and never against a user line the thread already had', () => {// An OLD "yes" (key 100, already rendered) must not confirm the NEW unconfirmed "yes".const t = base([say(100, 'yes', 'user'), say(undefined, 'yes', 'user'), say(undefined, 'yes', 'user')], 100)diff --git a/src/renderer/lib/chatPaging.ts b/src/renderer/lib/chatPaging.tsindex cc3b565e1..45f19ae26 100644--- a/src/renderer/lib/chatPaging.ts+++ b/src/renderer/lib/chatPaging.ts@@ -129,6 +129,10 @@ const userText = (m: ChatMessage): string =>.join('').trim()+// Whitespace runs collapsed: a TYPED send (core/typed-input.ts) turns each tab into a space, so its+// transcript copy is not byte-identical to what was sent.+const looseText = (s: string): string => s.replace(/\s+/g, ' ')+/** The thread's TRAILING unkeyed user messages — the optimistic sends a live read may still carry. */function trailingSends(t: ChatThread): ChatMessage[] {const trailing: ChatMessage[] = []@@ -168,7 +172,8 @@ function commandPart(m: ChatMessage): { name: string; arg: string } | null {* unkeyed; grok's thread is unkeyed throughout, but its whole-file read contains every prompt it* rendered, so each one is matched and dropped). Each one is dropped when the new read contains a user message with* the same trimmed text (or with that text as the reader renders a send the CLI recorded as ONE- * `<pasted_content>` span: `fencePasted(text).trim()`), ONE-FOR-ONE, and only among messages NEWER+ * `<pasted_content>` span: `fencePasted(text).trim()`, or — last — with every whitespace run+ * collapsed, for a typed send whose tabs became spaces), ONE-FOR-ONE, and only among messages NEWER* than anything the thread had keyed — an older identical "yes" already on screen must not confirm* a new "yes". A sent slash* command / `!` line is confirmed the same way by a command tool part (`sentCommand`): same name,@@ -197,6 +202,7 @@ function unconfirmedSends(t: ChatThread, res: ChatTranscriptResult): ChatMessage// The CLI may record a send delivered as a bracketed paste as ONE `<pasted_content>` span, which// the reader renders fenced — the same send, in the form the reader gives it.if (i < 0 && sentText) i = available.indexOf(fencePasted(sentText).trim())+ if (i < 0 && sentText) i = available.findIndex((a) => looseText(a) === looseText(sentText))if (i >= 0) {available.splice(i, 1)return falsediff --git a/src/renderer/nodes/ChatPanel.codexSend.test.tsx b/src/renderer/nodes/ChatPanel.codexSend.test.tsxindex 5129cac0a..ce6bbc97e 100644--- a/src/renderer/nodes/ChatPanel.codexSend.test.tsx+++ b/src/renderer/nodes/ChatPanel.codexSend.test.tsx@@ -92,6 +92,20 @@ describe('ChatPanel — codex send asks the kernel', () => {expect(toasts).toEqual(['Codex is no longer running in this terminal — the message was not sent.'])})+ it('pastes rather than types for codex: M-Enter is unmeasured in its composer', async () => {+ paneOwner.mockResolvedValue(CODEX)++ await send(await mount('codex'), 'first line\nsecond line')++ expect(sendText).toHaveBeenCalledWith(NODE, 'first line\nsecond line')+ })++ it('types for claude (TYPED_INPUT_CAPABLE)', async () => {+ await send(await mount('claude'), 'hello')++ expect(sendText).toHaveBeenCalledWith(NODE, 'hello', { typed: true })+ })+it('claude is not probed (its hooks announce a quit)', async () => {await send(await mount('claude'), 'hello')expect(paneOwner).not.toHaveBeenCalled()diff --git a/src/renderer/nodes/ChatPanel.composer.test.tsx b/src/renderer/nodes/ChatPanel.composer.test.tsxindex 7b45f7065..4b24f805c 100644--- a/src/renderer/nodes/ChatPanel.composer.test.tsx+++ b/src/renderer/nodes/ChatPanel.composer.test.tsx@@ -405,7 +405,7 @@ describe('model / effort labels', () => {textarea().dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))})await flush()- expect(sendText).toHaveBeenCalledWith(NODE, 'go')+ expect(sendText).toHaveBeenCalledWith(NODE, 'go', { typed: true })expect(modelBtn()!.disabled).toBe(true)expect(effortBtn()!.disabled).toBe(true)// The real state speaks (the turn ran and finished): the labels come back.diff --git a/src/renderer/nodes/ChatPanel.sendGate.test.tsx b/src/renderer/nodes/ChatPanel.sendGate.test.tsxindex ed23fbf87..b91f07b56 100644--- a/src/renderer/nodes/ChatPanel.sendGate.test.tsx+++ b/src/renderer/nodes/ChatPanel.sendGate.test.tsx@@ -84,7 +84,7 @@ describe('ChatPanel send gate', () => {expect(ta.disabled).toBe(false)await act(async () => type(ta, 'hello'))await act(async () => enter(ta))- expect(sendText).toHaveBeenCalledWith(NODE, 'hello')+ expect(sendText).toHaveBeenCalledWith(NODE, 'hello', { typed: true })})it.each(['waiting', 'blocked'] as const)('disables the composer and explains while %s', async (state) => {diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsxindex cbe4247f0..f1e2cc823 100644--- a/src/renderer/nodes/ChatPanel.tsx+++ b/src/renderer/nodes/ChatPanel.tsx@@ -25,7 +25,7 @@ import { Spinner } from '../components/Spinner'import { CHAT_LIVE_RELOAD_MIN_MS, CHAT_OPTIMISTIC_WORKING_MS, chatActivity, planLiveReload } from '../lib/chatLive'import { sentCommand } from '@shared/chat-command'import { isInteractiveBuiltin } from '@shared/chat-catalog'-import { capabilityAgentId, chatReadsLocalOnly } from '@shared/agents/config'+import { capabilityAgentId, chatReadsLocalOnly, typesChatInput } from '@shared/agents/config'import { ChatLoadingStatus } from './ChatPanelFallback'import { answerCardState, answerRebindPending, rebindRetryDelay, type BoundAnswerCard } from '../lib/chatAnswer'import { AnswerControlsUpdating, PlanAnswerControls, QuestionAnswerControls } from './ChatAnswerControls'@@ -673,60 +673,76 @@ export function ChatPanel({maybeLoadOlder()}+ // A typed send takes a moment (core waits for the pane to show the text before pressing Enter),+ // and core refuses a second one into the same pane meanwhile — which this panel would misread as+ // "can't write to this session". An Enter during a send is simply ignored.+ const sendingRef = useRef(false)+const send = useCallback(async () => {const text = input.trim()+ if (!text || sendingRef.current) return// Read the store at SEND time, not the render-time values: a PermissionRequest (or an Eco// hibernation) that landed between the last render and this keypress must still block.- if (!text || chatSendRefusal(agentId, useAgentStatus.getState().byId[nodeId] ?? {}) !== null) return- // The kernel's say (chatPaneGate.ts): an agent that announces no quit (codex) may have left a- // SHELL in the pane while the store still reads `done` — typed there, the message would run.- const pane = await chatPaneRefusal(agentId, nodeId, {- paneOwner: (n) => api.pty.paneOwner(n),- customAgents: useSettings.getState().settings.customAgents- })- if (pane) {- const message = chatPaneRefusalToast(pane, chatAgentLabel(agentId, useSettings.getState().settings.customAgents))- window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message } }))- return- }- const ok = await api.pty.sendText(nodeId, text)- if (ok === 'pasted-not-submitted') {- window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message: TEXT_NOT_SUBMITTED } }))+ if (chatSendRefusal(agentId, useAgentStatus.getState().byId[nodeId] ?? {}) !== null) return+ sendingRef.current = true+ try {+ // The kernel's say (chatPaneGate.ts): an agent that announces no quit (codex) may have left a+ // SHELL in the pane while the store still reads `done` — typed there, the message would run.+ const pane = await chatPaneRefusal(agentId, nodeId, {+ paneOwner: (n) => api.pty.paneOwner(n),+ customAgents: useSettings.getState().settings.customAgents+ })+ if (pane) {+ const message = chatPaneRefusalToast(pane, chatAgentLabel(agentId, useSettings.getState().settings.customAgents))+ window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message } }))+ return+ }+ // Typed, not pasted, for an agent whose composer was measured (`typesChatInput`): Claude Code+ // wraps a multi-line PASTE as <pasted_content>, content its model is told may not be the user's+ // own words (core/typed-input.ts). Ignored off tmux. Every other agent keeps the paste.+ const ok = typesChatInput(agentId)+ ? await api.pty.sendText(nodeId, text, { typed: true })+ : await api.pty.sendText(nodeId, text)+ if (ok === 'pasted-not-submitted') {+ window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message: TEXT_NOT_SUBMITTED } }))+ setInput('')+ return+ }+ if (!ok) {+ setReadonly(true)+ return+ }+ // Optimistic: show the prompt immediately. A live read keeps it until the transcript carries it+ // (`carryUnconfirmed`); the turn-end reload / ↻ reconcile from the transcript outright.+ justSentRef.current = true+ setThread((t) => ({ ...t, messages: [...t.messages, { role: 'user', parts: [{ kind: 'text', text }] }] }))+ setOptimistic(true)setInput('')- return- }- if (!ok) {- setReadonly(true)- return- }- // Optimistic: show the prompt immediately. A live read keeps it until the transcript carries it- // (`carryUnconfirmed`); the turn-end reload / ↻ reconcile from the transcript outright.- justSentRef.current = true- setThread((t) => ({ ...t, messages: [...t.messages, { role: 'user', parts: [{ kind: 'text', text }] }] }))- setOptimistic(true)- setInput('')- // A built-in that opens a dialog in the TUI (`/rewind`, `/resume`, `/model`, …) is now on screen- // THERE, invisible from here, and the state still reads `done`: the next message's Enter would- // answer it. Go to the terminal — the same hand-off the toolbar's model/effort labels make.- // Only after the send was confirmed (`ok === true` above): nothing opened otherwise.- if (onShowTerminal && isInteractiveBuiltin(agentId, text)) {- onShowTerminal()- return- }- // A local command (`/model`, `!ls`) fires no hook: schedule ONE live tail read, one throttle- // interval out (claude writes the command record once the command ran), so its confirmation- // retires the working row instead of the 15 s timeout. A read already in flight defers it.- if (sentCommand(text)) {- if (commandReadTimerRef.current !== null) clearTimeout(commandReadTimerRef.current)- const fire = () => {- if (tailInFlightRef.current || olderInFlightRef.current) {- commandReadTimerRef.current = setTimeout(fire, CHAT_LIVE_RELOAD_MIN_MS)- return+ // A built-in that opens a dialog in the TUI (`/rewind`, `/resume`, `/model`, …) is now on screen+ // THERE, invisible from here, and the state still reads `done`: the next message's Enter would+ // answer it. Go to the terminal — the same hand-off the toolbar's model/effort labels make.+ // Only after the send was confirmed (`ok === true` above): nothing opened otherwise.+ if (onShowTerminal && isInteractiveBuiltin(agentId, text)) {+ onShowTerminal()+ return+ }+ // A local command (`/model`, `!ls`) fires no hook: schedule ONE live tail read, one throttle+ // interval out (claude writes the command record once the command ran), so its confirmation+ // retires the working row instead of the 15 s timeout. A read already in flight defers it.+ if (sentCommand(text)) {+ if (commandReadTimerRef.current !== null) clearTimeout(commandReadTimerRef.current)+ const fire = () => {+ if (tailInFlightRef.current || olderInFlightRef.current) {+ commandReadTimerRef.current = setTimeout(fire, CHAT_LIVE_RELOAD_MIN_MS)+ return+ }+ commandReadTimerRef.current = null+ loadRef.current(true)}- commandReadTimerRef.current = null- loadRef.current(true)+ commandReadTimerRef.current = setTimeout(fire, CHAT_LIVE_RELOAD_MIN_MS)}- commandReadTimerRef.current = setTimeout(fire, CHAT_LIVE_RELOAD_MIN_MS)+ } finally {+ sendingRef.current = false}}, [api, input, nodeId, agentId, onShowTerminal])diff --git a/src/renderer/nodes/ChatPanel.ux.test.tsx b/src/renderer/nodes/ChatPanel.ux.test.tsxindex 543b89937..a7b1e218a 100644--- a/src/renderer/nodes/ChatPanel.ux.test.tsx+++ b/src/renderer/nodes/ChatPanel.ux.test.tsx@@ -124,7 +124,7 @@ describe('ChatPanel composer keys', () => {await act(async () => {key(textarea(), { key: 'Enter' })})- expect(sendText).toHaveBeenCalledWith(NODE, 'hi')+ expect(sendText).toHaveBeenCalledWith(NODE, 'hi', { typed: true })})})diff --git a/src/shared/agents/config.capabilities.test.ts b/src/shared/agents/config.capabilities.test.tsindex 0fbc48743..01e426772 100644--- a/src/shared/agents/config.capabilities.test.ts+++ b/src/shared/agents/config.capabilities.test.ts@@ -26,6 +26,9 @@ import {agentLaunchProgram,resumeCommand,hasHooksOverSsh,+ CHAT_CAPABLE,+ TYPED_INPUT_CAPABLE,+ typesChatInput,LOCAL_ONLY_HOOK_AGENTS,reportsSessionEnd} from './config'@@ -455,3 +458,14 @@ describe('title read vs rename write', () => {expect(canRename('custom:abc')).toBe(false)})})++describe('typed chat input (TYPED_INPUT_CAPABLE)', () => {+ it('types only for claude — M-Enter is a measured newline there and unmeasured anywhere else', () => {+ expect(typesChatInput('claude')).toBe(true)+ for (const id of CHAT_CAPABLE.filter((a) => a !== 'claude')) expect(typesChatInput(id)).toBe(false)+ })++ it('is a subset of CHAT_CAPABLE: only the chat view types', () => {+ for (const id of TYPED_INPUT_CAPABLE) expect((CHAT_CAPABLE as readonly string[]).includes(id)).toBe(true)+ })+})diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.tsindex 0ea95f66a..b025652da 100644--- a/src/shared/agents/config.ts+++ b/src/shared/agents/config.ts@@ -316,6 +316,13 @@ export const CHAT_CAPABLE = ['claude', 'grok', 'gemini', 'codex', 'copilot', 'op// opencode has no remote leg either but is NOT here: its `unreadable` also means a failed LOCAL// `opencode export`, which Retry heals — the panel gives it its own copy (`exportError`) instead.export const CHAT_LOCAL_ONLY = ['gemini', 'copilot'] as const+// CHAT_CAPABLE agents whose chat-view prompts are TYPED as keystrokes instead of pasted+// (core/typed-input.ts): a multi-line paste is recorded by Claude Code as <pasted_content>, content+// its model is told may not be the user's own words. The typed path puts a line break in as tmux's+// M-Enter key — a newline in Claude Code (MEASURED, 2.1.281) but unmeasured in every other CLI,+// where it could just as well SUBMIT, splitting one prompt into several. So only claude; the rest+// keep the paste. An agent joins once someone has measured what its composer does with M-Enter.+export const TYPED_INPUT_CAPABLE = ['claude'] as const// Agents whose transcript CLAUDE's own resolver can locate and parse — the gate for everything that// goes through `resolveTranscript` (the find bar's index, the meter's mount-time rehydration).//@@ -537,6 +544,7 @@ export const canContextLink = (id: AgentId): boolean => includes(CONTEXT_LINK_CAexport const hasUsage = (id: AgentId): boolean => includes(USAGE_CAPABLE, id)export const canChat = (id: AgentId): boolean => includes(CHAT_CAPABLE, id)export const chatReadsLocalOnly = (id: AgentId): boolean => includes(CHAT_LOCAL_ONLY, id)+export const typesChatInput = (id: AgentId): boolean => includes(TYPED_INPUT_CAPABLE, id)/** Can CLAUDE's transcript resolver locate and parse this agent's conversation? Never widen this* to mean "can we read this agent" — see CLAUDE_TRANSCRIPT_READABLE. */export const readsClaudeShapedTranscript = (id: AgentId): boolean =>diff --git a/src/shared/types.ts b/src/shared/types.tsindex d7a515843..44a18623f 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1288,8 +1288,11 @@ export interface PtyApi {/** Send literal text into a session, by default followed by Enter (e.g. a slash command).* `opts.enter: false` writes the text without submitting it (dictation's Insert). Returns* false if unavailable; `pasted-not-submitted` means input was accepted but Enter was not- * confirmed written. Surface it without automatically resending. True is not an app receipt. */- sendText(persistKey: string, text: string, opts?: { enter?: boolean }): Promise<TextDeliveryResult>+ * confirmed written. Surface it without automatically resending. True is not an app receipt.+ * `opts.typed` delivers as keystrokes rather than a bracketed paste, so an agent CLI records the+ * text as TYPED — the ⌘M chat view's prompts (core/typed-input.ts). tmux backends only;+ * elsewhere it is ignored and the paste path runs. */+ sendText(persistKey: string, text: string, opts?: { enter?: boolean; typed?: boolean }): Promise<TextDeliveryResult>/** Is tmux available on this host (else the silent plain-shell fallback), plus a suggested* install command for the "tmux not found" banner. */tmuxStatus(): Promise<TmuxStatus>