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.

Merge origin/main into fix/chat-type-not-paste; route typed sends through sendChatPrompt

review7f5c95b9750a
diff --cc CLAUDE.md
index ef1965189,cb49604f9..609eaeccd
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@@ -3353,6 -3410,17 +3410,31 @@@ command-bearing opens; this does not ad
store at send time, not only at render. Same trap as the in-place restart's `/exit`. The bar's ↻
reloads on demand (beside the empty state's Retry), since a session whose hooks never report
`working` never takes the turn-finish reload.
++ **A chat prompt is TYPED for claude, never pasted** (`core/typed-input.ts`, `TYPED_INPUT_CAPABLE`).
++ Claude Code records a multi-line paste as `<pasted_content>`, which its model is told may not be
++ the user's words; typed text (lines joined by tmux's `M-Enter`, measured on 2.1.281) is recorded
++ as plain user text. Three rules: (1) **core decides it from the agent id** inside
++ `sendChatPrompt` (`typedFor`), never a renderer-sent flag — every other agent and every other
++ `sendText` caller keeps the paste; (2) **every write into a pane is serialized per pane**
++ (`PtyManager.serializePaneWrite`, wrapping `sendText` AND `sendEnvelope`): a typed send takes
++ seconds (one paste per line, then a settle wait before Enter), and an agent message, a reminder
++ or dictation arriving in that window would otherwise land between its lines and be submitted as
++ part of it; (3) **the screen is checked again right before the Enter** (`TypedSurface.canSubmit`):
++ the dialog check `sendChatPrompt` makes is seconds old by then, and an Enter into a dialog that
++ opened meanwhile would ANSWER it — the text stays in the composer and the caller hears
++ `pasted-not-submitted`. The panel ignores a second Enter while a send is in flight (the draft is
++ cleared only once it lands).
+ **The agent's OWN dialogs are read off the screen** (`shared/agents/claude-screen.ts`, claude
+ only — `SCREEN_DIALOG_READABLE`). The folder-trust prompt, `/model` and one-time setup questions
+ fire NO hook, so the state gate above reads `done` while one owns the keyboard, and a paste into
+ it was swallowed while its Enter answered the dialog (the trust prompt's default is "No, exit").
+ A send therefore goes through `pty.sendChatPrompt`, where core captures the pane first and
+ refuses (`ChatPromptBlocked`, nothing written, the draft kept) when the bottom of the screen is a
+ dialog footer or has no input box; an empty or unreadable capture is NOT evidence and sends as
+ before. A LOCAL pane is also polled every 2 s while the view is visible, to disable the composer
+ and show the dialog's lines; SSH and relay panes are not polled (a round trip per read) and rely
+ on the send-time check. Another CLI's layout would read as a permanent dialog, so an agent joins
+ the list only with its own measured reader.
**Live progress (2026-09).** While the agent works, a `role=status` row closes the thread (the ONE
spinner + the placeholder's own "<agent> is working…"/"waiting for an answer" sentence; optimistic
right after a send, bounded by `CHAT_OPTIMISTIC_WORKING_MS`), and every hook event re-reads the
diff --cc src/core/pty-manager.chat-prompt.test.ts
index 000000000,2ad70ff5e..cfad376f5
mode 000000,100644..100644
--- a/src/core/pty-manager.chat-prompt.test.ts
+++ b/src/core/pty-manager.chat-prompt.test.ts
@@@ -1,0 -1,78 +1,137 @@@
+ // `PtyManager.sendChatPrompt` — the ⌘M chat view's send. For an agent whose screen we can read
+ // (claude), the pane's screen is checked BEFORE anything is written: Claude Code's own dialogs fire
+ // no hook, and a paste into one swallowed the text while its Enter answered the dialog. The screen
+ // reader itself is tested in shared/agents/claude-screen.test.ts; this file pins the dispatch.
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+ import { initPlatform, resetPlatformForTests } from './platform'
+ import { fakePlatform } from './platform-fake'
+
+ vi.mock('node-pty', () => ({ spawn: () => ({}) }))
+
+ const NODE = 'node-1'
+ const RULE = '─'.repeat(80)
+ const IDLE = [RULE, '❯ ', RULE, ' ? for shortcuts'].join('\n')
+ const TRUST = [RULE, ' Accessing workspace:', ' ❯ No, exit', ' Yes, I trust this folder', ' Enter to confirm · Esc to cancel'].join('\n')
+
+ async function manager(screen: string) {
+ const { PtyManager } = await import('./pty-manager')
+ const mgr = new PtyManager()
+ const captureSession = vi.spyOn(mgr, 'captureSession').mockResolvedValue(screen)
+ const sendText = vi.spyOn(mgr, 'sendText').mockResolvedValue(true)
+ return { mgr, captureSession, sendText }
+ }
+
+ describe('PtyManager.sendChatPrompt', () => {
+ beforeEach(() => {
+ vi.resetModules()
+ initPlatform(fakePlatform())
+ })
+ afterEach(() => {
+ resetPlatformForTests()
+ })
+
+ it('sends a claude prompt when its input box is on screen', async () => {
+ const { mgr, sendText } = await manager(IDLE)
+
+ const result = await mgr.sendChatPrompt(NODE, 'hello', 'claude')
+
+ expect(result).toBe(true)
- expect(sendText).toHaveBeenCalledWith(NODE, 'hello')
++ // Typed, not pasted (core/typed-input.ts): decided here from the agent id, not by the renderer.
++ expect(sendText).toHaveBeenCalledWith(NODE, 'hello', { typedFor: 'claude' })
+ })
+
+ it('refuses before writing anything when a claude dialog owns the screen, and returns its text', async () => {
+ const { mgr, sendText } = await manager(TRUST)
+
+ const result = await mgr.sendChatPrompt(NODE, 'hello', 'claude')
+
+ expect(sendText).not.toHaveBeenCalled()
+ expect(result).toEqual({ blocked: 'screen', dialog: expect.stringContaining('No, exit') })
+ })
+
+ it('refuses with no dialog text when the input box is gone (a shell owns the pane)', async () => {
+ const { mgr, sendText } = await manager('user@host ~ % ')
+
+ const result = await mgr.sendChatPrompt(NODE, 'hello', 'claude')
+
+ expect(sendText).not.toHaveBeenCalled()
+ expect(result).toEqual({ blocked: 'screen', dialog: null })
+ })
+
+ it('an empty capture is not evidence of a dialog: the prompt is sent as before', async () => {
+ const { mgr, sendText } = await manager('')
+
+ const result = await mgr.sendChatPrompt(NODE, 'hello', 'claude')
+
+ expect(result).toBe(true)
- expect(sendText).toHaveBeenCalledWith(NODE, 'hello')
++ expect(sendText).toHaveBeenCalledWith(NODE, 'hello', { typedFor: 'claude' })
+ })
+
+ it('never reads the screen of an agent without a measured reader', async () => {
+ const { mgr, captureSession, sendText } = await manager(TRUST)
+
+ const result = await mgr.sendChatPrompt(NODE, 'hello', 'codex')
+
+ expect(captureSession).not.toHaveBeenCalled()
+ expect(result).toBe(true)
+ expect(sendText).toHaveBeenCalledWith(NODE, 'hello')
+ })
+ })
++
++describe('PtyManager — one write into a pane at a time', () => {
++ beforeEach(() => {
++ vi.resetModules()
++ initPlatform(fakePlatform())
++ })
++ afterEach(() => {
++ resetPlatformForTests()
++ })
++
++ // A typed chat prompt takes seconds; a paste (an agent message, dictation) arriving meanwhile
++ // would land between its lines and be submitted as part of it.
++ it('a send into a pane waits for the one already writing there; another pane does not', async () => {
++ const { PtyManager } = await import('./pty-manager')
++ const mgr = new PtyManager()
++ const order: string[] = []
++ let release!: () => void
++ const gate = new Promise<void>((r) => (release = r))
++ const now = vi
++ .spyOn(mgr as unknown as { sendTextNow: (k: string, t: string) => Promise<boolean> }, 'sendTextNow')
++ .mockImplementation(async (key: string, text: string) => {
++ order.push(`start ${key} ${text}`)
++ if (text === 'slow') await gate
++ order.push(`end ${key} ${text}`)
++ return true
++ })
++ vi.spyOn(mgr as unknown as { sendEnvelopeNow: (k: string, e: string) => Promise<boolean> }, 'sendEnvelopeNow')
++ .mockImplementation(async (key: string, env: string) => {
++ order.push(`envelope ${key} ${env}`)
++ return true
++ })
++
++ const first = mgr.sendText(NODE, 'slow')
++ const second = mgr.sendText(NODE, 'after')
++ const envelope = mgr.sendEnvelope(NODE, 'msg')
++ const other = mgr.sendText('node-2', 'elsewhere')
++ await other
++ expect(order).toEqual(['start node-1 slow', 'start node-2 elsewhere', 'end node-2 elsewhere'])
++
++ release()
++ await Promise.all([first, second, envelope])
++ expect(order.slice(3)).toEqual(['end node-1 slow', 'start node-1 after', 'end node-1 after', 'envelope node-1 msg'])
++ expect(now).toHaveBeenCalledTimes(3)
++ })
++
++ it('a failed write does not block the next one', async () => {
++ const { PtyManager } = await import('./pty-manager')
++ const mgr = new PtyManager()
++ vi.spyOn(mgr as unknown as { sendTextNow: (k: string, t: string) => Promise<boolean> }, 'sendTextNow')
++ .mockImplementationOnce(async () => {
++ throw new Error('boom')
++ })
++ .mockImplementationOnce(async () => true)
++
++ await expect(mgr.sendText(NODE, 'a')).rejects.toThrow('boom')
++ await expect(mgr.sendText(NODE, 'b')).resolves.toBe(true)
++ })
++})
diff --cc src/core/pty-manager.ts
index 56aeee960,83bf106ad..7697903a5
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@@ -32,9 -33,10 +33,12 @@@ import
remoteTmuxPtyArgs,
type RemoteSessionEnv,
remotePasteDelivery,
+ remoteTypedArgs,
+ remoteTmuxEnterArgs,
remoteCapturePaneArgs,
+ remoteCaptureVisibleArgs,
+ remoteTmuxWatcherArgs,
+ remoteWindowSizeArgs,
remotePaneCommandArgs,
remotePaneCwdArgs,
remoteSessionAgeArgs,
@@@ -140,7 -153,8 +158,9 @@@ import { clearNode as clearNodeAgentSta
import {
capabilityAgentId,
hasSharedIdentity,
+ readsScreenDialogs,
setCustomAgentBaseResolver,
++ typesChatInput,
vanillaEnvStripPattern,
type AgentId
} from '../shared/agents/config'
@@@ -4945,20 -5323,10 +5348,56 @@@ 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 }
++ opts?: { enter?: boolean; typedFor?: AgentId }
++ ): Promise<TextDeliveryResult> {
++ return this.serializePaneWrite(persistKey, () => this.sendTextNow(persistKey, text, opts))
++ }
++
++ /** Per-pane write chain: see `serializePaneWrite`. */
++ private paneWrites = new Map<string, Promise<unknown>>()
++
++ /**
++ * Run one write into a pane only after every earlier write into the SAME pane has finished.
++ * A typed chat prompt (core/typed-input.ts) takes seconds — one tmux paste per line, then a
++ * settle wait before its Enter — and a paste arriving in that window (an agent message, a
++ * reminder, dictation) would land between its lines and be submitted as part of it. So every
++ * `sendText` and `sendEnvelope` queues here instead of interleaving. Each write is itself bounded
++ * (process timeouts, a fixed number of settle polls), so a slow one delays the next, never wedges
++ * it; a failed one does not poison the chain.
++ */
++ private serializePaneWrite<T>(persistKey: string, run: () => Promise<T>): Promise<T> {
++ const key = sessionName(persistKey)
++ const prev = this.paneWrites.get(key) ?? Promise.resolve()
++ const next = prev.then(run, run)
++ const settled = next.then(
++ () => undefined,
++ () => undefined
++ )
++ this.paneWrites.set(key, settled)
++ void settled.then(() => {
++ if (this.paneWrites.get(key) === settled) this.paneWrites.delete(key)
++ })
++ return next
++ }
++
++ private async sendTextNow(
++ persistKey: string,
++ text: string,
++ opts?: { enter?: boolean; typedFor?: AgentId }
+ ): Promise<TextDeliveryResult> {
const enter = opts?.enter ?? true
const 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)
++ // `typedFor` (the ⌘M chat view, set only by `sendChatPrompt`): 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?.typedFor !== undefined && enter) {
++ const typed = await this.sendTyped(persistKey, text, opts.typedFor)
+ 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)
@@@ -4996,62 -5364,24 +5435,87 @@@
}
}
- /** 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.
++ * Runs inside `serializePaneWrite`, so nothing else writes into the pane while it types.
++ *
++ * Typing takes seconds, so `sendChatPrompt`'s dialog check (made before the first keystroke) can
++ * be stale by the time the Enter goes: for an agent whose screen we can read, the screen is
++ * checked again right before the Enter, and a dialog that opened meanwhile gets no Enter — the
++ * text stays in the composer and the caller hears `pasted-not-submitted`.
+ */
- private async sendTyped(persistKey: string, text: string): Promise<TextDeliveryResult | null> {
++ private async sendTyped(persistKey: string, text: string, agentId: AgentId): 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) =>
+ runTypedScript(localTypedArgs(TMUX_SOCKET, target, pasteBufferName()), stdin, localTypedEnv(tmuxPath))
+ 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)),
++ // An empty capture is not evidence of a dialog (the `sendChatPrompt` rule).
++ canSubmit: async () => {
++ if (!readsScreenDialogs(agentId)) return true
++ const screen = await this.captureSession(persistKey)
++ return screen === '' || screenGate(screen) === null
++ },
+ submit: () => ok(submit)
+ })
+ } catch {
+ return 'pasted-not-submitted'
- } finally {
- this.typedInFlight.delete(target)
+ }
+ }
+
+ /**
+ * A prompt from the ⌘M chat view. For an agent whose screen we can read (`readsScreenDialogs`),
+ * refused before anything is written when the agent's own UI owns the keyboard: such dialogs
+ * (the folder-trust prompt, `/model`, one-time setup questions) fire no hook, so the chat view's
+ * state gate cannot see them, and a paste into one swallowed the text while its Enter answered
+ * the dialog. An empty capture (no session, a failed read) is not evidence of a dialog: the
- * prompt is sent exactly as before. There is no second look before the Enter — `sendText`
- * submits in the same step. Everything else is `sendText`, unchanged.
++ * prompt is sent exactly as before. A PASTED prompt submits in the same step; a TYPED one
++ * (`typesChatInput`, core/typed-input.ts) checks the screen again right before its Enter.
++ * Everything else is `sendText`, unchanged.
+ */
+ async sendChatPrompt(persistKey: string, text: string, agentId: string): Promise<ChatPromptResult> {
+ if (readsScreenDialogs(agentId)) {
+ const screen = await this.captureSession(persistKey)
+ const refused = screen === '' ? null : screenGate(screen)
+ if (refused !== null) return refused
+ }
- return this.sendText(persistKey, text)
++ // Typed, not pasted, for an agent whose composer is MEASURED to take M-Enter as a newline:
++ // Claude Code records a multi-line paste as <pasted_content>, which its model is told may not
++ // be the user's own words. Decided here from the agent id — never by a renderer-sent flag.
++ return typesChatInput(agentId) ? this.sendText(persistKey, text, { typedFor: agentId }) : this.sendText(persistKey, text)
+ }
+
/**
* 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.
@@@ -5390,6 -5720,6 +5854,10 @@@
* (`buildEnvelope` can never return '', so this is a guard against a future caller, not a path.)
*/
async sendEnvelope(persistKey: string, envelope: string, expected?: PaneOwner): Promise<boolean> {
++ return this.serializePaneWrite(persistKey, () => this.sendEnvelopeNow(persistKey, envelope, expected))
++ }
++
++ private async sendEnvelopeNow(persistKey: string, envelope: string, expected?: PaneOwner): Promise<boolean> {
if (envelope.length === 0) return false
const live = this.liveSessionForPersistKey(persistKey)
if (this.isZellij(persistKey, live)) return false
diff --cc src/core/remote-ssh/control-master.ts
index 947ebc612,fdf071f12..e0bde801d
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@@ -18,9 -18,10 +18,11 @@@ 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'
+ import { VISIBLE_CAPTURE_FORMAT, exactPaneTarget } from '../watch-link/capture-route'
+ import { WATCHER_CLIENT_FLAGS, WINDOW_SIZE_FORMAT } from '../watch-link/watcher-client'
// Dependency-free (no node-pty): safe to import from these pure builders.
/** Dedicated remote tmux socket so an SSH project never collides with the user's own tmux. */
diff --cc src/core/typed-input.test.ts
index 386687af4,000000000..269cbbe74
mode 100644,000000..100644
--- a/src/core/typed-input.test.ts
+++ b/src/core/typed-input.test.ts
@@@ -1,146 -1,0 +1,166 @@@
+import { describe, expect, it, vi } from 'vitest'
+import {
+ TYPED_TAB,
+ localTypedArgs,
+ localTypedEnv,
+ 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('withholds the Enter when canSubmit says something now owns the keyboard', async () => {
++ const surface = { ...fakeSurface({ lag: 0 }), canSubmit: vi.fn(async () => false) }
++
++ const result = await typeThenSubmitWhenSettled('hello', surface, noWait)
++
++ expect(result).toBe('pasted-not-submitted')
++ expect(surface.canSubmit).toHaveBeenCalledTimes(1)
++ expect(surface.submit).not.toHaveBeenCalled()
++ })
++
++ it('asks canSubmit only once the text is on screen, then submits', async () => {
++ const surface = { ...fakeSurface({ lag: 1 }), canSubmit: vi.fn(async () => true) }
++
++ const result = await typeThenSubmitWhenSettled('hello', surface, noWait)
++
++ expect(result).toBe(true)
++ expect(surface.canSubmit).toHaveBeenCalledTimes(1)
++ expect(surface.submit).toHaveBeenCalledTimes(1)
++ })
++
+ 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([])
+ })
+})
+
+describe('localTypedArgs / localTypedEnv', () => {
+ it('keeps the tmux path out of the shell command: it rides the environment', () => {
+ const args = localTypedArgs('node-terminal', 'nt-a', 'nt-paste-0123456789ab')
+
+ const env = localTypedEnv("/opt/it's here/tmux", { HOME: '/h' })
+
+ expect(args).toHaveLength(2)
+ expect(args[1]).toContain('"$NT_TYPED_TMUX" -L node-terminal')
+ expect(env).toEqual({ HOME: '/h', NT_TYPED_TMUX: "/opt/it's here/tmux" })
+ })
+})
diff --cc src/core/typed-input.ts
index 81d76766e,000000000..53551b217
mode 100644,000000..100644
--- a/src/core/typed-input.ts
+++ b/src/core/typed-input.ts
@@@ -1,157 -1,0 +1,166 @@@
+import type { TextDeliveryResult } from '../shared/text-delivery'
+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 FIXED shell word that runs tmux
+ * (`"$NT_TYPED_TMUX"` locally, see `localTypedArgs`; `tmux` on an SSH host) — never a path spliced in.
+ * `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')
+}
+
+/** Where a local run's script finds tmux (`localTypedEnv`). */
+export const TYPED_TMUX_ENV = 'NT_TYPED_TMUX'
+
+/**
+ * The same script, as `sh -c` argv for a local run (stdin carries the text). Nothing in it comes
+ * from outside: the tmux path is found by a PATH lookup, so it reaches the script through the
+ * environment (`localTypedEnv`), never as script text or an argument to the shell. (CodeQL's
+ * indirect command-line rule flagged it both spliced in through `posixQuote` and passed as `$1`.)
+ */
+export function localTypedArgs(socket: string, target: string, buffer: string): string[] {
+ return ['-c', typedInputScript(`"$${TYPED_TMUX_ENV}"`, socket, target, buffer)]
+}
+
+/** The environment for `localTypedArgs`: this process's, plus the tmux the script runs. */
+export function localTypedEnv(tmuxPath: string, base: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
+ return { ...base, [TYPED_TMUX_ENV]: tmuxPath }
+}
+
+/** 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>
++ /**
++ * Asked right before the Enter. Typing takes seconds, so a check made before the first keystroke
++ * can be stale: false means something now owns the keyboard (an agent dialog that opened
++ * meanwhile), and the Enter — which would ANSWER it — is not sent. Absent = always submit.
++ */
++ canSubmit?(): 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'
++ if (shown && seenOnce) {
++ if (surface.canSubmit && !(await surface.canSubmit())) return 'pasted-not-submitted'
++ return (await surface.submit()) ? true : 'pasted-not-submitted'
++ }
+ seenOnce = shown
+ }
+ return 'pasted-not-submitted'
+}
diff --cc src/renderer/nodes/ChatPanel.tsx
index f1e2cc823,83fc38b88..9e704c3fc
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@@ -673,78 -753,70 +753,83 @@@ 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 sendOnce = 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 (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)
+ 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
+ }
+ // Through core's chat-prompt path: where it can read the agent's screen, it refuses before
+ // writing anything when the agent's own dialog owns the keyboard (such dialogs fire no hook).
+ const ok = await api.pty.sendChatPrompt(nodeId, text, agentId)
+ if (isChatPromptBlocked(ok)) {
+ // Nothing reached the pane: the draft stays for a resend once the dialog is answered.
+ setScreenBlock({ kind: ok.dialog === null ? 'no-prompt' : 'dialog', text: ok.dialog, live: pollScreen })
+ return
+ }
+ if (ok === 'pasted-not-submitted') {
+ window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message: TEXT_NOT_SUBMITTED } }))
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
- }
- commandReadTimerRef.current = null
- loadRef.current(true)
+ 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.
+ setScreenBlock(null)
+ 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
}
- commandReadTimerRef.current = setTimeout(fire, CHAT_LIVE_RELOAD_MIN_MS)
+ commandReadTimerRef.current = null
+ loadRef.current(true)
}
+ commandReadTimerRef.current = setTimeout(fire, CHAT_LIVE_RELOAD_MIN_MS)
+ }
+ }, [api, input, nodeId, agentId, onShowTerminal, pollScreen])
++ // A send in flight. A typed send (core/typed-input.ts, claude) takes a moment — core waits for the
++ // pane to show the text before it presses Enter — and the draft is only cleared once it lands, so
++ // a second Enter in that window would send the same prompt twice. Ignore it instead.
++ const sendingRef = useRef(false)
++ const send = useCallback(async () => {
++ if (sendingRef.current) return
++ sendingRef.current = true
++ try {
++ await sendOnce()
+ } finally {
+ sendingRef.current = false
+ }
- }, [api, input, nodeId, agentId, onShowTerminal])
++ }, [sendOnce])
// The scheduled command read belongs to THIS transcript and this mount.
useEffect(
diff --cc src/shared/agents/config.capabilities.test.ts
index 01e426772,dbf099e32..64373b0dc
--- a/src/shared/agents/config.capabilities.test.ts
+++ b/src/shared/agents/config.capabilities.test.ts
@@@ -26,9 -26,7 +26,10 @@@ import
agentLaunchProgram,
resumeCommand,
hasHooksOverSsh,
+ CHAT_CAPABLE,
+ TYPED_INPUT_CAPABLE,
+ typesChatInput,
+ readsScreenDialogs,
LOCAL_ONLY_HOOK_AGENTS,
reportsSessionEnd
} from './config'
@@@ -459,13 -457,9 +460,20 @@@ describe('title read vs rename write',
})
})
+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)
+ })
+})
++
+ describe('readsScreenDialogs — whose own dialogs the chat view can see on screen', () => {
+ it('is claude only: its reader would read every other CLI\'s screen as a permanent dialog', () => {
+ expect(readsScreenDialogs('claude')).toBe(true)
+ for (const id of BUILTIN_AGENT_IDS.filter((a) => a !== 'claude')) expect(readsScreenDialogs(id)).toBe(false)
+ })
+ })
diff --cc src/shared/agents/config.ts
index b025652da,c740810cc..f699d8e9b
--- a/src/shared/agents/config.ts
+++ b/src/shared/agents/config.ts
@@@ -544,7 -544,7 +551,8 @@@ export const canContextLink = (id: Agen
export 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)
+ export const readsScreenDialogs = (id: AgentId): boolean => includes(SCREEN_DIALOG_READABLE, 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 =>