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 never typed into a permission prompt, a question, a menu or Claude Code's transcript view (#821)
Deee3147fb0fd5f
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjsindex 723e155da..34d7eb2b4 100644--- a/cli/e2e/harness/fakeEngine.mjs+++ b/cli/e2e/harness/fakeEngine.mjs@@ -20,7 +20,8 @@// middle of a turn as an automatic compaction does, `!version` answers with the version this// process is, `!goal` and `!goal done` (Codex) start and achieve a goal the way Codex 0.160 shows one// under its composer, `!browse` (Codex) leaves Codex browsing its transcript in its default fullscreen-// mode, and `!browse scrollback` in its scrollback mode, `!exit` ends the process.+// mode, and `!browse scrollback` in its scrollback mode, `!transcript` (Claude Code) leaves it in its+// transcript view, as ctrl+o does, `!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@@ -177,6 +178,10 @@ export async function run(engine, config) {const browsingBottom = { composer: '\x1b[2m› Ask Codex to do anything\x1b[0m', 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+ // hidden, and its footer row under a dim rule.+ const transcriptBottom = (prompt, answer) => ({ transcript: true, pager: `\x1b[?1049h\x1b[H\x1b[2J\x1b[48;5;237m❯ ${prompt}\x1b[49m`+ + `\r\n\r\n⏺ ${answer}\x1b[998;1H\x1b[2m${'─'.repeat(60)}\x1b[0m\x1b[999;1H \x1b[2mShowing detailed transcript · ctrl+o to toggle · ctrl+e to show all\x1b[0m` })const draw = (line = '') => {if (bottom?.pager) { process.stdout.write(bottom.pager); return }if (bottom && !line) {@@ -207,6 +212,8 @@ export async function run(engine, config) {// 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?'const CHOICES = [['Tea', 'Lighter, steeped leaves.'], ['Coffee', 'Stronger, roasted beans.']]const drawDialog = () => {@@ -238,22 +245,33 @@ export async function run(engine, config) {if (dialog?.drawn) process.stdout.write(`\x1b[${dialog.drawn}A\r\x1b[0J`)if (dialog) dialog.drawn = 0}+ // Keys and pastes as the real CLIs take them while a dialog is up. A bracketed paste is one event, never+ // keys, in both (Claude Code's Ink input parser; Codex's crossterm): neither engine's permission prompt+ // takes a paste (Claude Code's Select has no paste handler, Codex's ApprovalOverlay leaves+ // `handle_paste` to its default), so it is dropped, and Enter then confirms the focused row, which is+ // the first: approve (Codex's own test, approval_overlay.rs `enter_sets_last_selected_index…`, expects+ // Accept). In a question, Claude Code drops the paste the same way and Enter picks the focused option;+ // Codex takes a paste as notes on the focused option (request_user_input `handle_paste`) and Enter+ // submits it. Digits pick a row; Codex's `y` approves; arrows move; Esc declines or cancels.const dialogKeys = (chunk) => {- for (const key of chunk.match(/\x1b\[[AB]|\x1b|\r|\n|./gs) ?? []) {+ for (const key of chunk.match(/\x1b\[200~[\s\S]*?(?:\x1b\[201~|$)|\x1b\[[AB]|\x1b|\r|\n|./gs) ?? []) {if (!dialog) return- const settle = (choice) => { eraseDialog(); const asked = dialog; dialog = null; asked.resolve(choice) }+ const settle = (choice) => { eraseDialog(); const asked = dialog; dialog = null; notes = asked.notes ?? ''; asked.resolve(choice) }const rows = dialog.kind === 'permit' ? 3 : engine === 'claude' ? CHOICES.length : CHOICES.length + 1+ if (key.startsWith('\x1b[200~')) {+ if (dialog.kind !== 'permit' && engine === 'codex') dialog.notes = key.slice(6).replace(/\x1b\[201~$/, '')+ continue+ }+ if (key === '\x1b[B') { dialog.cursor = Math.min(dialog.cursor + 1, rows - 1); drawDialog(); continue }+ if (key === '\x1b[A') { dialog.cursor = Math.max(dialog.cursor - 1, 0); drawDialog(); continue }if (dialog.kind === 'permit') {- // Both CLIs take a row's digit (and Codex its letter) as the decision; Esc declines.if (key === '\x1b') settle(null)else if (key === 'y' && engine === 'codex') settle(0)else if (key === '\r' || key === '\n') settle(dialog.cursor)else if (/^[1-3]$/.test(key)) settle(Number(key) - 1)continue}- if (key === '\x1b[B') { dialog.cursor = Math.min(dialog.cursor + 1, rows - 1); drawDialog() }- else if (key === '\x1b[A') { dialog.cursor = Math.max(dialog.cursor - 1, 0); drawDialog() }- else if (key === '\x1b') settle(null)+ if (key === '\x1b') settle(null)else if (key === '\r' || key === '\n') settle(CHOICES[dialog.cursor]?.[0] ?? 'None of the above')else if (/^[1-9]$/.test(key) && Number(key) <= rows) {dialog.cursor = Number(key) - 1@@ -417,7 +435,7 @@ export async function run(engine, config) {codex('response_item', { type: 'function_call_output', call_id: id, output: JSON.stringify({ answers: { [QUESTION]: choice } }) })process.stdout.write(`\r\n• ${QUESTION} → ${choice}\r\n`)}- finish(`you chose ${choice}`)+ finish(`you chose ${choice}${notes ? ` (notes: ${notes})` : ''}`)return}if (directive?.[1] === 'version') { finish(versionLine); return }@@ -426,6 +444,11 @@ export async function run(engine, config) {finish(`answer ${turn}: ${prompt}`)return}+ if (engine === 'claude' && directive?.[1] === 'transcript') {+ bottom = transcriptBottom(prompt, `answer ${turn}: ${prompt}`)+ finish(`answer ${turn}: ${prompt}`)+ return+ }if (engine === 'codex' && directive?.[1] === 'browse') {// Reached in Codex by Esc twice on an empty composer; the directive goes straight there.bottom = directive[2] === 'scrollback' ? pagerBottom(prompt, `answer ${turn}: ${prompt}`) : browsingBottom@@ -446,6 +469,18 @@ export async function run(engine, config) {process.stdin.on('data', (input) => {if (dialog) { dialogKeys(input); return }let chunk = input+ if (bottom?.transcript) {+ // As Claude Code takes input in its transcript view: its Transcript keys only, where Esc, q and ctrl+c+ // close it; it has no Enter and no paste, so a message is lost there. Keys after the one that closes+ // it reach the prompt.+ 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?.transcript) rest += token+ else if (token === '\x1b' || token === 'q' || token === '\x03') { process.stdout.write('\x1b[?1049l'); bottom = null; draw() }+ }+ if (!rest) return+ chunk = rest+ }if (bottom?.browsing) {// As Codex 0.160 takes input while browsing (app.rs, app_backtrack): Esc goes back to the composer// and Enter reverts the conversation to the prompt in view, in both modes; arrows and hjkl movediff --git a/cli/e2e/input-safety.e2e.ts b/cli/e2e/input-safety.e2e.tsindex 9b808842a..431367c20 100644--- a/cli/e2e/input-safety.e2e.ts+++ b/cli/e2e/input-safety.e2e.ts@@ -1,7 +1,8 @@/*** What a message must never do, for Claude Code and Codex: reach the shell an exited engine leaves in- * its pane, where it would run as a command, or a picker for a point to rewind the conversation to,- * where its Enter would pick one. And what a client must never cost the others: one that+ * its pane, where it would run as a command, a picker for a point to rewind the conversation to, where+ * its Enter would pick one, or a view where it is lost. (A permission prompt or a question is in+ * questions.e2e.ts.) And what a client must never cost the others: one that* stops reading is cut off, alone, and the daemon's memory stays bounded while it is.*/import { existsSync, mkdirSync } from 'node:fs'@@ -98,6 +99,24 @@ describe('what a message must never do', () => {client.close()})+ it('claude: a message is not lost in its transcript view (ctrl+o): refused with the reason, it goes through once the view is closed', async () => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, 'claude', 'transcript-view')+ await turn(client, agent.id, '!transcript')+ await until('the view to be drawn', async () => (await d.capture(agent.tmuxPane)).includes('Showing detailed transcript') || null, 15_000, 250)+ const from = client.frames.length+ const refused = client.next((frame) => frame.type === 'error' && frame.agentId === agent.id, 15_000, 'the refusal')+ client.send('message', { agentId: agent.id, content: 'and the logout bug?' })+ expect(String((await refused).payload?.message)).toBe('Claude Code is showing its transcript (ctrl+o), where a message is not typed. Close it with Esc in its terminal, then send the message again.')+ expect(client.frames.slice(from).some(isTurn('turn_started', agent.id))).toBe(false)+ // Closed with Esc, as the refusal says, the same message goes through.+ await d.tmux.run('send-keys', '-t', agent.tmuxPane, 'Escape')+ await until('the prompt to be back', async () => !(await d.capture(agent.tmuxPane)).includes('Showing detailed transcript') || null, 15_000, 250)+ await turn(client, agent.id, 'and the logout bug?')+ client.close()+ })+it.each(engines)('%s: keystrokes queued for a terminal whose engine exited are the person\'s own to send', async (engine) => {// The terminal is a terminal: what a person types into the pane goes to whatever runs there. The// composer is what must never type into a shell; this pins that the two stay apart.diff --git a/cli/e2e/questions.e2e.ts b/cli/e2e/questions.e2e.tsindex 02fe3d2dd..4e69a244a 100644--- a/cli/e2e/questions.e2e.ts+++ b/cli/e2e/questions.e2e.ts@@ -2,7 +2,8 @@* An agent's question, end to end, for Claude Code and Codex: the dialog the engine draws reaches the* window as a question, the answer chosen there is typed into the dialog and is the one the agent gets,* and an answer to a question that is no longer the one on screen types nothing. A permission prompt- * is a question too: Yes in the window runs the command, No leaves it unrun.+ * is a question too: Yes in the window runs the command, No leaves it unrun. A message a person sends+ * meanwhile is not typed into either: the prompt drops a paste and takes its Enter as the focused row.*/import { mkdirSync } from 'node:fs'import { join } from 'node:path'@@ -113,4 +114,59 @@ describe('an agent asks a question', () => {expect(await d.capture(agent.tmuxPane)).toContain('you chose Tea')client.close()})++ it.each(engines)('%s: a message sent while a permission prompt is open approves nothing: refused with the reason, and the prompt still answers', async (engine) => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, engine, `permit-message-${engine}`)+ const asked = client.next((frame) => frame.type === 'commander_question' && frame.agentId === agent.id, 30_000, 'commander_question')+ client.send('message', { agentId: agent.id, content: '!permit printf hi' })+ const question = await asked+ const shaped = question.payload?.questions?.[0]+ const from = client.frames.length+ client.send('message', { agentId: agent.id, content: 'what will that command do?' })+ // Either the refusal arrives, or the message's Enter took the focused row, Yes, and the command ran.+ const outcome = await until('the refusal, or the command run by the message', async () => {+ if ((await d.capture(agent.tmuxPane)).includes('ran printf hi')) return 'the message approved the command'+ const refused = client.frames.slice(from).find((frame) => frame.type === 'error' && frame.agentId === agent.id)+ return refused ? String(refused.payload?.message) : null+ }, 20_000, 250)+ expect(outcome).toBe(engine === 'claude'+ ? 'Claude Code is asking for permission. Answer it first, in the app or in its terminal, then send the message again.'+ : 'Codex is asking for approval. Answer it first, in the app or in its terminal, then send the message again.')+ // Still asking: the answer goes through its own path, and No leaves the command unrun.+ 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 prompt answered, the same message goes through.+ await turn(client, agent.id, 'what will that command do?')+ client.close()+ })++ it.each(engines)('%s: a message sent while a question is open answers nothing: refused with the reason, and the question still answers', async (engine) => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, engine, `ask-message-${engine}`)+ const asked = client.next((frame) => frame.type === 'commander_question' && frame.agentId === agent.id, 30_000, 'commander_question')+ client.send('message', { agentId: agent.id, content: '!ask' })+ const question = await asked+ const shaped = question.payload?.questions?.[0]+ const from = client.frames.length+ client.send('message', { agentId: agent.id, content: 'something stronger' })+ // Claude Code drops the paste and its Enter picks the focused option; Codex takes the paste as notes+ // on it and its Enter submits that.+ const outcome = await until('the refusal, or the question answered by the message', async () => {+ if ((await d.capture(agent.tmuxPane)).includes('you chose')) return 'the message answered the question'+ const refused = client.frames.slice(from).find((frame) => frame.type === 'error' && frame.agentId === agent.id)+ return refused ? String(refused.payload?.message) : null+ }, 20_000, 250)+ expect(outcome).toBe(`${engine === 'claude' ? 'Claude Code' : 'Codex'} is asking you a question. Answer it first, in the app or in its terminal, then send the message again.`)+ 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]: 'Coffee' })).error).toBeUndefined()+ await ended+ expect(await d.capture(agent.tmuxPane)).toContain('you chose Coffee')+ expect(await d.capture(agent.tmuxPane)).not.toContain('notes:')+ client.close()+ })})diff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.tsindex b26295cb4..2f84863d3 100644--- a/cli/src/core/input.spec.ts+++ b/cli/src/core/input.spec.ts@@ -1,14 +1,20 @@+import { readdirSync, readFileSync } from 'node:fs'+import { join } from 'node:path'import { afterEach, describe, expect, it, vi } from 'vitest'import type { CommandCodeNormalizer } from '../engines/commandcode/normalizer.js'import type { AutonomousDeviceInput } from '../lib/autonomous-device/input.js'import { deviceErrorText } from '../lib/deviceErrors.js'import type { RegisteredSession } from '../lib/registry.js'import type { SessionInputDelivery } from '../lib/sessionInput.js'-import { REWIND_PICKER_OPEN, type TerminalActionResult } from '../lib/terminalTypes.js'+import type { TerminalActionResult } from '../lib/terminalTypes.js'import { CLAUDE_REWIND_LIST, CODEX_BROWSING_SCROLLBACK } from '../lib/__fixtures__/rewindPickers.js'-import { createInput, createMessageRequest, deviceInputDeps, sessionInputDeps, type InputDeps } from './input.js'+import { createInput, createMessageRequest, deviceInputDeps, messageWriter, sessionInputDeps, type InputDeps } from './input.js'const ok: TerminalActionResult = { state: 'succeeded', dispatch: 'executed' }+const fixture = (name: string) => readFileSync(new URL(`../lib/__fixtures__/${name}`, import.meta.url), 'utf8')+/** Claude Code asking to run a command, and Command Code the same: the Enter behind a paste approves. */+const CLAUDE_PERMISSION = fixture('permission-claude.txt')+const COMMANDCODE_PERMISSION = fixture('permission-commandcode.txt')/** A Claude Code composer that is empty and idle: ready for a team write. */const READY_PANE = '────────────\n❯\n────────────\n ? for shortcuts'@@ -97,26 +103,27 @@ describe('the session input controller\'s dependencies', () => {expect(calls).toEqual(['lock a1', 'submit a1 hello', 'lock a1', 'key a1 enter'])})- it('never types a person\'s message into a picker for a point to rewind to, and reads no other engine\'s pane for one', async () => {+ it('types a message only into a pane it has read in the pane\'s lock and found ready for one', async () => {const run = deps()const wired = sessionInputDeps(run.deps, () => lock(run.calls))- const refused = { state: 'failed', dispatch: 'not_started', reason: REWIND_PICKER_OPEN }+ run.setPane(CLAUDE_PERMISSION)+ expect(await wired.inject('a1', 'hello')).toEqual({ state: 'failed', dispatch: 'not_started', reason: 'permission_open' })run.setPane(CLAUDE_REWIND_LIST)- expect(await wired.inject('a1', 'hello')).toEqual(refused)+ expect(await wired.inject('a1', 'hello')).toEqual({ state: 'failed', dispatch: 'not_started', reason: 'rewind_picker_open' })run.setPane(CODEX_BROWSING_SCROLLBACK)- expect(await wired.inject('cx', 'hello')).toEqual(refused)- // Read inside the pane lock, and nothing written.- expect(run.calls).toEqual(['lock a1', 'lock cx'])- // A pane that cannot be read is written as before; so is one with no picker, and an engine without one.+ expect(await wired.inject('cx', 'hello')).toEqual({ state: 'failed', dispatch: 'not_started', reason: 'rewind_picker_open' })+ run.setPane(COMMANDCODE_PERMISSION)+ 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.run.setPane(null)expect(await wired.inject('cx', 'hi')).toBe(ok)run.setPane(READY_PANE)expect(await wired.inject('a1', 'hi')).toBe(ok)- vi.mocked(run.deps.terminal.captureTerminal).mockClear()- expect(await wired.inject('cc', 'hi')).toBe(ok)- expect(await wired.inject('nobody', 'hi')).toBe(ok)- expect(run.deps.terminal.captureTerminal).not.toHaveBeenCalled()- expect(run.calls.filter((call) => call.startsWith('submit'))).toEqual(['submit cx hi', 'submit a1 hi', 'submit cc hi', 'submit nobody hi'])+ 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'])})it('writes a team turn only into a ready pane whose delivery still holds control', async () => {@@ -154,14 +161,16 @@ describe('the session input controller\'s dependencies', () => {})describe('the device input\'s dependencies', () => {- it('reaches the terminal directly', async () => {+ it('reaches the terminal directly, its messages through the one writer', async () => {const { deps: given } = deps()const wired = deviceInputDeps(given, () => ({ acquireControl: vi.fn(), submit: vi.fn(), cancelDelivery: vi.fn() }))expect(wired.getSession('a1')?.sessionId).toBe('s1')expect(wired.validateRuntime).toBe(given.terminal.validateTerminal)- expect(wired.inject).toBe(given.terminal.submitTerminalAction)expect(wired.sendKey).toBe(given.terminal.keyTerminalAction)expect(wired.capture).toBe(given.terminal.captureTerminal)+ // Its writes are read first, as every message's is.+ expect(await wired.inject('a1', 'hello')).toBe(ok)+ expect(given.terminal.captureTerminal).toHaveBeenCalledWith('a1')})it('waits for the person when the pane cannot be read or asks a question', async () => {@@ -173,9 +182,11 @@ describe('the device input\'s dependencies', () => {expect(await wired.isAwaitingUser!(agents.get('a1')!)).toBe(false)})- it('waits for the person while a picker for a point to rewind to is open', async () => {+ it('waits for the person while anything a message is not typed into is open', async () => {const run = deps()const wired = deviceInputDeps(run.deps, () => ({ acquireControl: vi.fn(), submit: vi.fn(), cancelDelivery: vi.fn() }))+ run.setPane(CLAUDE_PERMISSION)+ expect(await wired.isAwaitingUser!(agents.get('a1')!)).toBe(true)run.setPane(CLAUDE_REWIND_LIST)expect(await wired.isAwaitingUser!(agents.get('a1')!)).toBe(true)run.setPane(CODEX_BROWSING_SCROLLBACK)@@ -294,3 +305,57 @@ describe('message', () => {expect(submit.mock.calls).toEqual([['a1', 'hi'], ['s1', 'hi'], ['a1', 'in a tab', undefined, 'swarm-a'], ['a1', 'not a tab']])})})++describe('every route a message takes to a pane', () => {+ afterEach(() => vi.restoreAllMocks())++ /** Each way a message reaches an agent's pane, and what it is told when the pane holds it back. */+ const asking = 'Claude Code is asking for permission. Answer it first, in the app or in its terminal, then send the message again.'+ const refused = (deliveryId: string, reason: string) => expect.objectContaining({ deliveryId, state: 'rejected', reason })+ const routes: Array<[string, string, (inputs: ReturnType<typeof createInput>) => void, (run: ReturnType<typeof deps>) => void]> = [+ ['the app', 'a1', (inputs) => inputs.messageRequest({ agentId: 'a1', content: 'from the app' }),+ (run) => expect(run.deps.clients.send).toHaveBeenCalledWith(expect.objectContaining({ type: 'error', agentId: 'a1', payload: { message: asking } }))],+ ['the phone, through the relay\'s message frame', 'a1', (inputs) => inputs.messageRequest({ sessionId: 's1', content: 'from the phone', tabId: 'tab-1' }),+ (run) => expect(run.deps.clients.send).toHaveBeenCalledWith(expect.objectContaining({ type: 'error', agentId: 'a1', payload: { message: asking } }))],+ ['the orchestrator', 'a1', (inputs) => inputs.submitAgent('a1', 'from the orchestrator', 'orchestrator-1'),+ (run) => expect(run.deps.teams.delivery).toHaveBeenCalledWith(refused('orchestrator-1', 'permission_open'))],+ ['a team', 'a1', (inputs) => inputs.submitAgent('a1', 'from a team', 'team:1'),+ (run) => expect(run.deps.teams.delivery).toHaveBeenCalledWith(refused('team:1', 'team_waiting_user'))],+ ['the Device, to Claude Code', 'a1', (inputs) => inputs.deviceInput.submit('a1', 'from the device', 'device-1'),+ (run) => expect(run.device.inputStatus).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'device-1', phase: 'waiting_for_user' }))],+ ['the Device, to an engine it queues for', 'cc', (inputs) => inputs.deviceInput.submit('cc', 'from the device', 'device-2'),+ (run) => expect(run.device.delivery).toHaveBeenCalledWith(refused('device-2', 'permission_open'))],+ ]++ it.each(routes)('%s: types nothing into a permission prompt, and says why', async (_route, agent, send, told) => {+ const run = deps()+ run.setPane(agent === 'cc' ? COMMANDCODE_PERMISSION : CLAUDE_PERMISSION)+ const inputs = createInput(run.deps)+ send(inputs)+ await vi.waitFor(() => told(run))+ expect(run.deps.terminal.submitTerminalAction).not.toHaveBeenCalled()+ inputs.deviceInput.forget(agent)+ inputs.input.forget(agent)+ })++ it.each(routes)('%s: reaches the pane when it is ready', async (_route, agent, send) => {+ const run = deps()+ const inputs = createInput(run.deps)+ send(inputs)+ await vi.waitFor(() => expect(run.deps.terminal.submitTerminalAction).toHaveBeenCalledTimes(1))+ inputs.deviceInput.forget(agent)+ inputs.input.forget(agent)+ })++ it('has one writer: nothing in the daemon submits text to a pane but it', () => {+ // A route added later that called the terminal directly would type into a permission prompt.+ const root = new URL('../', import.meta.url).pathname+ const sources = (dir: string): string[] => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => entry.isDirectory()+ ? sources(join(dir, entry.name))+ : entry.name.endsWith('.ts') && !entry.name.endsWith('.spec.ts') ? [join(dir, entry.name)] : [])+ const using = sources(root).filter((file) => readFileSync(file, 'utf8').includes('submitTerminalAction')).map((file) => file.slice(root.length))+ expect(using.sort()).toEqual(['core/input.ts', 'core/terminals/control.ts'])+ expect(readFileSync(join(root, 'core/input.ts'), 'utf8').match(/submitTerminalAction\(/g)).toHaveLength(1)+ expect(messageWriter).toBeTypeOf('function')+ })+})diff --git a/cli/src/core/input.ts b/cli/src/core/input.tsindex 369c8bcbc..861410990 100644--- a/cli/src/core/input.ts+++ b/cli/src/core/input.ts@@ -12,15 +12,14 @@import { AutonomousDeviceInput, type DeviceInputDeps } from '../lib/autonomous-device/input.js'import type { AutonomousDeviceService } from '../lib/autonomous-device/service.js'import type { CommandCodeNormalizer } from '../engines/commandcode/normalizer.js'-import { parseEngineQuestionPane } from '../lib/askQuestion.js'import { deviceErrorText } from '../lib/deviceErrors.js'import { adaptSlashCommand } from '../lib/goalCommand.js'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 { REWIND_PICKER_ENGINES, rewindPickerOpen } from '../lib/runtimeProfileController.js'-import { REWIND_PICKER_OPEN, terminalActionNotStarted } from '../lib/terminalTypes.js'+import { messageHold } from '../lib/messageHold.js'+import { terminalActionNotStarted, type TerminalActionResult } from '../lib/terminalTypes.js'import { Id } from '../teams/model.js'import { teamWriteHold } from '../teams/preflight.js'import type { TerminalControl } from './terminals/control.js'@@ -50,12 +49,33 @@ export interface InputDeps {emit: (sessionId: string, events: LiveEvent[]) => void}+/**+ * The one way a message reaches an agent's pane: a person's from the app or the phone (the relay hands+ * the phone's over as the same `message` frame), the orchestrator's, a team's, and the Device's alike.+ * 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.+ */+export function messageWriter({ resolve, terminal: { captureTerminal, submitTerminalAction } }: Pick<InputDeps, 'resolve' | 'terminal'>) {+ return async (id: string, text: string, hold?: (session: RegisteredSession, capture: string | null) => string | null): Promise<TerminalActionResult> => {+ const session = resolve(id)+ if (!session) return terminalActionNotStarted('terminal agent is unavailable')+ const capture = await captureTerminal(id)+ const reason = hold?.(session, capture) ?? messageHold(session.engine, capture)+ return reason ? terminalActionNotStarted(reason) : submitTerminalAction(id, text)+ }+}+/** What `SessionInputController` is given: every write takes the device's pane lock first. */export function sessionInputDeps(- { resolve, terminal, teams, device, clients, agentIdFor, commandcode, emit }: InputDeps,+ deps: InputDeps,deviceInput: () => Pick<AutonomousDeviceInput, 'legacyWrite'>,): SessionInputDeps {- const { captureTerminal, validateTerminal, submitTerminalAction, keyTerminalAction } = terminal+ const { resolve, terminal, teams, device, clients, agentIdFor, commandcode, emit } = deps+ const { captureTerminal, validateTerminal, keyTerminalAction } = terminal+ const writeMessage = messageWriter(deps)return {beforeSubmit: (id, text, tabId, deliveryId) => teams.prepare(id, text, tabId, deliveryId),getSession: (id) => resolve(id),@@ -68,24 +88,13 @@ export function sessionInputDeps(return teamWriteHold(session.engine, capture)},validateRuntime: validateTerminal,- // A person's message is typed into the pane as it stands, a draft or a running turn included, but not- // into a picker for a point to rewind the conversation to, where Enter picks one: Claude Code's Rewind- // menu drops the text, and so does Codex's transcript browser in its scrollback mode, so the Enter- // behind it rewinds. (Its fullscreen mode would take the text back to the composer; the two modes are- // not told apart before typing.) Read inside the pane's write lock, right before the paste.- inject: (id, text) => deviceInput().legacyWrite(id, async () => {- const engine = resolve(id)?.engine- if (engine && REWIND_PICKER_ENGINES.has(engine) && rewindPickerOpen(engine, await captureTerminal(id))) {- return terminalActionNotStarted(REWIND_PICKER_OPEN)- }- return submitTerminalAction(id, text)- }),+ // Typed into the pane as it stands, a draft or a running turn included, under the pane's write lock.+ inject: (id, text) => deviceInput().legacyWrite(id, () => writeMessage(id, text)),+ // A team's turn waits for a ready composer, and for its delivery to still hold the pane.injectTeam: (id, text, deliveryId) => deviceInput().legacyWrite(id, async () => {- const session = resolve(id)- const reason = session ? teamWriteHold(session.engine, await captureTerminal(id)) : 'team_waiting_unavailable'- if (reason) return { state: 'failed', dispatch: 'not_started', reason }- if (!teams.canWrite(deliveryId)) return terminalActionNotStarted('team_waiting_control')- return submitTerminalAction(id, text)+ if (!resolve(id)) return terminalActionNotStarted('team_waiting_unavailable')+ return writeMessage(id, text, (session, capture) => teamWriteHold(session.engine, capture)+ ?? (teams.canWrite(deliveryId) ? null : 'team_waiting_control'))}),sendKey: (id, key) => deviceInput().legacyWrite(id, () => keyTerminalAction(id, key)),capture: captureTerminal,@@ -112,21 +121,22 @@ export function sessionInputDeps(/** What `AutonomousDeviceInput` is given: the terminal directly, and the controller for queued input. */export function deviceInputDeps(- { resolve, byAgent, terminal, device }: InputDeps,+ deps: InputDeps,input: () => Pick<SessionInputController, 'acquireControl' | 'submit' | 'cancelDelivery'>,): DeviceInputDeps {- const { captureTerminal, validateTerminal, submitTerminalAction, keyTerminalAction } = terminal+ const { resolve, byAgent, terminal, device } = deps+ const { captureTerminal, validateTerminal, keyTerminalAction } = terminalreturn {getSession: id => resolve(id),validateRuntime: validateTerminal,- inject: submitTerminalAction,+ // The Device holds the pane's write lock itself while it writes.+ inject: messageWriter(deps),sendKey: keyTerminalAction,capture: captureTerminal,- // A question on screen, or a picker for a point to rewind to: the Device's message waits for either to- // close rather than be typed into it.+ // Whatever a message is not typed into, the Device's waits for it to close, rather than be refused.isAwaitingUser: async session => {const pane = await captureTerminal(session.agentId)- return pane === null || parseEngineQuestionPane(session.engine, pane) !== null || rewindPickerOpen(session.engine, pane)+ return pane === null || messageHold(session.engine, pane) !== null},acquireControl: id => input().acquireControl(id, { forAnswer: true }),legacySubmit: (id, text, deliveryId) => input().submit(id, text, deliveryId),diff --git a/cli/src/lib/autonomous-device/input.spec.ts b/cli/src/lib/autonomous-device/input.spec.tsindex ec669ad6d..6d7a1748f 100644--- a/cli/src/lib/autonomous-device/input.spec.ts+++ b/cli/src/lib/autonomous-device/input.spec.ts@@ -391,3 +391,20 @@ it('excludes legacy writes only during Device ownership of the same pane', asyncexpect(writes).toEqual(['local-before', 'device', 'other-pane', 'local-after'])controller.forget('agent')})++it('says why a write the pane refused was not typed, when a dialog opened after the look for one', async () => {+ // The look before the write found the composer; the engine opened a permission prompt in between, and the+ // write refused it unwritten (core/input.ts, messageHold.ts). The refusal carries that reason, not a paste+ // that failed.+ const onDelivery = vi.fn()+ const results: TerminalActionResult[] = [+ { state: 'failed', dispatch: 'not_started', reason: 'permission_open' },+ { state: 'failed', dispatch: 'not_started', reason: 'terminal agent is unavailable' },+ ]+ const device = makeDevice({ inject: async () => results.shift()!, isAwaitingUser: async () => false, onDelivery })+ device.submit('agent', 'A', 'delivery-A')+ await vi.waitFor(() => expect(onDelivery).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'delivery-A', state: 'rejected', reason: 'permission_open' })))+ device.submit('agent', 'B', 'delivery-B')+ await vi.waitFor(() => expect(onDelivery).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'delivery-B', state: 'rejected', reason: 'paste_failed' })))+ device.forget('agent')+})diff --git a/cli/src/lib/autonomous-device/input.ts b/cli/src/lib/autonomous-device/input.tsindex aea482f3a..6e4e07d1e 100644--- a/cli/src/lib/autonomous-device/input.ts+++ b/cli/src/lib/autonomous-device/input.ts@@ -3,6 +3,7 @@ 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'const NATIVE = new Set(['claude', 'codex'])const VERIFY_MS = 1500@@ -194,7 +195,9 @@ export class AutonomousDeviceInput {if (item.started) { this.finishWrite(id, state, item); return }if (rejected(result)) {state.pending = state.pending.filter(next => next !== item)- this.delivery(id, item, 'rejected', 'paste_failed'); this.finishWrite(id, state, item); return+ // A dialog that opened between the look for one and the write: refused unwritten, and why.+ const reason = typeof result !== 'boolean' && result.state === 'failed' && isMessageHold(result.reason) ? result.reason : 'paste_failed'+ this.delivery(id, item, 'rejected', reason); this.finishWrite(id, state, item); return}item.retry = executed(result)this.status(id, item, 'submitted')diff --git a/cli/src/lib/messageHold.spec.ts b/cli/src/lib/messageHold.spec.tsnew file mode 100644index 000000000..19d4046a9--- /dev/null+++ b/cli/src/lib/messageHold.spec.ts@@ -0,0 +1,93 @@+import { readFileSync } from 'node:fs'+import { describe, expect, it } from 'vitest'+import { isMessageHold, messageHold, messageHoldText, 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'++const fixture = (name: string) => readFileSync(new URL(`./__fixtures__/${name}`, import.meta.url), 'utf8')+const RULE = '─'.repeat(100)++/**+ * Claude Code's transcript view (ctrl+o), as 2.1.289 draws it: the conversation, its prompt hidden, and+ * a footer row under a dim rule: `Showing detailed transcript · ctrl+o to toggle · ctrl+e to show all`,+ * `verbose` on the right.+ */+const CLAUDE_TRANSCRIPT = [+ '\u001b[38;5;239m\u001b[48;5;237m❯ \u001b[38;5;231mfix the login bug\u001b[39m\u001b[49m',+ '',+ '\u001b[38;5;246m⏺\u001b[39m Fixed: the session cookie was never refreshed.',+ '',+ `\u001b[2m${RULE}\u001b[0m`,+ ' \u001b[2mShowing detailed transcript · ctrl+o to toggle · ctrl+e to show all\u001b[0m \u001b[2mverbose \u001b[0m',+].join('\n')++/**+ * Codex's model picker, as the runtime profile spec has it (runtimeProfileController.spec.ts): a menu+ * where Enter picks the highlighted model. One that the question reader also reads, as Claude Code's+ * menus with a numbered footer are, is held as a question, the way the app shows it.+ */+const CODEX_MODEL_MENU = 'Select Model and Effort\n› 1. gpt-5.6-sol (current)\n 2. gpt-5.6-terra'++describe('what a message is not typed into', () => {+ it('is a permission prompt, in Claude Code, Codex and every engine whose prompt the daemon reads', () => {+ for (const [engine, name] of [['claude', 'permission-claude.txt'], ['claude', 'permission-claude-edit.txt'], ['claude', 'permission-claude-plan.txt'],+ ['codex', 'permission-codex.txt'], ['commandcode', 'permission-commandcode.txt'], ['cursor', 'permission-cursor.txt']] as const) {+ expect(messageHold(engine, fixture(name)), name).toBe('permission_open')+ }+ })++ it('is a question, which is answered through its own path', () => {+ for (const [engine, name] of [['claude', 'question-single.txt'], ['claude', 'question-multi.txt'], ['codex', 'question-codex.txt']] as const) {+ expect(messageHold(engine, fixture(name)), name).toBe('question_open')+ }+ })++ it('is, in Claude Code and Codex, a menu, a picker for a point to rewind to, or Claude Code\'s transcript view', () => {+ expect(messageHold('codex', CODEX_MODEL_MENU)).toBe('menu_open')+ expect(messageHold('claude', CLAUDE_REWIND_LIST)).toBe('rewind_picker_open')+ expect(messageHold('claude', CLAUDE_REWIND_CONFIRM)).toBe('rewind_picker_open')+ expect(messageHold('codex', CODEX_BROWSING_FULLSCREEN)).toBe('rewind_picker_open')+ expect(messageHold('codex', CODEX_BROWSING_SCROLLBACK)).toBe('rewind_picker_open')+ expect(messageHold('claude', CLAUDE_TRANSCRIPT)).toBe('transcript_open')+ // With a dialog waiting behind it, and the footer cut short by a narrow pane.+ expect(messageHold('claude', CLAUDE_TRANSCRIPT.replace('Showing detailed', 'dialog waiting · Showing detailed'))).toBe('transcript_open')+ expect(messageHold('claude', CLAUDE_TRANSCRIPT.replace(/Showing detailed transcript ·.*/, 'Showing detailed transcript · ctrl+o to tog…'))).toBe('transcript_open')+ })++ it('is not a ready composer, a turn at work, an unreadable pane, or the MCP boot notice, which takes typing', () => {+ 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()+ // Another engine's screen is read only for its prompts: a menu or a view it may draw is its own.+ expect(messageHold('cursor', CODEX_MODEL_MENU)).toBeNull()+ expect(messageHold('cursor', CLAUDE_TRANSCRIPT)).toBeNull()+ })+})++describe('what the person is told', () => {+ const holds: MessageHold[] = ['permission_open', 'question_open', 'menu_open', 'rewind_picker_open', 'transcript_open']++ it('names the engine, what is open, and exactly what lets the message through', () => {+ expect(holds.map((hold) => messageHoldText('claude', hold))).toEqual([+ 'Claude Code is asking for permission. Answer it first, in the app or in its terminal, then send the message again.',+ 'Claude Code is asking you a question. Answer it first, in the app or in its terminal, then send the message again.',+ 'Claude Code has a menu open, where Enter would pick from it. Close it with Esc in its terminal, then send the message again.',+ 'Claude Code has its Rewind menu open, where Enter would pick a point to rewind to. Close it with Esc in its terminal, then send the message again.',+ 'Claude Code is showing its transcript (ctrl+o), where a message is not typed. Close it with Esc in its terminal, then send the message again.',+ ])+ expect(messageHoldText('codex', 'permission_open')).toBe('Codex is asking for approval. Answer it first, in the app or in its terminal, then send the message again.')+ expect(messageHoldText('codex', 'rewind_picker_open')).toBe('Codex is browsing its transcript, where Enter would rewind the conversation. Close it with Esc in its terminal, then send the message again.')+ expect(messageHoldText('commandcode', 'permission_open')).toBe('Command Code is asking for permission. Answer it first, in the app or in its terminal, then send the message again.')+ })++ it('tells a hold from any other refusal', () => {+ for (const hold of holds) expect(isMessageHold(hold)).toBe(true)+ expect(isMessageHold('team_waiting_user')).toBe(false)+ expect(isMessageHold('terminal agent is unavailable')).toBe(false)+ })+})diff --git a/cli/src/lib/messageHold.ts b/cli/src/lib/messageHold.tsnew file mode 100644index 000000000..f2ee0346f--- /dev/null+++ b/cli/src/lib/messageHold.ts@@ -0,0 +1,83 @@+/**+ * Whether a message can be typed into an agent's pane as it stands, and if not, why not and what the+ * person can do about it.+ *+ * A message is a bracketed paste followed by Enter. Typed into the composer, that sends it. Typed into+ * a dialog, it does something else: the dialogs below drop the paste, and the Enter confirms what is+ * highlighted. Read from the engines' own code (Claude Code 2.1.289's bundle, Codex 0.160's tui/src):+ * - a permission prompt approves its highlighted row, the first: Yes, run it (Claude Code's Select has+ * no paste handler; Codex's ApprovalOverlay leaves `handle_paste` to its default, and its own test+ * `enter_sets_last_selected_index_without_dismissing` expects Accept);+ * - a question picks its highlighted option (Claude Code), or takes the paste as notes on it and+ * submits that (Codex's request_user_input);+ * - a menu (model, effort and the other pickers) picks its highlighted row;+ * - a picker for a point to rewind to rewinds, or loses the message (Codex's transcript browser,+ * Claude Code's Rewind menu);+ * - Claude Code's transcript view (ctrl+o) loses it.+ * So none of them is typed into. A question is answered through its own path (`question_response`),+ * never by a message.+ *+ * 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 { 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'++const HOLDS: ReadonlySet<string> = new Set<MessageHold>(['permission_open', 'question_open', 'menu_open', 'rewind_picker_open', 'transcript_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'])++/**+ * Claude Code's transcript view (ctrl+o): the prompt is hidden, and the footer row starts+ * `Showing detailed transcript · ctrl+o to toggle`, after `dialog waiting · ` when a dialog sits behind+ * it (2.1.289). It has no Enter, so a message typed there is lost. Esc, q or ctrl+c close it.+ */+const CLAUDE_TRANSCRIPT_FOOTER = /^\s*(?:dialog waiting · )?Showing detailed transcript\b/++function claudeTranscriptOpen(capture: string): boolean {+ const lines = capture.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').split('\n').filter((line) => line.trim())+ return lines.slice(-3).some((line) => CLAUDE_TRANSCRIPT_FOOTER.test(line))+}++/** 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 view = parseEngineQuestionPane(engine, capture)+ if (view) return view.kind === 'question' && isApprovalDialog(view) ? 'permission_open' : 'question_open'+ if (!MODAL_ENGINES.has(engine)) return null+ if (engine === 'claude' && claudeTranscriptOpen(capture)) return 'transcript_open'+ const modal = paneModal(engine, capture)+ return modal === 'rewind' ? 'rewind_picker_open' : modal === 'permission' ? 'permission_open' : modal === 'menu' ? 'menu_open' : null+}++export function isMessageHold(reason: string): reason is MessageHold {+ return HOLDS.has(reason)+}++function engineName(engine: string): string {+ return engine === 'claude' ? 'Claude Code' : engineLabel(engine)+}++/** 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)+ switch (hold) {+ case 'permission_open':+ return `${name} is asking for ${engine === 'codex' ? 'approval' : 'permission'}. Answer it first, in the app or in its terminal, then send the message again.`+ case 'question_open':+ return `${name} is asking you a question. Answer it first, in the app or in its terminal, then send the message again.`+ case 'menu_open':+ return `${name} has a menu open, where Enter would pick from it. Close it with Esc in its terminal, then send the message again.`+ case 'rewind_picker_open':+ return engine === 'codex'+ ? 'Codex is browsing its transcript, where Enter would rewind the conversation. Close it with Esc in its terminal, then send the message again.'+ : `${name} has its Rewind menu open, where Enter would pick a point to rewind to. Close it with Esc in its terminal, then send the message again.`+ case 'transcript_open':+ return `${name} is showing its transcript (ctrl+o), where a message is not typed. Close it with Esc in its terminal, then send the message again.`+ }+}diff --git a/cli/src/lib/runtimeProfileController.spec.ts b/cli/src/lib/runtimeProfileController.spec.tsindex 3b0e7fc1e..0c95ce902 100644--- a/cli/src/lib/runtimeProfileController.spec.ts+++ b/cli/src/lib/runtimeProfileController.spec.ts@@ -9,8 +9,8 @@ import {parseCodexModelRows,parseCursorModelPicker,parseCursorParameterRows,+ paneModal,RuntimeProfileController,- rewindPickerOpen,} from './runtimeProfileController.js'import {CLAUDE_PROMPT, CLAUDE_REWIND_CONFIRM, CLAUDE_REWIND_EMPTY, CLAUDE_REWIND_LIST, CLAUDE_REWIND_LIST_MESSAGE_FOCUSED,@@ -69,26 +69,34 @@ describe('runtime pane parsing', () => {// menu and drops what was pasted, and, on a message, takes it a step from restoring the conversation.for (const [view, screen] of Object.entries({ CLAUDE_REWIND_LIST, CLAUDE_REWIND_LIST_MESSAGE_FOCUSED, CLAUDE_REWIND_CONFIRM, CLAUDE_REWIND_EMPTY })) {expect(inspectRuntimePane('claude', screen), view).toMatchObject({ idle: false, dialog: true })- expect(rewindPickerOpen('claude', screen), view).toBe(true)+ expect(paneModal('claude', screen), view).toBe('rewind')}// Its prompt back between its rules under any leftover of it, it is closed.expect(inspectRuntimePane('claude', `${CLAUDE_REWIND_LIST}\n${CLAUDE_PROMPT}`)).toMatchObject({ idle: true, dialog: false })- expect(rewindPickerOpen('claude', `${CLAUDE_REWIND_LIST}\n${CLAUDE_PROMPT}`)).toBe(false)+ expect(paneModal('claude', `${CLAUDE_REWIND_LIST}\n${CLAUDE_PROMPT}`)).toBeNull()// A message that reads `Rewind`, in the transcript or the list, is not the menu's title.- expect(rewindPickerOpen('claude', `\u001b[38;5;239m\u001b[48;5;237m❯ \u001b[38;5;231mRewind\u001b[39m\u001b[49m\n\n${CLAUDE_PROMPT}`)).toBe(false)- expect(rewindPickerOpen('claude', CLAUDE_REWIND_LIST.replace(' fix the login bug', ' Rewind'))).toBe(true)+ expect(paneModal('claude', `\u001b[38;5;239m\u001b[48;5;237m❯ \u001b[38;5;231mRewind\u001b[39m\u001b[49m\n\n${CLAUDE_PROMPT}`)).toBeNull()+ expect(paneModal('claude', CLAUDE_REWIND_LIST.replace(' fix the login bug', ' Rewind'))).toBe('rewind')// Another engine's pane is not read for it.- expect(rewindPickerOpen('cursor', CLAUDE_REWIND_LIST)).toBe(false)+ expect(paneModal('cursor', CLAUDE_REWIND_LIST)).toBeNull()})- it('finds Codex browsing its transcript in both its screen modes, and nothing in an unreadable pane', () => {+ it('finds Codex browsing its transcript in both its screen modes', () => {for (const [mode, screen] of Object.entries({ CODEX_BROWSING_FULLSCREEN, CODEX_BROWSING_SCROLLBACK })) {expect(inspectRuntimePane('codex', screen), mode).toMatchObject({ idle: false, dialog: true })- expect(rewindPickerOpen('codex', screen), mode).toBe(true)+ expect(paneModal('codex', screen), mode).toBe('rewind')}- expect(rewindPickerOpen('codex', CODEX_PROMPT)).toBe(false)- expect(rewindPickerOpen('codex', null)).toBe(false)- expect(rewindPickerOpen('claude', '')).toBe(false)+ expect(paneModal('codex', CODEX_PROMPT)).toBeNull()+ expect(paneModal('claude', '')).toBeNull()+ })++ it('tells an approval prompt and a menu from the MCP boot notice, which takes typing and is no modal for a message', () => {+ expect(paneModal('claude', ' Bash command\n printf hi\n Do you want to proceed?\n ❯ 1. Yes\n 2. No')).toBe('permission')+ expect(paneModal('codex', 'Select Model and Effort\n› 1. gpt-5.6-sol (current)')).toBe('menu')+ const booting = `${CLAUDE_PROMPT}\n Starting MCP servers (1/3)…`+ expect(paneModal('claude', booting)).toBeNull()+ // Still a dialog to every reader that holds work back from a booting pane.+ expect(inspectRuntimePane('claude', booting)).toMatchObject({ dialog: true })})it('reads hermes, which italicises its placeholder instead of dimming it', () => {diff --git a/cli/src/lib/runtimeProfileController.ts b/cli/src/lib/runtimeProfileController.tsindex d3fd1107c..bd8109ca0 100644--- a/cli/src/lib/runtimeProfileController.ts+++ b/cli/src/lib/runtimeProfileController.ts@@ -330,19 +330,19 @@ function currentPaneUi(rawLines: string[], promptIndex: number): string {return stripAnsi((promptIndex >= 0 ? rawLines.slice(promptIndex) : rawLines).join('\n')).replace(/\u00a0/g, ' ')}-/** The engines that have one, so a caller can leave every other pane unread. */-export const REWIND_PICKER_ENGINES: ReadonlySet<string> = new Set(['claude', 'codex'])-/**- * Whether the pane shows a picker for a point in the conversation to go back to, over its composer:- * Codex browsing its transcript, or Claude Code's Rewind menu. Nothing typed there is a message, and- * Enter there picks a point to go back to, so nothing is typed into one: not a team delivery (read- * as a dialog, through [inspectRuntimePane]) and not a person's own message either.+ * The modal over a Claude Code or Codex pane, read for a message about to be typed into it+ * (messageHold.ts): a picker for a point in the conversation to go back to (Codex browsing its+ * transcript, Claude Code's Rewind menu), an approval prompt, or another menu. Every one of them is a+ * dialog to [inspectRuntimePane], except the MCP boot notice: Claude Code takes typing while it shows,+ * so a message sent the moment an agent starts still goes in.*/-export function rewindPickerOpen(engine: RegisteredSession['engine'], capture: string | null): boolean {- if (!capture || !REWIND_PICKER_ENGINES.has(engine)) return false+export function paneModal(engine: RegisteredSession['engine'], capture: string): 'rewind' | 'permission' | 'menu' | null {const rawLines = capture.split('\n')- return rewindPickerIn(engine, capture, currentPaneUi(rawLines, latestPromptLine(rawLines, promptMarker(engine))))+ const currentUi = currentPaneUi(rawLines, latestPromptLine(rawLines, promptMarker(engine)))+ if (rewindPickerIn(engine, capture, currentUi)) return 'rewind'+ if (PERMISSION_UI.test(currentUi)) return 'permission'+ return DIALOG_UI.test(currentUi.replace(/Starting MCP servers?/gi, '')) ? 'menu' : null}function rewindPickerIn(engine: RegisteredSession['engine'], capture: string, currentUi: string): boolean {@@ -360,6 +360,9 @@ function rewindPickerIn(engine: RegisteredSession['engine'], capture: string, cu*/const DIALOG_UI = /Select Model(?: and Effort)?|Select Reasoning Level|Advanced Reasoning|Available models|Models matching|Edit Parameters|Type to filter.*Tab to edit|Esc to go back|Press enter to confirm|Do you want to proceed|Allow this action|permission required|Starting MCP servers?/i+/** The approval prompts among them. */+const PERMISSION_UI = /Do you want to proceed|Allow this action|permission required/i+/*** Codex browsing its own transcript: Esc twice on an empty composer, and its footer row reads* `Browsing transcript · ↑↓/jk scroll · ←→/hl prompts · … · ↵ rewind · esc back`, down to a barediff --git a/cli/src/lib/sessionInput.spec.ts b/cli/src/lib/sessionInput.spec.tsindex 56d39cc55..c5ec485b5 100644--- a/cli/src/lib/sessionInput.spec.ts+++ b/cli/src/lib/sessionInput.spec.ts@@ -1,7 +1,7 @@import { afterEach, describe, expect, it, vi } from 'vitest'import { SessionInputController } from './sessionInput.js'import type { RegisteredSession } from './registry.js'-import { REWIND_PICKER_OPEN, TERMINAL_LEASE_REFUSED, type TerminalActionResult } from './terminalTypes.js'+import { TERMINAL_LEASE_REFUSED, type TerminalActionResult } from './terminalTypes.js'function session(engine: 'claude' | 'codex' | 'cursor' | 'commandcode' = 'codex'): RegisteredSession {return {@@ -17,15 +17,17 @@ function session(engine: 'claude' | 'codex' | 'cursor' | 'commandcode' = 'codex'describe('SessionInputController', () => {afterEach(() => vi.useRealTimers())- describe('a message not typed because a picker for a point to rewind to is open', () => {- const refused: TerminalActionResult = { state: 'failed', dispatch: 'not_started', reason: REWIND_PICKER_OPEN }+ describe('a message not typed because of what its pane shows', () => {+ const held = (reason: string): TerminalActionResult => ({ state: 'failed', dispatch: 'not_started', reason })it.each([- ['codex', 'Codex is browsing its transcript, where Enter would rewind the conversation. Close it with Esc in its terminal, then send the message again.'],- ['claude', 'Claude Code has its Rewind menu open, where Enter would pick a point to rewind to. Close it with Esc in its terminal, then send the message again.'],- ] as const)('%s: tells the person why and how to get the next one through, asks no lease again, and awaits nothing', async (engine, text) => {+ ['codex', 'rewind_picker_open', 'Codex is browsing its transcript, where Enter would rewind the conversation. Close it with Esc in its terminal, then send the message again.'],+ ['claude', 'rewind_picker_open', 'Claude Code has its Rewind menu open, where Enter would pick a point to rewind to. Close it with Esc in its terminal, then send the message again.'],+ ['claude', 'permission_open', 'Claude Code is asking for permission. Answer it first, in the app or in its terminal, then send the message again.'],+ ['codex', 'question_open', 'Codex is asking you a question. Answer it first, in the app or in its terminal, then send the message again.'],+ ] as const)('%s, %s: tells the person why and what to do, asks no lease again, and awaits nothing', async (engine, reason, text) => {const onError = vi.fn(), onSubmitted = vi.fn(), sleep = vi.fn(async () => {})- const inject = vi.fn(async () => refused)+ const inject = vi.fn(async () => held(reason))const controller = new SessionInputController({ getSession: () => session(engine), validateRuntime: async () => true,inject, sendKey: async () => true, onError, onSubmitted, sleep })controller.submit('s1', 'a message from the app')@@ -39,10 +41,20 @@ describe('SessionInputController', () => {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,- inject: async () => refused, sendKey: async () => true, onError, onDelivery })+ inject: async () => held('permission_open'), sendKey: async () => true, onError, onDelivery })controller.submit('s1', 'a message from the device', 'd1')- await vi.waitFor(() => expect(onDelivery).toHaveBeenCalledWith({ sessionId: 's1', deliveryId: 'd1', state: 'rejected', reason: REWIND_PICKER_OPEN }))- expect(onError).toHaveBeenCalledWith('s1', expect.stringMatching(/^Codex is browsing its transcript/))+ await vi.waitFor(() => expect(onDelivery).toHaveBeenCalledWith({ sessionId: 's1', deliveryId: 'd1', state: 'rejected', reason: 'permission_open' }))+ expect(onError).toHaveBeenCalledWith('s1', 'Codex is asking for approval. Answer it first, in the app or in its terminal, then send the message again.')+ controller.forget('s1')+ })++ it('rejects a team\'s turn with the reason, and tells no person: its team hears of it', async () => {+ const onError = vi.fn(), onDelivery = vi.fn()+ const controller = new SessionInputController({ getSession: () => session('claude'), validateRuntime: async () => true,+ beforeTeamWrite: async () => null, inject: vi.fn(), injectTeam: async () => held('menu_open'), sendKey: async () => true, onError, onDelivery })+ controller.submit('s1', 'a team turn', 'team:1')+ await vi.waitFor(() => expect(onDelivery).toHaveBeenCalledWith({ sessionId: 's1', deliveryId: 'team:1', state: 'rejected', reason: 'menu_open' }))+ expect(onError).not.toHaveBeenCalled()controller.forget('s1')})})diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.tsindex 03f4f32c0..dbfc1ba67 100644--- a/cli/src/lib/sessionInput.ts+++ b/cli/src/lib/sessionInput.ts@@ -1,7 +1,8 @@import { createHash } from 'crypto'import type { RegisteredSession } from './registry.js'import { sid } from './log.js'-import { REWIND_PICKER_OPEN, TERMINAL_LEASE_REFUSED, type TerminalActionResult } from './terminalTypes.js'+import { isMessageHold, messageHoldText, type MessageHold } from './messageHold.js'+import { TERMINAL_LEASE_REFUSED, type TerminalActionResult } from './terminalTypes.js'const MAX_QUEUE_ITEMS = 8const MAX_QUEUE_BYTES = 24 * 1024@@ -129,17 +130,10 @@ export interface SessionInputDeps {sleep?: (ms: number) => Promise<void>}-/** A message not typed because the pane shows a picker for a point to rewind to: nothing was written. */-function refusedForRewindPicker(delivery: boolean | TerminalActionResult): boolean {+/** A message not typed because of what the pane showed (messageHold.ts): nothing was written. */+function heldBack(delivery: boolean | TerminalActionResult): MessageHold | null {return typeof delivery !== 'boolean' && delivery.state === 'failed' && delivery.dispatch === 'not_started'- && delivery.reason === REWIND_PICKER_OPEN-}--/** What the person is told: why their message was not typed, and what lets the next one through. */-function rewindPickerRefusal(engine: string): string {- return engine === 'codex'- ? 'Codex is browsing its transcript, where Enter would rewind the conversation. Close it with Esc in its terminal, then send the message again.'- : 'Claude Code has its Rewind menu open, where Enter would pick a point to rewind to. Close it with Esc in its terminal, then send the message again.'+ && isMessageHold(delivery.reason) ? delivery.reason : null}/** A write the pane's control lease refused before a byte of it was written. */@@ -466,9 +460,10 @@ export class SessionInputController {: delivery.state === 'succeeded' || delivery.dispatch === 'possibly_executed'if (!accepted) {forgetScope?.()- if (refusedForRewindPicker(delivery)) {- console.warn(`[inject] ${sid(sessionId)} not typed · engine=${session.engine} · a rewind picker is open`)- this.deps.onError(sessionId, rewindPickerRefusal(session.engine))+ const held = heldBack(delivery)+ if (held) {+ console.warn(`[inject] ${sid(sessionId)} not typed · engine=${session.engine} · ${held}`)+ this.deps.onError(sessionId, messageHoldText(session.engine, held))return}console.warn(`[inject] ${sid(sessionId)} paste failed · engine=${session.engine} · target=${session.agentId}`)@@ -540,10 +535,12 @@ export class SessionInputController {this.finishDelivery(sessionId, state, 'rejected', delivery.reason)return}- if (refusedForRewindPicker(delivery)) {- console.warn(`[inject] ${sid(sessionId)} not typed · engine=${session.engine} · a rewind picker is open`)- this.finishDelivery(sessionId, state, 'rejected', REWIND_PICKER_OPEN)- this.deps.onError(sessionId, rewindPickerRefusal(session.engine))+ const held = heldBack(delivery)+ if (held) {+ console.warn(`[inject] ${sid(sessionId)} not typed · engine=${session.engine} · ${held}`)+ this.finishDelivery(sessionId, state, 'rejected', held)+ // A team's turn is automatic, and its team hears of the refusal; anyone else's is a person's to see.+ if (!deliveryId.startsWith('team:')) this.deps.onError(sessionId, messageHoldText(session.engine, held))return}const accepted = typeof delivery === 'boolean'diff --git a/cli/src/lib/terminalTypes.ts b/cli/src/lib/terminalTypes.tsindex 592081474..185b897bd 100644--- a/cli/src/lib/terminalTypes.ts+++ b/cli/src/lib/terminalTypes.ts@@ -186,10 +186,6 @@ export const TERMINAL_ACTION_SUCCEEDED: TerminalActionResult = {* not the one the registry holds (just relaunched, not yet confirmed) or another writer holds it. */export const TERMINAL_LEASE_REFUSED = 'terminal control lease is unavailable or changed'-/** The reason a person's message is not typed: the pane shows a picker for a point to rewind the- * conversation to, where its Enter would pick one (runtimeProfileController's `rewindPickerOpen`). */-export const REWIND_PICKER_OPEN = 'rewind_picker_open'-export function terminalActionNotStarted(reason: string): {state: 'failed'; dispatch: 'not_started'; reason: string} {