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 Codex's transcript browser or Claude Code's Rewind menu (#818)
Deea8ce14666cf1
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjsindex ff5bea63e..cbdf395aa 100644--- a/cli/e2e/harness/fakeEngine.mjs+++ b/cli/e2e/harness/fakeEngine.mjs@@ -19,7 +19,8 @@// `/compact` does (and Claude Code then announces the same session again), `!compactmid` compacts in the// 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, `!exit` ends the process.+// 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.// 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@@ -165,15 +166,17 @@ export async function run(engine, config) {// 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).let bottom = nullconst 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` })- const browsingBottom = {- composer: '\x1b[2m› Ask Codex to do anything\x1b[0m',- footer: '\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',- browsing: true,- }+ 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 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}` })const draw = (line = '') => {+ if (bottom?.pager) { process.stdout.write(bottom.pager); return }if (bottom && !line) {// The footer on the row under the composer, then the cursor back to the composer, after its glyph.process.stdout.write(`\r\x1b[2K${bottom.composer}\r\n\x1b[2K${bottom.footer}\x1b[1A\r\x1b[2C`)@@ -181,6 +184,15 @@ export async function run(engine, config) {}process.stdout.write(`\r\x1b[2K› ${line}`)}+ // Out of the browser, back to the composer: the pager's alternate screen left, or the footer row+ // under the composer cleared. Enter rewinds on the way out.+ const leaveBrowsing = (rewound) => {+ if (bottom.pager) process.stdout.write('\x1b[?1049l')+ else process.stdout.write('\r\n\x1b[2K\x1b[1A')+ if (rewound) process.stdout.write('\r\x1b[2K(rewound to an earlier prompt)\r\n')+ bottom = null+ 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`)draw()@@ -413,7 +425,7 @@ export async function run(engine, config) {}if (engine === 'codex' && directive?.[1] === 'browse') {// Reached in Codex by Esc twice on an empty composer; the directive goes straight there.- bottom = browsingBottom+ bottom = directive[2] === 'scrollback' ? pagerBottom(prompt, `answer ${turn}: ${prompt}`) : browsingBottomfinish(`answer ${turn}: ${prompt}`)return}@@ -428,15 +440,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- process.stdin.on('data', (chunk) => {- if (dialog) { dialogKeys(chunk); return }+ process.stdin.on('data', (input) => {+ if (dialog) { dialogKeys(input); return }+ let chunk = inputif (bottom?.browsing) {- // Keys move through the transcript there. Esc goes back to the composer; Enter rewinds the- // conversation to the prompt in view, which is what a message typed into it would do.- if (chunk.includes('\r') || chunk.includes('\n')) process.stdout.write('\r\n\x1b[2K(rewound to an earlier prompt)\r\n')- else if (chunk.includes('\x1b')) process.stdout.write('\r\n\x1b[2K\x1b[1A')- if (chunk.includes('\x1b') || chunk.includes('\r') || chunk.includes('\n')) { bottom = null; draw() }- return+ // 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 move+ // through the transcript. Anything else, a paste included, leaves the fullscreen browser for the+ // composer it was meant for, while the scrollback pager drops it, so the Enter behind it rewinds.+ 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?.browsing) rest += token+ else if (token === '\x1b') leaveBrowsing(false)+ else if (token === '\r' || token === '\n') leaveBrowsing(true)+ else if (/^(?:\x1b\[[ABCD]|[hjkl])$/.test(token) || bottom.pager) continue+ else { leaveBrowsing(false); rest += token }+ }+ if (!rest) return+ chunk = rest}for (const part of chunk.split(/(\x1b\[20[01]~|\r|\n|\x03)/)) {if (part === '\x1b[200~') { pasting = true; continue }diff --git a/cli/e2e/input-safety.e2e.ts b/cli/e2e/input-safety.e2e.tsindex 6e695f9d8..9b808842a 100644--- a/cli/e2e/input-safety.e2e.ts+++ b/cli/e2e/input-safety.e2e.ts@@ -1,6 +1,7 @@/*** 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. And what a client must never cost the others: one that+ * 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* stops reading is cut off, alone, and the daemon's memory stays bounded while it is.*/import { existsSync, mkdirSync } from 'node:fs'@@ -72,6 +73,31 @@ describe('what a message must never do', () => {client.close()})+ it('codex: a message is not typed into its transcript browser, whose Enter rewinds: refused with the reason, it goes through once the browser is closed', async () => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, 'codex', 'browsing-scrollback')+ // Codex browsing in its scrollback mode: a transcript pager over the pane, which drops a paste, so+ // the Enter behind it would revert the conversation to the prompt in view.+ await turn(client, agent.id, '!browse scrollback')+ await until('the pager to be drawn', async () => (await d.capture(agent.tmuxPane)).includes('Browsing 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: 'what changed since then?' })+ expect(String((await refused).payload?.message)).toBe('Codex is browsing its transcript, where Enter would rewind the conversation. Close it with Esc in its terminal, then send the message again.')+ // Nothing typed: still browsing, nothing rewound, no turn.+ const pane = await d.capture(agent.tmuxPane)+ expect(pane).toContain('Browsing transcript')+ expect(pane).not.toContain('rewound')+ 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 composer to be back', async () => !(await d.capture(agent.tmuxPane)).includes('Browsing transcript') || null, 15_000, 250)+ await turn(client, agent.id, 'what changed since then?')+ expect(await d.capture(agent.tmuxPane)).not.toContain('rewound')+ 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/src/core/input.spec.ts b/cli/src/core/input.spec.tsindex 5f944b019..b26295cb4 100644--- a/cli/src/core/input.spec.ts+++ b/cli/src/core/input.spec.ts@@ -4,7 +4,8 @@ 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 type { TerminalActionResult } from '../lib/terminalTypes.js'+import { REWIND_PICKER_OPEN, 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'const ok: TerminalActionResult = { state: 'succeeded', dispatch: 'executed' }@@ -13,6 +14,7 @@ const READY_PANE = '────────────\n❯\n─────const agents = new Map<string, RegisteredSession>([['a1', { agentId: 'a1', sessionId: 's1', engine: 'claude' } as RegisteredSession],+ ['cx', { agentId: 'cx', sessionId: 'cx-s', engine: 'codex' } as RegisteredSession],['s1', { agentId: 'a1', sessionId: 's1', engine: 'claude' } as RegisteredSession],['cc', { agentId: 'cc', sessionId: 'cc-s', engine: 'commandcode' } as RegisteredSession],['cc-new', { agentId: 'cc-new', sessionId: '', engine: 'commandcode' } as RegisteredSession],@@ -95,6 +97,28 @@ 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 () => {+ 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_REWIND_LIST)+ expect(await wired.inject('a1', 'hello')).toEqual(refused)+ 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.+ 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'])+ })+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))@@ -149,6 +173,15 @@ 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 () => {+ const run = deps()+ const wired = deviceInputDeps(run.deps, () => ({ acquireControl: vi.fn(), submit: vi.fn(), cancelDelivery: vi.fn() }))+ run.setPane(CLAUDE_REWIND_LIST)+ expect(await wired.isAwaitingUser!(agents.get('a1')!)).toBe(true)+ run.setPane(CODEX_BROWSING_SCROLLBACK)+ expect(await wired.isAwaitingUser!(agents.get('cx')!)).toBe(true)+ })+it('hands queued input to the controller, answering control included', () => {const { deps: given } = deps()const controller = { acquireControl: vi.fn(() => null), submit: vi.fn(), cancelDelivery: vi.fn(() => true) }diff --git a/cli/src/core/input.ts b/cli/src/core/input.tsindex 642d4ab06..369c8bcbc 100644--- a/cli/src/core/input.ts+++ b/cli/src/core/input.ts@@ -19,7 +19,8 @@ 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 { terminalActionNotStarted } from '../lib/terminalTypes.js'+import { REWIND_PICKER_ENGINES, rewindPickerOpen } from '../lib/runtimeProfileController.js'+import { REWIND_PICKER_OPEN, terminalActionNotStarted } from '../lib/terminalTypes.js'import { Id } from '../teams/model.js'import { teamWriteHold } from '../teams/preflight.js'import type { TerminalControl } from './terminals/control.js'@@ -67,7 +68,18 @@ export function sessionInputDeps(return teamWriteHold(session.engine, capture)},validateRuntime: validateTerminal,- inject: (id, text) => deviceInput().legacyWrite(id, () => submitTerminalAction(id, text)),+ // 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)+ }),injectTeam: (id, text, deliveryId) => deviceInput().legacyWrite(id, async () => {const session = resolve(id)const reason = session ? teamWriteHold(session.engine, await captureTerminal(id)) : 'team_waiting_unavailable'@@ -110,9 +122,11 @@ export function deviceInputDeps(inject: submitTerminalAction,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.isAwaitingUser: async session => {const pane = await captureTerminal(session.agentId)- return pane === null || parseEngineQuestionPane(session.engine, pane) !== null+ return pane === null || parseEngineQuestionPane(session.engine, pane) !== null || rewindPickerOpen(session.engine, pane)},acquireControl: id => input().acquireControl(id, { forAnswer: true }),legacySubmit: (id, text, deliveryId) => input().submit(id, text, deliveryId),diff --git a/cli/src/lib/__fixtures__/rewindPickers.ts b/cli/src/lib/__fixtures__/rewindPickers.tsnew file mode 100644index 000000000..290fab002--- /dev/null+++ b/cli/src/lib/__fixtures__/rewindPickers.ts@@ -0,0 +1,105 @@+/**+ * The pickers for a point to rewind the conversation to, as the engines draw them in a tmux pane. Built+ * from the engines' own code, read only: Claude Code 2.1.289's bundled MessageSelector (its Dialog pane:+ * a blank row, a rule in the dialog's colour, the bold title, then the body a blank row below it, padded+ * one column; its list rows: the `❯` pointer on the focused row, one column, then the row), and Codex+ * 0.160's tui/src (app_backtrack/prompt_navigation.rs for the footer, bottom_pane for the dimmed+ * composer, pager_overlay/transcript.rs for the scrollback pager). Not captures: the engines were not+ * run, so colours are the ones their code names, in tmux's 256-colour spelling.+ */++const RULE = '─'.repeat(100)+const dot = '\u001b[2m · \u001b[0m'++/** Claude Code with its Rewind menu just opened: earlier messages listed, `(current)` focused. */+export const CLAUDE_REWIND_LIST = [+ '\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[38;5;153m${RULE}\u001b[39m`,+ ' \u001b[1m\u001b[38;5;153mRewind\u001b[0m',+ '',+ ' Restore the code and/or conversation to the point before…',+ '',+ ' fix the login bug',+ ' \u001b[38;5;246mauth.ts \u001b[32m+4\u001b[39m \u001b[31m-1\u001b[39m\u001b[39m',+ '',+ ' \u001b[38;5;153m❯\u001b[39m \u001b[3m\u001b[38;5;153m(current)\u001b[0m',+ '',+ '',+ ' \u001b[2m\u001b[3mEnter to continue · Esc to cancel\u001b[0m',+].join('\n')++/** The same menu with an earlier message focused, Enter away from the confirmation. */+export const CLAUDE_REWIND_LIST_MESSAGE_FOCUSED = CLAUDE_REWIND_LIST+ .replace(' fix the login bug', ' \u001b[38;5;153m❯\u001b[39m \u001b[38;5;153mfix the login bug\u001b[39m')+ .replace(' \u001b[38;5;153m❯\u001b[39m \u001b[3m\u001b[38;5;153m(current)\u001b[0m', ' \u001b[3m(current)\u001b[0m')++/** A message picked: Enter on the focused option restores the conversation to before it. */+export const CLAUDE_REWIND_CONFIRM = [+ '\u001b[38;5;239m\u001b[48;5;237m❯ \u001b[38;5;231mfix the login bug\u001b[39m\u001b[49m',+ '',+ `\u001b[38;5;153m${RULE}\u001b[39m`,+ ' \u001b[1m\u001b[38;5;153mRewind\u001b[0m',+ '',+ ' Confirm you want to restore to the point before you sent this message:',+ ' \u001b[2m│\u001b[0m fix the login bug',+ ' \u001b[2m│\u001b[0m \u001b[2m(2m ago)\u001b[0m',+ ' \u001b[2mThe conversation will be forked.\u001b[0m',+ ' \u001b[2mThe code will be restored \u001b[32m+4\u001b[39m \u001b[31m-1\u001b[39m in auth.ts.\u001b[0m',+ ' \u001b[38;5;153m❯\u001b[39m \u001b[2m1.\u001b[0m \u001b[38;5;153mRestore code and conversation\u001b[39m',+ ' \u001b[2m2.\u001b[0m Restore conversation',+ ' \u001b[2m3.\u001b[0m Restore code',+ ' \u001b[2m4.\u001b[0m Summarize from here',+ ' \u001b[2m5.\u001b[0m Summarize up to here',+ ' \u001b[2m6.\u001b[0m Never mind',+ '',+ ' \u001b[2m⚠ Rewinding does not affect files edited manually or via bash.\u001b[0m',+].join('\n')++/** The menu opened before anything was sent. */+export const CLAUDE_REWIND_EMPTY = [+ `\u001b[38;5;153m${RULE}\u001b[39m`,+ ' \u001b[1m\u001b[38;5;153mRewind\u001b[0m',+ '',+ ' \u001b[2mNothing to rewind to yet.\u001b[0m',+ '',+ ' \u001b[2m\u001b[3mEsc to cancel\u001b[0m',+].join('\n')++/** Claude Code's empty prompt, between its two rules, footer below. */+export const CLAUDE_PROMPT = [+ `\u001b[38;5;244m${RULE}\u001b[39m`,+ '\u001b[39m❯ \u001b[2mTry "fix lint errors"\u001b[0m',+ `\u001b[38;5;244m${RULE}\u001b[39m`,+ ' \u001b[2m? for shortcuts\u001b[0m',+].join('\n')++/** Codex's transcript browser footer, at full width. */+export const CODEX_BROWSING_FOOTER = `\u001b[36mBrowsing transcript\u001b[0m${dot}↑↓/jk\u001b[2m scroll\u001b[0m${dot}←→/hl\u001b[2m prompts\u001b[0m${dot}ctrl + t\u001b[2m details\u001b[0m${dot}↵\u001b[2m rewind\u001b[0m${dot}esc\u001b[2m back\u001b[0m`++/** Codex browsing in its default fullscreen mode: the composer stays, dimmed whole, over the footer. */+export const CODEX_BROWSING_FULLSCREEN = [+ '\u001b[1m›\u001b[0m fix the login bug',+ '',+ '\u001b[2m•\u001b[0m Fixed: the session cookie was never refreshed.',+ '',+ '\u001b[2m\u001b[1m›\u001b[0m\u001b[2m \u001b[2mAsk Codex to do anything\u001b[0m',+ '',+ CODEX_BROWSING_FOOTER,+].join('\n')++/** Codex browsing in its scrollback mode: a transcript pager over the whole pane, its footer last. */+export const CODEX_BROWSING_SCROLLBACK = [+ `\u001b[2m/ T R A N S C R I P T ${'/ '.repeat(39)}\u001b[0m`,+ '\u001b[7m\u001b[1m›\u001b[0m\u001b[7m fix the login bug\u001b[0m',+ '',+ '\u001b[2m•\u001b[0m Fixed: the session cookie was never refreshed.',+ '',+ '',+ CODEX_BROWSING_FOOTER,+].join('\n')++/** Codex's empty composer with its status line under it. */+export const CODEX_PROMPT = '\u001b[1m›\u001b[0m \u001b[2mAsk Codex to do anything\u001b[0m\n\n gpt-5.6-sol default · /tmp/project'diff --git a/cli/src/lib/runtimeProfileController.spec.ts b/cli/src/lib/runtimeProfileController.spec.tsindex 8232300c5..3b0e7fc1e 100644--- a/cli/src/lib/runtimeProfileController.spec.ts+++ b/cli/src/lib/runtimeProfileController.spec.ts@@ -10,7 +10,12 @@ import {parseCursorModelPicker,parseCursorParameterRows,RuntimeProfileController,+ rewindPickerOpen,} from './runtimeProfileController.js'+import {+ CLAUDE_PROMPT, CLAUDE_REWIND_CONFIRM, CLAUDE_REWIND_EMPTY, CLAUDE_REWIND_LIST, CLAUDE_REWIND_LIST_MESSAGE_FOCUSED,+ CODEX_BROWSING_FULLSCREEN, CODEX_BROWSING_SCROLLBACK, CODEX_PROMPT,+} from './__fixtures__/rewindPickers.js'// The id inside a `runtime-v1:` string is the AGENT id ('h1' here) — a client only ever echoes back an id// the catalog minted, and the catalog is agent-scoped. `setProfile` is still addressed with either id.@@ -59,6 +64,33 @@ describe('runtime pane parsing', () => {expect(inspectRuntimePane('codex', ` Browsing transcript · as before\n${composer}\n\n gpt-5.6-sol default · /tmp/project`)).toMatchObject({ dialog: false })})+ it('reads Claude Code\'s Rewind menu as a modal, in each of its views, and as closed once its prompt is back', () => {+ // Its focused row is `❯ (current)` in italics: read as an empty, idle prompt, where Enter closes the+ // 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)+ }+ // 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)+ // 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)+ // Another engine's pane is not read for it.+ expect(rewindPickerOpen('cursor', CLAUDE_REWIND_LIST)).toBe(false)+ })++ it('finds Codex browsing its transcript in both its screen modes, and nothing in an unreadable pane', () => {+ 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(rewindPickerOpen('codex', CODEX_PROMPT)).toBe(false)+ expect(rewindPickerOpen('codex', null)).toBe(false)+ expect(rewindPickerOpen('claude', '')).toBe(false)+ })+it('reads hermes, which italicises its placeholder instead of dimming it', () => {// Copied byte-for-byte off a live pane. Hermes carries no SGR 2 at all: the placeholder is// italic (3) over a 256-colour gold, so a dim-only rule read every hermes pane as holding adiff --git a/cli/src/lib/runtimeProfileController.ts b/cli/src/lib/runtimeProfileController.tsindex 36ae31a63..d3fd1107c 100644--- a/cli/src/lib/runtimeProfileController.ts+++ b/cli/src/lib/runtimeProfileController.ts@@ -298,16 +298,10 @@ export function inspectRuntimePane(engine: RegisteredSession['engine'], capture:if (engine === 'grok') return inspectGrokPane(capture)const rawLines = capture.split('\n')const marks = promptMarker(engine)- const promptIndex = rawLines.findLastIndex((line) => {- const visible = stripAnsi(line)- const marker = visible.search(marks)- return marker >= 0 && !/^\s*\d+\.\s/.test(visible.slice(marker + 1))- })+ const promptIndex = latestPromptLine(rawLines, marks)const prompt = promptIndex >= 0 ? rawLines[promptIndex] : ''- // Old picker/plan text can remain in tmux history. Only UI below the latest prompt belongs to the- // current interaction; if no prompt is visible, inspect the whole capture as a conservative fallback.- const currentUi = stripAnsi((promptIndex >= 0 ? rawLines.slice(promptIndex) : rawLines).join('\n')).replace(/\u00a0/g, ' ')- const dialog = DIALOG_UI.test(currentUi) || (engine === 'codex' && CODEX_TRANSCRIPT_BROWSING.test(currentUi))+ const currentUi = currentPaneUi(rawLines, promptIndex)+ const dialog = DIALOG_UI.test(currentUi) || rewindPickerIn(engine, capture, currentUi)const plan = engine === 'codex' ? /\bplan mode\b/i.test(currentUi) : /\bplan mode on\b/i.test(currentUi)const marker = stripAnsi(prompt).search(marks)let visible = marker >= 0 ? stripAnsi(prompt).slice(marker + 1).replace(/\u00a0/g, ' ').trim() : ''@@ -319,6 +313,44 @@ export function inspectRuntimePane(engine: RegisteredSession['engine'], capture:return { idle: !!prompt && !dialog && !draft, plan, dialog, draft }}+/** The latest composer prompt line; picker rows use the same glyphs, but numbered rows are not prompts. */+function latestPromptLine(rawLines: string[], marks: RegExp): number {+ return rawLines.findLastIndex((line) => {+ const visible = stripAnsi(line)+ const marker = visible.search(marks)+ return marker >= 0 && !/^\s*\d+\.\s/.test(visible.slice(marker + 1))+ })+}++/**+ * Old picker/plan text can remain in tmux history. Only UI below the latest prompt belongs to the+ * current interaction; if no prompt is visible, inspect the whole capture as a conservative fallback.+ */+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.+ */+export function rewindPickerOpen(engine: RegisteredSession['engine'], capture: string | null): boolean {+ if (!capture || !REWIND_PICKER_ENGINES.has(engine)) return false+ const rawLines = capture.split('\n')+ return rewindPickerIn(engine, capture, currentPaneUi(rawLines, latestPromptLine(rawLines, promptMarker(engine))))+}++function rewindPickerIn(engine: RegisteredSession['engine'], capture: string, currentUi: string): boolean {+ if (engine === 'codex') return CODEX_TRANSCRIPT_BROWSING.test(currentUi)+ if (engine === 'claude') return claudeRewindMenuOpen(capture)+ return false+}+/*** A modal drawn over the pane — a picker, a permission prompt, an MCP boot notice.*@@ -331,12 +363,36 @@ const DIALOG_UI = /Select Model(?: and Effort)?|Select Reasoning Level|Advanced/*** 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 bare- * `Browsing` as the pane narrows (0.160, tui/src/app_backtrack/prompt_navigation.rs). The composer is- * dimmed meanwhile, its placeholder and any draft in it alike, so it read as empty and idle: a delivery- * typed into it lands as keys that scroll, and its Enter rewinds the conversation. A modal, then.+ * `Browsing` as the pane narrows (0.160, tui/src/app_backtrack/prompt_navigation.rs). In its default+ * fullscreen mode the composer stays, dimmed whole, placeholder and any draft in it alike, so it read+ * as empty and idle; in its scrollback mode (`tui.fullscreen_transcript = false`, no alternate screen,+ * or over SSH) the footer closes a transcript pager drawn over the whole pane. Either way Enter+ * reverts the conversation to the prompt in view. A paste leaves the fullscreen browser and lands in+ * the composer, but the scrollback one drops it, and its Enter then rewinds (app.rs and+ * pager_overlay/transcript.rs).*/const CODEX_TRANSCRIPT_BROWSING = /^\s*Browsing(?: transcript)?(?:\s+·|\s*$)/m+/**+ * Claude Code's Rewind menu (Esc twice on an empty prompt, or `/rewind`), which hides the prompt while+ * it is open. Under its title, `Rewind`, it lists the messages sent so far, `(current)` focused, behind+ * one of these lines, or asks to confirm one picked (2.1.289, MessageSelector). Enter on a message asks+ * to confirm it, and Enter again restores the conversation, the code or both to before it (with file+ * checkpoints off, the first Enter restores the conversation); Enter on `(current)` closes the menu.+ * A message pasted into it is dropped either way. Its focused row is drawn `❯ (current)` in italics,+ * which read as an empty, idle prompt.+ */+const CLAUDE_REWIND_BODY = /^(?:Restore the code and\/or conversation to the point before|Restore and fork the conversation to the point before|Confirm you want to restore|Nothing to rewind to yet)/++function claudeRewindMenuOpen(capture: string): boolean {+ const lines = stripAnsi(capture).replace(/\u00a0/g, ' ').split('\n').map((line) => line.trim())+ // The title, with its body a blank line under it, and no rule after it: the prompt the menu hides+ // comes back between two rules once it closes.+ return lines.some((line, index) => line === 'Rewind'+ && lines.slice(index + 1, index + 4).some((next) => CLAUDE_REWIND_BODY.test(next))+ && !lines.slice(index + 1).some((next) => /[─━]{8,}/u.test(next)))+}+/** The rule a gutter-box composer is closed with: `╹▀▀▀▀…`. */const GUTTER_BOX_RULE = /[─▀▁▔]{8,}/udiff --git a/cli/src/lib/sessionInput.spec.ts b/cli/src/lib/sessionInput.spec.tsindex e6fd50b3d..56d39cc55 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 { TERMINAL_LEASE_REFUSED, type TerminalActionResult } from './terminalTypes.js'+import { REWIND_PICKER_OPEN, TERMINAL_LEASE_REFUSED, type TerminalActionResult } from './terminalTypes.js'function session(engine: 'claude' | 'codex' | 'cursor' | 'commandcode' = 'codex'): RegisteredSession {return {@@ -17,6 +17,36 @@ 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 }++ 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) => {+ const onError = vi.fn(), onSubmitted = vi.fn(), sleep = vi.fn(async () => {})+ const inject = vi.fn(async () => refused)+ 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')+ await vi.waitFor(() => expect(onError).toHaveBeenCalledWith('s1', text))+ expect(inject).toHaveBeenCalledTimes(1)+ expect(sleep).not.toHaveBeenCalled()+ expect(onSubmitted).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,+ inject: async () => refused, 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/))+ controller.forget('s1')+ })+ })+describe('a paste the control lease refuses before a byte is written', () => {const refused: TerminalActionResult = { state: 'failed', dispatch: 'not_started', reason: TERMINAL_LEASE_REFUSED }const done: TerminalActionResult = { state: 'succeeded', dispatch: 'executed' }diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.tsindex 710419aa5..03f4f32c0 100644--- a/cli/src/lib/sessionInput.ts+++ b/cli/src/lib/sessionInput.ts@@ -1,7 +1,7 @@import { createHash } from 'crypto'import type { RegisteredSession } from './registry.js'import { sid } from './log.js'-import { TERMINAL_LEASE_REFUSED, type TerminalActionResult } from './terminalTypes.js'+import { REWIND_PICKER_OPEN, TERMINAL_LEASE_REFUSED, type TerminalActionResult } from './terminalTypes.js'const MAX_QUEUE_ITEMS = 8const MAX_QUEUE_BYTES = 24 * 1024@@ -129,6 +129,19 @@ 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 {+ 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.'+}+/** A write the pane's control lease refused before a byte of it was written. */function leaseRefused(delivery: boolean | TerminalActionResult): boolean {return typeof delivery !== 'boolean' && delivery.state === 'failed' && delivery.dispatch === 'not_started'@@ -453,6 +466,11 @@ 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))+ return+ }console.warn(`[inject] ${sid(sessionId)} paste failed · engine=${session.engine} · target=${session.agentId}`)this.deps.onError(sessionId, 'The message could not be delivered to the agent.')return@@ -522,6 +540,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))+ return+ }const accepted = typeof delivery === 'boolean'? delivery: delivery.state === 'succeeded' || delivery.dispatch === 'possibly_executed'diff --git a/cli/src/lib/terminalTypes.ts b/cli/src/lib/terminalTypes.tsindex 185b897bd..592081474 100644--- a/cli/src/lib/terminalTypes.ts+++ b/cli/src/lib/terminalTypes.ts@@ -186,6 +186,10 @@ 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} {diff --git a/cli/src/teams/preflight.spec.ts b/cli/src/teams/preflight.spec.tsindex 1a4887a7b..91a3ad2f3 100644--- a/cli/src/teams/preflight.spec.ts+++ b/cli/src/teams/preflight.spec.ts@@ -1,5 +1,6 @@import { expect, it } from 'vitest'import { teamWriteHold } from './preflight.js'+import { CLAUDE_REWIND_CONFIRM, CLAUDE_REWIND_EMPTY, CLAUDE_REWIND_LIST, CODEX_BROWSING_SCROLLBACK } from '../lib/__fixtures__/rewindPickers.js'it('holds multiline drafts with an empty first line', () => {expect(teamWriteHold('claude', '────────────\n❯\n a human draft\n────────────\n ? for shortcuts')).toBe('team_waiting_draft')@@ -24,3 +25,11 @@ it('holds a delivery while Codex browses its transcript, where its Enter would rconst browsing = '\u001b[2m› Ask Codex to do anything\u001b[0m\n\n\u001b[36mBrowsing transcript\u001b[0m · ↑↓/jk scroll · ←→/hl prompts · ↵ rewind · esc back'expect(teamWriteHold('codex', browsing)).toBe('team_waiting_user')})++it('holds a delivery while Claude Code\'s Rewind menu is open, as someone at the pane rather than by luck', () => {+ // Read before as an idle prompt (`❯ (current)` is italic) held only by its `Esc to cancel`, or as a+ // draft: a person's own message went in, and its Enter closed the menu or confirmed a rewind.+ for (const screen of [CLAUDE_REWIND_LIST, CLAUDE_REWIND_CONFIRM, CLAUDE_REWIND_EMPTY]) expect(teamWriteHold('claude', screen)).toBe('team_waiting_user')+ // And Codex's scrollback browser, a pager over the whole pane, the same way as its fullscreen one.+ expect(teamWriteHold('codex', CODEX_BROWSING_SCROLLBACK)).toBe('team_waiting_user')+})