TUI interactive client
Overview
The interactive terminal client is the codex-tui binary and library in codex-rs/tui. codex-rs/…/main.rs parses the top-level CLI, merges shared config overrides, and calls codex_tui::run_main; codex-rs/…/lib.rs routes that through startup_orchestration::run_main_inner, builds config/auth/app-server state, initializes terminal recovery hooks, and finally enters run_ratatui_app. After bootstrap, codex-rs/…/lib.rs calls App::run in codex-rs/…/startup.rs, which constructs the App, ChatWidget, app-event channel, backend sessions, and the main event loop.
The main loop in codex-rs/…/startup.rs is a tokio::select! over: app events from AppEventSender, active-thread notifications buffered in App::active_thread_rx, terminal events from Tui::event_stream, app-server events from backend sessions, reconnect futures, resize telemetry timers, periodic rate-limit refreshes, terminal-title refreshes, and commit-animation ticks. This loop gates terminal input while startup or thread-switch replay events are pending so delayed keypresses cannot approve a protected modal before it is painted. It exits by pausing terminal events, flushing mention usage, finishing archive work, shutting down backend sessions, clearing retained images, and returning AppExitInfo.
Terminal ownership lives in codex-rs/…/tui.rs. Tui wraps custom_terminal::Terminal<CrosstermBackend<Stdout>>, owns the draw broadcast channel, the shared crossterm EventBroker, terminal focus state, alternate-screen state, scrollback strategy, clipboard worker, and retained inline images. Tui::set_owned_screen, enter_alt_screen, leave_alt_screen, and with_restored manage fullscreen transcript/overlay ownership, shell handoff, external editors, suspension, and raw-mode restoration. codex-rs/…/alternate_screen.rs pairs alternate-screen enter/leave with a separate keyboard enhancement stack, mouse/pointer capture, SGR mouse mode, and scroll-mode restoration; panic/exit cleanup can use its static ALTERNATE_SCREEN even when no Tui borrow is available. codex-rs/…/event_stream.rs maps crossterm events into TuiEvent (Key, Paste, Mouse, Resize, Draw, Resume, focus changes) and can drop/recreate the underlying crossterm EventStream so terminal handoffs do not steal stdin from editors or terminal probes.
Rendering is model/update driven rather than immediate-input driven. FrameRequester in codex-rs/…/frame_requester.rs is cloned into widgets and background tasks; it coalesces draw requests through a scheduler task, and codex-rs/…/frame_rate_limiter.rs clamps draw notifications to a 120 FPS minimum interval. On TuiEvent::Draw, Resize, Resume, or FocusGained, App::handle_tui_event in codex-rs/…/app.rs lets ChatWidget run pre-draw timers, refreshes visible usage/status surfaces, and calls render_chat_widget_frame. Inline mode renders a flexible stack of active transcript content plus the bottom pane; owned/fullscreen transcript mode is handled by the owned transcript path in codex-rs/…/owned_transcript.rs and transcript view code under codex-rs/tui/src/transcript_view/**. Inline scrollback is updated through Tui::insert_history_lines in codex-rs/…/tui.rs, while retained history/source cells are HistoryCell implementations under codex-rs/tui/src/history_cell/**.
App in codex-rs/…/app.rs is the top-level UI state. It holds ChatWidget, FileSearchManager, transcript cells and transcript view state, overlays, keymap/chord state, reconnect state, side-thread/subagent state, rate-limit state, pending worktree/session transitions, and backend/thread routing state. Widgets and background tasks communicate with the loop via AppEvent from codex-rs/…/app_event.rs, sent through AppEventSender in codex-rs/…/app_event_sender.rs; codex-rs/…/event_dispatch.rs is the central dispatcher that turns app events into UI mutations, backend RPCs, session transitions, config writes, or AppRunControl::Exit. Outbound operations to the app server are modeled as AppCommand in codex-rs/…/app_command.rs, including user turns, interrupts, shell commands, approvals, MCP elicitation responses, permission responses, realtime voice, reviews, and config reloads.
ChatWidget in codex-rs/…/chatwidget.rs is the main chat surface. It consumes app-server protocol notifications/requests, updates committed HistoryCells and the mutable active streaming cell, owns turn/input queue state, drives status line and terminal title updates, manages approvals/MCP/user-input prompts, and exposes a Renderable for App to paint. codex-rs/…/input_submission.rs turns composer submissions into AppCommand::UserTurn or local shell commands, queues prompts while session setup, image preparation, rate-limit recovery, or safety recourse are pending, and records message history only after accepted submissions. codex-rs/…/slash_dispatch.rs handles accepted slash commands after the bottom pane has parsed/staged them, enforcing busy-state, side-conversation, and feature constraints before sending app events or backend commands.
The bottom pane is the interactive footer. codex-rs/…/mod.rs owns ChatComposer plus a stack of modal/popup BottomPaneViews; it routes local keys to the top view or composer and leaves higher-level interrupt/quit semantics to ChatWidget. codex-rs/…/chat_composer.rs is the large composer state machine for editing, Vim mode, Enter/Tab submission, shell ! mode, slash-command completion, @/$ mention menus, local and persistent history recall, paste-burst handling, startup draft handoff, right-click paste guards, shortcut help, and owned-transcript footer placement. codex-rs/…/list_selection_view.rs provides reusable searchable pickers; codex-rs/…/command_popup.rs filters visible slash/service-tier commands; codex-rs/…/slash_commands.rs centralizes feature-gated slash command discovery and lookup; and codex-rs/…/file_search_popup.rs renders @ file completions with fuzzy highlights.
Search and picker behavior is split between UI state and search services. codex-rs/…/file_search.rs owns one codex-file-search session per search root, receives AppEvent::StartFileSearch from the composer, drops the session on empty query, and emits AppEvent::FileSearchResult only for the current session token/query. codex-rs/…/lib.rs supplies the case-insensitive subsequence matcher used by slash and file-search UIs; it returns original character indices for highlighting even when lowercase expansion changes character counts. Generic picker rows use these match indices to render highlights without coupling the search provider to ratatui row layout.
External process and terminal-program integration is in the covered PTY crate. codex-rs/…/lib.rs exposes spawn_pty_process, spawn_pipe_process, ProcessHandle, SpawnedProcess, and TerminalSize. PTY spawning in codex-rs/…/pty.rs uses portable_pty where possible, falls back to Unix openpty when file descriptors must be preserved, and returns stdout/stderr/exit receivers plus a ProcessHandle that can write raw bytes, resize, interrupt, close stdin, or terminate. Pipe spawning in codex-rs/…/pipe.rs creates non-interactive children with explicit env/cwd/stdin, process-group or Windows job containment, and split output readers. codex-rs/…/process.rs is the common handle/driver adapter; codex-rs/…/process_group.rs centralizes Unix process-group/session/parent-death helpers; codex-rs/…/unix_io.rs performs nonblocking PTY I/O with AsyncFd; and codex-rs/…/windows_input.rs normalizes bytes written to ConPTY (LF to CR, CRLF collapse, Backspace to DEL).
Several small covered crates feed rendering and diagnostics surfaces. codex-rs/…/lib.rs converts ANSI output to ratatui Text/Line, expanding tabs to four spaces so command output and transcript gutters render predictably. codex-rs/…/lib.rs stores capped output as a stable head plus newest tail with an omission marker; codex-rs/…/lib.rs applies byte/token truncation to text, MCP results, and mixed function-call output while preserving images, audio charging, and caller-supplied token boundaries. codex-rs/…/lib.rs exposes process snapshots and registered gauges for content-free diagnostic reporting. codex-rs/…/recorder.rs and codex-rs/…/runtime.rs record critical-path timing for direct tool calls, automated reviews, user waits, batches, and execution-lock admission. codex-rs/…/lib.rs prevents idle sleep while a turn is running, using IOKit assertions on macOS, systemd-inhibit/gnome-session-inhibit helper processes on Linux, Windows power requests, or a no-op backend elsewhere.
Path-routing notes: changes under codex-rs/tui/src/tui/** generally affect terminal modes, event mapping, scrollback, alternate-screen, size, focus, notifications, and handoff behavior; changes under codex-rs/tui/src/app/**, codex-rs/…/app.rs, codex-rs/…/app_event.rs, and codex-rs/…/app_command.rs affect event-loop routing, app-server integration, backend/thread ownership, reconnects, and session transitions; changes under codex-rs/tui/src/chatwidget/** and codex-rs/…/chatwidget.rs affect protocol-to-history updates, submissions, status surfaces, permissions, realtime, and slash dispatch; changes under codex-rs/tui/src/bottom_pane/** affect composer, picker, approval, and modal input state; changes under codex-rs/tui/src/history_cell/**, codex-rs/tui/src/transcript_view/**, codex-rs/…/markdown*.rs, codex-rs/tui/src/render/**, and codex-rs/tui/src/ui_tree/** affect transcript/history rendering; covered utility crate changes should be reviewed as TUI dependencies when they alter process I/O, search highlighting, truncation, ANSI rendering, diagnostics, timing, or sleep prevention.
Coupling
- If
TuiEventor event mapping changes in codex-rs/…/event_stream.rs, updateApp::handle_tui_eventin codex-rs/…/app.rs and the startup select loop in codex-rs/…/startup.rs; the loop relies on the current separation ofResize, scheduledDraw, focus changes, andResumeto run pre-render work and protected-input gates in the right order. - If terminal handoff or alternate-screen behavior changes in codex-rs/…/tui.rs or codex-rs/…/alternate_screen.rs, verify external-editor/suspend paths that call
Tui::pause_events,Tui::resume_events, andTui::with_restored; codex-rs/…/event_stream.rs intentionally drops the crossterm stream during handoff so other programs can read stdin. - If frame scheduling changes in codex-rs/…/frame_requester.rs, check every caller that depends on deferred redraws rather than synchronous painting, especially
ChatWidgetrendering in codex-rs/…/rendering.rs, pending history insertion in codex-rs/…/tui.rs, paste burst handling in codex-rs/…/chat_composer.rs, and animation ticks in codex-rs/…/startup.rs. - If
AppEventorAppCommandvariants are added in codex-rs/…/app_event.rs or codex-rs/…/app_command.rs, update the dispatcher in codex-rs/…/event_dispatch.rs, session logging in codex-rs/…/app_event_sender.rs, and any thread-routing paths that buffer/replay events in codex-rs/…/thread_events.rs; unhandled variants can silently drop UI actions or backend operations. - If app-server protocol notification/request handling changes, verify codex-rs/…/thread_events.rs, codex-rs/…/thread_routing.rs, and codex-rs/…/chatwidget.rs together. Thread event stores preserve replay state, interactive request state, active turn IDs, and realtime delegation markers across thread switches; changing one consumer without the replay buffer can break side threads or subagent switching.
- If slash command availability changes in codex-rs/…/slash_command.rs, also update codex-rs/…/slash_commands.rs, codex-rs/…/command_popup.rs, and dispatch validation in codex-rs/…/slash_dispatch.rs; the composer popup, command lookup, and busy/side-conversation rejection paths intentionally share but do not fully duplicate gating.
- If mention/file-search behavior changes in codex-rs/…/chat_composer.rs, verify codex-rs/…/file_search.rs, codex-rs/…/file_search_popup.rs, and codex-rs/…/lib.rs; the search session computes indices for full paths, while the popup may recompute fuzzy indices against truncated display text.
- If output truncation changes in codex-rs/…/lib.rs or codex-rs/…/lib.rs, verify TUI history cells and command-output rendering under
codex-rs/tui/src/history_cell/**, codex-rs/…/command_output.rs, andcodex-rs/tui/src/exec_cell/**; these surfaces depend on omission markers and boundary remapping to explain clipped output without corrupting rendered transcript offsets. - If PTY/pipe process semantics change in codex-rs/…/pty.rs, codex-rs/…/pipe.rs, or codex-rs/…/process.rs, verify TUI terminal-program integrations under
codex-rs/tui/src/exec_cell/**, codex-rs/…/terminal_program_status.rs, and any external-editor or shell-command paths; interactive PTY output is stdout-only, while pipe mode preserves split stdout/stderr and both rely onProcessHandlefor resize/interrupt/termination. - If sleep-inhibitor lifecycle changes in codex-rs/…/lib.rs, verify turn-running state updates in codex-rs/…/chatwidget.rs and app-server turn lifecycle handling; the inhibitor is intentionally driven by running-turn state, not by generic UI busy state.
- If diagnostic or direct-tool timing schemas change in codex-rs/…/lib.rs or
codex-rs/direct-tool-timing/src/**, verify/status, warning, telemetry, and review/timing displays incodex-rs/tui/src/app/**andcodex-rs/tui/src/chatwidget/**; these crates expose content-free process/timing values that UI surfaces can show or copy without leaking prompt/output text.
Risks
- codex-rs/…/startup.rs has many input-blocking gates around startup draft restoration, active-thread replay, pending app events, and protected modals. If a new event source bypasses
can_read_terminal_after_thread_switchor theblock_terminal_input_for_pending_startup_eventslogic, delayed paste/key events can act on approvals or setup prompts before the user sees the rendered screen. - codex-rs/…/event_stream.rs documents that crossterm can keep reading stdin even when not actively polled. If
Tui::pause_events/resume_eventsstops dropping the underlying stream, external editors, terminal palette/size probes, or shell handoffs from codex-rs/…/tui.rs can lose input or consume terminal query responses. - codex-rs/…/alternate_screen.rs tracks mouse, keyboard enhancement, and scroll restoration with independent atomic flags because partial writes can enable terminal modes before returning an error. If cleanup starts trusting only requested state instead of actual/dirty state, a failed transition can leave mouse capture, modifyOtherKeys, or alternate scroll enabled after exit.
- codex-rs/…/pipe.rs explicitly notes that Windows process-tree containment is best-effort because job assignment occurs after spawn. If TUI code assumes
ProcessHandle::terminatealways kills descendants on Windows, background grandchildren from a shell command can survive after the visible command exits. - codex-rs/…/pty.rs treats PTY output as a single stdout stream and keeps PTY slave/master handles alive so the process does not receive unintended control signals. If callers drop
ProcessHandleor PTY handles while still draining output, interactive shells/REPLs can be killed early or lose final output.