The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
A message is typed only into the engine's own composer, and its Enter only if the composer is still there (#837)
Dee3e9a1d90cdc0
diff --git a/cli/e2e/composer.e2e.ts b/cli/e2e/composer.e2e.tsnew file mode 100644index 000000000..3bbf86393--- /dev/null+++ b/cli/e2e/composer.e2e.ts@@ -0,0 +1,116 @@+/**+ * A message is typed only into the engine's own composer, for Claude Code and Codex: a screen of theirs+ * the daemon has no name for is refused, never typed into, and so is a list of suggestions open over the+ * composer, whose Enter picks a row. The composer is typed into while a turn runs (the engines queue+ * it), in a narrow pane, and with CJK and emoji in the message. The fake engines draw the composers the+ * engines draw (e2e/harness/fakeEngine.mjs): Claude Code's ruled box, Codex's `›` row and footer.+ */+import { mkdirSync } from 'node:fs'+import { join } from 'node:path'+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'+import { LocalClient, type Frame } from './harness/client.js'+import { IsolatedDaemon, until } from './harness/daemon.js'++type Engine = 'claude' | 'codex'+const engines: Engine[] = ['claude', 'codex']+const name = (engine: Engine) => (engine === 'claude' ? 'Claude Code' : 'Codex')++const row = async (client: LocalClient, agentId: string) =>+ ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents)+ .find((agent) => agent.id === agentId)+async function create(daemon: IsolatedDaemon, client: LocalClient, engine: Engine, folder: string): Promise<Record<string, any>> {+ const cwd = join(daemon.projectsDir, folder)+ mkdirSync(cwd, { recursive: true })+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)+ expect(created.error, `${folder}: ${JSON.stringify(created)}`).toBeUndefined()+ return until(`${folder} to bind its conversation`, async () => {+ const agent = await row(client, created.agent.id)+ return agent?.sessionId && agent.status === 'active' ? agent : null+ }, 60_000, 500)+}+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId+async function turn(client: LocalClient, agentId: string, content: string): Promise<void> {+ const started = client.next(isTurn('turn_started', agentId), 45_000, `turn_started (${content})`)+ const ended = client.next(isTurn('turn_ended', agentId), 45_000, `turn_ended (${content})`)+ client.send('message', { agentId, content })+ expect((await started).payload?.userMessage).toBe(content)+ await ended+}+const refusal = (client: LocalClient, agentId: string, ms: number) =>+ client.next((frame) => frame.type === 'error' && frame.agentId === agentId, ms, 'the refusal')++describe('a message goes only into the engine\'s own composer', () => {+ let daemon: IsolatedDaemon | undefined+ afterEach(async () => { await daemon?.close(); daemon = undefined })+ const fresh = async () => {+ const d = await IsolatedDaemon.create()+ daemon = d+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })+ await d.start()+ return d+ }++ it.each(engines)('%s: a screen the daemon has no name for is refused, never typed into; closed, the message goes through', async (engine) => {+ // Claude Code's settings take a paste as a search and Enter changes the highlighted setting; Codex's+ // agent command center opens the highlighted task on Enter.+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, engine, `unnamed-${engine}`)+ await turn(client, agent.id, engine === 'claude' ? '!config' : '!center')+ const drawn = engine === 'claude' ? 'Search settings' : 'Agent command center'+ await until('the screen to be drawn', async () => (await d.capture(agent.tmuxPane)).includes(drawn) || null, 15_000, 250)+ const from = client.frames.length+ const refused = refusal(client, agent.id, 40_000)+ client.send('message', { agentId: agent.id, content: 'auto' })+ expect(String((await refused).payload?.message)).toBe(`${name(engine)} isn't showing its prompt; finish what's on its screen in its terminal, then send the message again.`)+ const pane = await d.capture(agent.tmuxPane)+ expect(pane).not.toContain('changed)')+ expect(pane).not.toContain('(opened')+ expect(client.frames.slice(from).some(isTurn('turn_started', agent.id))).toBe(false)+ await d.tmux.run('send-keys', '-t', agent.tmuxPane, 'Escape')+ await until('the composer to be back', async () => !(await d.capture(agent.tmuxPane)).includes(drawn) || null, 15_000, 250)+ await turn(client, agent.id, 'auto')+ client.close()+ })++ it.each(engines)('%s: a /command typed in the terminal with its suggestions open refuses a message; put away, the message goes through', async (engine) => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, engine, `popup-${engine}`)+ await d.tmux.run('send-keys', '-t', agent.tmuxPane, '/mo')+ await until('the suggestions to be drawn', async () => (await d.capture(agent.tmuxPane)).includes('Set the AI model') || null, 15_000, 250)+ const refused = refusal(client, agent.id, 15_000)+ client.send('message', { agentId: agent.id, content: 'what changed?' })+ expect(String((await refused).payload?.message)).toBe(`${name(engine)} has a list of suggestions open in its prompt, where Enter would pick one. Close it with Esc in its terminal, then send the message again.`)+ await d.tmux.run('send-keys', '-t', agent.tmuxPane, 'Escape', 'BSpace', 'BSpace', 'BSpace')+ await until('the suggestions to be put away', async () => !(await d.capture(agent.tmuxPane)).includes('Set the AI model') || null, 15_000, 250)+ await turn(client, agent.id, 'what changed?')+ client.close()+ })++ it.each(engines)('%s: a message sent while a turn runs is typed, and the engine takes it next', async (engine) => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, engine, `busy-${engine}`)+ const first = client.next(isTurn('turn_started', agent.id), 45_000, 'the first turn')+ client.send('message', { agentId: agent.id, content: '!slow 4000' })+ await first+ const second = client.next((frame) => isTurn('turn_started', agent.id)(frame) && frame.payload?.userMessage === 'and then this', 45_000, 'the second turn')+ client.send('message', { agentId: agent.id, content: 'and then this' })+ await second+ client.close()+ })++ it.each(engines)('%s: a message in CJK and emoji goes through in a narrow pane', async (engine) => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, engine, `narrow-${engine}`)+ await d.tmux.run('resize-window', '-t', agent.tmuxPane, '-x', '36')+ await until('the composer to be redrawn narrow', async () => {+ const pane = await d.capture(agent.tmuxPane)+ return pane.split('\n').some((line) => line.length > 0 && line.length <= 36 && (line.includes('─'.repeat(36)) || line.startsWith('›'))) || null+ }, 15_000, 250)+ await turn(client, agent.id, '修复登录 🎉 now')+ client.close()+ })+})diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjsindex aa3126cac..c6981bcaf 100644--- a/cli/e2e/harness/fakeEngine.mjs+++ b/cli/e2e/harness/fakeEngine.mjs@@ -25,7 +25,10 @@// under its composer, `!browse` (Codex) leaves Codex browsing its transcript in its default fullscreen// mode, and `!browse scrollback` in its scrollback mode, `!transcript` (Claude Code) leaves it in its// transcript view, as ctrl+o does, `!overlay` (Codex) in its transcript overlay, as ctrl+t does in its-// scrollback mode, `!search` searching its prompt history, as ctrl+r does, `!exit` ends the process.+// scrollback mode, `!search` searching its prompt history, as ctrl+r does, `!config` (Claude Code) in its+// settings and `!center` (Codex) in its agent command center, screens the daemon has no name for,+// `!permitnext <command>` keeps its turn open and asks permission to run the command the moment a+// message is pasted, before its Enter (a request arriving mid-turn), `!exit` ends the process.// Everything else is echoed as the answer.//// Which release is installed is the config's business, so a test can update an engine in place by@@ -305,18 +308,29 @@ export async function run(engine, config) {// above it, and it is drawn again below. The fake used to leave a submitted prompt on its composer line// until the answer came, which the daemon reads as a draft never sent: it pressed Enter again for it// (sessionInput.ts) whenever the turn was slow to start, as one is behind its UserPromptSubmit hook.+ //+ // Drawn as each engine draws its own, as the daemon reads it to know a message can be typed there+ // (lib/composerScreen.ts): Claude Code 2.1.289's box ruled above and below (its `borderStyle: "round"`+ // with no sides), `❯` and the prompt or a dim example in it, and its footer row under the box+ // (`? for shortcuts` while the prompt is empty); Codex 0.160's blank row, bold `›` and the draft or its+ // dim placeholder, a blank row, and its status line (tui/src/bottom_pane, snapshot `empty`). A draft's+ // further lines are indented under the first.let buffer = ''let composerRows = 0- // What Codex 0.160 draws under its empty composer in the two states the daemon must read off the pane- // (tui/src/bottom_pane): a goal it is pursuing, on the right of its status line, and the footer of- // its transcript browser, with the composer dimmed whole. Null draws the composer alone, as before.- // Browsing in its scrollback mode is a transcript pager over the whole pane instead, on the alternate- // screen, with the same footer on its last row (pager_overlay/transcript.rs).+ // What else is drawn there (`bottom`): Codex's footer pursuing a goal (on the right of its status line),+ // the footer of its transcript browser with the composer dimmed whole, a search through the prompt+ // history (the match in the composer, the search under it), a screen of the engine's own in the+ // composer's place (`screen`), and the screens drawn over the whole pane instead (`pager`, on the+ // alternate screen): Codex's transcript browser and overlay in its scrollback mode, Claude Code's+ // transcript view.let bottom = null- const placeholder = '\x1b[1m›\x1b[0m \x1b[2mAsk Codex to do anything\x1b[0m'- const goalBottom = (goal) => ({ composer: placeholder, footer: ` gpt-6 high · ${cwd} \x1b[35m${goal}\x1b[0m` })+ let dialog = null+ const columns = () => Math.max(20, process.stdout.columns || 80)+ // Cut to the pane's width, as Codex fits its status line to one row.+ const statusLine = () => ` \x1b[2m${`gpt-6 high · ${cwd}`.slice(0, columns() - 3)}\x1b[0m`+ const goalBottom = (goal) => ({ footer: ` gpt-6 high · ${cwd} \x1b[35m${goal}\x1b[0m` })const browsingFooter = '\x1b[36mBrowsing transcript\x1b[0m\x1b[2m · \x1b[0m↑↓/jk\x1b[2m scroll · \x1b[0m←→/hl\x1b[2m prompts · \x1b[0m↵\x1b[2m rewind · \x1b[0mesc\x1b[2m back\x1b[0m'- const browsingBottom = { composer: '\x1b[2m› Ask Codex to do anything\x1b[0m', footer: browsingFooter, browsing: true }+ const browsingBottom = { dim: true, footer: browsingFooter, browsing: true }const pagerBottom = (prompt, answer) => ({ browsing: true, pager: `\x1b[?1049h\x1b[H\x1b[2J\x1b[2m/ T R A N S C R I P T ${'/ '.repeat(30)}\x1b[0m`+ `\r\n\x1b[7m› ${prompt}\x1b[0m\r\n\r\n\x1b[2m•\x1b[0m ${answer}\x1b[999;1H${browsingFooter}` })// Claude Code's transcript view (ctrl+o, 2.1.289): the conversation over the whole pane, its prompt@@ -328,20 +342,110 @@ export async function run(engine, config) {const overlayBottom = (prompt, answer) => ({ overlay: true, prompt, answer, pager: `\x1b[?1049h\x1b[H\x1b[2J\x1b[2m/ T R A N S C R I P T ${'/ '.repeat(30)}\x1b[0m`+ `\r\n\r\n\x1b[1m›\x1b[0m ${prompt}\r\n\r\n\x1b[2m•\x1b[0m ${answer}\x1b[997;1H\x1b[2mCtrl+Space select\x1b[0m`+ '\x1b[998;1H\x1b[2m ↑/↓ to scroll · pgup/pgdn to page · home/end to jump\x1b[0m\x1b[999;1H\x1b[2m q close · f3 find · esc browse prompts\x1b[0m' })+ // Screens of the engines' own, drawn in the composer's place, that the daemon has no name for: Claude+ // Code's settings (/config, 2.1.289: its Settings tabs, `Search settings…`, and its rows, where Enter+ // and Space change the highlighted setting) and Codex's agent command center (0.160, snapshot+ // `agents_overview_recent_sessions`, where Enter opens the highlighted task). Esc closes either.+ const SETTINGS = [['Auto-compact', 'true'], ['Show tips', 'true'], ['Thinking mode', 'true']]+ const configScreen = () => {+ const state = { query: '', config: true }+ state.screen = () => {+ const rows = SETTINGS.filter(([name]) => name.toLowerCase().includes(state.query.toLowerCase()))+ return [`\x1b[38;5;153m${'─'.repeat(columns())}\x1b[39m`,+ ' \x1b[1m\x1b[38;5;153mSettings:\x1b[0m \x1b[7m Status \x1b[0m Config Usage \x1b[2m(←/→ or tab to cycle)\x1b[0m', '',+ ` ⌕ ${state.query || '\x1b[2mSearch settings…\x1b[0m'}`, '',+ ...rows.map(([name, value], index) => `${index === 0 ? ' \x1b[38;5;153m❯\x1b[39m' : ' '} ${name.padEnd(40)}${value}`),+ '', ' \x1b[2m\x1b[3mEnter/Space to change · Esc to close\x1b[0m']+ }+ return state+ }+ const centerScreen = () => ({ center: true, screen: () => [+ ' Agent command center Group: Project g',+ ' All 2 Needs you 0 Working 0 Ready 0 Inactive 2',+ ` ${'─'.repeat(Math.max(10, columns() - 4))}`,+ ' Tasks Status Updated',+ ' / 2',+ ' › ○ Task 2 Inactive 1m',+ ' ○ Task 1 Inactive 2m',+ '', ' ? help esc back ↑/↓ move enter open n new'] })// The prompts sent so far, newest last, which a search through the prompt history (ctrl+r) looks in.const history = []- // Searching them, as each engine draws it under its composer: the match in the composer, and Claude- // Code's `search prompts: …` (or `no matching prompt: …`) or Codex's `reverse-i-search: …` footer.+ // Searching them, as each engine draws it: the match in the composer, and Claude Code's+ // `search prompts: …` (or `no matching prompt: …`) or Codex's `reverse-i-search: …` under it.const searchBottom = (query) => {const match = query ? history.findLast((sent) => sent.toLowerCase().includes(query.toLowerCase())) ?? null : nullconst footer = engine === 'claude'? ` \x1b[2m${query && !match ? 'no matching prompt:' : 'search prompts:'}\x1b[0m ${query}`: ` \x1b[2mreverse-i-search: \x1b[0m${query} \x1b[2menter accept · esc cancel\x1b[0m`- return { search: true, query, match, composer: `› ${match ?? ''}`, footer }+ return { search: true, query, match, text: match ?? '', footer }+ }+ // The suggestions each engine opens while a `/command` or an `@mention` is typed at the end of the+ // draft, until Esc puts them away: Claude Code's under its box, in its footer's place, padded to six rows+ // and the highlighted one coloured (2.1.289, `Kge`); Codex's above its composer, the `/command` list+ // (snapshot `slash_popup_footer_wide`) or the mention menu (`default_unified_mention_popup`).+ const COMMANDS = [['/model', 'Set the AI model'], ['/memory', 'Edit memory files'], ['/mcp', 'Manage MCP servers'], ['/compact', 'Compact the conversation']]+ const FILES = ['README.md', 'src/index.ts', 'src/login.ts']+ let dismissed = null+ const suggestions = (text) => {+ const token = text.split(/\s/).at(-1) ?? ''+ if (bottom || token === dismissed || !/^[/@]/.test(token)) return null+ const found = token.startsWith('/')+ ? COMMANDS.filter(([name]) => name.startsWith(token))+ : FILES.filter((file) => file.startsWith(token.slice(1))).map((file) => [file, ''])+ return found.length ? { token, found } : null+ }+ const popupRows = (popup) => {+ if (engine === 'claude') {+ const rows = popup.found.map(([name, description], index) => ` ${index === 0 ? '\x1b[38;5;153m' : ''}${name.padEnd(16)}${description}${index === 0 ? '\x1b[39m' : ''}`)+ return [...Array(Math.max(0, 6 - rows.length)).fill(''), ...rows]+ }+ if (popup.token.startsWith('/')) {+ return [...popup.found.map(([name, description], index) => index === 0+ ? `\x1b[1;7m› ${name.padEnd(9)}\x1b[22m ${description}\x1b[0m`+ : ` \x1b[1m${name.padEnd(9)}\x1b[0m \x1b[2m${description}\x1b[0m`), '']+ }+ return [' Mentions', ' All Results Filesystem Only Plugins', ` ${popup.token.slice(1)}`,+ ...popup.found.map(([file], index) => `${index === 0 ? '›' : ' '} ${file}`),+ ' enter/tab insert · esc close · ↑/↓ select · ←/→ filter', '']+ }+ /** The rows of the pane a row of text takes, wide (CJK, emoji) characters taking two columns. */+ const WIDE = /[ᄀ-ᅟ⺀-가-힣豈-︰-﹏-⦆¢-₩\u{1f300}-\u{1faff}\u{20000}-\u{3fffd}]/u+ const rowsOf = (row) => {+ let width = 0+ for (const char of row.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '')) width += WIDE.test(char) ? 2 : 1+ return Math.max(1, Math.ceil(width / columns()))+ }+ // A draft's lines wrapped to the composer, as both engines wrap theirs, two columns in from the edge+ // where their prompt glyph stands: every row after the first is indented under the text.+ const wrapDraft = (text) => text.split('\n').flatMap((line) => {+ const rows = []+ let row = ''+ let width = 0+ for (const char of line) {+ const w = WIDE.test(char) ? 2 : 1+ if (width + w > columns() - 3) { rows.push(row); row = ''; width = 0 }+ row += char+ width += w+ }+ return [...rows, row]+ })+ /** What the composer draws, row by row. */+ const composerLines = () => {+ if (bottom?.screen) return bottom.screen()+ const text = bottom?.text ?? buffer+ const [first = '', ...more] = wrapDraft(text)+ const rest = more.map((row) => ` ${row}`)+ if (engine === 'claude') {+ const rule = `\x1b[38;5;244m${'─'.repeat(columns())}\x1b[39m`+ const input = text ? `\x1b[39m❯ ${first}` : '\x1b[39m❯ \x1b[2mTry "fix lint errors"\x1b[0m'+ const popup = suggestions(text)+ return [rule, input, ...rest, rule, ...(popup ? popupRows(popup) : [bottom?.footer ?? (text ? '' : ' \x1b[2m? for shortcuts\x1b[0m')])]+ }+ const input = bottom?.dim ? '\x1b[2m› Ask Codex to do anything\x1b[0m'+ : text ? `\x1b[1m›\x1b[0m ${first}` : '\x1b[1m›\x1b[0m \x1b[2mAsk Codex to do anything\x1b[0m'+ const popup = suggestions(text)+ return [...(popup ? popupRows(popup) : ['']), input, ...rest, '', bottom?.footer ?? statusLine()]}- /** Rows the composer takes now: a long or multi-line draft wraps. */- const rowsOf = (text) => text.split('\n')- .reduce((rows, line) => rows + Math.max(1, Math.ceil([...line].length / Math.max(20, process.stdout.columns || 80))), 0)/** Clears the composer and what is drawn under it, leaving the cursor where it began. */const eraseComposer = () => {process.stdout.write(`${composerRows > 1 ? `\x1b[${composerRows - 1}A` : ''}\r\x1b[0J`)@@ -349,27 +453,30 @@ export async function run(engine, config) {}const drawComposer = () => {if (bottom?.pager) { process.stdout.write(bottom.pager); composerRows = 0; return }- if (bottom && !buffer) {- // The footer on the row under the composer, then the cursor back to the composer, after its glyph.- process.stdout.write(`${bottom.composer}\r\n\x1b[2K${bottom.footer}\x1b[1A\r\x1b[2C`)- composerRows = 1- return- }- process.stdout.write(`› ${buffer}`)- composerRows = rowsOf(`› ${buffer}`)+ // A dialog takes the composer's place, as the CLIs draw theirs, until it is answered.+ if (dialog) return+ const rows = composerLines()+ process.stdout.write(rows.join('\r\n'))+ composerRows = rows.reduce((sum, row) => sum + rowsOf(row), 0)}const draw = () => { eraseComposer(); drawComposer() }/** The conversation, written above the composer. `text` ends at the start of a line. */const say = (text) => { eraseComposer(); process.stdout.write(text); drawComposer() }- // Out of the browser, back to the composer: the pager's alternate screen left, or the dimmed composer- // and its footer cleared. Enter rewinds on the way out.- const leaveBrowsing = (rewound) => {- if (bottom.pager) process.stdout.write('\x1b[?1049l')- else eraseComposer()- bottom = null+ // A resize redraws the whole frame, as the TUIs do: the composer measured at the old width cannot be+ // taken back row by row.+ process.stdout.on?.('resize', () => {+ if (bottom?.pager || dialog) return+ process.stdout.write('\x1b[H\x1b[2J')composerRows = 0- if (rewound) process.stdout.write('\r\x1b[2K(rewound to an earlier prompt)\r\n')drawComposer()+ })+ // Out of the browser, back to the composer: the pager's alternate screen left, or the dimmed composer+ // and its footer redrawn. Enter rewinds on the way out.+ const leaveBrowsing = (rewound) => {+ if (bottom.pager) { process.stdout.write('\x1b[?1049l'); bottom = null }+ else { eraseComposer(); bottom = null; composerRows = 0 }+ if (rewound) say('(rewound to an earlier prompt)\r\n')+ else draw()}process.stdout.write(`\x1b[?2004h${engine === 'claude' ? '✻ Welcome to Claude Code (fake)' : '>_ OpenAI Codex (fake)'}\r\n`)process.stdout.write(` session ${sessionId}${resumed ? ' (resumed)' : ''}\r\n\r\n`)@@ -382,7 +489,6 @@ export async function run(engine, config) {// The question dialog `!ask` draws, as the real CLIs draw theirs (the parser's fixtures,// src/lib/__fixtures__/question-single.txt and question-codex.txt). Claude takes a digit as the// choice; Codex moves its cursor on a digit and takes Enter; Esc cancels either.- let dialog = null// What a person pasted as notes on the option Codex then submitted, for the answer to say.let notes = ''const QUESTION = 'Which drink would you like?'@@ -473,6 +579,33 @@ export async function run(engine, config) {await runHooks('Stop', { stop_hook_active: false })}+ // A permission asked for in a turn, answered: the command run (and written as the engine writes it)+ // or not, and the turn over. `turnOf` is the turn that asked.+ const permitted = (command, row, turnOf = turn) => {+ const allowed = row === 0 || row === 1+ const id = `call_${turnOf}_p`+ if (allowed) {+ if (engine === 'claude') {+ claude({ type: 'assistant', message: { id: `msg_${turnOf}_p`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'tool_use', id, name: 'Bash', input: { command } }], stop_reason: 'tool_use' } })+ claude({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, content: `ran ${command}` }] } })+ } else {+ codex('response_item', { type: 'function_call', call_id: id, name: 'exec_command', arguments: JSON.stringify({ cmd: command }) })+ codex('response_item', { type: 'function_call_output', call_id: id, output: `ran ${command}` })+ }+ }+ return finish(allowed ? `ran ${command}` : `did not run ${command}`)+ }+ // `!permitnext`: the request waiting for the next paste.+ let armed = null+ const askOnPaste = () => {+ if (!armed) return+ const { command, turn: turnOf } = armed+ armed = null+ eraseComposer()+ dialog = { kind: 'permit', command, cursor: 0, drawn: 0, resolve: (row) => { void permitted(command, row, turnOf) } }+ drawDialog()+ }+const handle = async (raw) => {const prompt = raw.trim()// Enter on an empty composer takes nothing.@@ -579,23 +712,17 @@ export async function run(engine, config) {await new Promise((resolve) => setTimeout(resolve, 300))}if (directive?.[1] === 'hold') return+ if (directive?.[1] === 'permitnext') {+ // The turn goes on; its request arrives with the next paste, between it and its Enter.+ armed = { command: directive[2] || 'printf hi', turn }+ return+ }if (directive?.[1] === 'permit') {const command = directive[2] || 'printf hi'await new Promise((resolve) => setTimeout(resolve, 2_000))// The dialog takes the composer's place, as the CLIs draw theirs, until it is answered.const row = await new Promise((resolve) => { eraseComposer(); dialog = { kind: 'permit', command, cursor: 0, drawn: 0, resolve }; drawDialog() })- const allowed = row === 0 || row === 1- const id = `call_${turn}_p`- if (allowed) {- if (engine === 'claude') {- claude({ type: 'assistant', message: { id: `msg_${turn}_p`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'tool_use', id, name: 'Bash', input: { command } }], stop_reason: 'tool_use' } })- claude({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, content: `ran ${command}` }] } })- } else {- codex('response_item', { type: 'function_call', call_id: id, name: 'exec_command', arguments: JSON.stringify({ cmd: command }) })- codex('response_item', { type: 'function_call_output', call_id: id, output: `ran ${command}` })- }- }- await finish(allowed ? `ran ${command}` : `did not run ${command}`)+ await permitted(command, row)return}if (directive?.[1] === 'ask') {@@ -635,6 +762,16 @@ export async function run(engine, config) {await finish(`answer ${turn}: ${prompt}`)return}+ if (engine === 'claude' && directive?.[1] === 'config') {+ bottom = configScreen()+ await finish(`answer ${turn}: ${prompt}`)+ return+ }+ if (engine === 'codex' && directive?.[1] === 'center') {+ bottom = centerScreen()+ await finish(`answer ${turn}: ${prompt}`)+ return+ }if (engine === 'codex' && directive?.[1] === 'overlay') {bottom = overlayBottom(prompt, `answer ${turn}: ${prompt}`)finish(`answer ${turn}: ${prompt}`)@@ -661,6 +798,24 @@ export async function run(engine, config) {// Inside a bracketed paste a carriage return or newline is a newline in the prompt, as Ink and// ratatui read it; only one typed outside a paste submits. The paste's markers say which.let pasting = false+ // A large paste is shown in the draft as a placeholder and sent whole: Claude Code's+ // `[Pasted text #1 +4 lines]` past 800 characters or two lines (2.1.289), Codex's+ // `[Pasted Content 1200 chars]` past 1000 characters (chat_composer.rs LARGE_PASTE_CHAR_THRESHOLD).+ let pasted = ''+ const pastes = new Map()+ const placeholder = (text) => {+ const lines = (text.match(/\n/g) ?? []).length+ if (engine === 'claude' ? text.length <= 800 && lines <= 2 : text.length <= 1000) return text+ const label = engine === 'claude' ? `[Pasted text #${pastes.size + 1}${lines ? ` +${lines} lines` : ''}]` : `[Pasted Content ${text.length} chars]`+ pastes.set(label, text)+ return label+ }+ const expand = (draft) => {+ let text = draft+ for (const [label, content] of pastes) text = text.replace(label, content)+ pastes.clear()+ return text+ }process.stdin.on('data', (input) => {if (dialog) { dialogKeys(input); return }let chunk = input@@ -688,6 +843,22 @@ export async function run(engine, config) {if (!rest) returnchunk = rest}+ if (bottom?.screen) {+ // Claude Code's settings take a paste as what to search for, and Enter or Space change the highlighted+ // setting; Codex's command center opens the highlighted task on Enter. Esc closes either.+ let rest = ''+ for (const token of chunk.match(/\x1b\[200~[\s\S]*?(?:\x1b\[201~|$)|\x1b\[[0-9;]*[A-Za-z~]|\x1b|[\s\S]/g) ?? []) {+ if (!bottom?.screen) { rest += token; continue }+ if (token === '\x1b') { eraseComposer(); bottom = null; drawComposer() }+ else if (bottom.config && token.startsWith('\x1b[200~')) { bottom.query += token.slice(6).replace(/\x1b\[201~$/, ''); draw() }+ else if (bottom.config && (token === '\r' || token === ' ')) {+ const [name] = SETTINGS.find(([setting]) => setting.toLowerCase().includes(bottom.query.toLowerCase())) ?? []+ if (name) say(`(${name} changed)\r\n`)+ } else if (bottom.center && token === '\r') { eraseComposer(); bottom = null; say('(opened Task 2)\r\n') }+ }+ if (!rest) return+ chunk = rest+ }if (bottom?.search) {// As each engine takes input while searching its prompt history. A paste and typing extend the// search. Claude Code's Enter SENDS the earlier prompt found (2.1.289, historySearch:execute), its Esc@@ -730,10 +901,33 @@ export async function run(engine, config) {if (!rest) returnchunk = rest}- for (const part of chunk.split(/(\x1b\[20[01]~|\r|\n|\x03)/)) {- if (part === '\x1b[200~') { pasting = true; continue }- if (part === '\x1b[201~') { pasting = false; continue }- if (pasting && (part === '\r' || part === '\n')) { buffer += '\n'; continue }+ const parts = chunk.split(/(\x1b\[20[01]~|\x1b\[[0-9;]*[A-Za-z~]|\x1b|\x7f|\r|\n|\x03)/)+ for (const [index, part] of parts.entries()) {+ if (part === '\x1b[200~') { pasting = true; pasted = ''; continue }+ if (part === '\x1b[201~') {+ pasting = false+ buffer += placeholder(pasted)+ draw()+ askOnPaste()+ // What follows the paste goes to the request, once it is up.+ if (dialog) { dialogKeys(parts.slice(index + 1).join('')); return }+ continue+ }+ if (pasting) { pasted += part === '\r' ? '\n' : part; continue }+ if (part.startsWith('\x1b')) {+ // Esc puts the suggestions away, the draft kept; other keys move nothing here.+ const popup = suggestions(buffer)+ if (part === '\x1b' && popup) { dismissed = popup.token; draw() }+ continue+ }+ if (part === '\x7f') { buffer = buffer.slice(0, -1); draw(); continue }+ if ((part === '\r' || part === '\n') && suggestions(buffer)) {+ // Enter with suggestions open takes the highlighted one into the draft, and sends nothing.+ const popup = suggestions(buffer)+ buffer = `${buffer.slice(0, buffer.length - popup.token.length)}${popup.token.startsWith('@') ? '@' : ''}${popup.found[0][0]} `+ draw()+ continue+ }if (part === '\x03') {// Ctrl-C ends a running turn, and empties the composer either way.buffer = ''@@ -744,7 +938,7 @@ export async function run(engine, config) {say('(interrupted)\r\n')} else draw()} else if (part === '\r' || part === '\n') {- const line = buffer+ const line = expand(buffer)buffer = ''// Taken off the composer at once, whatever the engine is doing: a prompt sent while a turn runs// waits its turn out of the composer, as both CLIs queue one.diff --git a/cli/e2e/questions.e2e.ts b/cli/e2e/questions.e2e.tsindex 4e69a244a..69e257373 100644--- a/cli/e2e/questions.e2e.ts+++ b/cli/e2e/questions.e2e.ts@@ -169,4 +169,36 @@ describe('an agent asks a question', () => {expect(await d.capture(agent.tmuxPane)).not.toContain('notes:')client.close()})++ it.each(engines)('%s: a request that opens between a message\'s paste and its Enter gets no Enter: the message waits unsent, and the person is told', async (engine) => {+ const name = engine === 'claude' ? 'Claude Code' : 'Codex'+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, engine, `between-${engine}`)+ // A turn that asks permission the moment a message is pasted: a request arriving mid-turn, in the gap+ // the daemon leaves for the engine to take a long or multi-line paste in before its Enter.+ const started = client.next(isTurn('turn_started', agent.id), 45_000, 'turn_started')+ client.send('message', { agentId: agent.id, content: '!permitnext printf hi' })+ await started+ const asked = client.next((frame) => frame.type === 'commander_question' && frame.agentId === agent.id, 30_000, 'commander_question')+ const refused = client.next((frame) => frame.type === 'error' && frame.agentId === agent.id, 30_000, 'the refusal')+ client.send('message', { agentId: agent.id, content: 'first line\nsecond line' })+ expect(String((await refused).payload?.message)).toBe(`${name} asked for permission just as your message was typed, so it was not sent; it waits in ${name}'s prompt. Answer the request in the app or in its terminal, then press Enter in its terminal to send the message, or clear it there.`)+ expect(await d.capture(agent.tmuxPane)).not.toContain('ran printf hi')+ // Still asking, and answered through its own path: No.+ const question = await asked+ const shaped = question.payload?.questions?.[0]+ const ended = client.next(isTurn('turn_ended', agent.id), 45_000, 'turn_ended')+ expect((await answer(client, agent.id, String(question.payload?.requestId), { [shaped.q]: shaped.options[2] })).error).toBeUndefined()+ await ended+ expect(await d.capture(agent.tmuxPane)).toContain('did not run printf hi')+ // The message waits in the composer, unsent, and the daemon presses nothing; Enter in the terminal sends it.+ await until('the message to wait in the composer', async () => (await d.capture(agent.tmuxPane)).includes('second line') || null, 15_000, 250)+ await new Promise((resolve) => setTimeout(resolve, 5_000))+ expect(client.frames.some((frame) => isTurn('turn_started', agent.id)(frame) && String(frame.payload?.userMessage).includes('second line'))).toBe(false)+ const sent = client.next((frame) => isTurn('turn_started', agent.id)(frame) && String(frame.payload?.userMessage).includes('second line'), 30_000, 'the message sent')+ await d.tmux.run('send-keys', '-t', agent.tmuxPane, 'Enter')+ await sent+ client.close()+ })})diff --git a/cli/e2e/terminal.e2e.ts b/cli/e2e/terminal.e2e.tsindex 5466c96a6..15811044f 100644--- a/cli/e2e/terminal.e2e.ts+++ b/cli/e2e/terminal.e2e.ts@@ -203,7 +203,9 @@ describe('the terminal', () => {const words = 'pasted ' + 'words '.repeat(400).trim()const started = client.next(isTurn('turn_started', agent.id), 30_000, 'turn_started')terminal.paste(words)- await until('the paste to reach the composer', async () => (await d.capture(agent.tmuxPane)).includes('words words') || null, 15_000, 100)+ // Shown in the composer as the engines show a large paste, a placeholder, and sent whole on Enter.+ const shown = engine === 'claude' ? '[Pasted text #1]' : `[Pasted Content ${words.length} chars]`+ await until('the paste to reach the composer', async () => (await d.capture(agent.tmuxPane)).includes(shown) || null, 15_000, 100)terminal.type('\r')expect((await started).payload?.userMessage).toBe(words)client.close()diff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.tsindex 1dac1e999..c1857fc79 100644--- a/cli/src/core/input.spec.ts+++ b/cli/src/core/input.spec.ts@@ -116,14 +116,17 @@ describe('the session input controller\'s dependencies', () => {expect(await wired.inject('cc', 'hello')).toEqual({ state: 'failed', dispatch: 'not_started', reason: 'permission_open' })// Nothing written, each read inside the lock.expect(run.calls).toEqual(['lock a1', 'lock a1', 'lock cx', 'lock cc'])- // A pane that cannot be read is written as before, and so is a ready one; an agent that is not there is- // not written to at all.+ // Claude Code's and Codex's panes are typed into only when read and their composer is on screen; another+ // engine's pane that cannot be read is written as before; an agent that is not there, not at all.run.setPane(null)- expect(await wired.inject('cx', 'hi')).toBe(ok)+ expect(await wired.inject('cx', 'hi')).toEqual({ state: 'failed', dispatch: 'not_started', reason: 'screen_unreadable' })+ expect(await wired.inject('cc', 'hi')).toBe(ok)+ run.setPane('✻ Welcome to Claude Code')+ expect(await wired.inject('a1', 'hi')).toEqual({ state: 'failed', dispatch: 'not_started', reason: 'prompt_hidden' })run.setPane(READY_PANE)expect(await wired.inject('a1', 'hi')).toBe(ok)expect(await wired.inject('nobody', 'hi')).toEqual({ state: 'failed', dispatch: 'not_started', reason: 'terminal agent is unavailable' })- expect(run.calls.filter((call) => call.startsWith('submit'))).toEqual(['submit cx hi', 'submit a1 hi'])+ expect(run.calls.filter((call) => call.startsWith('submit'))).toEqual(['submit cc hi', 'submit a1 hi'])})it('reads the pane after its engine has answered, so a dialog opened during the wait is seen', async () => {@@ -144,6 +147,59 @@ describe('the session input controller\'s dependencies', () => {expect(run.calls.filter((call) => call.startsWith('submit'))).toEqual([])})+ it('reads the pane again right before the Enter, and gives the reason not to press it, a popup of the message\'s own aside', async () => {+ const screens = [READY_PANE, CLAUDE_PERMISSION, READY_PANE, null, READY_PANE, READY_PANE, `────────────\n❯ /mo\n────────────\n /model Set the AI model`]+ const answers: Array<string | null> = []+ const write = messageWriter({+ resolve: (id) => agents.get(id),+ terminal: {+ validateTerminal: vi.fn(async () => true),+ captureTerminal: vi.fn(async () => screens.shift() ?? null),+ submitTerminalAction: vi.fn(async (_id: string, _text: string, options?: { beforeEnter?: () => Promise<string | null> }) => {+ answers.push(await options!.beforeEnter!())+ return ok+ }),+ } as unknown as InputDeps['terminal'],+ })+ vi.useFakeTimers()+ try {+ for (let i = 0; i < 3; i++) {+ const written = write('a1', 'hello')+ await vi.advanceTimersByTimeAsync(1_000)+ await written+ }+ } finally { vi.useRealTimers() }+ // A permission prompt opened between the paste and the Enter; the pane unread once, then the composer;+ // the message's own `/mo`.+ expect(answers).toEqual(['permission_open', null, null])+ })++ it('holds the Enter back when the pane cannot be read for three seconds, or shows no composer that long', async () => {+ for (const screen of [null, '✻ Welcome to Claude Code']) {+ let reads = 0+ const answers: Array<string | null> = []+ const write = messageWriter({+ resolve: (id) => agents.get(id),+ terminal: {+ validateTerminal: vi.fn(async () => true),+ captureTerminal: vi.fn(async () => (reads++ === 0 ? READY_PANE : screen)),+ submitTerminalAction: vi.fn(async (_id: string, _text: string, options?: { beforeEnter?: () => Promise<string | null> }) => {+ answers.push(await options!.beforeEnter!())+ return ok+ }),+ } as unknown as InputDeps['terminal'],+ })+ vi.useFakeTimers()+ try {+ const written = write('a1', 'hello')+ await vi.advanceTimersByTimeAsync(5_000)+ await written+ } finally { vi.useRealTimers() }+ expect(answers).toEqual([screen === null ? 'screen_unreadable' : 'prompt_hidden'])+ expect(reads).toBe(13)+ }+ })+it('writes a team turn only into a ready pane whose delivery still holds control', async () => {const run = deps()const wired = sessionInputDeps(run.deps, () => lock(run.calls))diff --git a/cli/src/core/input.ts b/cli/src/core/input.tsindex dc79cbef3..f597b74f9 100644--- a/cli/src/core/input.ts+++ b/cli/src/core/input.ts@@ -18,7 +18,7 @@ import { sid } from '../lib/log.js'import type { LiveEvent } from '../lib/normalize.js'import type { RegisteredSession } from '../lib/registry.js'import { SessionInputController, type SessionInputDelivery, type SessionInputDeps } from '../lib/sessionInput.js'-import { messageHold } from '../lib/messageHold.js'+import { messageHold, passingHold } from '../lib/messageHold.js'import { TERMINAL_LEASE_REFUSED, terminalActionNotStarted, type TerminalActionResult } from '../lib/terminalTypes.js'import { Id } from '../teams/model.js'import { teamWriteHold } from '../teams/preflight.js'@@ -55,8 +55,12 @@ export interface InputDeps {* The pane is read right before the paste, by the caller that holds the pane's write lock, and nothing* is typed into a dialog, a menu or a view a message does not belong in (messageHold.ts): the reason* comes back instead, with nothing written. `hold` adds a caller's own check of the same reading (a- * team's, which waits for a draft too). `submitTerminalAction` is called here and nowhere else in this- * file, and input.spec.ts keeps it so.+ * team's, which waits for a draft too). The pane is read again once the text is in, right before its+ * Enter: a dialog opened in between (a long or multi-line paste waits up to 1.5 s for the engine to take+ * it, mid-turn) keeps the Enter from being pressed, which would answer it, and the text waits in the+ * composer, unsent (sessionInput.ts says so). A list of suggestions opened by the message itself is no+ * reason. `submitTerminalAction` is called here and nowhere else in this file, and input.spec.ts keeps+ * it so.*/export function messageWriter({ resolve, terminal: { captureTerminal, validateTerminal, submitTerminalAction } }: Pick<InputDeps, 'resolve' | 'terminal'>) {return async (id: string, text: string, hold?: (session: RegisteredSession, capture: string | null) => string | null): Promise<TerminalActionResult> => {@@ -70,10 +74,27 @@ export function messageWriter({ resolve, terminal: { captureTerminal, validateTeif (!await validateTerminal(session)) return terminalActionNotStarted(TERMINAL_LEASE_REFUSED)const capture = await captureTerminal(id)const reason = hold?.(session, capture) ?? messageHold(session.engine, capture)- return reason ? terminalActionNotStarted(reason) : submitTerminalAction(id, text)+ if (reason) return terminalActionNotStarted(reason)+ return submitTerminalAction(id, text, {+ beforeEnter: async () => {+ // A read that came back empty, or a composer caught between frames, is asked again for a moment+ // (a re-attach can blank one capture): only what is on screen holds the Enter back, never a+ // read that failed once. Still not read after that, it is held, as nothing says it is safe.+ for (let tries = 1; ; tries++) {+ const before = messageHold(session.engine, await captureTerminal(id))+ if (before === 'popup_open') return null+ if (!before || !passingHold(before) || tries >= ENTER_CHECK_TRIES) return before+ await new Promise((settle) => setTimeout(settle, ENTER_CHECK_RETRY_MS))+ }+ },+ })}}+/** How long the check before a message's Enter asks again after a read that says nothing: 3 s. */+const ENTER_CHECK_TRIES = 12+const ENTER_CHECK_RETRY_MS = 250+/** What `SessionInputController` is given: every write takes the device's pane lock first. */export function sessionInputDeps(deps: InputDeps,diff --git a/cli/src/core/terminals/control.ts b/cli/src/core/terminals/control.tsindex f2039ae11..cf4b40031 100644--- a/cli/src/core/terminals/control.ts+++ b/cli/src/core/terminals/control.ts@@ -9,7 +9,7 @@*/import type { RegisteredSession } from '../../lib/registry.js'import type { TerminalBackendCoordinator } from '../../lib/terminalBackendCoordinator.js'-import { TERMINAL_LEASE_REFUSED, terminalActionNotStarted, type TerminalActionResult } from '../../lib/terminalTypes.js'+import { TERMINAL_LEASE_REFUSED, terminalActionNotStarted, type SubmitOptions, type TerminalActionResult } from '../../lib/terminalTypes.js'export type TerminalControlBackend = Pick<TerminalBackendCoordinator,'acquireLease' | 'validateLease' | 'capture' | 'captureLease' | 'submitText' | 'submitTextLease'@@ -81,14 +81,14 @@ export function createTerminalControl({ resolve, terminals }: TerminalControlDep}const terminalActionSucceeded = (result: Awaited<ReturnType<typeof terminals.submitText>>): boolean =>result.state === 'succeeded'- const submitTerminalAction = async (target: string, text: string): Promise<TerminalActionResult> => {+ const submitTerminalAction = async (target: string, text: string, options?: SubmitOptions): Promise<TerminalActionResult> => {const session = terminalSession(target)if (!session) return terminalActionNotStarted('terminal agent is unavailable')const lease = await leasedTerminal(session)if (!lease) return terminalActionNotStarted(TERMINAL_LEASE_REFUSED)const result = pinnedControls.has(session.agentId)- ? await terminals.submitTextLease(lease.value, text)- : await terminals.submitTextForLease(session, lease.value, text)+ ? await terminals.submitTextLease(lease.value, text, options)+ : await terminals.submitTextForLease(session, lease.value, text, options)if (result.state !== 'succeeded' && pinnedControls.has(session.agentId)) invalidateTerminalControl(session.agentId)return result}diff --git a/cli/src/lib/autonomous-device/input.spec.ts b/cli/src/lib/autonomous-device/input.spec.tsindex 6d7a1748f..1ff111878 100644--- a/cli/src/lib/autonomous-device/input.spec.ts+++ b/cli/src/lib/autonomous-device/input.spec.ts@@ -408,3 +408,14 @@ it('says why a write the pane refused was not typed, when a dialog opened afterawait vi.waitFor(() => expect(onDelivery).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'delivery-B', state: 'rejected', reason: 'paste_failed' })))device.forget('agent')})++it('refuses with the reason a message typed but not sent, its Enter withheld as a dialog opened, and presses no Enter later', async () => {+ const onDelivery = vi.fn(), sendKey = vi.fn(async () => true)+ const device = makeDevice({ inject: async () => ({ state: 'unknown', dispatch: 'possibly_executed', reason: 'enter_withheld:question_open' }),+ isAwaitingUser: async () => false, onDelivery, sendKey, capture: async () => '› A' })+ device.submit('agent', 'A', 'delivery-A')+ await vi.waitFor(() => expect(onDelivery).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'delivery-A', state: 'rejected', reason: 'enter_withheld' })))+ await new Promise((resolve) => setTimeout(resolve, 2_000))+ expect(sendKey).not.toHaveBeenCalled()+ device.forget('agent')+})diff --git a/cli/src/lib/autonomous-device/input.ts b/cli/src/lib/autonomous-device/input.tsindex 6e4e07d1e..474385021 100644--- a/cli/src/lib/autonomous-device/input.ts+++ b/cli/src/lib/autonomous-device/input.ts@@ -1,9 +1,9 @@import { createHash } from 'node:crypto'import type { RegisteredSession } from '../registry.js'import type { SessionInputDelivery } from '../sessionInput.js'-import type { TerminalActionResult } from '../terminalTypes.js'import type { LiveEvent } from '../normalize.js'import { isMessageHold } from '../messageHold.js'+import { enterWithheldReason, type TerminalActionResult } from '../terminalTypes.js'const NATIVE = new Set(['claude', 'codex'])const VERIFY_MS = 1500@@ -193,6 +193,11 @@ export class AutonomousDeviceInput {const result = await this.deps.inject(session.agentId, item.content)if (this.states.get(id) !== state) returnif (item.started) { this.finishWrite(id, state, item); return }+ if (enterWithheldReason(result)) {+ // Typed, its Enter not pressed: something opened before it, and the Enter is never pressed later.+ state.pending = state.pending.filter(next => next !== item)+ this.delivery(id, item, 'rejected', 'enter_withheld'); this.finishWrite(id, state, item); return+ }if (rejected(result)) {state.pending = state.pending.filter(next => next !== item)// A dialog that opened between the look for one and the write: refused unwritten, and why.diff --git a/cli/src/lib/composerScreen.spec.ts b/cli/src/lib/composerScreen.spec.tsnew file mode 100644index 000000000..933772d10--- /dev/null+++ b/cli/src/lib/composerScreen.spec.ts@@ -0,0 +1,131 @@+import { readFileSync } from 'node:fs'+import { describe, expect, it } from 'vitest'+import { composerState } from './composerScreen.js'++const fixture = (name: string) => readFileSync(new URL(`./__fixtures__/${name}`, import.meta.url), 'utf8')+const rule = (width = 100) => `\u001b[38;5;244m${'─'.repeat(width)}\u001b[39m`++/** Claude Code 2.1.289's prompt box: ruled above and below, `❯` and the prompt or a dim example. */+const claudeBox = (prompt: string, footer: string[] = [' \u001b[2m? for shortcuts\u001b[0m'], width = 100, more: string[] = []) => [+ rule(width), `\u001b[39m❯ ${prompt}`, ...more, rule(width), ...footer,+].join('\n')+const CLAUDE_EMPTY = claudeBox('\u001b[2mTry "fix lint errors"\u001b[0m')++/** Codex 0.160's composer (snapshots `empty`, `draft_composer`): a blank row, bold `›` and the draft or+ * the dim placeholder, a blank row, the footer. */+const codexComposer = (draft: string, footer = ' ? for shortcuts 100% context left', more: string[] = []) => [+ '', `\u001b[1m›\u001b[0m ${draft}`, ...more, '', footer,+].join('\n')+const CODEX_EMPTY = codexComposer('\u001b[2mAsk Codex to do anything\u001b[0m')++describe('Claude Code\'s prompt', () => {+ it('is ready empty, with a draft, a draft over several lines, or one in CJK and emoji', () => {+ expect(composerState('claude', CLAUDE_EMPTY)).toBe('ready')+ expect(composerState('claude', claudeBox('fix the login bug', ['']))).toBe('ready')+ expect(composerState('claude', claudeBox('first line', [''], 100, [' second line', ' third line']))).toBe('ready')+ expect(composerState('claude', claudeBox('下一步:修复登录 🎉👩💻', ['']))).toBe('ready')+ })++ it('is ready while a turn runs, under its notices and in a narrow pane, its top rule carrying text', () => {+ // Typing is taken while a turn runs, and queued.+ expect(composerState('claude', `✶ Pondering… (12s · esc to interrupt)\n\n${CLAUDE_EMPTY}`)).toBe('ready')+ expect(composerState('claude', claudeBox('next', [' ⏵⏵ accept edits on (shift+tab to cycle)', ' Starting MCP servers (1/3)…', ' Update available! Run: claude update']))).toBe('ready')+ expect(composerState('claude', claudeBox('\u001b[2mTry "fix"\u001b[0m', [' ? for shortcuts'], 20))).toBe('ready')+ expect(composerState('claude', [`${'─'.repeat(40)} ↯ fast ${'─'.repeat(40)}`, '❯ next', '─'.repeat(88), ''].join('\n'))).toBe('ready')+ // Scrolled: the conversation's own `❯` lines above the box are not the box.+ expect(composerState('claude', `\u001b[48;5;237m❯ an earlier prompt\u001b[49m\n\n⏺ its answer\n\n${CLAUDE_EMPTY}`)).toBe('ready')+ })++ it('is ready with a draft taller than the pane, its top rule and `❯` row scrolled off', () => {+ // 2.1.289 caps the prompt's height only in its fullscreen renderer; inline, the box outgrows the pane.+ const rows = Array.from({ length: 20 }, (_, index) => ` line ${index + 2} of a long draft 下一步 🎉`)+ expect(composerState('claude', [...rows, rule(), ''].join('\n'))).toBe('ready')+ expect(composerState('claude', [...rows.slice(0, 18), '', ' /mo', rule(), '', '', '', '', '', ' /model Set the AI model'].join('\n'))).toBe('popup')+ // Not a dialog's rows (indented by one column), nor the conversation's (at the edge).+ expect(composerState('claude', [' Bash command', ' printf hi', ' Do you want to proceed?', rule(), ''].join('\n'))).toBe('absent')+ expect(composerState('claude', ['⏺ the answer', ' more of it', rule(), ''].join('\n'))).toBe('absent')+ expect(composerState('claude', [rule(), ''].join('\n'))).toBe('absent')+ })++ it('has a popup open while a /command or an @mention is suggested under it, and only then', () => {+ expect(composerState('claude', claudeBox('/mo', ['', '', '', '', '', ' \u001b[38;5;153m/model Set the AI model\u001b[39m']))).toBe('popup')+ expect(composerState('claude', claudeBox('look at @src/lo', ['', '', '', '', '', ' \u001b[38;5;153msrc/login.ts\u001b[39m']))).toBe('popup')+ expect(composerState('claude', claudeBox('@', ['', '', '', ' README.md', ' src/index.ts', ' src/login.ts']))).toBe('popup')+ // Nothing suggested, or put away with Esc: the footer is back.+ expect(composerState('claude', claudeBox('/mo', ['']))).toBe('ready')+ expect(composerState('claude', claudeBox('mail @bob', [' ⏵⏵ accept edits on (shift+tab to cycle)']))).toBe('ready')+ })++ it('is absent when anything else is on screen: a dialog, a view, a screen never seen, or nothing yet', () => {+ expect(composerState('claude', fixture('permission-claude.txt'))).toBe('absent')+ expect(composerState('claude', fixture('question-single.txt'))).toBe('absent')+ // Its settings (/config): a dialog ruled at the top, its rows under a `❯`.+ expect(composerState('claude', [rule(), ' Settings: Status Config Usage', '', ' ⌕ Search settings…', '', ' ❯ Auto-compact true', ' Show tips true', '', ' Enter/Space to change · Esc to close'].join('\n'))).toBe('absent')+ // A dialog drawn ruled under what was the box.+ expect(composerState('claude', `${CLAUDE_EMPTY}\n${rule()}\n Something new\n ❯ 1. Yes`)).toBe('absent')+ expect(composerState('claude', '')).toBe('absent')+ expect(composerState('claude', '✻ Welcome to Claude Code\n\n /help for help')).toBe('absent')+ // A box with no bottom rule yet, half drawn.+ expect(composerState('claude', `${rule()}\n❯ next`)).toBe('absent')+ })+})++describe('Codex\'s composer', () => {+ it('is ready empty, with a draft, a draft over several lines, or one in CJK and emoji', () => {+ expect(composerState('codex', CODEX_EMPTY)).toBe('ready')+ expect(composerState('codex', codexComposer('Explore the night sky', ' 100% context left'))).toBe('ready')+ expect(composerState('codex', codexComposer('first line', ' ? for shortcuts', [' second line']))).toBe('ready')+ expect(composerState('codex', codexComposer('下一步:修复登录 🎉👩💻'))).toBe('ready')+ // At its top reasoning effort the glyph is `»`, still bold.+ expect(composerState('codex', ['', '\u001b[1;38;2;186;130;255m»\u001b[0m next', '', ' ? for shortcuts'].join('\n'))).toBe('ready')+ })++ it('is ready while a turn runs with messages queued, while MCP servers start, and in a narrow pane', () => {+ // Snapshot `status_and_queued_messages`.+ expect(composerState('codex', ['• Working (0s • esc to interrupt)', '', '• Queued follow-up inputs', ' ↳ Queued follow-up question',+ ' shift+← edit last queued message', CODEX_EMPTY].join('\n'))).toBe('ready')+ expect(composerState('codex', `• Starting MCP servers (0/2): docs, search\n${CODEX_EMPTY}`)).toBe('ready')+ expect(composerState('codex', codexComposer('\u001b[2mAsk Codex to do a\u001b[0m', ' ? for shortcuts'))).toBe('ready')+ // Find in its transcript keeps the composer, two footer rows under it.+ expect(composerState('codex', ['', '\u001b[1m›\u001b[0m /', '', '', ' Find: needle', ' Enter next · Esc close'].join('\n'))).toBe('ready')+ })++ it('has a popup open while its /command list or mention menu is drawn above it, and only then', () => {+ // Snapshot `slash_popup_footer_wide`.+ expect(composerState('codex', [' /model choose what model and reasoning effort to use', '\u001b[1;7m› /memories configure memory use\u001b[0m',+ ' /mention mention a file', '', '\u001b[1m›\u001b[0m /m', '', ' model · high · fast'].join('\n'))).toBe('popup')+ // Snapshot `default_unified_mention_popup`.+ expect(composerState('codex', [' Mentions', ' All Results Filesystem Only Plugins', ' sa', '› Sample Plugin Plugin with skills',+ ' enter/tab insert · esc close · ↑/↓ select · ←/→ filter', '', '\u001b[1m›\u001b[0m @sa', '', ' 100% context left'].join('\n'))).toBe('popup')+ // The same drafts with nothing drawn above.+ expect(composerState('codex', codexComposer('/m'))).toBe('ready')+ expect(composerState('codex', codexComposer('ask @sa'))).toBe('ready')+ })++ it('is absent under its session picker, whose highlighted row is drawn two columns in', () => {+ // resume_picker/layout.rs renders the list at `list.x + 2`, the header and search one column in, a dim+ // rule over its footer; the selected row is `› ` in the selection style (resume_picker.rs+ // `selection_marker`), so never at the left edge, bold or not.+ expect(composerState('codex', [' \u001b[1mResume a previous session\u001b[0m', ' All This folder', ' \u001b[2mType to search\u001b[0m',+ ' \u001b[1;7m› \u001b[0m\u001b[7m15m ago Propose session picker redesign\u001b[0m', ' 2h ago Fix the login bug', '',+ `\u001b[2m${'─'.repeat(80)}\u001b[0m`, ' enter resume · esc new session'].join('\n'))).toBe('absent')+ })++ it('is absent when anything else is on screen: a picker, a screen never seen, a line of the conversation, or nothing yet', () => {+ // Its agent command center (snapshot `agents_overview_recent_sessions`): its highlighted row is indented.+ expect(composerState('codex', [' Agent command center Group: Project g', ' Tasks Status', ' › ○ Task 12 Inactive',+ ' ○ Task 11 Inactive', '', ' ? help esc back ↑/↓ move enter open n new'].join('\n'))).toBe('absent')+ // A picker's rows are numbered (picker_option.rs).+ expect(composerState('codex', [' Update available', '', '\u001b[1;36m› 1. Update now\u001b[0m', ' 2. Skip', '', ' enter continue'].join('\n'))).toBe('absent')+ // The conversation's own `›` line with its answer under it, the composer gone.+ expect(composerState('codex', ['', '\u001b[1m›\u001b[0m fix the bug', '', '• Fixed it.', ' Details one.', ' Details two.', ' Details three.',+ ' Would you like to run the following command?'].join('\n'))).toBe('absent')+ // Input disabled: the glyph is dim.+ expect(composerState('codex', ['', '\u001b[2m›\u001b[0m \u001b[2mInput disabled.\u001b[0m', '', ' ? for shortcuts'].join('\n'))).toBe('absent')+ // Shell mode: `!` in its place.+ expect(composerState('codex', ['', '\u001b[1;91m!\u001b[0m ls', '', ' ? for shortcuts'].join('\n'))).toBe('absent')+ // Not under a blank row.+ expect(composerState('codex', ['something', '\u001b[1m›\u001b[0m next', '', ' ? for shortcuts'].join('\n'))).toBe('absent')+ expect(composerState('codex', '')).toBe('absent')+ })+})diff --git a/cli/src/lib/composerScreen.ts b/cli/src/lib/composerScreen.tsnew file mode 100644index 000000000..ab47fb131--- /dev/null+++ b/cli/src/lib/composerScreen.ts@@ -0,0 +1,113 @@+/**+ * Whether Claude Code's or Codex's own composer is on screen, ready for a message: what a message is+ * typed into, and nothing else (messageHold.ts). An allowlist, so a screen never seen before is not+ * typed into: it is refused, where a list of screens to refuse would have let it through.+ *+ * Read from the engines' own code (Claude Code 2.1.289's bundle, Codex 0.160's tui/src), not run:+ * - Claude Code draws its prompt in a box ruled above and below (`borderStyle: "round"` with no+ * sides, the rule full width, text in the top rule at times), `❯` and the prompt in it, its further+ * lines under the first; under the box, its footer, or the suggestions for a `/command` or an+ * `@mention` being typed, which take the footer's place (`Kge`, padded to six rows or more).+ * Every dialog, menu and view hides the box.+ * - Codex draws a blank row, then `›` in bold (`»` at its top reasoning effort; dim while input is+ * disabled, `!` in shell mode) and the draft or its dim placeholder at the left edge, its further+ * lines under it, then a blank row and its footer, one or two rows, at the bottom of the pane+ * (chat_composer.rs, snapshots `empty`, `draft_composer`, `status_and_queued_messages`). Its popups+ * are drawn above the composer: the `/command` list (snapshot `slash_popup_footer_wide`) and the+ * mention menu with its `enter/tab insert · esc close` row (`default_unified_mention_popup`). Its+ * approvals, questions, pickers and startup screens replace it; a picker's rows are numbered.+ * A popup open over the composer is no composer to type into: its Enter picks the highlighted row.+ */+import { stripVTControlCharacters } from 'node:util'+import type { RegisteredSession } from './registry.js'++export type ComposerState = 'ready' | 'popup' | 'absent'++/** The engines read this way. Every other engine is read only for the screens known to refuse. */+export const COMPOSER_ENGINES: ReadonlySet<string> = new Set(['claude', 'codex'])++/** A row of Claude Code's rule: all `─`, or `─` at both ends with text set in it. */+const CLAUDE_RULE = /^─{3,}$|^─{3,}.*─{3,}$/++/** Codex's composer row: `›` (or `»`) at the left edge, never a numbered row of a picker. */+const CODEX_COMPOSER = /^[›»](?:\s|$)/+const CODEX_PICKER_ROW = /^[›»]\s*\d+\.\s/++function screenLines(capture: string): { lines: string[]; raw: string[] } {+ const raw = capture.split('\n')+ const lines = raw.map((line) => stripVTControlCharacters(line).replace(/ /g, ' ').trimEnd())+ while (lines.length && !lines.at(-1)) { lines.pop(); raw.pop() }+ return { lines, raw }+}++/** Whether the first character of a row is drawn bold: the SGR in force when it is written. */+function startsBold(row: string): boolean {+ let bold = false+ const sgr = /^\u001b\[([0-9;:]*)m/+ let rest = row+ for (let match = sgr.exec(rest); match; match = sgr.exec(rest)) {+ for (const code of match[1].split(/[;:]/)) {+ if (code === '1') bold = true+ else if (code === '' || code === '0' || code === '22') bold = false+ }+ rest = rest.slice(match[0].length)+ }+ return bold+}++/** The word being typed at the end of a draft, where a `/command` or an `@mention` opens its popup. */+function typedToken(draft: string): string {+ return draft.split(/\s/).at(-1) ?? ''+}++export function composerState(engine: RegisteredSession['engine'], capture: string): ComposerState {+ const { lines, raw } = screenLines(capture)+ return engine === 'codex' ? codexComposer(lines, raw) : claudeComposer(lines)+}++function claudeComposer(lines: string[]): ComposerState {+ let prompt = lines.findLastIndex((line) => /^❯(?:\s|$)/.test(line))+ let bottom = lines.findIndex((line, index) => index > prompt && CLAUDE_RULE.test(line.trim()))+ if (prompt < 1 || !CLAUDE_RULE.test(lines[prompt - 1].trim()) || bottom < 0) {+ // A draft taller than the pane: Claude Code does not cap the prompt's height outside its fullscreen+ // renderer (2.1.289 passes `maxVisibleLines` only there), so the box's top rule and its `❯` row+ // scroll off, and the pane shows the draft's further rows, indented under the `❯`, down to the+ // bottom rule. Every row above that rule is one of them; a dialog's are indented by one column, the+ // conversation's start at the edge.+ bottom = lines.findIndex((line) => CLAUDE_RULE.test(line.trim()))+ if (bottom < 1 || !lines.slice(0, bottom).every((line) => !line || line.startsWith(' '))) return 'absent'+ prompt = -1+ }+ const below = lines.slice(bottom + 1)+ // Nothing ruled under the box: a dialog of Claude Code's own is drawn ruled, in its place.+ if (below.some((line) => CLAUDE_RULE.test(line.trim()))) return 'absent'+ const draft = [prompt < 0 ? '' : lines[prompt].replace(/^❯\s?/, ''), ...lines.slice(prompt + 1, bottom).map((line) => line.trim())].join(' ').trim()+ const token = typedToken(draft)+ const rows = below.map((line) => line.trim()).filter(Boolean)+ if (token.startsWith('/') && rows.some((row) => /^\/[\w:.-]/.test(row))) return 'popup'+ if (token.startsWith('@')) {+ const typed = token.slice(1).toLowerCase()+ // A file or agent suggestion, by what is typed after the `@`; with nothing typed yet, any row but the+ // footer's own (its mode and its hints).+ if (rows.some((row) => typed ? row.replace(/^@/, '').toLowerCase().startsWith(typed) : !/^(?:\?|⏵|esc\b)/.test(row))) return 'popup'+ }+ return 'ready'+}++function codexComposer(lines: string[], raw: string[]): ComposerState {+ const composer = lines.findLastIndex((line) => CODEX_COMPOSER.test(line) && !CODEX_PICKER_ROW.test(line))+ // Bold, on a row of its own under a blank one: not a line of the conversation, nor a disabled composer.+ if (composer < 0 || !startsBold(raw[composer]) || (composer > 0 && lines[composer - 1].trim())) return 'absent'+ // The draft's further lines, then a blank row and the footer: nothing more is drawn under Codex's+ // composer, so more is some other screen under a line of the conversation.+ let end = composer + 1+ while (end < lines.length && lines[end].trim()) end+++ const footer = lines.slice(end).filter((line) => line.trim())+ if (footer.length > 3) return 'absent'+ const draft = [lines[composer].replace(/^›\s?/, ''), ...lines.slice(composer + 1, end).map((line) => line.trim())].join(' ').trim()+ const token = typedToken(draft)+ const above = lines.slice(Math.max(0, composer - 20), composer)+ if (token.startsWith('/') && above.some((line) => /^(?:›\s*|\s+)\/[\w-]+\s{2,}\S/.test(line))) return 'popup'+ if (token.startsWith('@') && above.some((line) => /\benter\/tab insert · esc close\b/.test(line))) return 'popup'+ return 'ready'+}diff --git a/cli/src/lib/messageHold.spec.ts b/cli/src/lib/messageHold.spec.tsindex 5c82c3080..f5a91c051 100644--- a/cli/src/lib/messageHold.spec.ts+++ b/cli/src/lib/messageHold.spec.ts@@ -1,6 +1,6 @@import { readFileSync } from 'node:fs'import { describe, expect, it } from 'vitest'-import { isMessageHold, messageHold, messageHoldText, type MessageHold } from './messageHold.js'+import { isMessageHold, messageHold, messageHoldText, messageWithheldText, passingHold, type MessageHold } from './messageHold.js'import {CLAUDE_PROMPT, CLAUDE_REWIND_CONFIRM, CLAUDE_REWIND_LIST, CODEX_BROWSING_FULLSCREEN, CODEX_BROWSING_SCROLLBACK, CODEX_PROMPT,} from './__fixtures__/rewindPickers.js'@@ -78,7 +78,7 @@ describe('what a message is not typed into', () => {RULE, '❯ ', RULE, ' ? for shortcuts',].join('\n')expect(messageHold('claude', working)).toBeNull()- const codex = ['› tidy up the release script', '', '• Plan:', ' 1. Run the existing tests first', ' 2. Stop publishing the debug build', '', '◦ Working (5s • esc to interrupt)', '', '› ', '', ' ? for shortcuts'].join('\n')+ const codex = ['› tidy up the release script', '', '• Plan:', ' 1. Run the existing tests first', ' 2. Stop publishing the debug build', '', '◦ Working (5s • esc to interrupt)', '', '\u001b[1m›\u001b[0m ', '', ' ? for shortcuts'].join('\n')expect(messageHold('codex', codex)).toBeNull()})@@ -122,7 +122,6 @@ describe('what a message is not typed into', () => {expect(messageHold('claude', CLAUDE_PROMPT)).toBeNull()expect(messageHold('codex', CODEX_PROMPT)).toBeNull()expect(messageHold('claude', `✶ Thinking… (esc to interrupt)\n${CLAUDE_PROMPT}`)).toBeNull()- expect(messageHold('claude', null)).toBeNull()expect(messageHold('claude', `${CLAUDE_PROMPT}\n Starting MCP servers (1/3)…`)).toBeNull()// The conversation's own words are not the view's footer, nor a menu.expect(messageHold('claude', `⏺ Showing detailed transcript is what ctrl+o does.\n${CLAUDE_PROMPT}`)).toBeNull()@@ -186,9 +185,30 @@ describe('the engines\' own screens that take the composer\'s place', () => {})})+describe('anything but the engine\'s own composer, for Claude Code and Codex', () => {+ it('is refused: a screen never seen, a popup over the composer, a pane not drawn yet or not read', () => {+ // Claude Code's settings (/config), which the daemon has no name for.+ expect(messageHold('claude', `${'─'.repeat(80)}\n Settings: Status Config Usage\n\n ⌕ Search settings…\n\n ❯ Auto-compact true\n\n Enter/Space to change · Esc to close`)).toBe('prompt_hidden')+ // Codex's agent command center.+ expect(messageHold('codex', ' Agent command center\n › ○ Task 12 Inactive\n ○ Task 11 Inactive\n\n ? help esc back ↑/↓ move enter open')).toBe('prompt_hidden')+ expect(messageHold('codex', [' /model choose what model', '\u001b[1;7m› /memories configure memory\u001b[0m', '', '\u001b[1m›\u001b[0m /m', '', ' ? for shortcuts'].join('\n'))).toBe('popup_open')+ expect(messageHold('claude', '')).toBe('prompt_hidden')+ expect(messageHold('claude', null)).toBe('screen_unreadable')+ expect(messageHold('codex', null)).toBe('screen_unreadable')+ // Another engine is read for its prompts only: an unknown screen or an unread pane is typed into as before.+ expect(messageHold('cursor', '')).toBeNull()+ expect(messageHold('cursor', null)).toBeNull()+ })++ it('waits a little for the passing ones, an engine starting or a pane read once in vain, before refusing', () => {+ expect(['prompt_hidden', 'screen_unreadable'].every(passingHold)).toBe(true)+ expect(['permission_open', 'popup_open', 'menu_open', 'team_waiting_user'].some(passingHold)).toBe(false)+ })+})+describe('what the person is told', () => {const holds: MessageHold[] = ['permission_open', 'question_open', 'menu_open', 'rewind_picker_open', 'transcript_open',- 'search_open', 'trust_open', 'update_prompt_open', 'model_prompt_open', 'sign_in_open']+ 'search_open', 'trust_open', 'update_prompt_open', 'model_prompt_open', 'sign_in_open', 'popup_open', 'prompt_hidden', 'screen_unreadable']it('names the engine, what is open, and exactly what lets the message through', () => {expect(holds.map((hold) => messageHoldText('claude', hold))).toEqual([@@ -202,7 +222,11 @@ describe('what the person is told', () => {'Claude Code is asking whether to update. Answer it in its terminal, then send the message again.','Claude Code is asking whether to switch to a new model. Answer it in its terminal, then send the message again.','Claude Code is asking how to sign in. Sign in in its terminal, then send the message again.',+ 'Claude Code has a list of suggestions open in its prompt, where Enter would pick one. Close it with Esc in its terminal, then send the message again.',+ 'Claude Code isn\'t showing its prompt; finish what\'s on its screen in its terminal, then send the message again.',+ 'Claude Code\'s screen could not be read, so the message was not typed. Send it again in a moment.',])+ expect(messageHoldText('codex', 'prompt_hidden')).toBe('Codex isn\'t showing its prompt; finish what\'s on its screen in its terminal, then send the message again.')expect(messageHoldText('codex', 'transcript_open')).toBe('Codex is showing its transcript (ctrl+t), where a message is not typed. Close it with q in its terminal, then send the message again.')expect(messageHoldText('codex', 'search_open')).toBe('Codex has a search open, where a message would become what it searches for. Close it with Esc in its terminal, then send the message again.')expect(messageHoldText('codex', 'update_prompt_open')).toBe('Codex is asking whether to update. Answer it in its terminal, then send the message again.')@@ -217,3 +241,10 @@ describe('what the person is told', () => {expect(isMessageHold('terminal agent is unavailable')).toBe(false)})})++describe('what the person is told when their message was typed and its Enter withheld', () => {+ it('says what opened, that the message waits unsent in the prompt, and what sends or clears it', () => {+ expect(messageWithheldText('codex', 'question_open')).toBe('Codex asked you a question just as your message was typed, so it was not sent; it waits in Codex\'s prompt. Answer the question in the app or in its terminal, then press Enter in its terminal to send the message, or clear it there.')+ expect(messageWithheldText('claude', 'prompt_hidden')).toBe('Claude Code opened another screen just as your message was typed, so it was not sent; it waits in Claude Code\'s prompt. Finish what\'s on its screen in its terminal, then press Enter in its terminal to send the message, or clear it there.')+ })+})diff --git a/cli/src/lib/messageHold.ts b/cli/src/lib/messageHold.tsindex bdb60389d..b2f0706d1 100644--- a/cli/src/lib/messageHold.ts+++ b/cli/src/lib/messageHold.ts@@ -23,19 +23,37 @@* So none of them is typed into. A question is answered through its own path (`question_response`),* never by a message.*+ * For Claude Code and Codex the screens above are named, to say what is open; anything else is typed+ * into only when the engine's own composer is on screen (composerScreen.ts), so a screen never seen+ * before is refused, never typed into. Other engines are read for their questions and permission+ * prompts only.+ ** One function for every route a message takes to a pane, so that none can skip it (core/input.ts).*/import { engineLabel } from './agentNames.js'import { isApprovalDialog, parseEngineQuestionPane } from './askQuestion.js'import type { RegisteredSession } from './registry.js'+import { COMPOSER_ENGINES, composerState } from './composerScreen.js'import { paneModal } from './runtimeProfileController.js'/** Why a message was not typed, as the reason its delivery is refused with. */export type MessageHold = 'permission_open' | 'question_open' | 'menu_open' | 'rewind_picker_open' | 'transcript_open'- | 'search_open' | 'trust_open' | 'update_prompt_open' | 'model_prompt_open' | 'sign_in_open'+ | 'search_open' | 'trust_open' | 'update_prompt_open' | 'model_prompt_open' | 'sign_in_open' | 'popup_open'+ | 'prompt_hidden' | 'screen_unreadable'const HOLDS: ReadonlySet<string> = new Set<MessageHold>(['permission_open', 'question_open', 'menu_open', 'rewind_picker_open',- 'transcript_open', 'search_open', 'trust_open', 'update_prompt_open', 'model_prompt_open', 'sign_in_open'])+ 'transcript_open', 'search_open', 'trust_open', 'update_prompt_open', 'model_prompt_open', 'sign_in_open', 'popup_open',+ 'prompt_hidden', 'screen_unreadable'])++/**+ * The holds that can be passing: an engine still starting draws nothing yet, a redraw can be caught+ * between frames, a capture can fail once. A message waits a little for these to clear before it is+ * refused (sessionInput.ts), as it does for the pane's control lease.+ */+const PASSING: ReadonlySet<string> = new Set<MessageHold>(['prompt_hidden', 'screen_unreadable'])+export function passingHold(reason: string): boolean {+ return PASSING.has(reason)+}/** The hold for each of the engines' own screens and modals (runtimeProfileController.ts `paneModal`). */const MODAL_HOLDS: Record<NonNullable<ReturnType<typeof paneModal>>, MessageHold> = {@@ -43,17 +61,17 @@ const MODAL_HOLDS: Record<NonNullable<ReturnType<typeof paneModal>>, MessageHoldupdate: 'update_prompt_open', model: 'model_prompt_open', sign_in: 'sign_in_open', permission: 'permission_open', menu: 'menu_open',}-/** The engines whose screens are read for more than a question: the menus, rewind pickers and views. */-const MODAL_ENGINES: ReadonlySet<string> = new Set(['claude', 'codex'])-/** What the pane shows that a message must not be typed into, or null when it can be typed. */export function messageHold(engine: RegisteredSession['engine'], capture: string | null): MessageHold | null {- if (!capture) return null+ const allowlisted = COMPOSER_ENGINES.has(engine)+ if (capture === null) return allowlisted ? 'screen_unreadable' : nullconst view = parseEngineQuestionPane(engine, capture)if (view) return view.kind === 'question' && isApprovalDialog(view) ? 'permission_open' : 'question_open'- if (!MODAL_ENGINES.has(engine)) return null+ if (!allowlisted) return nullconst modal = paneModal(engine, capture)- return modal ? MODAL_HOLDS[modal] : null+ if (modal) return MODAL_HOLDS[modal]+ const composer = composerState(engine, capture)+ return composer === 'ready' ? null : composer === 'popup' ? 'popup_open' : 'prompt_hidden'}export function isMessageHold(reason: string): reason is MessageHold {@@ -64,6 +82,18 @@ function engineName(engine: string): string {return engine === 'claude' ? 'Claude Code' : engineLabel(engine)}+/**+ * What the person is told when their message was typed but its Enter not pressed: the engine opened+ * something between the two, which the Enter would have answered. The text waits in the composer.+ */+export function messageWithheldText(engine: string, hold: string): string {+ const name = engineName(engine)+ const [what, then] = hold === 'permission_open' ? ['asked for permission', 'Answer the request in the app or in its terminal']+ : hold === 'question_open' ? ['asked you a question', 'Answer the question in the app or in its terminal']+ : ['opened another screen', 'Finish what\'s on its screen in its terminal']+ return `${name} ${what} just as your message was typed, so it was not sent; it waits in ${name}'s prompt. ${then}, then press Enter in its terminal to send the message, or clear it there.`+}+/** What the person is told: why their message was not typed, and what lets it through. */export function messageHoldText(engine: string, hold: MessageHold): string {const name = engineName(engine)@@ -94,5 +124,11 @@ export function messageHoldText(engine: string, hold: MessageHold): string {return `${name} is asking whether to switch to a new model. Answer it in its terminal, then send the message again.`case 'sign_in_open':return `${name} is asking how to sign in. Sign in in its terminal, then send the message again.`+ case 'popup_open':+ return `${name} has a list of suggestions open in its prompt, where Enter would pick one. Close it with Esc in its terminal, then send the message again.`+ case 'prompt_hidden':+ return `${name} isn't showing its prompt; finish what's on its screen in its terminal, then send the message again.`+ case 'screen_unreadable':+ return `${name}'s screen could not be read, so the message was not typed. Send it again in a moment.`}}diff --git a/cli/src/lib/sessionInput.spec.ts b/cli/src/lib/sessionInput.spec.tsindex 8ba1cf3d3..0c01cc21f 100644--- a/cli/src/lib/sessionInput.spec.ts+++ b/cli/src/lib/sessionInput.spec.ts@@ -17,6 +17,13 @@ function session(engine: 'claude' | 'codex' | 'cursor' | 'commandcode' = 'codex'}}+/**+ * The composers as the engines draw them, which a message is typed into only when on screen+ * (composerScreen.ts): Claude Code's ruled box and Codex's bold `›` row under a blank one.+ */+const claudeBox = (draft: string, above = '') => `${above}${'─'.repeat(40)}\n❯ ${draft}\n${'─'.repeat(40)}\n ? for shortcuts`+const codexComposer = (draft: string, footer = ' ? for shortcuts') => `\n\u001b[1m›\u001b[0m ${draft}\n\n${footer}`+describe('SessionInputController', () => {afterEach(() => vi.useRealTimers())@@ -41,6 +48,59 @@ describe('SessionInputController', () => {controller.forget('s1')})+ it('waits for an engine to draw its composer, as for the lease, and types once it is there', async () => {+ // A message sent while the engine starts: its pane holds nothing yet.+ const time = { at: 0, now: () => time.at, sleep: vi.fn(async (ms: number) => { time.at += ms }) }+ const onError = vi.fn(), onSubmitted = vi.fn()+ const inject = vi.fn<() => Promise<TerminalActionResult>>().mockResolvedValueOnce(held('prompt_hidden'))+ .mockResolvedValueOnce(held('screen_unreadable')).mockResolvedValue({ state: 'succeeded', dispatch: 'executed' })+ const controller = new SessionInputController({ getSession: () => session('codex'), validateRuntime: async () => true,+ inject, sendKey: async () => true, onError, onSubmitted, now: time.now, sleep: time.sleep })+ controller.submit('s1', 'sent while it starts')+ await vi.waitFor(() => expect(onSubmitted).toHaveBeenCalledWith('s1', 'sent while it starts'))+ expect(inject).toHaveBeenCalledTimes(3)+ expect(onError).not.toHaveBeenCalled()+ controller.forget('s1')+ })++ it('refuses with the reason once the wait is over and the composer never came', async () => {+ const time = { at: 0, now: () => time.at, sleep: vi.fn(async (ms: number) => { time.at += ms }) }+ const onError = vi.fn()+ const inject = vi.fn(async () => held('prompt_hidden'))+ const controller = new SessionInputController({ getSession: () => session('claude'), validateRuntime: async () => true,+ inject, sendKey: async () => true, onError, now: time.now, sleep: time.sleep })+ controller.submit('s1', 'into a screen never seen')+ await vi.waitFor(() => expect(onError).toHaveBeenCalledWith('s1', 'Claude Code isn\'t showing its prompt; finish what\'s on its screen in its terminal, then send the message again.'))+ expect(time.at).toBeGreaterThanOrEqual(15_000)+ controller.forget('s1')+ })++ it('typed but its Enter withheld, as something opened: never pressed later, and the person told where the text is', async () => {+ const withheld: TerminalActionResult = { state: 'unknown', dispatch: 'possibly_executed', reason: 'enter_withheld:permission_open' }+ const onError = vi.fn(), onSubmitted = vi.fn(), sendKey = vi.fn(async () => true), forget = vi.fn(), onDelivery = vi.fn()+ vi.useFakeTimers()+ const controller = new SessionInputController({ getSession: () => session('claude'), validateRuntime: async () => true,+ inject: async () => withheld, sendKey, onError, onSubmitted, onDelivery, beforeSubmit: () => forget, beforeTeamWrite: async () => null })+ controller.submit('s1', 'a message from the app')+ await vi.advanceTimersByTimeAsync(30_000)+ expect(onError).toHaveBeenCalledWith('s1', 'Claude Code asked for permission just as your message was typed, so it was not sent; it waits in Claude Code\'s prompt. Answer the request in the app or in its terminal, then press Enter in its terminal to send the message, or clear it there.')+ expect(forget).toHaveBeenCalled()+ expect(onSubmitted).not.toHaveBeenCalled()+ expect(sendKey).not.toHaveBeenCalled()+ // With a receipt: refused with the reason; a team's, without telling a person.+ onError.mockClear()+ controller.submit('s1', 'from the device', 'd1')+ await vi.advanceTimersByTimeAsync(30_000)+ expect(onDelivery).toHaveBeenCalledWith({ sessionId: 's1', deliveryId: 'd1', state: 'rejected', reason: 'enter_withheld' })+ expect(onError).toHaveBeenCalledTimes(1)+ controller.submit('s1', 'a team turn', 'team:1')+ await vi.advanceTimersByTimeAsync(30_000)+ expect(onDelivery).toHaveBeenCalledWith({ sessionId: 's1', deliveryId: 'team:1', state: 'rejected', reason: 'enter_withheld' })+ expect(onError).toHaveBeenCalledTimes(1)+ expect(sendKey).not.toHaveBeenCalled()+ controller.forget('s1')+ })+it('rejects a message that wants a receipt with the reason, and says why', async () => {const onError = vi.fn(), onDelivery = vi.fn()const controller = new SessionInputController({ getSession: () => session('codex'), validateRuntime: async () => true,@@ -411,7 +471,7 @@ describe('SessionInputController', () => {validateRuntime: async () => true,inject: async () => true,sendKey,- capture: async () => '❯ \n✻ Working (esc to interrupt)',+ capture: async () => claudeBox('', '✻ Working (esc to interrupt)\n\n'),onError,})@@ -548,7 +608,7 @@ describe('SessionInputController', () => {validateRuntime: async () => true,inject: async () => true,sendKey,- capture: async () => '❯ hello',+ capture: async () => claudeBox('hello'),onError,})@@ -569,7 +629,7 @@ describe('SessionInputController', () => {validateRuntime: async () => true,inject: async () => true,sendKey,- capture: async () => '› Find and fix a bug in @filename\n gpt-5.5 medium ·',+ capture: async () => codexComposer('\u001b[2mFind and fix a bug in @filename\u001b[0m', ' gpt-5.5 medium ·'),onError,})@@ -590,7 +650,7 @@ describe('SessionInputController', () => {validateRuntime: async () => true,inject: async () => true,sendKey,- capture: async () => '› hello',+ capture: async () => codexComposer('hello'),onError,})@@ -656,7 +716,7 @@ describe('SessionInputController', () => {validateRuntime: async () => true,inject: async () => ambiguous,sendKey,- capture: async () => '› hello',+ capture: async () => codexComposer('hello'),onError: vi.fn(),})@@ -693,7 +753,7 @@ describe('SessionInputController', () => {it('requires fresh draft evidence before retrying an ambiguously completed Enter', async () => {vi.useFakeTimers()- const captures = ['› hello', null]+ const captures = [codexComposer('hello'), null]const sendKey = vi.fn(async (_target: string, _key: string): Promise<TerminalActionResult> => ({state: 'unknown', dispatch: 'possibly_executed', reason: 'Enter response was lost',}))diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.tsindex 46df3ee7c..ed54b8b02 100644--- a/cli/src/lib/sessionInput.ts+++ b/cli/src/lib/sessionInput.ts@@ -1,8 +1,8 @@import { createHash } from 'crypto'import type { RegisteredSession } from './registry.js'import { sid } from './log.js'-import { isMessageHold, messageHold, messageHoldText, type MessageHold } from './messageHold.js'-import { TERMINAL_LEASE_REFUSED, type TerminalActionResult } from './terminalTypes.js'+import { isMessageHold, messageHold, messageHoldText, messageWithheldText, passingHold, type MessageHold } from './messageHold.js'+import { enterWithheldReason, TERMINAL_LEASE_REFUSED, type TerminalActionResult } from './terminalTypes.js'const MAX_QUEUE_ITEMS = 8const MAX_QUEUE_BYTES = 24 * 1024@@ -136,10 +136,13 @@ function heldBack(delivery: boolean | TerminalActionResult): MessageHold | null&& isMessageHold(delivery.reason) ? delivery.reason : null}-/** A write the pane's control lease refused before a byte of it was written. */+/**+ * A write refused before a byte of it was written for a reason that passes: the pane's control lease, or+ * a screen with no composer on it yet, an engine starting or redrawing (messageHold.ts `passingHold`).+ */function leaseRefused(delivery: boolean | TerminalActionResult): boolean {return typeof delivery !== 'boolean' && delivery.state === 'failed' && delivery.dispatch === 'not_started'- && delivery.reason === TERMINAL_LEASE_REFUSED+ && (delivery.reason === TERMINAL_LEASE_REFUSED || passingHold(delivery.reason))}function fingerprint(content: string): string {@@ -458,6 +461,14 @@ export class SessionInputController {const accepted = typeof delivery === 'boolean'? delivery: delivery.state === 'succeeded' || delivery.dispatch === 'possibly_executed'+ const withheld = enterWithheldReason(delivery)+ if (withheld) {+ // Typed, its Enter not pressed: never pressed later either, which would send it into whatever is open.+ forgetScope?.()+ console.warn(`[inject] ${sid(sessionId)} typed, not sent · engine=${session.engine} · ${withheld} opened before Enter`)+ this.deps.onError(sessionId, messageWithheldText(session.engine, withheld))+ return+ }if (!accepted) {forgetScope?.()const held = heldBack(delivery)@@ -535,6 +546,15 @@ export class SessionInputController {this.finishDelivery(sessionId, state, 'rejected', delivery.reason)return}+ const withheld = enterWithheldReason(delivery)+ if (withheld) {+ // Typed, its Enter not pressed: never pressed later either, which would send it into whatever is open.+ forgetScope?.()+ console.warn(`[inject] ${sid(sessionId)} typed, not sent · engine=${session.engine} · ${withheld} opened before Enter`)+ this.finishDelivery(sessionId, state, 'rejected', 'enter_withheld')+ if (!deliveryId.startsWith('team:')) this.deps.onError(sessionId, messageWithheldText(session.engine, withheld))+ return+ }const held = heldBack(delivery)if (held) {console.warn(`[inject] ${sid(sessionId)} not typed · engine=${session.engine} · ${held}`)diff --git a/cli/src/lib/terminalBackend.ts b/cli/src/lib/terminalBackend.tsindex 0208d5724..0dad5ea1c 100644--- a/cli/src/lib/terminalBackend.ts+++ b/cli/src/lib/terminalBackend.ts@@ -1,4 +1,5 @@import type {+ SubmitOptions,TerminalActionResult,TerminalBackendName,TerminalCaptureOptions,@@ -29,7 +30,7 @@ export interface TerminalBackend<Ref extends TerminalRuntimeRef = TerminalRuntimvalidate(runtime: Ref, expected: TerminalProcessExpectation): Promise<RuntimeValidation>capture(runtime: Ref, options?: TerminalCaptureOptions): Promise<TerminalReadResult<string>>typeLiteral(runtime: Ref, text: string): Promise<TerminalActionResult>- submitText(runtime: Ref, text: string): Promise<TerminalActionResult>+ submitText(runtime: Ref, text: string, options?: SubmitOptions): Promise<TerminalActionResult>sendKey(runtime: Ref, key: TerminalLogicalKey): Promise<TerminalActionResult>setTitle(runtime: Ref, title: string): Promise<TerminalActionResult>notify(runtime: Ref, title: string, body: string): Promise<TerminalActionResult>diff --git a/cli/src/lib/terminalBackendCoordinator.spec.ts b/cli/src/lib/terminalBackendCoordinator.spec.tsindex 95ec3025d..a7e6f7ab2 100644--- a/cli/src/lib/terminalBackendCoordinator.spec.ts+++ b/cli/src/lib/terminalBackendCoordinator.spec.ts@@ -109,7 +109,7 @@ describe('TerminalBackendCoordinator', () => {const result = await new TerminalBackendCoordinator([backend('tmux:default', submit)], ['tmux']).submitText(session(), 'hello')expect(result).toEqual({ state: 'succeeded', dispatch: 'executed' })expect(submit).toHaveBeenCalledTimes(2)- expect(submit).toHaveBeenLastCalledWith(second, 'hello')+ expect(submit).toHaveBeenLastCalledWith(second, 'hello', undefined)})it('never retries a possibly executed side effect', async () => {@@ -200,7 +200,19 @@ describe('TerminalBackendCoordinator', () => {state: 'failed', dispatch: 'rejected',})expect(submit).toHaveBeenCalledOnce()- expect(submit).toHaveBeenCalledWith(tmux, 'hello')+ expect(submit).toHaveBeenCalledWith(tmux, 'hello', undefined)+ })++ it('hands the check before the Enter to the backend, on every way a text is submitted', async () => {+ const submit = submitBy({ state: 'succeeded', dispatch: 'executed' })+ const coordinator = new TerminalBackendCoordinator([backend('tmux:default', submit)], ['tmux'])+ const options = { beforeEnter: async () => null }+ await coordinator.submitText(session(), 'hello', options)+ const acquired = await coordinator.acquireLease(session())+ if (acquired.state !== 'succeeded') throw new Error('no lease')+ await coordinator.submitTextLease(acquired.value, 'hello', options)+ await coordinator.submitTextForLease(session(), acquired.value, 'hello', options)+ expect(submit.mock.calls.map((call) => (call as unknown[])[2])).toEqual([options, options, options])})it('keeps an active lease valid when the backends are replaced by the same instance', async () => {diff --git a/cli/src/lib/terminalBackendCoordinator.ts b/cli/src/lib/terminalBackendCoordinator.tsindex 2e371c7ca..bd92e6588 100644--- a/cli/src/lib/terminalBackendCoordinator.ts+++ b/cli/src/lib/terminalBackendCoordinator.ts@@ -4,6 +4,7 @@ import { processIdentityKey, terminalInstanceId, terminalPlacementKey, terminalRimport {terminalActionNotStarted,type RuntimeValidation,+ type SubmitOptions,type TerminalActionResult,type TerminalCaptureOptions,type TerminalLogicalKey,@@ -258,10 +259,10 @@ export class TerminalBackendCoordinator {: Promise.resolve(terminalActionNotStarted('leased terminal backend is disabled'))}- submitTextLease(lease: TerminalControlLease, text: string): Promise<TerminalActionResult> {+ submitTextLease(lease: TerminalControlLease, text: string, options?: SubmitOptions): Promise<TerminalActionResult> {const backend = this.backendFor(lease.runtime)return backend- ? backend.submitText(lease.runtime, text)+ ? backend.submitText(lease.runtime, text, options): Promise.resolve(terminalActionNotStarted('leased terminal backend is disabled'))}@@ -270,6 +271,7 @@ export class TerminalBackendCoordinator {session: RegisteredSession,lease: TerminalControlLease,text: string,+ options?: SubmitOptions,): Promise<TerminalActionResult> {if (!this.leaseIsCurrent(lease, session)) return terminalActionNotStarted('terminal control lease changed')const ordered = this.orderedRuntimes(session)@@ -283,7 +285,7 @@ export class TerminalBackendCoordinator {if (!backend) continueconst validation = await this.validateRuntime(backend, runtime, session)if (validation.state !== 'alive') continue- const result = await backend.submitText(runtime, text)+ const result = await backend.submitText(runtime, text, options)if (result.state === 'succeeded') {lease.runtime = runtimelease.placementKey = terminalPlacementKey(runtime)@@ -325,8 +327,8 @@ export class TerminalBackendCoordinator {return last}- submitText(session: RegisteredSession, text: string): Promise<TerminalActionResult> {- return this.sideEffect(session, (backend, runtime) => backend.submitText(runtime, text))+ submitText(session: RegisteredSession, text: string, options?: SubmitOptions): Promise<TerminalActionResult> {+ return this.sideEffect(session, (backend, runtime) => backend.submitText(runtime, text, options))}typeLiteral(session: RegisteredSession, text: string): Promise<TerminalActionResult> {diff --git a/cli/src/lib/terminalTypes.ts b/cli/src/lib/terminalTypes.tsindex 185b897bd..e08bfb124 100644--- a/cli/src/lib/terminalTypes.ts+++ b/cli/src/lib/terminalTypes.ts@@ -198,6 +198,24 @@ export function terminalActionRejected(reason: string): {return { state: 'failed', dispatch: 'rejected', reason }}+/**+ * What a submit checks right before its Enter, the text already typed: a reason not to press it. The+ * engine can open a dialog between a paste and its Enter (a long or multi-line one waits up to 1.5 s for+ * the engine to take it in, tmux.ts), and that Enter would answer the dialog.+ */+export interface SubmitOptions { beforeEnter?: () => Promise<string | null> }++/** The text was typed and its Enter not pressed, for `reason`: it waits in the composer, unsent. */+export function terminalEnterWithheld(reason: string): { state: 'unknown'; dispatch: 'possibly_executed'; reason: string } {+ return { state: 'unknown', dispatch: 'possibly_executed', reason: `enter_withheld:${reason}` }+}++/** Why a submit's Enter was not pressed, or null when it was, or the submit did not get that far. */+export function enterWithheldReason(result: boolean | TerminalActionResult): string | null {+ return typeof result !== 'boolean' && result.state === 'unknown' && result.reason.startsWith('enter_withheld:')+ ? result.reason.slice('enter_withheld:'.length) : null+}+export function terminalActionPossiblyExecuted(reason: string): {state: 'unknown'; dispatch: 'possibly_executed'; reason: string} {diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.tsindex 5682ad4fa..f7235869f 100644--- a/cli/src/lib/tmux.spec.ts+++ b/cli/src/lib/tmux.spec.ts@@ -597,6 +597,19 @@ if [ "$1" = "paste-buffer" ] && [ "$TMUX_SUBMIT_FAIL" = "1" ]; then exit 2; fi'load-buffer -b buffer -', 'paste-buffer -t %7 -b buffer -d',])+ // Asked right before the Enter, after the paste: a reason keeps the Enter from being pressed, and an+ // engine that opened a dialog in between gets the text and no Enter.+ for (const message of ['short', 'first\nsecond']) {+ writeFileSync(argsFile, '')+ const asked: string[] = []+ expect(await sendToTmux('%7', message, async () => { asked.push(commands().at(-1)!); return 'permission_open' })).toEqual({ withheld: 'permission_open' })+ expect(asked).toEqual(['paste-buffer -t %7 -b buffer -p -d'])+ expect(commands()).toEqual(['load-buffer -b buffer -', 'paste-buffer -t %7 -b buffer -p -d'])+ }+ writeFileSync(argsFile, '')+ expect(await sendToTmux('%7', 'clear to send', async () => null)).toBe(true)+ expect(commands().at(-1)).toBe('send-keys -t %7 Enter')+writeFileSync(argsFile, '')process.env.TMUX_SUBMIT_FAIL = '1'expect(await sendToTmux('%7', 'must not send')).toBe(false)diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.tsindex 7a44ca794..137b967ff 100644--- a/cli/src/lib/tmux.ts+++ b/cli/src/lib/tmux.ts@@ -1334,13 +1334,19 @@ async function tmuxPasteText(pane: string, content: string, bracketed: boolean):* Short single-line input is submitted immediately after that explicit paste boundary.** Long/multiline input is allowed to settle before Enter. (Verified: reliably submits up to ~28 KB.)+ *+ * `beforeEnter` is asked once the text is in, right before the Enter: a reason it gives keeps the Enter+ * from being pressed, and comes back as `{ withheld }`, the text left typed. An engine can open a dialog+ * in that gap, mid-turn, and the Enter would answer it.*/-export function sendToTmux(pane: string, text: string): Promise<boolean> {+export function sendToTmux(pane: string, text: string, beforeEnter?: () => Promise<string | null>): Promise<boolean | { withheld: string }> {const content = text.replace(/[\r\n]+$/, '') // strip trailing newlines so the submit Enter isn't doubledreturn (async () => {const needsSettle = content.length > INJECT_FASTPATH_MAXLEN || /[\r\n]/.test(content)if (!(await tmuxPasteText(pane, content, true))) return falseif (needsSettle) await sleep(Math.min(1500, INJECT_PASTE_DELAY_BASE_MS + Math.floor(content.length / 60)))+ const withheld = beforeEnter ? await beforeEnter() : null+ if (withheld) return { withheld }return tmuxEnter(pane)})()}diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.tsindex 4df8d1c5e..c2b7b21bf 100644--- a/cli/src/lib/tmuxBackend.spec.ts+++ b/cli/src/lib/tmuxBackend.spec.ts@@ -79,6 +79,21 @@ describe('TmuxBackend lifecycle', () => {})).toMatchObject({ state: 'unknown' })})+ it('submits a text, and leaves it typed with no Enter when the check before the Enter says so', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-submit-'))+ dirs.push(dir)+ const calls = join(dir, 'calls')+ writeFileSync(join(dir, 'tmux'), `#!/bin/sh\nprintf '%s\\n' "$1" >> "$TMUX_BACKEND_CALLS"\nif [ "$1" = "load-buffer" ]; then cat > /dev/null; fi\n`, { mode: 0o700 })+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`+ process.env.TMUX_BACKEND_CALLS = calls+ const backend = new TmuxBackend(undefined, () => 'daemon-a')+ const pane = { backend: 'tmux' as const, paneId: '%42' }+ await expect(backend.submitText(pane, 'hi', { beforeEnter: async () => null })).resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })+ await expect(backend.submitText(pane, 'hi', { beforeEnter: async () => 'permission_open' })).resolves+ .toEqual({ state: 'unknown', dispatch: 'possibly_executed', reason: 'enter_withheld:permission_open' })+ expect(readFileSync(calls, 'utf8').trim().split('\n')).toEqual(['load-buffer', 'paste-buffer', 'send-keys', 'load-buffer', 'paste-buffer'])+ })+it('creates a detached session and closes only its exact pane', async () => {const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-lifecycle-'))dirs.push(dir)diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.tsindex 5e8d1fc24..dcf6c258a 100644--- a/cli/src/lib/tmuxBackend.ts+++ b/cli/src/lib/tmuxBackend.ts@@ -5,6 +5,8 @@ import {TERMINAL_ACTION_SUCCEEDED,terminalActionNotStarted,terminalActionPossiblyExecuted,+ terminalEnterWithheld,+ type SubmitOptions,type TerminalActionResult,type TerminalCaptureOptions,type TerminalCreateRequest,@@ -431,8 +433,9 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {return legacyActionResult(await sendLiteralToTmux(runtime.paneId, text), 'tmux literal input')}- async submitText(runtime: TmuxRuntimeRef, text: string): Promise<TerminalActionResult> {- return legacyActionResult(await sendToTmux(runtime.paneId, text), 'tmux submission')+ async submitText(runtime: TmuxRuntimeRef, text: string, options?: SubmitOptions): Promise<TerminalActionResult> {+ const sent = await sendToTmux(runtime.paneId, text, options?.beforeEnter)+ return typeof sent === 'boolean' ? legacyActionResult(sent, 'tmux submission') : terminalEnterWithheld(sent.withheld)}async sendKey(runtime: TmuxRuntimeRef, key: TerminalLogicalKey): Promise<TerminalActionResult> {