Introducing a new way to review your PRs.

Read the announcement

openai / codex

Lightweight coding agent that runs in your terminal

View on GitHub

13 documents · Updated Nov 16, 2026

docs / tui-interactive-client

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

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_switch or the block_terminal_input_for_pending_startup_events logic, 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_events stops 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::terminate always 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 ProcessHandle or PTY handles while still draining output, interactive shells/REPLs can be killed early or lose final output.