22. The Terminal UI
The terminal user interface is an app-server client with a large
rendering engine attached. By default it starts or reuses a shared local
daemon and talks to it over WebSocket frames on a Unix socket;
everything it shows comes from notifications that one event loop routes
per thread into ChatWidget, which streams markdown at
newline boundaries and paces it on a 120-per-second tick.
Running codex with no subcommand opens the terminal user
interface (TUI). It is the largest crate in the workspace: 576,883 lines
of Rust across 1,369 files, tests included, slightly more than
codex-core at 569,876 (counted with wc).
Almost none of that code runs the agent. The codex-tui
crate has no dependency on codex-core; it sends requests to
an app server and renders what comes back, like any other client in Chapter 21.
This chapter follows that path. It covers how the TUI picks its
backend and when it starts the daemon, the event loop that multiplexes
terminal input and server events, how a notification becomes lines on
screen, how approval requests become overlays in the bottom pane, the
local rules in two AGENTS.md files, and, briefly, the
snapshot tests that pin the rendering. Chapter 26 covers testing in
depth.
The picture
The top half is streaming. The app server sends
item/agentMessage/delta; the App loop receives
it from backends.next_event, routes it through the thread’s
channel, and hands it to
ChatWidget::handle_server_notification.
ChatWidget pushes the text into its
StreamController and asks the loop to start the commit
animation. On each tick the controller releases complete lines, either
one at a time or in a batch, and the loop draws a frame no more than 120
times a second. The bottom half is an approval: the request follows the
same route, ChatWidget places it in the bottom pane, and
the user’s choice returns to the server as the JSON-RPC result.
Choosing a backend
Four targets
AppServerTarget in codex-rs/tui/src/lib.rs
names every backend the TUI can use. The table summarizes when each
applies.
| Target | Connection | Chosen when |
|---|---|---|
Embedded |
In-process channels | An exclusion applies, or no daemon is wanted |
LocalDaemon |
WebSocket over the Unix socket | Default socket found or daemon auto-started |
Remote |
WebSocket to another endpoint | --remote ADDR names a non-default endpoint |
Cloud |
Codex Cloud client | --cloud |
app_server_target_for_launch decides. An explicit
--remote endpoint that equals the default daemon socket
becomes LocalDaemon with no fallback; any other explicit
endpoint becomes Remote. With no explicit endpoint, the TUI
probes the default socket with a 50-millisecond connect timeout
(AUTO_CONNECT_DAEMON_CONNECT_TIMEOUT). A daemon that
answers becomes
LocalDaemon { allow_embedded_fallback: true }. Otherwise
the target starts as Embedded.
Whatever the target, the TUI identifies itself the same way. Both
connect_remote_app_server and the embedded start path send
client name codex-tui, experimental_api: true,
and required_human_approval: true. The last capability lets
the server route humanCommand approvals, which only a
person may answer, to this client.
Daemon auto-start
The feature flag daemon_auto_start is STABLE and on by
default. Its doc comment reads: “Automatically start the shared local
daemon for eligible interactive launches.” In
startup_orchestration.rs the launch is eligible when all of
these hold:
- The build targets Unix or Windows.
- The flag is on, or the user opened the agents overview.
- The connection is implicit: no
--remoteand no--cloud. --no-daemonis absent.daemon_startup::exclusionreturned nothing.
When the launch is eligible, the TUI calls
codex_app_server_daemon::start_with_features_classified,
which starts the daemon or confirms that one runs, and then targets
LocalDaemon { allow_embedded_fallback: false }. The
composer stays visible during this wait; the comment there says daemon
startup “needs no terminal input.” Chapter 21 described what the daemon is:
the same binary run as
codex app-server --listen unix://.
Exclusions
A shared daemon serves many launches, so it cannot honor options that
only one launch asked for. daemon_startup::exclusion
returns a reason string for each such option, checked in this order:
--no-daemon; --oss with
CODEX_OSS_BASE_URL or CODEX_OSS_PORT; workload
identity; CODEX_EXEC_SERVER_URL; --profile.
config_exclusion then rejects, in order, any
-c override other than a boolean under
features, tui.fullscreen_transcript, or
suppress_unstable_features_warning; a custom configuration
loader; --strict-config; and
--dangerously-bypass-hook-trust. Later checks add a custom
--oss provider, provider sign-in wizards, a Windows-mounted
WSL CODEX_HOME, and an elevated Windows session.
Any exclusion sends the launch to Embedded. When
auto-start would otherwise have applied, the TUI also says why: “Running
without the shared background server: <reason>
requires embedded mode.” The design is a capability check written as a
list of refusals. It trades convenience for correctness: a
-c model=... override silently ignored by a daemon started
yesterday would be worse than a slower embedded start.
One more check runs after the target is set.
daemon_recovery::check compares the launch’s explicit
feature overrides with the configuration the running daemon reports. Per
the module doc of daemon_startup.rs, “removed features are
inert, and unreported features are assumed disabled.” A mismatch also
falls back to Embedded. When the daemon connection itself
fails, start_app_server falls back only if the target
allows it; otherwise it fails with a hint: “To work without the
background server, rerun the same command with –no-daemon.”
The event loop
One select over many sources
The TUI runs one asynchronous loop in
codex-rs/tui/src/app/startup.rs. A single
select! waits on several sources at once and handles
whichever is ready:
- A pending input drain and a daemon restart task, when present.
- App events from
AppEventsenders throughout the UI, read throughsaved_openings.next_event(&mut app_event_rx). - Buffered events for the active thread, read from its channel.
- Terminal events, keys, paste, and resize, from
tui_events.next_event. - Server events from every connected backend, through
backends.next_event(paused_backend).
This is a reactor: one task owns all UI state, and every input
becomes a message it handles in turn. No widget needs a lock, because no
two handlers run at once. The cost is that a slow handler stalls
everything. So fetches for MCP inventory, skills, plugins, and rate
limits run as background requests, which, per the module doc of
app/background_requests.rs, route results back through
AppEvent “so the main event loop remains
single-threaded.”
Routing by thread
Server events do not go straight to the widget.
App::handle_app_server_event first checks which backend
owns the thread a notification names, then
enqueue_thread_notification places it on that thread’s
ThreadEventChannel. Each channel holds a bounded sender and
receiver plus a ThreadEventStore. The loop drains only the
active thread’s channel into ChatWidget. When the user
switches to another thread, the TUI replays that thread’s stored events
with ReplayKind::ThreadSnapshot, so ChatWidget
rebuilds its state from the same notifications a live client saw.
Background threads keep collecting events without touching the
screen.
Some events are about the connection, not a thread.
AppServerEvent::Lagged means the client dropped events
under pressure; the TUI logs a warning, resets overview caches, and
refreshes thread lists from the server. A closed event stream starts a
reconnect.
From notification to screen
ChatWidget
ChatWidget is the state machine of the chat screen. Its
doc comment says it “owns the state derived from the protocol event
stream (history cells, streaming buffers, bottom-pane overlays, and
transient status text)” and turns key presses into user intent.
handle_server_notification in
chatwidget/protocol.rs is one large match.
TurnStarted marks the task running;
ItemStarted and ItemCompleted open and close
history cells; AgentMessageDelta goes to
on_keyed_agent_message_delta, keyed by
(turn_id, item_id); reasoning deltas update the status row;
CommandExecutionOutputDelta appends to a running command;
TurnDiffUpdated refreshes the turn diff;
TurnCompleted finishes the turn.
Streaming markdown at newline boundaries
Rendering half a line of markdown is unstable. A * might
open emphasis or a list; a | might start a table.
MarkdownStreamCollector in
codex-rs/tui/src/markdown_stream.rs avoids the problem by
committing only completed lines:
/// Newline-gated accumulator that buffers raw markdown source and commits only completed lines.
// ...
/// The collector does not parse markdown in production. It only defines stable source boundaries;
/// rendering lives in the stream controllers so width changes can re-render from one accumulated
/// source string.
pub(crate) struct MarkdownStreamCollector {
buffer: String,
committed_source_len: usize,
// ...
}The stream controllers in streaming/controller.rs render
the accumulated source and split the result into a stable region, queued
for scrollback, and a mutable tail shown in the active cell. Tables get
special care, because a new row can change every column’s width. The
holdback mechanism keeps a pipe table in the tail until its block is
complete. On a resize, the controller re-renders from the one source
string at the new width. The trade-off is latency: text can wait up to
one line before it is committed.
Pacing the stream
Model output arrives in bursts, and printing each burst at once would
look jerky. AdaptiveChunkingPolicy in
streaming/chunking.rs drains the queue of committed lines
in one of two modes. In Smooth it releases one line per
commit tick; in CatchUp it releases the whole queue. Let
be the number of queued lines and
the age of the oldest one. The policy enters catch-up when
and starts to leave it when
but only after condition 22.2 has held for
QueueSnapshot at each
tick. After an exit, the policy refuses to re-enter for another 250 ms
unless the backlog is severe,
The tick sets the smooth speed. COMMIT_ANIMATION_TICK
equals TARGET_FRAME_INTERVAL, which equals
MIN_FRAME_INTERVAL of 8,333,334 nanoseconds. So the smooth
rate is
where
History cells and two transcript modes
Everything in the transcript is a HistoryCell, a trait
in history_cell/mod.rs whose core method is
display_lines(width). Concrete cells cover user and agent
messages, command runs, patches, MCP calls, plans, approvals, and
warnings. Width is a parameter, not state, so a cell can re-wrap on
resize.
Where finished cells go depends on the transcript mode. With
tui.fullscreen_transcript, which defaults to true, and an
alternate screen available, TranscriptMode::Owned lets the
TUI own scrolling, selection, and search. Otherwise
TranscriptMode::Terminal writes finished cells into the
terminal’s own scrollback; the module doc of
insert_history.rs notes that this makes inserting a cell
“an escape-sequence operation rather than a normal ratatui render.”
Approvals in the bottom pane
The bottom pane
The bottom pane is the footer of the chat screen. Per its module doc,
it owns the ChatComposer for prompt input and “a stack of
transient BottomPaneViews (popups/modals) that temporarily
replace the composer.” Input goes only to the top of the stack. Key
routing is layered: the pane decides whether the view or the composer
gets a key, and ChatWidget decides process-level intent,
such as whether an unhandled Ctrl+C interrupts the turn or arms the
double-press quit.
The approval overlay
A server request reaches
ChatWidget::handle_server_request. For a command approval,
on_exec_approval_request calls
defer_or_handle. If an answer is streaming, or earlier
interrupts are queued, the request joins the
InterruptManager queue; otherwise it shows at once. A
comment there explains the rule: once anything is queued, keep queueing
“to avoid reordering.” The overlay then arrives through
BottomPane::push_approval_request as one of four
ApprovalRequest variants: Exec,
Permissions, ApplyPatch, or
McpElicitation.
The module doc of approval_overlay.rs states two
contracts. Every selection emits an explicit decision event. And an MCP
elicitation keeps Esc mapped to Cancel, even
with custom keybindings, “so dismissal never silently becomes ‘continue
without info’.” The overlay decides nothing about safety; it presents
choices and routes the answer. The snapshot
codex_tui__chatwidget__tests__approval_modal_exec.snap,
from the test file chatwidget/tests/exec_flow.rs, pins what
a user sees:
Would you like to run the following command?
Reason: this is a test reason such as one that would be produced by the model
$ echo hello world
› 1. Yes, proceed (y)
2. Yes, and don't ask again for commands that start with `echo hello world` (p)
3. No, and tell Codex what to do differently (esc)
The choice travels back as an AppCommand::ExecApproval
with a CommandExecutionApprovalDecision.
App::try_resolve_app_server_request finds the pending
request for the thread, serializes a
CommandExecutionRequestApprovalResponse, and resolves it on
the connection that sent it. Option 2 maps to an execpolicy amendment
(see Chapter 15); the wider approval
policy belongs to Chapter 13.
Local rules for contributors
Two folders carry their own AGENTS.md, instructions
aimed at coding agents and humans who edit them.
codex-rs/tui/src/bottom_pane/AGENTS.md covers the
paste-burst and chat-composer state machines. Whoever changes them must
update the module docs of chat_composer.rs and
paste_burst.rs so the docs stay a top-down explanation of
current behavior. The file asks for a check after each edit that the
docs mention only APIs that exist, “especially the Enter/newline paths
and disable_paste_burst semantics.”
codex-rs/tui/src/ui_tree/AGENTS.md covers the UI tree, a
JSON element tree the status line can render from an MCP resource. Its
rule is about decoding. Object-shaped types must pair
#[serde(remote = "Self")] with the
impl_object_serde! macro, and callers must always decode
through the Deserialize trait. The reason is in
decode.rs: serde’s derived decoder also accepts positional
arrays, and the macro passes only maps to it, so a JSON array cannot
pose as an object. The same file enforces the limits from
ui_tree.rs: 64 KiB of JSON, 256 non-null nodes, depth 16,
and 16 KiB of text.
Snapshot tests
The TUI pins its rendering with snapshot tests from the
insta crate. A test renders a widget into a test terminal
backend at a fixed width and calls assert_snapshot!;
insta compares the text with a checked-in
.snap file and fails on any difference. The approval
snapshot above is one of 1,597 .snap files under
codex-rs/tui (counted). A reviewer reads a rendering change
as a text diff. Chapter 26
covers the test tooling.
Status at commit 081295be9d.
daemon_auto_start: STABLE, on by default.
tui_app_server: REMOVED, default true; the TUI always uses
the app server. Daemon auto-start: PLATFORM-SPECIFIC to Unix and Windows
builds, skipped for elevated Windows sessions and Windows-mounted WSL
homes. tui.fullscreen_transcript: configuration, default
true, subject to alternate-screen support. Read in code and snapshot
files, not run.
What breaks
| Symptom | Cause | Check |
|---|---|---|
| “Running without the shared background server” | An exclusion such as -c or --profile |
daemon_startup::exclusion |
| “Cannot use the shared background server” | Daemon unreachable or feature mismatch | Rerun with --no-daemon |
A -c setting seems ignored |
Launch attached to an existing daemon | Use --no-daemon or restart the daemon |
| Text appears a line late | Newline-gated commits | MarkdownStreamCollector |
| Approval prompt waits until output ends | Deferred while streaming | defer_or_handle |
| A rendering test fails after a UI change | Snapshot differs | Review the .snap diff |
Code map
| What it is | Where it lives | Identifier |
|---|---|---|
| Backend targets | codex:codex-rs/tui/src/lib.rs |
app_server_target_for_launch |
| Daemon exclusions | codex:codex-rs/tui/src/daemon_startup.rs |
config_exclusion |
| Auto-start decision | codex:codex-rs/tui/src/startup_orchestration.rs |
start_with_features_classified |
| Notification dispatch | codex:codex-rs/tui/src/chatwidget/protocol.rs |
handle_server_notification |
| Newline commits | codex:codex-rs/tui/src/markdown_stream.rs |
MarkdownStreamCollector |
| Stream pacing | codex:codex-rs/tui/src/streaming/chunking.rs |
AdaptiveChunkingPolicy |
| Approval overlay | codex:codex-rs/tui/src/bottom_pane/approval_overlay.rs |
ApprovalRequest |
| Approval deferral | codex:codex-rs/tui/src/chatwidget/streaming.rs |
defer_or_handle |
Recall check
Why does a -c override force an embedded app
server?
A shared daemon cannot apply one launch’s settings, so
config_exclusion refuses reuse.
What makes the TUI fall back to embedded mode
silently?
A LocalDaemon target found by probing allows fallback; an
auto-started one does not.
Why does streamed text commit only at
newlines?
Partial markdown lines render unstably; newline boundaries give the
renderer stable source.
When does the stream drain all queued lines at
once?
In catch-up mode, entered at 8 queued lines or 120 ms of age.
Why can an approval prompt appear only after output
finishes?
defer_or_handle queues it behind an active stream to keep
events in order.